Make X86ISD::ANDNP more general and Codegen 256-bit VANDNP. A more
[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::SREM_I64, "_allrem");
239     setLibcallName(RTLIB::UREM_I64, "_aullrem");
240     setLibcallName(RTLIB::MUL_I64, "_allmul");
241     setLibcallName(RTLIB::FPTOUINT_F64_I64, "_ftol2");
242     setLibcallName(RTLIB::FPTOUINT_F32_I64, "_ftol2");
243     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
244     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
245     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
246     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
247     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
248     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::C);
249     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::C);
250   }
251
252   if (Subtarget->isTargetDarwin()) {
253     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
254     setUseUnderscoreSetJmp(false);
255     setUseUnderscoreLongJmp(false);
256   } else if (Subtarget->isTargetMingw()) {
257     // MS runtime is weird: it exports _setjmp, but longjmp!
258     setUseUnderscoreSetJmp(true);
259     setUseUnderscoreLongJmp(false);
260   } else {
261     setUseUnderscoreSetJmp(true);
262     setUseUnderscoreLongJmp(true);
263   }
264
265   // Set up the register classes.
266   addRegisterClass(MVT::i8, X86::GR8RegisterClass);
267   addRegisterClass(MVT::i16, X86::GR16RegisterClass);
268   addRegisterClass(MVT::i32, X86::GR32RegisterClass);
269   if (Subtarget->is64Bit())
270     addRegisterClass(MVT::i64, X86::GR64RegisterClass);
271
272   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
273
274   // We don't accept any truncstore of integer registers.
275   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
276   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
277   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
278   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
279   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
280   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
281
282   // SETOEQ and SETUNE require checking two conditions.
283   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
284   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
285   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
286   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
287   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
288   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
289
290   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
291   // operation.
292   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
293   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
294   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
295
296   if (Subtarget->is64Bit()) {
297     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
298     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Expand);
299   } else if (!UseSoftFloat) {
300     // We have an algorithm for SSE2->double, and we turn this into a
301     // 64-bit FILD followed by conditional FADD for other targets.
302     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
303     // We have an algorithm for SSE2, and we turn this into a 64-bit
304     // FILD for other targets.
305     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
306   }
307
308   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
309   // this operation.
310   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
311   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
312
313   if (!UseSoftFloat) {
314     // SSE has no i16 to fp conversion, only i32
315     if (X86ScalarSSEf32) {
316       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
317       // f32 and f64 cases are Legal, f80 case is not
318       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
319     } else {
320       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
321       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
322     }
323   } else {
324     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
325     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
326   }
327
328   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
329   // are Legal, f80 is custom lowered.
330   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
331   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
332
333   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
334   // this operation.
335   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
336   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
337
338   if (X86ScalarSSEf32) {
339     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
340     // f32 and f64 cases are Legal, f80 case is not
341     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
342   } else {
343     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
344     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
345   }
346
347   // Handle FP_TO_UINT by promoting the destination to a larger signed
348   // conversion.
349   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
350   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
351   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
352
353   if (Subtarget->is64Bit()) {
354     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
355     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
356   } else if (!UseSoftFloat) {
357     if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
358       // Expand FP_TO_UINT into a select.
359       // FIXME: We would like to use a Custom expander here eventually to do
360       // the optimal thing for SSE vs. the default expansion in the legalizer.
361       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
362     else
363       // With SSE3 we can use fisttpll to convert to a signed i64; without
364       // SSE, we're stuck with a fistpll.
365       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
366   }
367
368   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
369   if (!X86ScalarSSEf64) {
370     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
371     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
372     if (Subtarget->is64Bit()) {
373       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
374       // Without SSE, i64->f64 goes through memory.
375       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
376     }
377   }
378
379   // Scalar integer divide and remainder are lowered to use operations that
380   // produce two results, to match the available instructions. This exposes
381   // the two-result form to trivial CSE, which is able to combine x/y and x%y
382   // into a single instruction.
383   //
384   // Scalar integer multiply-high is also lowered to use two-result
385   // operations, to match the available instructions. However, plain multiply
386   // (low) operations are left as Legal, as there are single-result
387   // instructions for this in x86. Using the two-result multiply instructions
388   // when both high and low results are needed must be arranged by dagcombine.
389   for (unsigned i = 0, e = 4; i != e; ++i) {
390     MVT VT = IntVTs[i];
391     setOperationAction(ISD::MULHS, VT, Expand);
392     setOperationAction(ISD::MULHU, VT, Expand);
393     setOperationAction(ISD::SDIV, VT, Expand);
394     setOperationAction(ISD::UDIV, VT, Expand);
395     setOperationAction(ISD::SREM, VT, Expand);
396     setOperationAction(ISD::UREM, VT, Expand);
397
398     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
399     setOperationAction(ISD::ADDC, VT, Custom);
400     setOperationAction(ISD::ADDE, VT, Custom);
401     setOperationAction(ISD::SUBC, VT, Custom);
402     setOperationAction(ISD::SUBE, VT, Custom);
403   }
404
405   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
406   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
407   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
408   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
409   if (Subtarget->is64Bit())
410     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
411   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
412   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
413   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
414   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
415   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
416   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
417   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
418   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
419
420   setOperationAction(ISD::CTTZ             , MVT::i8   , Custom);
421   setOperationAction(ISD::CTLZ             , MVT::i8   , Custom);
422   setOperationAction(ISD::CTTZ             , MVT::i16  , Custom);
423   setOperationAction(ISD::CTLZ             , MVT::i16  , Custom);
424   setOperationAction(ISD::CTTZ             , MVT::i32  , Custom);
425   setOperationAction(ISD::CTLZ             , MVT::i32  , Custom);
426   if (Subtarget->is64Bit()) {
427     setOperationAction(ISD::CTTZ           , MVT::i64  , Custom);
428     setOperationAction(ISD::CTLZ           , MVT::i64  , Custom);
429   }
430
431   if (Subtarget->hasPOPCNT()) {
432     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
433   } else {
434     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
435     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
436     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
437     if (Subtarget->is64Bit())
438       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
439   }
440
441   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
442   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
443
444   // These should be promoted to a larger select which is supported.
445   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
446   // X86 wants to expand cmov itself.
447   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
448   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
449   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
450   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
451   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
452   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
453   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
454   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
455   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
456   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
457   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
458   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
459   if (Subtarget->is64Bit()) {
460     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
461     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
462   }
463   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
464
465   // Darwin ABI issue.
466   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
467   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
468   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
469   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
470   if (Subtarget->is64Bit())
471     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
472   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
473   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
474   if (Subtarget->is64Bit()) {
475     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
476     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
477     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
478     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
479     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
480   }
481   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
482   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
483   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
484   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
485   if (Subtarget->is64Bit()) {
486     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
487     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
488     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
489   }
490
491   if (Subtarget->hasXMM())
492     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
493
494   // We may not have a libcall for MEMBARRIER so we should lower this.
495   setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
496
497   // On X86 and X86-64, atomic operations are lowered to locked instructions.
498   // Locked instructions, in turn, have implicit fence semantics (all memory
499   // operations are flushed before issuing the locked instruction, and they
500   // are not buffered), so we can fold away the common pattern of
501   // fence-atomic-fence.
502   setShouldFoldAtomicFences(true);
503
504   // Expand certain atomics
505   for (unsigned i = 0, e = 4; i != e; ++i) {
506     MVT VT = IntVTs[i];
507     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
508     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
509   }
510
511   if (!Subtarget->is64Bit()) {
512     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
513     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
514     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
515     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
516     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
517     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
518     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
519   }
520
521   // FIXME - use subtarget debug flags
522   if (!Subtarget->isTargetDarwin() &&
523       !Subtarget->isTargetELF() &&
524       !Subtarget->isTargetCygMing()) {
525     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
526   }
527
528   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
529   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
530   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
531   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
532   if (Subtarget->is64Bit()) {
533     setExceptionPointerRegister(X86::RAX);
534     setExceptionSelectorRegister(X86::RDX);
535   } else {
536     setExceptionPointerRegister(X86::EAX);
537     setExceptionSelectorRegister(X86::EDX);
538   }
539   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
540   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
541
542   setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
543
544   setOperationAction(ISD::TRAP, MVT::Other, Legal);
545
546   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
547   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
548   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
549   if (Subtarget->is64Bit()) {
550     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
551     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
552   } else {
553     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
554     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
555   }
556
557   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
558   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
559   setOperationAction(ISD::DYNAMIC_STACKALLOC,
560                      (Subtarget->is64Bit() ? MVT::i64 : MVT::i32),
561                      (Subtarget->isTargetCOFF()
562                       && !Subtarget->isTargetEnvMacho()
563                       ? Custom : Expand));
564
565   if (!UseSoftFloat && X86ScalarSSEf64) {
566     // f32 and f64 use SSE.
567     // Set up the FP register classes.
568     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
569     addRegisterClass(MVT::f64, X86::FR64RegisterClass);
570
571     // Use ANDPD to simulate FABS.
572     setOperationAction(ISD::FABS , MVT::f64, Custom);
573     setOperationAction(ISD::FABS , MVT::f32, Custom);
574
575     // Use XORP to simulate FNEG.
576     setOperationAction(ISD::FNEG , MVT::f64, Custom);
577     setOperationAction(ISD::FNEG , MVT::f32, Custom);
578
579     // Use ANDPD and ORPD to simulate FCOPYSIGN.
580     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
581     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
582
583     // Lower this to FGETSIGNx86 plus an AND.
584     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
585     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
586
587     // We don't support sin/cos/fmod
588     setOperationAction(ISD::FSIN , MVT::f64, Expand);
589     setOperationAction(ISD::FCOS , MVT::f64, Expand);
590     setOperationAction(ISD::FSIN , MVT::f32, Expand);
591     setOperationAction(ISD::FCOS , MVT::f32, Expand);
592
593     // Expand FP immediates into loads from the stack, except for the special
594     // cases we handle.
595     addLegalFPImmediate(APFloat(+0.0)); // xorpd
596     addLegalFPImmediate(APFloat(+0.0f)); // xorps
597   } else if (!UseSoftFloat && X86ScalarSSEf32) {
598     // Use SSE for f32, x87 for f64.
599     // Set up the FP register classes.
600     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
601     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
602
603     // Use ANDPS to simulate FABS.
604     setOperationAction(ISD::FABS , MVT::f32, Custom);
605
606     // Use XORP to simulate FNEG.
607     setOperationAction(ISD::FNEG , MVT::f32, Custom);
608
609     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
610
611     // Use ANDPS and ORPS to simulate FCOPYSIGN.
612     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
613     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
614
615     // We don't support sin/cos/fmod
616     setOperationAction(ISD::FSIN , MVT::f32, Expand);
617     setOperationAction(ISD::FCOS , MVT::f32, Expand);
618
619     // Special cases we handle for FP constants.
620     addLegalFPImmediate(APFloat(+0.0f)); // xorps
621     addLegalFPImmediate(APFloat(+0.0)); // FLD0
622     addLegalFPImmediate(APFloat(+1.0)); // FLD1
623     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
624     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
625
626     if (!UnsafeFPMath) {
627       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
628       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
629     }
630   } else if (!UseSoftFloat) {
631     // f32 and f64 in x87.
632     // Set up the FP register classes.
633     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
634     addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
635
636     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
637     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
638     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
639     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
640
641     if (!UnsafeFPMath) {
642       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
643       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
644     }
645     addLegalFPImmediate(APFloat(+0.0)); // FLD0
646     addLegalFPImmediate(APFloat(+1.0)); // FLD1
647     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
648     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
649     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
650     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
651     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
652     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
653   }
654
655   // We don't support FMA.
656   setOperationAction(ISD::FMA, MVT::f64, Expand);
657   setOperationAction(ISD::FMA, MVT::f32, Expand);
658
659   // Long double always uses X87.
660   if (!UseSoftFloat) {
661     addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
662     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
663     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
664     {
665       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
666       addLegalFPImmediate(TmpFlt);  // FLD0
667       TmpFlt.changeSign();
668       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
669
670       bool ignored;
671       APFloat TmpFlt2(+1.0);
672       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
673                       &ignored);
674       addLegalFPImmediate(TmpFlt2);  // FLD1
675       TmpFlt2.changeSign();
676       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
677     }
678
679     if (!UnsafeFPMath) {
680       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
681       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
682     }
683
684     setOperationAction(ISD::FMA, MVT::f80, Expand);
685   }
686
687   // Always use a library call for pow.
688   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
689   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
690   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
691
692   setOperationAction(ISD::FLOG, MVT::f80, Expand);
693   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
694   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
695   setOperationAction(ISD::FEXP, MVT::f80, Expand);
696   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
697
698   // First set operation action for all vector types to either promote
699   // (for widening) or expand (for scalarization). Then we will selectively
700   // turn on ones that can be effectively codegen'd.
701   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
702        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
703     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
704     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
705     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
706     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
707     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
708     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
709     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
710     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
711     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
712     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
713     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
714     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
715     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
716     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
717     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
718     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
719     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
720     setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
721     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
722     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
723     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
724     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
725     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
726     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
727     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
728     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
729     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
730     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
731     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
732     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
733     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
734     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
735     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
736     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
737     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
738     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
739     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
740     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
741     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
742     setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
743     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
744     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
745     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
746     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
747     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
748     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
749     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
750     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
751     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
752     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
753     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
754     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
755     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
756     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
757     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
758          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
759       setTruncStoreAction((MVT::SimpleValueType)VT,
760                           (MVT::SimpleValueType)InnerVT, Expand);
761     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
762     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
763     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
764   }
765
766   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
767   // with -msoft-float, disable use of MMX as well.
768   if (!UseSoftFloat && Subtarget->hasMMX()) {
769     addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass);
770     // No operations on x86mmx supported, everything uses intrinsics.
771   }
772
773   // MMX-sized vectors (other than x86mmx) are expected to be expanded
774   // into smaller operations.
775   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
776   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
777   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
778   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
779   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
780   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
781   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
782   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
783   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
784   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
785   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
786   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
787   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
788   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
789   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
790   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
791   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
792   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
793   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
794   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
795   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
796   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
797   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
798   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
799   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
800   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
801   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
802   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
803   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
804
805   if (!UseSoftFloat && Subtarget->hasXMM()) {
806     addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
807
808     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
809     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
810     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
811     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
812     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
813     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
814     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
815     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
816     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
817     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
818     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
819     setOperationAction(ISD::VSETCC,             MVT::v4f32, Custom);
820   }
821
822   if (!UseSoftFloat && Subtarget->hasXMMInt()) {
823     addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
824
825     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
826     // registers cannot be used even for integer operations.
827     addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
828     addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
829     addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
830     addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
831
832     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
833     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
834     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
835     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
836     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
837     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
838     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
839     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
840     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
841     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
842     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
843     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
844     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
845     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
846     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
847     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
848
849     setOperationAction(ISD::VSETCC,             MVT::v2f64, Custom);
850     setOperationAction(ISD::VSETCC,             MVT::v16i8, Custom);
851     setOperationAction(ISD::VSETCC,             MVT::v8i16, Custom);
852     setOperationAction(ISD::VSETCC,             MVT::v4i32, Custom);
853
854     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
855     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
856     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
857     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
858     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
859
860     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2f64, Custom);
861     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2i64, Custom);
862     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i8, Custom);
863     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i16, Custom);
864     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i32, Custom);
865
866     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
867     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
868       EVT VT = (MVT::SimpleValueType)i;
869       // Do not attempt to custom lower non-power-of-2 vectors
870       if (!isPowerOf2_32(VT.getVectorNumElements()))
871         continue;
872       // Do not attempt to custom lower non-128-bit vectors
873       if (!VT.is128BitVector())
874         continue;
875       setOperationAction(ISD::BUILD_VECTOR,
876                          VT.getSimpleVT().SimpleTy, Custom);
877       setOperationAction(ISD::VECTOR_SHUFFLE,
878                          VT.getSimpleVT().SimpleTy, Custom);
879       setOperationAction(ISD::EXTRACT_VECTOR_ELT,
880                          VT.getSimpleVT().SimpleTy, Custom);
881     }
882
883     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
884     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
885     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
886     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
887     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
888     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
889
890     if (Subtarget->is64Bit()) {
891       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
892       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
893     }
894
895     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
896     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
897       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
898       EVT VT = SVT;
899
900       // Do not attempt to promote non-128-bit vectors
901       if (!VT.is128BitVector())
902         continue;
903
904       setOperationAction(ISD::AND,    SVT, Promote);
905       AddPromotedToType (ISD::AND,    SVT, MVT::v2i64);
906       setOperationAction(ISD::OR,     SVT, Promote);
907       AddPromotedToType (ISD::OR,     SVT, MVT::v2i64);
908       setOperationAction(ISD::XOR,    SVT, Promote);
909       AddPromotedToType (ISD::XOR,    SVT, MVT::v2i64);
910       setOperationAction(ISD::LOAD,   SVT, Promote);
911       AddPromotedToType (ISD::LOAD,   SVT, MVT::v2i64);
912       setOperationAction(ISD::SELECT, SVT, Promote);
913       AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
914     }
915
916     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
917
918     // Custom lower v2i64 and v2f64 selects.
919     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
920     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
921     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
922     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
923
924     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
925     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
926   }
927
928   if (Subtarget->hasSSE41()) {
929     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
930     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
931     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
932     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
933     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
934     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
935     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
936     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
937     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
938     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
939
940     // FIXME: Do we need to handle scalar-to-vector here?
941     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
942
943     // Can turn SHL into an integer multiply.
944     setOperationAction(ISD::SHL,                MVT::v4i32, Custom);
945     setOperationAction(ISD::SHL,                MVT::v16i8, Custom);
946
947     // i8 and i16 vectors are custom , because the source register and source
948     // source memory operand types are not the same width.  f32 vectors are
949     // custom since the immediate controlling the insert encodes additional
950     // information.
951     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
952     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
953     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
954     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
955
956     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
957     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
958     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
959     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
960
961     if (Subtarget->is64Bit()) {
962       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Legal);
963       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
964     }
965   }
966
967   if (Subtarget->hasSSE2()) {
968     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
969     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
970     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
971
972     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
973     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
974     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
975
976     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
977     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
978   }
979
980   if (Subtarget->hasSSE42())
981     setOperationAction(ISD::VSETCC,             MVT::v2i64, Custom);
982
983   if (!UseSoftFloat && Subtarget->hasAVX()) {
984     addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
985     addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
986     addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
987     addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
988     addRegisterClass(MVT::v32i8, X86::VR256RegisterClass);
989
990     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
991     setOperationAction(ISD::LOAD,               MVT::v8i32, Legal);
992     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
993     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
994
995     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
996     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
997     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
998     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
999     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1000     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1001
1002     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1003     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1004     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1005     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1006     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1007     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1008
1009     // Custom lower build_vector, vector_shuffle, scalar_to_vector,
1010     // insert_vector_elt extract_subvector and extract_vector_elt for
1011     // 256-bit types.
1012     for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1013          i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE;
1014          ++i) {
1015       MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
1016       // Do not attempt to custom lower non-256-bit vectors
1017       if (!isPowerOf2_32(MVT(VT).getVectorNumElements())
1018           || (MVT(VT).getSizeInBits() < 256))
1019         continue;
1020       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1021       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1022       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1023       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1024       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1025     }
1026     // Custom-lower insert_subvector and extract_subvector based on
1027     // the result type.
1028     for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1029          i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE;
1030          ++i) {
1031       MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
1032       // Do not attempt to custom lower non-256-bit vectors
1033       if (!isPowerOf2_32(MVT(VT).getVectorNumElements()))
1034         continue;
1035
1036       if (MVT(VT).getSizeInBits() == 128) {
1037         setOperationAction(ISD::EXTRACT_SUBVECTOR,  VT, Custom);
1038       }
1039       else if (MVT(VT).getSizeInBits() == 256) {
1040         setOperationAction(ISD::INSERT_SUBVECTOR,  VT, Custom);
1041       }
1042     }
1043
1044     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1045     // Don't promote loads because we need them for VPERM vector index versions.
1046
1047     for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1048          VT != (unsigned)MVT::LAST_VECTOR_VALUETYPE;
1049          VT++) {
1050       if (!isPowerOf2_32(MVT((MVT::SimpleValueType)VT).getVectorNumElements())
1051           || (MVT((MVT::SimpleValueType)VT).getSizeInBits() < 256))
1052         continue;
1053       setOperationAction(ISD::AND,    (MVT::SimpleValueType)VT, Promote);
1054       AddPromotedToType (ISD::AND,    (MVT::SimpleValueType)VT, MVT::v4i64);
1055       setOperationAction(ISD::OR,     (MVT::SimpleValueType)VT, Promote);
1056       AddPromotedToType (ISD::OR,     (MVT::SimpleValueType)VT, MVT::v4i64);
1057       setOperationAction(ISD::XOR,    (MVT::SimpleValueType)VT, Promote);
1058       AddPromotedToType (ISD::XOR,    (MVT::SimpleValueType)VT, MVT::v4i64);
1059       //setOperationAction(ISD::LOAD,   (MVT::SimpleValueType)VT, Promote);
1060       //AddPromotedToType (ISD::LOAD,   (MVT::SimpleValueType)VT, MVT::v4i64);
1061       setOperationAction(ISD::SELECT, (MVT::SimpleValueType)VT, Promote);
1062       AddPromotedToType (ISD::SELECT, (MVT::SimpleValueType)VT, MVT::v4i64);
1063     }
1064   }
1065
1066   // We want to custom lower some of our intrinsics.
1067   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1068
1069
1070   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1071   // handle type legalization for these operations here.
1072   //
1073   // FIXME: We really should do custom legalization for addition and
1074   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1075   // than generic legalization for 64-bit multiplication-with-overflow, though.
1076   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1077     // Add/Sub/Mul with overflow operations are custom lowered.
1078     MVT VT = IntVTs[i];
1079     setOperationAction(ISD::SADDO, VT, Custom);
1080     setOperationAction(ISD::UADDO, VT, Custom);
1081     setOperationAction(ISD::SSUBO, VT, Custom);
1082     setOperationAction(ISD::USUBO, VT, Custom);
1083     setOperationAction(ISD::SMULO, VT, Custom);
1084     setOperationAction(ISD::UMULO, VT, Custom);
1085   }
1086
1087   // There are no 8-bit 3-address imul/mul instructions
1088   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1089   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1090
1091   if (!Subtarget->is64Bit()) {
1092     // These libcalls are not available in 32-bit.
1093     setLibcallName(RTLIB::SHL_I128, 0);
1094     setLibcallName(RTLIB::SRL_I128, 0);
1095     setLibcallName(RTLIB::SRA_I128, 0);
1096   }
1097
1098   // We have target-specific dag combine patterns for the following nodes:
1099   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1100   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1101   setTargetDAGCombine(ISD::BUILD_VECTOR);
1102   setTargetDAGCombine(ISD::SELECT);
1103   setTargetDAGCombine(ISD::SHL);
1104   setTargetDAGCombine(ISD::SRA);
1105   setTargetDAGCombine(ISD::SRL);
1106   setTargetDAGCombine(ISD::OR);
1107   setTargetDAGCombine(ISD::AND);
1108   setTargetDAGCombine(ISD::ADD);
1109   setTargetDAGCombine(ISD::SUB);
1110   setTargetDAGCombine(ISD::STORE);
1111   setTargetDAGCombine(ISD::ZERO_EXTEND);
1112   setTargetDAGCombine(ISD::SINT_TO_FP);
1113   if (Subtarget->is64Bit())
1114     setTargetDAGCombine(ISD::MUL);
1115
1116   computeRegisterProperties();
1117
1118   // On Darwin, -Os means optimize for size without hurting performance,
1119   // do not reduce the limit.
1120   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1121   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1122   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1123   maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1124   maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1125   maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1126   setPrefLoopAlignment(16);
1127   benefitFromCodePlacementOpt = true;
1128
1129   setPrefFunctionAlignment(4);
1130 }
1131
1132
1133 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
1134   return MVT::i8;
1135 }
1136
1137
1138 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1139 /// the desired ByVal argument alignment.
1140 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
1141   if (MaxAlign == 16)
1142     return;
1143   if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1144     if (VTy->getBitWidth() == 128)
1145       MaxAlign = 16;
1146   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1147     unsigned EltAlign = 0;
1148     getMaxByValAlign(ATy->getElementType(), EltAlign);
1149     if (EltAlign > MaxAlign)
1150       MaxAlign = EltAlign;
1151   } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1152     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1153       unsigned EltAlign = 0;
1154       getMaxByValAlign(STy->getElementType(i), EltAlign);
1155       if (EltAlign > MaxAlign)
1156         MaxAlign = EltAlign;
1157       if (MaxAlign == 16)
1158         break;
1159     }
1160   }
1161   return;
1162 }
1163
1164 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1165 /// function arguments in the caller parameter area. For X86, aggregates
1166 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1167 /// are at 4-byte boundaries.
1168 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1169   if (Subtarget->is64Bit()) {
1170     // Max of 8 and alignment of type.
1171     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1172     if (TyAlign > 8)
1173       return TyAlign;
1174     return 8;
1175   }
1176
1177   unsigned Align = 4;
1178   if (Subtarget->hasXMM())
1179     getMaxByValAlign(Ty, Align);
1180   return Align;
1181 }
1182
1183 /// getOptimalMemOpType - Returns the target specific optimal type for load
1184 /// and store operations as a result of memset, memcpy, and memmove
1185 /// lowering. If DstAlign is zero that means it's safe to destination
1186 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1187 /// means there isn't a need to check it against alignment requirement,
1188 /// probably because the source does not need to be loaded. If
1189 /// 'NonScalarIntSafe' is true, that means it's safe to return a
1190 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1191 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1192 /// constant so it does not need to be loaded.
1193 /// It returns EVT::Other if the type should be determined using generic
1194 /// target-independent logic.
1195 EVT
1196 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1197                                        unsigned DstAlign, unsigned SrcAlign,
1198                                        bool NonScalarIntSafe,
1199                                        bool MemcpyStrSrc,
1200                                        MachineFunction &MF) const {
1201   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1202   // linux.  This is because the stack realignment code can't handle certain
1203   // cases like PR2962.  This should be removed when PR2962 is fixed.
1204   const Function *F = MF.getFunction();
1205   if (NonScalarIntSafe &&
1206       !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1207     if (Size >= 16 &&
1208         (Subtarget->isUnalignedMemAccessFast() ||
1209          ((DstAlign == 0 || DstAlign >= 16) &&
1210           (SrcAlign == 0 || SrcAlign >= 16))) &&
1211         Subtarget->getStackAlignment() >= 16) {
1212       if (Subtarget->hasSSE2())
1213         return MVT::v4i32;
1214       if (Subtarget->hasSSE1())
1215         return MVT::v4f32;
1216     } else if (!MemcpyStrSrc && Size >= 8 &&
1217                !Subtarget->is64Bit() &&
1218                Subtarget->getStackAlignment() >= 8 &&
1219                Subtarget->hasXMMInt()) {
1220       // Do not use f64 to lower memcpy if source is string constant. It's
1221       // better to use i32 to avoid the loads.
1222       return MVT::f64;
1223     }
1224   }
1225   if (Subtarget->is64Bit() && Size >= 8)
1226     return MVT::i64;
1227   return MVT::i32;
1228 }
1229
1230 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1231 /// current function.  The returned value is a member of the
1232 /// MachineJumpTableInfo::JTEntryKind enum.
1233 unsigned X86TargetLowering::getJumpTableEncoding() const {
1234   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1235   // symbol.
1236   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1237       Subtarget->isPICStyleGOT())
1238     return MachineJumpTableInfo::EK_Custom32;
1239
1240   // Otherwise, use the normal jump table encoding heuristics.
1241   return TargetLowering::getJumpTableEncoding();
1242 }
1243
1244 const MCExpr *
1245 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1246                                              const MachineBasicBlock *MBB,
1247                                              unsigned uid,MCContext &Ctx) const{
1248   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1249          Subtarget->isPICStyleGOT());
1250   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1251   // entries.
1252   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1253                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1254 }
1255
1256 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1257 /// jumptable.
1258 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1259                                                     SelectionDAG &DAG) const {
1260   if (!Subtarget->is64Bit())
1261     // This doesn't have DebugLoc associated with it, but is not really the
1262     // same as a Register.
1263     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1264   return Table;
1265 }
1266
1267 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1268 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1269 /// MCExpr.
1270 const MCExpr *X86TargetLowering::
1271 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1272                              MCContext &Ctx) const {
1273   // X86-64 uses RIP relative addressing based on the jump table label.
1274   if (Subtarget->isPICStyleRIPRel())
1275     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1276
1277   // Otherwise, the reference is relative to the PIC base.
1278   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1279 }
1280
1281 // FIXME: Why this routine is here? Move to RegInfo!
1282 std::pair<const TargetRegisterClass*, uint8_t>
1283 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1284   const TargetRegisterClass *RRC = 0;
1285   uint8_t Cost = 1;
1286   switch (VT.getSimpleVT().SimpleTy) {
1287   default:
1288     return TargetLowering::findRepresentativeClass(VT);
1289   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1290     RRC = (Subtarget->is64Bit()
1291            ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1292     break;
1293   case MVT::x86mmx:
1294     RRC = X86::VR64RegisterClass;
1295     break;
1296   case MVT::f32: case MVT::f64:
1297   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1298   case MVT::v4f32: case MVT::v2f64:
1299   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1300   case MVT::v4f64:
1301     RRC = X86::VR128RegisterClass;
1302     break;
1303   }
1304   return std::make_pair(RRC, Cost);
1305 }
1306
1307 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1308                                                unsigned &Offset) const {
1309   if (!Subtarget->isTargetLinux())
1310     return false;
1311
1312   if (Subtarget->is64Bit()) {
1313     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1314     Offset = 0x28;
1315     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1316       AddressSpace = 256;
1317     else
1318       AddressSpace = 257;
1319   } else {
1320     // %gs:0x14 on i386
1321     Offset = 0x14;
1322     AddressSpace = 256;
1323   }
1324   return true;
1325 }
1326
1327
1328 //===----------------------------------------------------------------------===//
1329 //               Return Value Calling Convention Implementation
1330 //===----------------------------------------------------------------------===//
1331
1332 #include "X86GenCallingConv.inc"
1333
1334 bool
1335 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1336                                   MachineFunction &MF, bool isVarArg,
1337                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1338                         LLVMContext &Context) const {
1339   SmallVector<CCValAssign, 16> RVLocs;
1340   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1341                  RVLocs, Context);
1342   return CCInfo.CheckReturn(Outs, RetCC_X86);
1343 }
1344
1345 SDValue
1346 X86TargetLowering::LowerReturn(SDValue Chain,
1347                                CallingConv::ID CallConv, bool isVarArg,
1348                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1349                                const SmallVectorImpl<SDValue> &OutVals,
1350                                DebugLoc dl, SelectionDAG &DAG) const {
1351   MachineFunction &MF = DAG.getMachineFunction();
1352   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1353
1354   SmallVector<CCValAssign, 16> RVLocs;
1355   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1356                  RVLocs, *DAG.getContext());
1357   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1358
1359   // Add the regs to the liveout set for the function.
1360   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1361   for (unsigned i = 0; i != RVLocs.size(); ++i)
1362     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1363       MRI.addLiveOut(RVLocs[i].getLocReg());
1364
1365   SDValue Flag;
1366
1367   SmallVector<SDValue, 6> RetOps;
1368   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1369   // Operand #1 = Bytes To Pop
1370   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1371                    MVT::i16));
1372
1373   // Copy the result values into the output registers.
1374   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1375     CCValAssign &VA = RVLocs[i];
1376     assert(VA.isRegLoc() && "Can only return in registers!");
1377     SDValue ValToCopy = OutVals[i];
1378     EVT ValVT = ValToCopy.getValueType();
1379
1380     // If this is x86-64, and we disabled SSE, we can't return FP values,
1381     // or SSE or MMX vectors.
1382     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1383          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1384           (Subtarget->is64Bit() && !Subtarget->hasXMM())) {
1385       report_fatal_error("SSE register return with SSE disabled");
1386     }
1387     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1388     // llvm-gcc has never done it right and no one has noticed, so this
1389     // should be OK for now.
1390     if (ValVT == MVT::f64 &&
1391         (Subtarget->is64Bit() && !Subtarget->hasXMMInt()))
1392       report_fatal_error("SSE2 register return with SSE2 disabled");
1393
1394     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1395     // the RET instruction and handled by the FP Stackifier.
1396     if (VA.getLocReg() == X86::ST0 ||
1397         VA.getLocReg() == X86::ST1) {
1398       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1399       // change the value to the FP stack register class.
1400       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1401         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1402       RetOps.push_back(ValToCopy);
1403       // Don't emit a copytoreg.
1404       continue;
1405     }
1406
1407     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1408     // which is returned in RAX / RDX.
1409     if (Subtarget->is64Bit()) {
1410       if (ValVT == MVT::x86mmx) {
1411         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1412           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1413           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1414                                   ValToCopy);
1415           // If we don't have SSE2 available, convert to v4f32 so the generated
1416           // register is legal.
1417           if (!Subtarget->hasSSE2())
1418             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1419         }
1420       }
1421     }
1422
1423     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1424     Flag = Chain.getValue(1);
1425   }
1426
1427   // The x86-64 ABI for returning structs by value requires that we copy
1428   // the sret argument into %rax for the return. We saved the argument into
1429   // a virtual register in the entry block, so now we copy the value out
1430   // and into %rax.
1431   if (Subtarget->is64Bit() &&
1432       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1433     MachineFunction &MF = DAG.getMachineFunction();
1434     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1435     unsigned Reg = FuncInfo->getSRetReturnReg();
1436     assert(Reg &&
1437            "SRetReturnReg should have been set in LowerFormalArguments().");
1438     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1439
1440     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1441     Flag = Chain.getValue(1);
1442
1443     // RAX now acts like a return value.
1444     MRI.addLiveOut(X86::RAX);
1445   }
1446
1447   RetOps[0] = Chain;  // Update chain.
1448
1449   // Add the flag if we have it.
1450   if (Flag.getNode())
1451     RetOps.push_back(Flag);
1452
1453   return DAG.getNode(X86ISD::RET_FLAG, dl,
1454                      MVT::Other, &RetOps[0], RetOps.size());
1455 }
1456
1457 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1458   if (N->getNumValues() != 1)
1459     return false;
1460   if (!N->hasNUsesOfValue(1, 0))
1461     return false;
1462
1463   SDNode *Copy = *N->use_begin();
1464   if (Copy->getOpcode() != ISD::CopyToReg &&
1465       Copy->getOpcode() != ISD::FP_EXTEND)
1466     return false;
1467
1468   bool HasRet = false;
1469   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1470        UI != UE; ++UI) {
1471     if (UI->getOpcode() != X86ISD::RET_FLAG)
1472       return false;
1473     HasRet = true;
1474   }
1475
1476   return HasRet;
1477 }
1478
1479 EVT
1480 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1481                                             ISD::NodeType ExtendKind) const {
1482   MVT ReturnMVT;
1483   // TODO: Is this also valid on 32-bit?
1484   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1485     ReturnMVT = MVT::i8;
1486   else
1487     ReturnMVT = MVT::i32;
1488
1489   EVT MinVT = getRegisterType(Context, ReturnMVT);
1490   return VT.bitsLT(MinVT) ? MinVT : VT;
1491 }
1492
1493 /// LowerCallResult - Lower the result values of a call into the
1494 /// appropriate copies out of appropriate physical registers.
1495 ///
1496 SDValue
1497 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1498                                    CallingConv::ID CallConv, bool isVarArg,
1499                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1500                                    DebugLoc dl, SelectionDAG &DAG,
1501                                    SmallVectorImpl<SDValue> &InVals) const {
1502
1503   // Assign locations to each value returned by this call.
1504   SmallVector<CCValAssign, 16> RVLocs;
1505   bool Is64Bit = Subtarget->is64Bit();
1506   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1507                  getTargetMachine(), RVLocs, *DAG.getContext());
1508   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1509
1510   // Copy all of the result registers out of their specified physreg.
1511   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1512     CCValAssign &VA = RVLocs[i];
1513     EVT CopyVT = VA.getValVT();
1514
1515     // If this is x86-64, and we disabled SSE, we can't return FP values
1516     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1517         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) {
1518       report_fatal_error("SSE register return with SSE disabled");
1519     }
1520
1521     SDValue Val;
1522
1523     // If this is a call to a function that returns an fp value on the floating
1524     // point stack, we must guarantee the the value is popped from the stack, so
1525     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1526     // if the return value is not used. We use the FpPOP_RETVAL instruction
1527     // instead.
1528     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1529       // If we prefer to use the value in xmm registers, copy it out as f80 and
1530       // use a truncate to move it from fp stack reg to xmm reg.
1531       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1532       SDValue Ops[] = { Chain, InFlag };
1533       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1534                                          MVT::Other, MVT::Glue, Ops, 2), 1);
1535       Val = Chain.getValue(0);
1536
1537       // Round the f80 to the right size, which also moves it to the appropriate
1538       // xmm register.
1539       if (CopyVT != VA.getValVT())
1540         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1541                           // This truncation won't change the value.
1542                           DAG.getIntPtrConstant(1));
1543     } else {
1544       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1545                                  CopyVT, InFlag).getValue(1);
1546       Val = Chain.getValue(0);
1547     }
1548     InFlag = Chain.getValue(2);
1549     InVals.push_back(Val);
1550   }
1551
1552   return Chain;
1553 }
1554
1555
1556 //===----------------------------------------------------------------------===//
1557 //                C & StdCall & Fast Calling Convention implementation
1558 //===----------------------------------------------------------------------===//
1559 //  StdCall calling convention seems to be standard for many Windows' API
1560 //  routines and around. It differs from C calling convention just a little:
1561 //  callee should clean up the stack, not caller. Symbols should be also
1562 //  decorated in some fancy way :) It doesn't support any vector arguments.
1563 //  For info on fast calling convention see Fast Calling Convention (tail call)
1564 //  implementation LowerX86_32FastCCCallTo.
1565
1566 /// CallIsStructReturn - Determines whether a call uses struct return
1567 /// semantics.
1568 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1569   if (Outs.empty())
1570     return false;
1571
1572   return Outs[0].Flags.isSRet();
1573 }
1574
1575 /// ArgsAreStructReturn - Determines whether a function uses struct
1576 /// return semantics.
1577 static bool
1578 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1579   if (Ins.empty())
1580     return false;
1581
1582   return Ins[0].Flags.isSRet();
1583 }
1584
1585 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1586 /// by "Src" to address "Dst" with size and alignment information specified by
1587 /// the specific parameter attribute. The copy will be passed as a byval
1588 /// function parameter.
1589 static SDValue
1590 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1591                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1592                           DebugLoc dl) {
1593   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1594
1595   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1596                        /*isVolatile*/false, /*AlwaysInline=*/true,
1597                        MachinePointerInfo(), MachinePointerInfo());
1598 }
1599
1600 /// IsTailCallConvention - Return true if the calling convention is one that
1601 /// supports tail call optimization.
1602 static bool IsTailCallConvention(CallingConv::ID CC) {
1603   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1604 }
1605
1606 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1607   if (!CI->isTailCall())
1608     return false;
1609
1610   CallSite CS(CI);
1611   CallingConv::ID CalleeCC = CS.getCallingConv();
1612   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1613     return false;
1614
1615   return true;
1616 }
1617
1618 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1619 /// a tailcall target by changing its ABI.
1620 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1621   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1622 }
1623
1624 SDValue
1625 X86TargetLowering::LowerMemArgument(SDValue Chain,
1626                                     CallingConv::ID CallConv,
1627                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1628                                     DebugLoc dl, SelectionDAG &DAG,
1629                                     const CCValAssign &VA,
1630                                     MachineFrameInfo *MFI,
1631                                     unsigned i) const {
1632   // Create the nodes corresponding to a load from this parameter slot.
1633   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1634   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1635   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1636   EVT ValVT;
1637
1638   // If value is passed by pointer we have address passed instead of the value
1639   // itself.
1640   if (VA.getLocInfo() == CCValAssign::Indirect)
1641     ValVT = VA.getLocVT();
1642   else
1643     ValVT = VA.getValVT();
1644
1645   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1646   // changed with more analysis.
1647   // In case of tail call optimization mark all arguments mutable. Since they
1648   // could be overwritten by lowering of arguments in case of a tail call.
1649   if (Flags.isByVal()) {
1650     unsigned Bytes = Flags.getByValSize();
1651     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1652     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1653     return DAG.getFrameIndex(FI, getPointerTy());
1654   } else {
1655     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1656                                     VA.getLocMemOffset(), isImmutable);
1657     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1658     return DAG.getLoad(ValVT, dl, Chain, FIN,
1659                        MachinePointerInfo::getFixedStack(FI),
1660                        false, false, 0);
1661   }
1662 }
1663
1664 SDValue
1665 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1666                                         CallingConv::ID CallConv,
1667                                         bool isVarArg,
1668                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1669                                         DebugLoc dl,
1670                                         SelectionDAG &DAG,
1671                                         SmallVectorImpl<SDValue> &InVals)
1672                                           const {
1673   MachineFunction &MF = DAG.getMachineFunction();
1674   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1675
1676   const Function* Fn = MF.getFunction();
1677   if (Fn->hasExternalLinkage() &&
1678       Subtarget->isTargetCygMing() &&
1679       Fn->getName() == "main")
1680     FuncInfo->setForceFramePointer(true);
1681
1682   MachineFrameInfo *MFI = MF.getFrameInfo();
1683   bool Is64Bit = Subtarget->is64Bit();
1684   bool IsWin64 = Subtarget->isTargetWin64();
1685
1686   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1687          "Var args not supported with calling convention fastcc or ghc");
1688
1689   // Assign locations to all of the incoming arguments.
1690   SmallVector<CCValAssign, 16> ArgLocs;
1691   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1692                  ArgLocs, *DAG.getContext());
1693
1694   // Allocate shadow area for Win64
1695   if (IsWin64) {
1696     CCInfo.AllocateStack(32, 8);
1697   }
1698
1699   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1700
1701   unsigned LastVal = ~0U;
1702   SDValue ArgValue;
1703   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1704     CCValAssign &VA = ArgLocs[i];
1705     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1706     // places.
1707     assert(VA.getValNo() != LastVal &&
1708            "Don't support value assigned to multiple locs yet");
1709     LastVal = VA.getValNo();
1710
1711     if (VA.isRegLoc()) {
1712       EVT RegVT = VA.getLocVT();
1713       TargetRegisterClass *RC = NULL;
1714       if (RegVT == MVT::i32)
1715         RC = X86::GR32RegisterClass;
1716       else if (Is64Bit && RegVT == MVT::i64)
1717         RC = X86::GR64RegisterClass;
1718       else if (RegVT == MVT::f32)
1719         RC = X86::FR32RegisterClass;
1720       else if (RegVT == MVT::f64)
1721         RC = X86::FR64RegisterClass;
1722       else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1723         RC = X86::VR256RegisterClass;
1724       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1725         RC = X86::VR128RegisterClass;
1726       else if (RegVT == MVT::x86mmx)
1727         RC = X86::VR64RegisterClass;
1728       else
1729         llvm_unreachable("Unknown argument type!");
1730
1731       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1732       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1733
1734       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1735       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1736       // right size.
1737       if (VA.getLocInfo() == CCValAssign::SExt)
1738         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1739                                DAG.getValueType(VA.getValVT()));
1740       else if (VA.getLocInfo() == CCValAssign::ZExt)
1741         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1742                                DAG.getValueType(VA.getValVT()));
1743       else if (VA.getLocInfo() == CCValAssign::BCvt)
1744         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1745
1746       if (VA.isExtInLoc()) {
1747         // Handle MMX values passed in XMM regs.
1748         if (RegVT.isVector()) {
1749           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1750                                  ArgValue);
1751         } else
1752           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1753       }
1754     } else {
1755       assert(VA.isMemLoc());
1756       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1757     }
1758
1759     // If value is passed via pointer - do a load.
1760     if (VA.getLocInfo() == CCValAssign::Indirect)
1761       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1762                              MachinePointerInfo(), false, false, 0);
1763
1764     InVals.push_back(ArgValue);
1765   }
1766
1767   // The x86-64 ABI for returning structs by value requires that we copy
1768   // the sret argument into %rax for the return. Save the argument into
1769   // a virtual register so that we can access it from the return points.
1770   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1771     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1772     unsigned Reg = FuncInfo->getSRetReturnReg();
1773     if (!Reg) {
1774       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1775       FuncInfo->setSRetReturnReg(Reg);
1776     }
1777     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1778     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1779   }
1780
1781   unsigned StackSize = CCInfo.getNextStackOffset();
1782   // Align stack specially for tail calls.
1783   if (FuncIsMadeTailCallSafe(CallConv))
1784     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1785
1786   // If the function takes variable number of arguments, make a frame index for
1787   // the start of the first vararg value... for expansion of llvm.va_start.
1788   if (isVarArg) {
1789     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1790                     CallConv != CallingConv::X86_ThisCall)) {
1791       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1792     }
1793     if (Is64Bit) {
1794       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1795
1796       // FIXME: We should really autogenerate these arrays
1797       static const unsigned GPR64ArgRegsWin64[] = {
1798         X86::RCX, X86::RDX, X86::R8,  X86::R9
1799       };
1800       static const unsigned GPR64ArgRegs64Bit[] = {
1801         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1802       };
1803       static const unsigned XMMArgRegs64Bit[] = {
1804         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1805         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1806       };
1807       const unsigned *GPR64ArgRegs;
1808       unsigned NumXMMRegs = 0;
1809
1810       if (IsWin64) {
1811         // The XMM registers which might contain var arg parameters are shadowed
1812         // in their paired GPR.  So we only need to save the GPR to their home
1813         // slots.
1814         TotalNumIntRegs = 4;
1815         GPR64ArgRegs = GPR64ArgRegsWin64;
1816       } else {
1817         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1818         GPR64ArgRegs = GPR64ArgRegs64Bit;
1819
1820         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1821       }
1822       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1823                                                        TotalNumIntRegs);
1824
1825       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1826       assert(!(NumXMMRegs && !Subtarget->hasXMM()) &&
1827              "SSE register cannot be used when SSE is disabled!");
1828       assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1829              "SSE register cannot be used when SSE is disabled!");
1830       if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasXMM())
1831         // Kernel mode asks for SSE to be disabled, so don't push them
1832         // on the stack.
1833         TotalNumXMMRegs = 0;
1834
1835       if (IsWin64) {
1836         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1837         // Get to the caller-allocated home save location.  Add 8 to account
1838         // for the return address.
1839         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1840         FuncInfo->setRegSaveFrameIndex(
1841           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1842         // Fixup to set vararg frame on shadow area (4 x i64).
1843         if (NumIntRegs < 4)
1844           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1845       } else {
1846         // For X86-64, if there are vararg parameters that are passed via
1847         // registers, then we must store them to their spots on the stack so they
1848         // may be loaded by deferencing the result of va_next.
1849         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1850         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1851         FuncInfo->setRegSaveFrameIndex(
1852           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1853                                false));
1854       }
1855
1856       // Store the integer parameter registers.
1857       SmallVector<SDValue, 8> MemOps;
1858       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1859                                         getPointerTy());
1860       unsigned Offset = FuncInfo->getVarArgsGPOffset();
1861       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1862         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1863                                   DAG.getIntPtrConstant(Offset));
1864         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1865                                      X86::GR64RegisterClass);
1866         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1867         SDValue Store =
1868           DAG.getStore(Val.getValue(1), dl, Val, FIN,
1869                        MachinePointerInfo::getFixedStack(
1870                          FuncInfo->getRegSaveFrameIndex(), Offset),
1871                        false, false, 0);
1872         MemOps.push_back(Store);
1873         Offset += 8;
1874       }
1875
1876       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1877         // Now store the XMM (fp + vector) parameter registers.
1878         SmallVector<SDValue, 11> SaveXMMOps;
1879         SaveXMMOps.push_back(Chain);
1880
1881         unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1882         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1883         SaveXMMOps.push_back(ALVal);
1884
1885         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1886                                FuncInfo->getRegSaveFrameIndex()));
1887         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1888                                FuncInfo->getVarArgsFPOffset()));
1889
1890         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1891           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
1892                                        X86::VR128RegisterClass);
1893           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1894           SaveXMMOps.push_back(Val);
1895         }
1896         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1897                                      MVT::Other,
1898                                      &SaveXMMOps[0], SaveXMMOps.size()));
1899       }
1900
1901       if (!MemOps.empty())
1902         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1903                             &MemOps[0], MemOps.size());
1904     }
1905   }
1906
1907   // Some CCs need callee pop.
1908   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt)) {
1909     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1910   } else {
1911     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1912     // If this is an sret function, the return should pop the hidden pointer.
1913     if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1914       FuncInfo->setBytesToPopOnReturn(4);
1915   }
1916
1917   if (!Is64Bit) {
1918     // RegSaveFrameIndex is X86-64 only.
1919     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1920     if (CallConv == CallingConv::X86_FastCall ||
1921         CallConv == CallingConv::X86_ThisCall)
1922       // fastcc functions can't have varargs.
1923       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1924   }
1925
1926   return Chain;
1927 }
1928
1929 SDValue
1930 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1931                                     SDValue StackPtr, SDValue Arg,
1932                                     DebugLoc dl, SelectionDAG &DAG,
1933                                     const CCValAssign &VA,
1934                                     ISD::ArgFlagsTy Flags) const {
1935   unsigned LocMemOffset = VA.getLocMemOffset();
1936   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1937   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1938   if (Flags.isByVal())
1939     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1940
1941   return DAG.getStore(Chain, dl, Arg, PtrOff,
1942                       MachinePointerInfo::getStack(LocMemOffset),
1943                       false, false, 0);
1944 }
1945
1946 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1947 /// optimization is performed and it is required.
1948 SDValue
1949 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1950                                            SDValue &OutRetAddr, SDValue Chain,
1951                                            bool IsTailCall, bool Is64Bit,
1952                                            int FPDiff, DebugLoc dl) const {
1953   // Adjust the Return address stack slot.
1954   EVT VT = getPointerTy();
1955   OutRetAddr = getReturnAddressFrameIndex(DAG);
1956
1957   // Load the "old" Return address.
1958   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
1959                            false, false, 0);
1960   return SDValue(OutRetAddr.getNode(), 1);
1961 }
1962
1963 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
1964 /// optimization is performed and it is required (FPDiff!=0).
1965 static SDValue
1966 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1967                          SDValue Chain, SDValue RetAddrFrIdx,
1968                          bool Is64Bit, int FPDiff, DebugLoc dl) {
1969   // Store the return address to the appropriate stack slot.
1970   if (!FPDiff) return Chain;
1971   // Calculate the new stack slot for the return address.
1972   int SlotSize = Is64Bit ? 8 : 4;
1973   int NewReturnAddrFI =
1974     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
1975   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1976   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1977   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1978                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
1979                        false, false, 0);
1980   return Chain;
1981 }
1982
1983 SDValue
1984 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1985                              CallingConv::ID CallConv, bool isVarArg,
1986                              bool &isTailCall,
1987                              const SmallVectorImpl<ISD::OutputArg> &Outs,
1988                              const SmallVectorImpl<SDValue> &OutVals,
1989                              const SmallVectorImpl<ISD::InputArg> &Ins,
1990                              DebugLoc dl, SelectionDAG &DAG,
1991                              SmallVectorImpl<SDValue> &InVals) const {
1992   MachineFunction &MF = DAG.getMachineFunction();
1993   bool Is64Bit        = Subtarget->is64Bit();
1994   bool IsWin64        = Subtarget->isTargetWin64();
1995   bool IsStructRet    = CallIsStructReturn(Outs);
1996   bool IsSibcall      = false;
1997
1998   if (isTailCall) {
1999     // Check if it's really possible to do a tail call.
2000     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2001                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
2002                                                    Outs, OutVals, Ins, DAG);
2003
2004     // Sibcalls are automatically detected tailcalls which do not require
2005     // ABI changes.
2006     if (!GuaranteedTailCallOpt && isTailCall)
2007       IsSibcall = true;
2008
2009     if (isTailCall)
2010       ++NumTailCalls;
2011   }
2012
2013   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2014          "Var args not supported with calling convention fastcc or ghc");
2015
2016   // Analyze operands of the call, assigning locations to each operand.
2017   SmallVector<CCValAssign, 16> ArgLocs;
2018   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2019                  ArgLocs, *DAG.getContext());
2020
2021   // Allocate shadow area for Win64
2022   if (IsWin64) {
2023     CCInfo.AllocateStack(32, 8);
2024   }
2025
2026   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2027
2028   // Get a count of how many bytes are to be pushed on the stack.
2029   unsigned NumBytes = CCInfo.getNextStackOffset();
2030   if (IsSibcall)
2031     // This is a sibcall. The memory operands are available in caller's
2032     // own caller's stack.
2033     NumBytes = 0;
2034   else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
2035     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2036
2037   int FPDiff = 0;
2038   if (isTailCall && !IsSibcall) {
2039     // Lower arguments at fp - stackoffset + fpdiff.
2040     unsigned NumBytesCallerPushed =
2041       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2042     FPDiff = NumBytesCallerPushed - NumBytes;
2043
2044     // Set the delta of movement of the returnaddr stackslot.
2045     // But only set if delta is greater than previous delta.
2046     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2047       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2048   }
2049
2050   if (!IsSibcall)
2051     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2052
2053   SDValue RetAddrFrIdx;
2054   // Load return address for tail calls.
2055   if (isTailCall && FPDiff)
2056     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2057                                     Is64Bit, FPDiff, dl);
2058
2059   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2060   SmallVector<SDValue, 8> MemOpChains;
2061   SDValue StackPtr;
2062
2063   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2064   // of tail call optimization arguments are handle later.
2065   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2066     CCValAssign &VA = ArgLocs[i];
2067     EVT RegVT = VA.getLocVT();
2068     SDValue Arg = OutVals[i];
2069     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2070     bool isByVal = Flags.isByVal();
2071
2072     // Promote the value if needed.
2073     switch (VA.getLocInfo()) {
2074     default: llvm_unreachable("Unknown loc info!");
2075     case CCValAssign::Full: break;
2076     case CCValAssign::SExt:
2077       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2078       break;
2079     case CCValAssign::ZExt:
2080       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2081       break;
2082     case CCValAssign::AExt:
2083       if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2084         // Special case: passing MMX values in XMM registers.
2085         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2086         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2087         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2088       } else
2089         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2090       break;
2091     case CCValAssign::BCvt:
2092       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2093       break;
2094     case CCValAssign::Indirect: {
2095       // Store the argument.
2096       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2097       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2098       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2099                            MachinePointerInfo::getFixedStack(FI),
2100                            false, false, 0);
2101       Arg = SpillSlot;
2102       break;
2103     }
2104     }
2105
2106     if (VA.isRegLoc()) {
2107       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2108       if (isVarArg && IsWin64) {
2109         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2110         // shadow reg if callee is a varargs function.
2111         unsigned ShadowReg = 0;
2112         switch (VA.getLocReg()) {
2113         case X86::XMM0: ShadowReg = X86::RCX; break;
2114         case X86::XMM1: ShadowReg = X86::RDX; break;
2115         case X86::XMM2: ShadowReg = X86::R8; break;
2116         case X86::XMM3: ShadowReg = X86::R9; break;
2117         }
2118         if (ShadowReg)
2119           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2120       }
2121     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2122       assert(VA.isMemLoc());
2123       if (StackPtr.getNode() == 0)
2124         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2125       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2126                                              dl, DAG, VA, Flags));
2127     }
2128   }
2129
2130   if (!MemOpChains.empty())
2131     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2132                         &MemOpChains[0], MemOpChains.size());
2133
2134   // Build a sequence of copy-to-reg nodes chained together with token chain
2135   // and flag operands which copy the outgoing args into registers.
2136   SDValue InFlag;
2137   // Tail call byval lowering might overwrite argument registers so in case of
2138   // tail call optimization the copies to registers are lowered later.
2139   if (!isTailCall)
2140     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2141       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2142                                RegsToPass[i].second, InFlag);
2143       InFlag = Chain.getValue(1);
2144     }
2145
2146   if (Subtarget->isPICStyleGOT()) {
2147     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2148     // GOT pointer.
2149     if (!isTailCall) {
2150       Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2151                                DAG.getNode(X86ISD::GlobalBaseReg,
2152                                            DebugLoc(), getPointerTy()),
2153                                InFlag);
2154       InFlag = Chain.getValue(1);
2155     } else {
2156       // If we are tail calling and generating PIC/GOT style code load the
2157       // address of the callee into ECX. The value in ecx is used as target of
2158       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2159       // for tail calls on PIC/GOT architectures. Normally we would just put the
2160       // address of GOT into ebx and then call target@PLT. But for tail calls
2161       // ebx would be restored (since ebx is callee saved) before jumping to the
2162       // target@PLT.
2163
2164       // Note: The actual moving to ECX is done further down.
2165       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2166       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2167           !G->getGlobal()->hasProtectedVisibility())
2168         Callee = LowerGlobalAddress(Callee, DAG);
2169       else if (isa<ExternalSymbolSDNode>(Callee))
2170         Callee = LowerExternalSymbol(Callee, DAG);
2171     }
2172   }
2173
2174   if (Is64Bit && isVarArg && !IsWin64) {
2175     // From AMD64 ABI document:
2176     // For calls that may call functions that use varargs or stdargs
2177     // (prototype-less calls or calls to functions containing ellipsis (...) in
2178     // the declaration) %al is used as hidden argument to specify the number
2179     // of SSE registers used. The contents of %al do not need to match exactly
2180     // the number of registers, but must be an ubound on the number of SSE
2181     // registers used and is in the range 0 - 8 inclusive.
2182
2183     // Count the number of XMM registers allocated.
2184     static const unsigned XMMArgRegs[] = {
2185       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2186       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2187     };
2188     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2189     assert((Subtarget->hasXMM() || !NumXMMRegs)
2190            && "SSE registers cannot be used when SSE is disabled");
2191
2192     Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2193                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2194     InFlag = Chain.getValue(1);
2195   }
2196
2197
2198   // For tail calls lower the arguments to the 'real' stack slot.
2199   if (isTailCall) {
2200     // Force all the incoming stack arguments to be loaded from the stack
2201     // before any new outgoing arguments are stored to the stack, because the
2202     // outgoing stack slots may alias the incoming argument stack slots, and
2203     // the alias isn't otherwise explicit. This is slightly more conservative
2204     // than necessary, because it means that each store effectively depends
2205     // on every argument instead of just those arguments it would clobber.
2206     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2207
2208     SmallVector<SDValue, 8> MemOpChains2;
2209     SDValue FIN;
2210     int FI = 0;
2211     // Do not flag preceding copytoreg stuff together with the following stuff.
2212     InFlag = SDValue();
2213     if (GuaranteedTailCallOpt) {
2214       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2215         CCValAssign &VA = ArgLocs[i];
2216         if (VA.isRegLoc())
2217           continue;
2218         assert(VA.isMemLoc());
2219         SDValue Arg = OutVals[i];
2220         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2221         // Create frame index.
2222         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2223         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2224         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2225         FIN = DAG.getFrameIndex(FI, getPointerTy());
2226
2227         if (Flags.isByVal()) {
2228           // Copy relative to framepointer.
2229           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2230           if (StackPtr.getNode() == 0)
2231             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2232                                           getPointerTy());
2233           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2234
2235           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2236                                                            ArgChain,
2237                                                            Flags, DAG, dl));
2238         } else {
2239           // Store relative to framepointer.
2240           MemOpChains2.push_back(
2241             DAG.getStore(ArgChain, dl, Arg, FIN,
2242                          MachinePointerInfo::getFixedStack(FI),
2243                          false, false, 0));
2244         }
2245       }
2246     }
2247
2248     if (!MemOpChains2.empty())
2249       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2250                           &MemOpChains2[0], MemOpChains2.size());
2251
2252     // Copy arguments to their registers.
2253     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2254       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2255                                RegsToPass[i].second, InFlag);
2256       InFlag = Chain.getValue(1);
2257     }
2258     InFlag =SDValue();
2259
2260     // Store the return address to the appropriate stack slot.
2261     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2262                                      FPDiff, dl);
2263   }
2264
2265   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2266     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2267     // In the 64-bit large code model, we have to make all calls
2268     // through a register, since the call instruction's 32-bit
2269     // pc-relative offset may not be large enough to hold the whole
2270     // address.
2271   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2272     // If the callee is a GlobalAddress node (quite common, every direct call
2273     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2274     // it.
2275
2276     // We should use extra load for direct calls to dllimported functions in
2277     // non-JIT mode.
2278     const GlobalValue *GV = G->getGlobal();
2279     if (!GV->hasDLLImportLinkage()) {
2280       unsigned char OpFlags = 0;
2281       bool ExtraLoad = false;
2282       unsigned WrapperKind = ISD::DELETED_NODE;
2283
2284       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2285       // external symbols most go through the PLT in PIC mode.  If the symbol
2286       // has hidden or protected visibility, or if it is static or local, then
2287       // we don't need to use the PLT - we can directly call it.
2288       if (Subtarget->isTargetELF() &&
2289           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2290           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2291         OpFlags = X86II::MO_PLT;
2292       } else if (Subtarget->isPICStyleStubAny() &&
2293                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2294                  (!Subtarget->getTargetTriple().isMacOSX() ||
2295                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2296         // PC-relative references to external symbols should go through $stub,
2297         // unless we're building with the leopard linker or later, which
2298         // automatically synthesizes these stubs.
2299         OpFlags = X86II::MO_DARWIN_STUB;
2300       } else if (Subtarget->isPICStyleRIPRel() &&
2301                  isa<Function>(GV) &&
2302                  cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2303         // If the function is marked as non-lazy, generate an indirect call
2304         // which loads from the GOT directly. This avoids runtime overhead
2305         // at the cost of eager binding (and one extra byte of encoding).
2306         OpFlags = X86II::MO_GOTPCREL;
2307         WrapperKind = X86ISD::WrapperRIP;
2308         ExtraLoad = true;
2309       }
2310
2311       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2312                                           G->getOffset(), OpFlags);
2313
2314       // Add a wrapper if needed.
2315       if (WrapperKind != ISD::DELETED_NODE)
2316         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2317       // Add extra indirection if needed.
2318       if (ExtraLoad)
2319         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2320                              MachinePointerInfo::getGOT(),
2321                              false, false, 0);
2322     }
2323   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2324     unsigned char OpFlags = 0;
2325
2326     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2327     // external symbols should go through the PLT.
2328     if (Subtarget->isTargetELF() &&
2329         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2330       OpFlags = X86II::MO_PLT;
2331     } else if (Subtarget->isPICStyleStubAny() &&
2332                (!Subtarget->getTargetTriple().isMacOSX() ||
2333                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2334       // PC-relative references to external symbols should go through $stub,
2335       // unless we're building with the leopard linker or later, which
2336       // automatically synthesizes these stubs.
2337       OpFlags = X86II::MO_DARWIN_STUB;
2338     }
2339
2340     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2341                                          OpFlags);
2342   }
2343
2344   // Returns a chain & a flag for retval copy to use.
2345   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2346   SmallVector<SDValue, 8> Ops;
2347
2348   if (!IsSibcall && isTailCall) {
2349     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2350                            DAG.getIntPtrConstant(0, true), InFlag);
2351     InFlag = Chain.getValue(1);
2352   }
2353
2354   Ops.push_back(Chain);
2355   Ops.push_back(Callee);
2356
2357   if (isTailCall)
2358     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2359
2360   // Add argument registers to the end of the list so that they are known live
2361   // into the call.
2362   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2363     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2364                                   RegsToPass[i].second.getValueType()));
2365
2366   // Add an implicit use GOT pointer in EBX.
2367   if (!isTailCall && Subtarget->isPICStyleGOT())
2368     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2369
2370   // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2371   if (Is64Bit && isVarArg && !IsWin64)
2372     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2373
2374   if (InFlag.getNode())
2375     Ops.push_back(InFlag);
2376
2377   if (isTailCall) {
2378     // We used to do:
2379     //// If this is the first return lowered for this function, add the regs
2380     //// to the liveout set for the function.
2381     // This isn't right, although it's probably harmless on x86; liveouts
2382     // should be computed from returns not tail calls.  Consider a void
2383     // function making a tail call to a function returning int.
2384     return DAG.getNode(X86ISD::TC_RETURN, dl,
2385                        NodeTys, &Ops[0], Ops.size());
2386   }
2387
2388   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2389   InFlag = Chain.getValue(1);
2390
2391   // Create the CALLSEQ_END node.
2392   unsigned NumBytesForCalleeToPush;
2393   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt))
2394     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2395   else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2396     // If this is a call to a struct-return function, the callee
2397     // pops the hidden struct pointer, so we have to push it back.
2398     // This is common for Darwin/X86, Linux & Mingw32 targets.
2399     NumBytesForCalleeToPush = 4;
2400   else
2401     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2402
2403   // Returns a flag for retval copy to use.
2404   if (!IsSibcall) {
2405     Chain = DAG.getCALLSEQ_END(Chain,
2406                                DAG.getIntPtrConstant(NumBytes, true),
2407                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2408                                                      true),
2409                                InFlag);
2410     InFlag = Chain.getValue(1);
2411   }
2412
2413   // Handle result values, copying them out of physregs into vregs that we
2414   // return.
2415   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2416                          Ins, dl, DAG, InVals);
2417 }
2418
2419
2420 //===----------------------------------------------------------------------===//
2421 //                Fast Calling Convention (tail call) implementation
2422 //===----------------------------------------------------------------------===//
2423
2424 //  Like std call, callee cleans arguments, convention except that ECX is
2425 //  reserved for storing the tail called function address. Only 2 registers are
2426 //  free for argument passing (inreg). Tail call optimization is performed
2427 //  provided:
2428 //                * tailcallopt is enabled
2429 //                * caller/callee are fastcc
2430 //  On X86_64 architecture with GOT-style position independent code only local
2431 //  (within module) calls are supported at the moment.
2432 //  To keep the stack aligned according to platform abi the function
2433 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2434 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2435 //  If a tail called function callee has more arguments than the caller the
2436 //  caller needs to make sure that there is room to move the RETADDR to. This is
2437 //  achieved by reserving an area the size of the argument delta right after the
2438 //  original REtADDR, but before the saved framepointer or the spilled registers
2439 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2440 //  stack layout:
2441 //    arg1
2442 //    arg2
2443 //    RETADDR
2444 //    [ new RETADDR
2445 //      move area ]
2446 //    (possible EBP)
2447 //    ESI
2448 //    EDI
2449 //    local1 ..
2450
2451 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2452 /// for a 16 byte align requirement.
2453 unsigned
2454 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2455                                                SelectionDAG& DAG) const {
2456   MachineFunction &MF = DAG.getMachineFunction();
2457   const TargetMachine &TM = MF.getTarget();
2458   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2459   unsigned StackAlignment = TFI.getStackAlignment();
2460   uint64_t AlignMask = StackAlignment - 1;
2461   int64_t Offset = StackSize;
2462   uint64_t SlotSize = TD->getPointerSize();
2463   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2464     // Number smaller than 12 so just add the difference.
2465     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2466   } else {
2467     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2468     Offset = ((~AlignMask) & Offset) + StackAlignment +
2469       (StackAlignment-SlotSize);
2470   }
2471   return Offset;
2472 }
2473
2474 /// MatchingStackOffset - Return true if the given stack call argument is
2475 /// already available in the same position (relatively) of the caller's
2476 /// incoming argument stack.
2477 static
2478 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2479                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2480                          const X86InstrInfo *TII) {
2481   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2482   int FI = INT_MAX;
2483   if (Arg.getOpcode() == ISD::CopyFromReg) {
2484     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2485     if (!TargetRegisterInfo::isVirtualRegister(VR))
2486       return false;
2487     MachineInstr *Def = MRI->getVRegDef(VR);
2488     if (!Def)
2489       return false;
2490     if (!Flags.isByVal()) {
2491       if (!TII->isLoadFromStackSlot(Def, FI))
2492         return false;
2493     } else {
2494       unsigned Opcode = Def->getOpcode();
2495       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2496           Def->getOperand(1).isFI()) {
2497         FI = Def->getOperand(1).getIndex();
2498         Bytes = Flags.getByValSize();
2499       } else
2500         return false;
2501     }
2502   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2503     if (Flags.isByVal())
2504       // ByVal argument is passed in as a pointer but it's now being
2505       // dereferenced. e.g.
2506       // define @foo(%struct.X* %A) {
2507       //   tail call @bar(%struct.X* byval %A)
2508       // }
2509       return false;
2510     SDValue Ptr = Ld->getBasePtr();
2511     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2512     if (!FINode)
2513       return false;
2514     FI = FINode->getIndex();
2515   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2516     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2517     FI = FINode->getIndex();
2518     Bytes = Flags.getByValSize();
2519   } else
2520     return false;
2521
2522   assert(FI != INT_MAX);
2523   if (!MFI->isFixedObjectIndex(FI))
2524     return false;
2525   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2526 }
2527
2528 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2529 /// for tail call optimization. Targets which want to do tail call
2530 /// optimization should implement this function.
2531 bool
2532 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2533                                                      CallingConv::ID CalleeCC,
2534                                                      bool isVarArg,
2535                                                      bool isCalleeStructRet,
2536                                                      bool isCallerStructRet,
2537                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2538                                     const SmallVectorImpl<SDValue> &OutVals,
2539                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2540                                                      SelectionDAG& DAG) const {
2541   if (!IsTailCallConvention(CalleeCC) &&
2542       CalleeCC != CallingConv::C)
2543     return false;
2544
2545   // If -tailcallopt is specified, make fastcc functions tail-callable.
2546   const MachineFunction &MF = DAG.getMachineFunction();
2547   const Function *CallerF = DAG.getMachineFunction().getFunction();
2548   CallingConv::ID CallerCC = CallerF->getCallingConv();
2549   bool CCMatch = CallerCC == CalleeCC;
2550
2551   if (GuaranteedTailCallOpt) {
2552     if (IsTailCallConvention(CalleeCC) && CCMatch)
2553       return true;
2554     return false;
2555   }
2556
2557   // Look for obvious safe cases to perform tail call optimization that do not
2558   // require ABI changes. This is what gcc calls sibcall.
2559
2560   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2561   // emit a special epilogue.
2562   if (RegInfo->needsStackRealignment(MF))
2563     return false;
2564
2565   // Also avoid sibcall optimization if either caller or callee uses struct
2566   // return semantics.
2567   if (isCalleeStructRet || isCallerStructRet)
2568     return false;
2569
2570   // An stdcall caller is expected to clean up its arguments; the callee
2571   // isn't going to do that.
2572   if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2573     return false;
2574
2575   // Do not sibcall optimize vararg calls unless all arguments are passed via
2576   // registers.
2577   if (isVarArg && !Outs.empty()) {
2578
2579     // Optimizing for varargs on Win64 is unlikely to be safe without
2580     // additional testing.
2581     if (Subtarget->isTargetWin64())
2582       return false;
2583
2584     SmallVector<CCValAssign, 16> ArgLocs;
2585     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2586                    getTargetMachine(), ArgLocs, *DAG.getContext());
2587
2588     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2589     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2590       if (!ArgLocs[i].isRegLoc())
2591         return false;
2592   }
2593
2594   // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2595   // Therefore if it's not used by the call it is not safe to optimize this into
2596   // a sibcall.
2597   bool Unused = false;
2598   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2599     if (!Ins[i].Used) {
2600       Unused = true;
2601       break;
2602     }
2603   }
2604   if (Unused) {
2605     SmallVector<CCValAssign, 16> RVLocs;
2606     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2607                    getTargetMachine(), RVLocs, *DAG.getContext());
2608     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2609     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2610       CCValAssign &VA = RVLocs[i];
2611       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2612         return false;
2613     }
2614   }
2615
2616   // If the calling conventions do not match, then we'd better make sure the
2617   // results are returned in the same way as what the caller expects.
2618   if (!CCMatch) {
2619     SmallVector<CCValAssign, 16> RVLocs1;
2620     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2621                     getTargetMachine(), RVLocs1, *DAG.getContext());
2622     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2623
2624     SmallVector<CCValAssign, 16> RVLocs2;
2625     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2626                     getTargetMachine(), RVLocs2, *DAG.getContext());
2627     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2628
2629     if (RVLocs1.size() != RVLocs2.size())
2630       return false;
2631     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2632       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2633         return false;
2634       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2635         return false;
2636       if (RVLocs1[i].isRegLoc()) {
2637         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2638           return false;
2639       } else {
2640         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2641           return false;
2642       }
2643     }
2644   }
2645
2646   // If the callee takes no arguments then go on to check the results of the
2647   // call.
2648   if (!Outs.empty()) {
2649     // Check if stack adjustment is needed. For now, do not do this if any
2650     // argument is passed on the stack.
2651     SmallVector<CCValAssign, 16> ArgLocs;
2652     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2653                    getTargetMachine(), ArgLocs, *DAG.getContext());
2654
2655     // Allocate shadow area for Win64
2656     if (Subtarget->isTargetWin64()) {
2657       CCInfo.AllocateStack(32, 8);
2658     }
2659
2660     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2661     if (CCInfo.getNextStackOffset()) {
2662       MachineFunction &MF = DAG.getMachineFunction();
2663       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2664         return false;
2665
2666       // Check if the arguments are already laid out in the right way as
2667       // the caller's fixed stack objects.
2668       MachineFrameInfo *MFI = MF.getFrameInfo();
2669       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2670       const X86InstrInfo *TII =
2671         ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2672       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2673         CCValAssign &VA = ArgLocs[i];
2674         SDValue Arg = OutVals[i];
2675         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2676         if (VA.getLocInfo() == CCValAssign::Indirect)
2677           return false;
2678         if (!VA.isRegLoc()) {
2679           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2680                                    MFI, MRI, TII))
2681             return false;
2682         }
2683       }
2684     }
2685
2686     // If the tailcall address may be in a register, then make sure it's
2687     // possible to register allocate for it. In 32-bit, the call address can
2688     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2689     // callee-saved registers are restored. These happen to be the same
2690     // registers used to pass 'inreg' arguments so watch out for those.
2691     if (!Subtarget->is64Bit() &&
2692         !isa<GlobalAddressSDNode>(Callee) &&
2693         !isa<ExternalSymbolSDNode>(Callee)) {
2694       unsigned NumInRegs = 0;
2695       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2696         CCValAssign &VA = ArgLocs[i];
2697         if (!VA.isRegLoc())
2698           continue;
2699         unsigned Reg = VA.getLocReg();
2700         switch (Reg) {
2701         default: break;
2702         case X86::EAX: case X86::EDX: case X86::ECX:
2703           if (++NumInRegs == 3)
2704             return false;
2705           break;
2706         }
2707       }
2708     }
2709   }
2710
2711   return true;
2712 }
2713
2714 FastISel *
2715 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2716   return X86::createFastISel(funcInfo);
2717 }
2718
2719
2720 //===----------------------------------------------------------------------===//
2721 //                           Other Lowering Hooks
2722 //===----------------------------------------------------------------------===//
2723
2724 static bool MayFoldLoad(SDValue Op) {
2725   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2726 }
2727
2728 static bool MayFoldIntoStore(SDValue Op) {
2729   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2730 }
2731
2732 static bool isTargetShuffle(unsigned Opcode) {
2733   switch(Opcode) {
2734   default: return false;
2735   case X86ISD::PSHUFD:
2736   case X86ISD::PSHUFHW:
2737   case X86ISD::PSHUFLW:
2738   case X86ISD::SHUFPD:
2739   case X86ISD::PALIGN:
2740   case X86ISD::SHUFPS:
2741   case X86ISD::MOVLHPS:
2742   case X86ISD::MOVLHPD:
2743   case X86ISD::MOVHLPS:
2744   case X86ISD::MOVLPS:
2745   case X86ISD::MOVLPD:
2746   case X86ISD::MOVSHDUP:
2747   case X86ISD::MOVSLDUP:
2748   case X86ISD::MOVDDUP:
2749   case X86ISD::MOVSS:
2750   case X86ISD::MOVSD:
2751   case X86ISD::UNPCKLPS:
2752   case X86ISD::UNPCKLPD:
2753   case X86ISD::VUNPCKLPS:
2754   case X86ISD::VUNPCKLPD:
2755   case X86ISD::VUNPCKLPSY:
2756   case X86ISD::VUNPCKLPDY:
2757   case X86ISD::PUNPCKLWD:
2758   case X86ISD::PUNPCKLBW:
2759   case X86ISD::PUNPCKLDQ:
2760   case X86ISD::PUNPCKLQDQ:
2761   case X86ISD::UNPCKHPS:
2762   case X86ISD::UNPCKHPD:
2763   case X86ISD::PUNPCKHWD:
2764   case X86ISD::PUNPCKHBW:
2765   case X86ISD::PUNPCKHDQ:
2766   case X86ISD::PUNPCKHQDQ:
2767     return true;
2768   }
2769   return false;
2770 }
2771
2772 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2773                                                SDValue V1, SelectionDAG &DAG) {
2774   switch(Opc) {
2775   default: llvm_unreachable("Unknown x86 shuffle node");
2776   case X86ISD::MOVSHDUP:
2777   case X86ISD::MOVSLDUP:
2778   case X86ISD::MOVDDUP:
2779     return DAG.getNode(Opc, dl, VT, V1);
2780   }
2781
2782   return SDValue();
2783 }
2784
2785 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2786                           SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2787   switch(Opc) {
2788   default: llvm_unreachable("Unknown x86 shuffle node");
2789   case X86ISD::PSHUFD:
2790   case X86ISD::PSHUFHW:
2791   case X86ISD::PSHUFLW:
2792     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2793   }
2794
2795   return SDValue();
2796 }
2797
2798 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2799                SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2800   switch(Opc) {
2801   default: llvm_unreachable("Unknown x86 shuffle node");
2802   case X86ISD::PALIGN:
2803   case X86ISD::SHUFPD:
2804   case X86ISD::SHUFPS:
2805     return DAG.getNode(Opc, dl, VT, V1, V2,
2806                        DAG.getConstant(TargetMask, MVT::i8));
2807   }
2808   return SDValue();
2809 }
2810
2811 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2812                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
2813   switch(Opc) {
2814   default: llvm_unreachable("Unknown x86 shuffle node");
2815   case X86ISD::MOVLHPS:
2816   case X86ISD::MOVLHPD:
2817   case X86ISD::MOVHLPS:
2818   case X86ISD::MOVLPS:
2819   case X86ISD::MOVLPD:
2820   case X86ISD::MOVSS:
2821   case X86ISD::MOVSD:
2822   case X86ISD::UNPCKLPS:
2823   case X86ISD::UNPCKLPD:
2824   case X86ISD::VUNPCKLPS:
2825   case X86ISD::VUNPCKLPD:
2826   case X86ISD::VUNPCKLPSY:
2827   case X86ISD::VUNPCKLPDY:
2828   case X86ISD::PUNPCKLWD:
2829   case X86ISD::PUNPCKLBW:
2830   case X86ISD::PUNPCKLDQ:
2831   case X86ISD::PUNPCKLQDQ:
2832   case X86ISD::UNPCKHPS:
2833   case X86ISD::UNPCKHPD:
2834   case X86ISD::PUNPCKHWD:
2835   case X86ISD::PUNPCKHBW:
2836   case X86ISD::PUNPCKHDQ:
2837   case X86ISD::PUNPCKHQDQ:
2838     return DAG.getNode(Opc, dl, VT, V1, V2);
2839   }
2840   return SDValue();
2841 }
2842
2843 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2844   MachineFunction &MF = DAG.getMachineFunction();
2845   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2846   int ReturnAddrIndex = FuncInfo->getRAIndex();
2847
2848   if (ReturnAddrIndex == 0) {
2849     // Set up a frame object for the return address.
2850     uint64_t SlotSize = TD->getPointerSize();
2851     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2852                                                            false);
2853     FuncInfo->setRAIndex(ReturnAddrIndex);
2854   }
2855
2856   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2857 }
2858
2859
2860 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2861                                        bool hasSymbolicDisplacement) {
2862   // Offset should fit into 32 bit immediate field.
2863   if (!isInt<32>(Offset))
2864     return false;
2865
2866   // If we don't have a symbolic displacement - we don't have any extra
2867   // restrictions.
2868   if (!hasSymbolicDisplacement)
2869     return true;
2870
2871   // FIXME: Some tweaks might be needed for medium code model.
2872   if (M != CodeModel::Small && M != CodeModel::Kernel)
2873     return false;
2874
2875   // For small code model we assume that latest object is 16MB before end of 31
2876   // bits boundary. We may also accept pretty large negative constants knowing
2877   // that all objects are in the positive half of address space.
2878   if (M == CodeModel::Small && Offset < 16*1024*1024)
2879     return true;
2880
2881   // For kernel code model we know that all object resist in the negative half
2882   // of 32bits address space. We may not accept negative offsets, since they may
2883   // be just off and we may accept pretty large positive ones.
2884   if (M == CodeModel::Kernel && Offset > 0)
2885     return true;
2886
2887   return false;
2888 }
2889
2890 /// isCalleePop - Determines whether the callee is required to pop its
2891 /// own arguments. Callee pop is necessary to support tail calls.
2892 bool X86::isCalleePop(CallingConv::ID CallingConv,
2893                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
2894   if (IsVarArg)
2895     return false;
2896
2897   switch (CallingConv) {
2898   default:
2899     return false;
2900   case CallingConv::X86_StdCall:
2901     return !is64Bit;
2902   case CallingConv::X86_FastCall:
2903     return !is64Bit;
2904   case CallingConv::X86_ThisCall:
2905     return !is64Bit;
2906   case CallingConv::Fast:
2907     return TailCallOpt;
2908   case CallingConv::GHC:
2909     return TailCallOpt;
2910   }
2911 }
2912
2913 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2914 /// specific condition code, returning the condition code and the LHS/RHS of the
2915 /// comparison to make.
2916 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2917                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2918   if (!isFP) {
2919     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2920       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2921         // X > -1   -> X == 0, jump !sign.
2922         RHS = DAG.getConstant(0, RHS.getValueType());
2923         return X86::COND_NS;
2924       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2925         // X < 0   -> X == 0, jump on sign.
2926         return X86::COND_S;
2927       } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2928         // X < 1   -> X <= 0
2929         RHS = DAG.getConstant(0, RHS.getValueType());
2930         return X86::COND_LE;
2931       }
2932     }
2933
2934     switch (SetCCOpcode) {
2935     default: llvm_unreachable("Invalid integer condition!");
2936     case ISD::SETEQ:  return X86::COND_E;
2937     case ISD::SETGT:  return X86::COND_G;
2938     case ISD::SETGE:  return X86::COND_GE;
2939     case ISD::SETLT:  return X86::COND_L;
2940     case ISD::SETLE:  return X86::COND_LE;
2941     case ISD::SETNE:  return X86::COND_NE;
2942     case ISD::SETULT: return X86::COND_B;
2943     case ISD::SETUGT: return X86::COND_A;
2944     case ISD::SETULE: return X86::COND_BE;
2945     case ISD::SETUGE: return X86::COND_AE;
2946     }
2947   }
2948
2949   // First determine if it is required or is profitable to flip the operands.
2950
2951   // If LHS is a foldable load, but RHS is not, flip the condition.
2952   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
2953       !ISD::isNON_EXTLoad(RHS.getNode())) {
2954     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2955     std::swap(LHS, RHS);
2956   }
2957
2958   switch (SetCCOpcode) {
2959   default: break;
2960   case ISD::SETOLT:
2961   case ISD::SETOLE:
2962   case ISD::SETUGT:
2963   case ISD::SETUGE:
2964     std::swap(LHS, RHS);
2965     break;
2966   }
2967
2968   // On a floating point condition, the flags are set as follows:
2969   // ZF  PF  CF   op
2970   //  0 | 0 | 0 | X > Y
2971   //  0 | 0 | 1 | X < Y
2972   //  1 | 0 | 0 | X == Y
2973   //  1 | 1 | 1 | unordered
2974   switch (SetCCOpcode) {
2975   default: llvm_unreachable("Condcode should be pre-legalized away");
2976   case ISD::SETUEQ:
2977   case ISD::SETEQ:   return X86::COND_E;
2978   case ISD::SETOLT:              // flipped
2979   case ISD::SETOGT:
2980   case ISD::SETGT:   return X86::COND_A;
2981   case ISD::SETOLE:              // flipped
2982   case ISD::SETOGE:
2983   case ISD::SETGE:   return X86::COND_AE;
2984   case ISD::SETUGT:              // flipped
2985   case ISD::SETULT:
2986   case ISD::SETLT:   return X86::COND_B;
2987   case ISD::SETUGE:              // flipped
2988   case ISD::SETULE:
2989   case ISD::SETLE:   return X86::COND_BE;
2990   case ISD::SETONE:
2991   case ISD::SETNE:   return X86::COND_NE;
2992   case ISD::SETUO:   return X86::COND_P;
2993   case ISD::SETO:    return X86::COND_NP;
2994   case ISD::SETOEQ:
2995   case ISD::SETUNE:  return X86::COND_INVALID;
2996   }
2997 }
2998
2999 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3000 /// code. Current x86 isa includes the following FP cmov instructions:
3001 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3002 static bool hasFPCMov(unsigned X86CC) {
3003   switch (X86CC) {
3004   default:
3005     return false;
3006   case X86::COND_B:
3007   case X86::COND_BE:
3008   case X86::COND_E:
3009   case X86::COND_P:
3010   case X86::COND_A:
3011   case X86::COND_AE:
3012   case X86::COND_NE:
3013   case X86::COND_NP:
3014     return true;
3015   }
3016 }
3017
3018 /// isFPImmLegal - Returns true if the target can instruction select the
3019 /// specified FP immediate natively. If false, the legalizer will
3020 /// materialize the FP immediate as a load from a constant pool.
3021 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3022   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3023     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3024       return true;
3025   }
3026   return false;
3027 }
3028
3029 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3030 /// the specified range (L, H].
3031 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3032   return (Val < 0) || (Val >= Low && Val < Hi);
3033 }
3034
3035 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3036 /// specified value.
3037 static bool isUndefOrEqual(int Val, int CmpVal) {
3038   if (Val < 0 || Val == CmpVal)
3039     return true;
3040   return false;
3041 }
3042
3043 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3044 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3045 /// the second operand.
3046 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3047   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3048     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3049   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3050     return (Mask[0] < 2 && Mask[1] < 2);
3051   return false;
3052 }
3053
3054 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
3055   SmallVector<int, 8> M;
3056   N->getMask(M);
3057   return ::isPSHUFDMask(M, N->getValueType(0));
3058 }
3059
3060 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3061 /// is suitable for input to PSHUFHW.
3062 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3063   if (VT != MVT::v8i16)
3064     return false;
3065
3066   // Lower quadword copied in order or undef.
3067   for (int i = 0; i != 4; ++i)
3068     if (Mask[i] >= 0 && Mask[i] != i)
3069       return false;
3070
3071   // Upper quadword shuffled.
3072   for (int i = 4; i != 8; ++i)
3073     if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
3074       return false;
3075
3076   return true;
3077 }
3078
3079 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
3080   SmallVector<int, 8> M;
3081   N->getMask(M);
3082   return ::isPSHUFHWMask(M, N->getValueType(0));
3083 }
3084
3085 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3086 /// is suitable for input to PSHUFLW.
3087 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3088   if (VT != MVT::v8i16)
3089     return false;
3090
3091   // Upper quadword copied in order.
3092   for (int i = 4; i != 8; ++i)
3093     if (Mask[i] >= 0 && Mask[i] != i)
3094       return false;
3095
3096   // Lower quadword shuffled.
3097   for (int i = 0; i != 4; ++i)
3098     if (Mask[i] >= 4)
3099       return false;
3100
3101   return true;
3102 }
3103
3104 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
3105   SmallVector<int, 8> M;
3106   N->getMask(M);
3107   return ::isPSHUFLWMask(M, N->getValueType(0));
3108 }
3109
3110 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3111 /// is suitable for input to PALIGNR.
3112 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
3113                           bool hasSSSE3) {
3114   int i, e = VT.getVectorNumElements();
3115
3116   // Do not handle v2i64 / v2f64 shuffles with palignr.
3117   if (e < 4 || !hasSSSE3)
3118     return false;
3119
3120   for (i = 0; i != e; ++i)
3121     if (Mask[i] >= 0)
3122       break;
3123
3124   // All undef, not a palignr.
3125   if (i == e)
3126     return false;
3127
3128   // Determine if it's ok to perform a palignr with only the LHS, since we
3129   // don't have access to the actual shuffle elements to see if RHS is undef.
3130   bool Unary = Mask[i] < (int)e;
3131   bool NeedsUnary = false;
3132
3133   int s = Mask[i] - i;
3134
3135   // Check the rest of the elements to see if they are consecutive.
3136   for (++i; i != e; ++i) {
3137     int m = Mask[i];
3138     if (m < 0)
3139       continue;
3140
3141     Unary = Unary && (m < (int)e);
3142     NeedsUnary = NeedsUnary || (m < s);
3143
3144     if (NeedsUnary && !Unary)
3145       return false;
3146     if (Unary && m != ((s+i) & (e-1)))
3147       return false;
3148     if (!Unary && m != (s+i))
3149       return false;
3150   }
3151   return true;
3152 }
3153
3154 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
3155   SmallVector<int, 8> M;
3156   N->getMask(M);
3157   return ::isPALIGNRMask(M, N->getValueType(0), true);
3158 }
3159
3160 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3161 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
3162 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3163   int NumElems = VT.getVectorNumElements();
3164   if (NumElems != 2 && NumElems != 4)
3165     return false;
3166
3167   int Half = NumElems / 2;
3168   for (int i = 0; i < Half; ++i)
3169     if (!isUndefOrInRange(Mask[i], 0, NumElems))
3170       return false;
3171   for (int i = Half; i < NumElems; ++i)
3172     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3173       return false;
3174
3175   return true;
3176 }
3177
3178 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
3179   SmallVector<int, 8> M;
3180   N->getMask(M);
3181   return ::isSHUFPMask(M, N->getValueType(0));
3182 }
3183
3184 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
3185 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
3186 /// half elements to come from vector 1 (which would equal the dest.) and
3187 /// the upper half to come from vector 2.
3188 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3189   int NumElems = VT.getVectorNumElements();
3190
3191   if (NumElems != 2 && NumElems != 4)
3192     return false;
3193
3194   int Half = NumElems / 2;
3195   for (int i = 0; i < Half; ++i)
3196     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3197       return false;
3198   for (int i = Half; i < NumElems; ++i)
3199     if (!isUndefOrInRange(Mask[i], 0, NumElems))
3200       return false;
3201   return true;
3202 }
3203
3204 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
3205   SmallVector<int, 8> M;
3206   N->getMask(M);
3207   return isCommutedSHUFPMask(M, N->getValueType(0));
3208 }
3209
3210 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3211 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3212 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3213   if (N->getValueType(0).getVectorNumElements() != 4)
3214     return false;
3215
3216   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3217   return isUndefOrEqual(N->getMaskElt(0), 6) &&
3218          isUndefOrEqual(N->getMaskElt(1), 7) &&
3219          isUndefOrEqual(N->getMaskElt(2), 2) &&
3220          isUndefOrEqual(N->getMaskElt(3), 3);
3221 }
3222
3223 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3224 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3225 /// <2, 3, 2, 3>
3226 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3227   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3228
3229   if (NumElems != 4)
3230     return false;
3231
3232   return isUndefOrEqual(N->getMaskElt(0), 2) &&
3233   isUndefOrEqual(N->getMaskElt(1), 3) &&
3234   isUndefOrEqual(N->getMaskElt(2), 2) &&
3235   isUndefOrEqual(N->getMaskElt(3), 3);
3236 }
3237
3238 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3239 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3240 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3241   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3242
3243   if (NumElems != 2 && NumElems != 4)
3244     return false;
3245
3246   for (unsigned i = 0; i < NumElems/2; ++i)
3247     if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3248       return false;
3249
3250   for (unsigned i = NumElems/2; i < NumElems; ++i)
3251     if (!isUndefOrEqual(N->getMaskElt(i), i))
3252       return false;
3253
3254   return true;
3255 }
3256
3257 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3258 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3259 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3260   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3261
3262   if ((NumElems != 2 && NumElems != 4)
3263       || N->getValueType(0).getSizeInBits() > 128)
3264     return false;
3265
3266   for (unsigned i = 0; i < NumElems/2; ++i)
3267     if (!isUndefOrEqual(N->getMaskElt(i), i))
3268       return false;
3269
3270   for (unsigned i = 0; i < NumElems/2; ++i)
3271     if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3272       return false;
3273
3274   return true;
3275 }
3276
3277 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3278 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3279 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3280                          bool V2IsSplat = false) {
3281   int NumElts = VT.getVectorNumElements();
3282   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3283     return false;
3284
3285   // Handle vector lengths > 128 bits.  Define a "section" as a set of
3286   // 128 bits.  AVX defines UNPCK* to operate independently on 128-bit
3287   // sections.
3288   unsigned NumSections = VT.getSizeInBits() / 128;
3289   if (NumSections == 0 ) NumSections = 1;  // Handle MMX
3290   unsigned NumSectionElts = NumElts / NumSections;
3291
3292   unsigned Start = 0;
3293   unsigned End = NumSectionElts;
3294   for (unsigned s = 0; s < NumSections; ++s) {
3295     for (unsigned i = Start, j = s * NumSectionElts;
3296          i != End;
3297          i += 2, ++j) {
3298       int BitI  = Mask[i];
3299       int BitI1 = Mask[i+1];
3300       if (!isUndefOrEqual(BitI, j))
3301         return false;
3302       if (V2IsSplat) {
3303         if (!isUndefOrEqual(BitI1, NumElts))
3304           return false;
3305       } else {
3306         if (!isUndefOrEqual(BitI1, j + NumElts))
3307           return false;
3308       }
3309     }
3310     // Process the next 128 bits.
3311     Start += NumSectionElts;
3312     End += NumSectionElts;
3313   }
3314
3315   return true;
3316 }
3317
3318 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3319   SmallVector<int, 8> M;
3320   N->getMask(M);
3321   return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
3322 }
3323
3324 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3325 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3326 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3327                          bool V2IsSplat = false) {
3328   int NumElts = VT.getVectorNumElements();
3329   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3330     return false;
3331
3332   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3333     int BitI  = Mask[i];
3334     int BitI1 = Mask[i+1];
3335     if (!isUndefOrEqual(BitI, j + NumElts/2))
3336       return false;
3337     if (V2IsSplat) {
3338       if (isUndefOrEqual(BitI1, NumElts))
3339         return false;
3340     } else {
3341       if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
3342         return false;
3343     }
3344   }
3345   return true;
3346 }
3347
3348 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3349   SmallVector<int, 8> M;
3350   N->getMask(M);
3351   return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
3352 }
3353
3354 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3355 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3356 /// <0, 0, 1, 1>
3357 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3358   int NumElems = VT.getVectorNumElements();
3359   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3360     return false;
3361
3362   // Handle vector lengths > 128 bits.  Define a "section" as a set of
3363   // 128 bits.  AVX defines UNPCK* to operate independently on 128-bit
3364   // sections.
3365   unsigned NumSections = VT.getSizeInBits() / 128;
3366   if (NumSections == 0 ) NumSections = 1;  // Handle MMX
3367   unsigned NumSectionElts = NumElems / NumSections;
3368
3369   for (unsigned s = 0; s < NumSections; ++s) {
3370     for (unsigned i = s * NumSectionElts, j = s * NumSectionElts;
3371          i != NumSectionElts * (s + 1);
3372          i += 2, ++j) {
3373       int BitI  = Mask[i];
3374       int BitI1 = Mask[i+1];
3375
3376       if (!isUndefOrEqual(BitI, j))
3377         return false;
3378       if (!isUndefOrEqual(BitI1, j))
3379         return false;
3380     }
3381   }
3382
3383   return true;
3384 }
3385
3386 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3387   SmallVector<int, 8> M;
3388   N->getMask(M);
3389   return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3390 }
3391
3392 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3393 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3394 /// <2, 2, 3, 3>
3395 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3396   int NumElems = VT.getVectorNumElements();
3397   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3398     return false;
3399
3400   for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3401     int BitI  = Mask[i];
3402     int BitI1 = Mask[i+1];
3403     if (!isUndefOrEqual(BitI, j))
3404       return false;
3405     if (!isUndefOrEqual(BitI1, j))
3406       return false;
3407   }
3408   return true;
3409 }
3410
3411 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3412   SmallVector<int, 8> M;
3413   N->getMask(M);
3414   return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3415 }
3416
3417 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3418 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3419 /// MOVSD, and MOVD, i.e. setting the lowest element.
3420 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3421   if (VT.getVectorElementType().getSizeInBits() < 32)
3422     return false;
3423
3424   int NumElts = VT.getVectorNumElements();
3425
3426   if (!isUndefOrEqual(Mask[0], NumElts))
3427     return false;
3428
3429   for (int i = 1; i < NumElts; ++i)
3430     if (!isUndefOrEqual(Mask[i], i))
3431       return false;
3432
3433   return true;
3434 }
3435
3436 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3437   SmallVector<int, 8> M;
3438   N->getMask(M);
3439   return ::isMOVLMask(M, N->getValueType(0));
3440 }
3441
3442 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3443 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3444 /// element of vector 2 and the other elements to come from vector 1 in order.
3445 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3446                                bool V2IsSplat = false, bool V2IsUndef = false) {
3447   int NumOps = VT.getVectorNumElements();
3448   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3449     return false;
3450
3451   if (!isUndefOrEqual(Mask[0], 0))
3452     return false;
3453
3454   for (int i = 1; i < NumOps; ++i)
3455     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3456           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3457           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3458       return false;
3459
3460   return true;
3461 }
3462
3463 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3464                            bool V2IsUndef = false) {
3465   SmallVector<int, 8> M;
3466   N->getMask(M);
3467   return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3468 }
3469
3470 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3471 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3472 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
3473   if (N->getValueType(0).getVectorNumElements() != 4)
3474     return false;
3475
3476   // Expect 1, 1, 3, 3
3477   for (unsigned i = 0; i < 2; ++i) {
3478     int Elt = N->getMaskElt(i);
3479     if (Elt >= 0 && Elt != 1)
3480       return false;
3481   }
3482
3483   bool HasHi = false;
3484   for (unsigned i = 2; i < 4; ++i) {
3485     int Elt = N->getMaskElt(i);
3486     if (Elt >= 0 && Elt != 3)
3487       return false;
3488     if (Elt == 3)
3489       HasHi = true;
3490   }
3491   // Don't use movshdup if it can be done with a shufps.
3492   // FIXME: verify that matching u, u, 3, 3 is what we want.
3493   return HasHi;
3494 }
3495
3496 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3497 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3498 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
3499   if (N->getValueType(0).getVectorNumElements() != 4)
3500     return false;
3501
3502   // Expect 0, 0, 2, 2
3503   for (unsigned i = 0; i < 2; ++i)
3504     if (N->getMaskElt(i) > 0)
3505       return false;
3506
3507   bool HasHi = false;
3508   for (unsigned i = 2; i < 4; ++i) {
3509     int Elt = N->getMaskElt(i);
3510     if (Elt >= 0 && Elt != 2)
3511       return false;
3512     if (Elt == 2)
3513       HasHi = true;
3514   }
3515   // Don't use movsldup if it can be done with a shufps.
3516   return HasHi;
3517 }
3518
3519 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3520 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3521 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3522   int e = N->getValueType(0).getVectorNumElements() / 2;
3523
3524   for (int i = 0; i < e; ++i)
3525     if (!isUndefOrEqual(N->getMaskElt(i), i))
3526       return false;
3527   for (int i = 0; i < e; ++i)
3528     if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3529       return false;
3530   return true;
3531 }
3532
3533 /// isVEXTRACTF128Index - Return true if the specified
3534 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3535 /// suitable for input to VEXTRACTF128.
3536 bool X86::isVEXTRACTF128Index(SDNode *N) {
3537   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3538     return false;
3539
3540   // The index should be aligned on a 128-bit boundary.
3541   uint64_t Index =
3542     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3543
3544   unsigned VL = N->getValueType(0).getVectorNumElements();
3545   unsigned VBits = N->getValueType(0).getSizeInBits();
3546   unsigned ElSize = VBits / VL;
3547   bool Result = (Index * ElSize) % 128 == 0;
3548
3549   return Result;
3550 }
3551
3552 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3553 /// operand specifies a subvector insert that is suitable for input to
3554 /// VINSERTF128.
3555 bool X86::isVINSERTF128Index(SDNode *N) {
3556   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3557     return false;
3558
3559   // The index should be aligned on a 128-bit boundary.
3560   uint64_t Index =
3561     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3562
3563   unsigned VL = N->getValueType(0).getVectorNumElements();
3564   unsigned VBits = N->getValueType(0).getSizeInBits();
3565   unsigned ElSize = VBits / VL;
3566   bool Result = (Index * ElSize) % 128 == 0;
3567
3568   return Result;
3569 }
3570
3571 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3572 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3573 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3574   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3575   int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3576
3577   unsigned Shift = (NumOperands == 4) ? 2 : 1;
3578   unsigned Mask = 0;
3579   for (int i = 0; i < NumOperands; ++i) {
3580     int Val = SVOp->getMaskElt(NumOperands-i-1);
3581     if (Val < 0) Val = 0;
3582     if (Val >= NumOperands) Val -= NumOperands;
3583     Mask |= Val;
3584     if (i != NumOperands - 1)
3585       Mask <<= Shift;
3586   }
3587   return Mask;
3588 }
3589
3590 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3591 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3592 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3593   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3594   unsigned Mask = 0;
3595   // 8 nodes, but we only care about the last 4.
3596   for (unsigned i = 7; i >= 4; --i) {
3597     int Val = SVOp->getMaskElt(i);
3598     if (Val >= 0)
3599       Mask |= (Val - 4);
3600     if (i != 4)
3601       Mask <<= 2;
3602   }
3603   return Mask;
3604 }
3605
3606 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3607 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3608 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3609   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3610   unsigned Mask = 0;
3611   // 8 nodes, but we only care about the first 4.
3612   for (int i = 3; i >= 0; --i) {
3613     int Val = SVOp->getMaskElt(i);
3614     if (Val >= 0)
3615       Mask |= Val;
3616     if (i != 0)
3617       Mask <<= 2;
3618   }
3619   return Mask;
3620 }
3621
3622 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3623 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3624 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3625   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3626   EVT VVT = N->getValueType(0);
3627   unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3628   int Val = 0;
3629
3630   unsigned i, e;
3631   for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3632     Val = SVOp->getMaskElt(i);
3633     if (Val >= 0)
3634       break;
3635   }
3636   return (Val - i) * EltSize;
3637 }
3638
3639 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
3640 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
3641 /// instructions.
3642 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
3643   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3644     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
3645
3646   uint64_t Index =
3647     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3648
3649   EVT VecVT = N->getOperand(0).getValueType();
3650   EVT ElVT = VecVT.getVectorElementType();
3651
3652   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3653
3654   return Index / NumElemsPerChunk;
3655 }
3656
3657 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
3658 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
3659 /// instructions.
3660 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
3661   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3662     llvm_unreachable("Illegal insert subvector for VINSERTF128");
3663
3664   uint64_t Index =
3665     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3666
3667   EVT VecVT = N->getValueType(0);
3668   EVT ElVT = VecVT.getVectorElementType();
3669
3670   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3671
3672   return Index / NumElemsPerChunk;
3673 }
3674
3675 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3676 /// constant +0.0.
3677 bool X86::isZeroNode(SDValue Elt) {
3678   return ((isa<ConstantSDNode>(Elt) &&
3679            cast<ConstantSDNode>(Elt)->isNullValue()) ||
3680           (isa<ConstantFPSDNode>(Elt) &&
3681            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3682 }
3683
3684 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3685 /// their permute mask.
3686 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3687                                     SelectionDAG &DAG) {
3688   EVT VT = SVOp->getValueType(0);
3689   unsigned NumElems = VT.getVectorNumElements();
3690   SmallVector<int, 8> MaskVec;
3691
3692   for (unsigned i = 0; i != NumElems; ++i) {
3693     int idx = SVOp->getMaskElt(i);
3694     if (idx < 0)
3695       MaskVec.push_back(idx);
3696     else if (idx < (int)NumElems)
3697       MaskVec.push_back(idx + NumElems);
3698     else
3699       MaskVec.push_back(idx - NumElems);
3700   }
3701   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3702                               SVOp->getOperand(0), &MaskVec[0]);
3703 }
3704
3705 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3706 /// the two vector operands have swapped position.
3707 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3708   unsigned NumElems = VT.getVectorNumElements();
3709   for (unsigned i = 0; i != NumElems; ++i) {
3710     int idx = Mask[i];
3711     if (idx < 0)
3712       continue;
3713     else if (idx < (int)NumElems)
3714       Mask[i] = idx + NumElems;
3715     else
3716       Mask[i] = idx - NumElems;
3717   }
3718 }
3719
3720 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3721 /// match movhlps. The lower half elements should come from upper half of
3722 /// V1 (and in order), and the upper half elements should come from the upper
3723 /// half of V2 (and in order).
3724 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3725   if (Op->getValueType(0).getVectorNumElements() != 4)
3726     return false;
3727   for (unsigned i = 0, e = 2; i != e; ++i)
3728     if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3729       return false;
3730   for (unsigned i = 2; i != 4; ++i)
3731     if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3732       return false;
3733   return true;
3734 }
3735
3736 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3737 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3738 /// required.
3739 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3740   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3741     return false;
3742   N = N->getOperand(0).getNode();
3743   if (!ISD::isNON_EXTLoad(N))
3744     return false;
3745   if (LD)
3746     *LD = cast<LoadSDNode>(N);
3747   return true;
3748 }
3749
3750 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3751 /// match movlp{s|d}. The lower half elements should come from lower half of
3752 /// V1 (and in order), and the upper half elements should come from the upper
3753 /// half of V2 (and in order). And since V1 will become the source of the
3754 /// MOVLP, it must be either a vector load or a scalar load to vector.
3755 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3756                                ShuffleVectorSDNode *Op) {
3757   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3758     return false;
3759   // Is V2 is a vector load, don't do this transformation. We will try to use
3760   // load folding shufps op.
3761   if (ISD::isNON_EXTLoad(V2))
3762     return false;
3763
3764   unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3765
3766   if (NumElems != 2 && NumElems != 4)
3767     return false;
3768   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3769     if (!isUndefOrEqual(Op->getMaskElt(i), i))
3770       return false;
3771   for (unsigned i = NumElems/2; i != NumElems; ++i)
3772     if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3773       return false;
3774   return true;
3775 }
3776
3777 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3778 /// all the same.
3779 static bool isSplatVector(SDNode *N) {
3780   if (N->getOpcode() != ISD::BUILD_VECTOR)
3781     return false;
3782
3783   SDValue SplatValue = N->getOperand(0);
3784   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3785     if (N->getOperand(i) != SplatValue)
3786       return false;
3787   return true;
3788 }
3789
3790 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3791 /// to an zero vector.
3792 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3793 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3794   SDValue V1 = N->getOperand(0);
3795   SDValue V2 = N->getOperand(1);
3796   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3797   for (unsigned i = 0; i != NumElems; ++i) {
3798     int Idx = N->getMaskElt(i);
3799     if (Idx >= (int)NumElems) {
3800       unsigned Opc = V2.getOpcode();
3801       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3802         continue;
3803       if (Opc != ISD::BUILD_VECTOR ||
3804           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3805         return false;
3806     } else if (Idx >= 0) {
3807       unsigned Opc = V1.getOpcode();
3808       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3809         continue;
3810       if (Opc != ISD::BUILD_VECTOR ||
3811           !X86::isZeroNode(V1.getOperand(Idx)))
3812         return false;
3813     }
3814   }
3815   return true;
3816 }
3817
3818 /// getZeroVector - Returns a vector of specified type with all zero elements.
3819 ///
3820 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3821                              DebugLoc dl) {
3822   assert(VT.isVector() && "Expected a vector type");
3823
3824   // Always build SSE zero vectors as <4 x i32> bitcasted
3825   // to their dest type. This ensures they get CSE'd.
3826   SDValue Vec;
3827   if (VT.getSizeInBits() == 128) {  // SSE
3828     if (HasSSE2) {  // SSE2
3829       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3830       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3831     } else { // SSE1
3832       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3833       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3834     }
3835   } else if (VT.getSizeInBits() == 256) { // AVX
3836     // 256-bit logic and arithmetic instructions in AVX are
3837     // all floating-point, no support for integer ops. Default
3838     // to emitting fp zeroed vectors then.
3839     SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3840     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3841     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
3842   }
3843   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3844 }
3845
3846 /// getOnesVector - Returns a vector of specified type with all bits set.
3847 ///
3848 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3849   assert(VT.isVector() && "Expected a vector type");
3850
3851   // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3852   // type.  This ensures they get CSE'd.
3853   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3854   SDValue Vec;
3855   Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3856   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3857 }
3858
3859
3860 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3861 /// that point to V2 points to its first element.
3862 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3863   EVT VT = SVOp->getValueType(0);
3864   unsigned NumElems = VT.getVectorNumElements();
3865
3866   bool Changed = false;
3867   SmallVector<int, 8> MaskVec;
3868   SVOp->getMask(MaskVec);
3869
3870   for (unsigned i = 0; i != NumElems; ++i) {
3871     if (MaskVec[i] > (int)NumElems) {
3872       MaskVec[i] = NumElems;
3873       Changed = true;
3874     }
3875   }
3876   if (Changed)
3877     return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3878                                 SVOp->getOperand(1), &MaskVec[0]);
3879   return SDValue(SVOp, 0);
3880 }
3881
3882 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3883 /// operation of specified width.
3884 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3885                        SDValue V2) {
3886   unsigned NumElems = VT.getVectorNumElements();
3887   SmallVector<int, 8> Mask;
3888   Mask.push_back(NumElems);
3889   for (unsigned i = 1; i != NumElems; ++i)
3890     Mask.push_back(i);
3891   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3892 }
3893
3894 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3895 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3896                           SDValue V2) {
3897   unsigned NumElems = VT.getVectorNumElements();
3898   SmallVector<int, 8> Mask;
3899   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3900     Mask.push_back(i);
3901     Mask.push_back(i + NumElems);
3902   }
3903   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3904 }
3905
3906 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3907 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3908                           SDValue V2) {
3909   unsigned NumElems = VT.getVectorNumElements();
3910   unsigned Half = NumElems/2;
3911   SmallVector<int, 8> Mask;
3912   for (unsigned i = 0; i != Half; ++i) {
3913     Mask.push_back(i + Half);
3914     Mask.push_back(i + NumElems + Half);
3915   }
3916   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3917 }
3918
3919 /// PromoteSplat - Promote a splat of v4i32, v8i16 or v16i8 to v4f32.
3920 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
3921   EVT PVT = MVT::v4f32;
3922   EVT VT = SV->getValueType(0);
3923   DebugLoc dl = SV->getDebugLoc();
3924   SDValue V1 = SV->getOperand(0);
3925   int NumElems = VT.getVectorNumElements();
3926   int EltNo = SV->getSplatIndex();
3927
3928   // unpack elements to the correct location
3929   while (NumElems > 4) {
3930     if (EltNo < NumElems/2) {
3931       V1 = getUnpackl(DAG, dl, VT, V1, V1);
3932     } else {
3933       V1 = getUnpackh(DAG, dl, VT, V1, V1);
3934       EltNo -= NumElems/2;
3935     }
3936     NumElems >>= 1;
3937   }
3938
3939   // Perform the splat.
3940   int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3941   V1 = DAG.getNode(ISD::BITCAST, dl, PVT, V1);
3942   V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3943   return DAG.getNode(ISD::BITCAST, dl, VT, V1);
3944 }
3945
3946 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3947 /// vector of zero or undef vector.  This produces a shuffle where the low
3948 /// element of V2 is swizzled into the zero/undef vector, landing at element
3949 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
3950 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3951                                              bool isZero, bool HasSSE2,
3952                                              SelectionDAG &DAG) {
3953   EVT VT = V2.getValueType();
3954   SDValue V1 = isZero
3955     ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3956   unsigned NumElems = VT.getVectorNumElements();
3957   SmallVector<int, 16> MaskVec;
3958   for (unsigned i = 0; i != NumElems; ++i)
3959     // If this is the insertion idx, put the low elt of V2 here.
3960     MaskVec.push_back(i == Idx ? NumElems : i);
3961   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3962 }
3963
3964 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
3965 /// element of the result of the vector shuffle.
3966 static SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
3967                                    unsigned Depth) {
3968   if (Depth == 6)
3969     return SDValue();  // Limit search depth.
3970
3971   SDValue V = SDValue(N, 0);
3972   EVT VT = V.getValueType();
3973   unsigned Opcode = V.getOpcode();
3974
3975   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
3976   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
3977     Index = SV->getMaskElt(Index);
3978
3979     if (Index < 0)
3980       return DAG.getUNDEF(VT.getVectorElementType());
3981
3982     int NumElems = VT.getVectorNumElements();
3983     SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
3984     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
3985   }
3986
3987   // Recurse into target specific vector shuffles to find scalars.
3988   if (isTargetShuffle(Opcode)) {
3989     int NumElems = VT.getVectorNumElements();
3990     SmallVector<unsigned, 16> ShuffleMask;
3991     SDValue ImmN;
3992
3993     switch(Opcode) {
3994     case X86ISD::SHUFPS:
3995     case X86ISD::SHUFPD:
3996       ImmN = N->getOperand(N->getNumOperands()-1);
3997       DecodeSHUFPSMask(NumElems,
3998                        cast<ConstantSDNode>(ImmN)->getZExtValue(),
3999                        ShuffleMask);
4000       break;
4001     case X86ISD::PUNPCKHBW:
4002     case X86ISD::PUNPCKHWD:
4003     case X86ISD::PUNPCKHDQ:
4004     case X86ISD::PUNPCKHQDQ:
4005       DecodePUNPCKHMask(NumElems, ShuffleMask);
4006       break;
4007     case X86ISD::UNPCKHPS:
4008     case X86ISD::UNPCKHPD:
4009       DecodeUNPCKHPMask(NumElems, ShuffleMask);
4010       break;
4011     case X86ISD::PUNPCKLBW:
4012     case X86ISD::PUNPCKLWD:
4013     case X86ISD::PUNPCKLDQ:
4014     case X86ISD::PUNPCKLQDQ:
4015       DecodePUNPCKLMask(VT, ShuffleMask);
4016       break;
4017     case X86ISD::UNPCKLPS:
4018     case X86ISD::UNPCKLPD:
4019     case X86ISD::VUNPCKLPS:
4020     case X86ISD::VUNPCKLPD:
4021     case X86ISD::VUNPCKLPSY:
4022     case X86ISD::VUNPCKLPDY:
4023       DecodeUNPCKLPMask(VT, ShuffleMask);
4024       break;
4025     case X86ISD::MOVHLPS:
4026       DecodeMOVHLPSMask(NumElems, ShuffleMask);
4027       break;
4028     case X86ISD::MOVLHPS:
4029       DecodeMOVLHPSMask(NumElems, ShuffleMask);
4030       break;
4031     case X86ISD::PSHUFD:
4032       ImmN = N->getOperand(N->getNumOperands()-1);
4033       DecodePSHUFMask(NumElems,
4034                       cast<ConstantSDNode>(ImmN)->getZExtValue(),
4035                       ShuffleMask);
4036       break;
4037     case X86ISD::PSHUFHW:
4038       ImmN = N->getOperand(N->getNumOperands()-1);
4039       DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4040                         ShuffleMask);
4041       break;
4042     case X86ISD::PSHUFLW:
4043       ImmN = N->getOperand(N->getNumOperands()-1);
4044       DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4045                         ShuffleMask);
4046       break;
4047     case X86ISD::MOVSS:
4048     case X86ISD::MOVSD: {
4049       // The index 0 always comes from the first element of the second source,
4050       // this is why MOVSS and MOVSD are used in the first place. The other
4051       // elements come from the other positions of the first source vector.
4052       unsigned OpNum = (Index == 0) ? 1 : 0;
4053       return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
4054                                  Depth+1);
4055     }
4056     default:
4057       assert("not implemented for target shuffle node");
4058       return SDValue();
4059     }
4060
4061     Index = ShuffleMask[Index];
4062     if (Index < 0)
4063       return DAG.getUNDEF(VT.getVectorElementType());
4064
4065     SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
4066     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
4067                                Depth+1);
4068   }
4069
4070   // Actual nodes that may contain scalar elements
4071   if (Opcode == ISD::BITCAST) {
4072     V = V.getOperand(0);
4073     EVT SrcVT = V.getValueType();
4074     unsigned NumElems = VT.getVectorNumElements();
4075
4076     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4077       return SDValue();
4078   }
4079
4080   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4081     return (Index == 0) ? V.getOperand(0)
4082                           : DAG.getUNDEF(VT.getVectorElementType());
4083
4084   if (V.getOpcode() == ISD::BUILD_VECTOR)
4085     return V.getOperand(Index);
4086
4087   return SDValue();
4088 }
4089
4090 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4091 /// shuffle operation which come from a consecutively from a zero. The
4092 /// search can start in two different directions, from left or right.
4093 static
4094 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
4095                                   bool ZerosFromLeft, SelectionDAG &DAG) {
4096   int i = 0;
4097
4098   while (i < NumElems) {
4099     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4100     SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
4101     if (!(Elt.getNode() &&
4102          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4103       break;
4104     ++i;
4105   }
4106
4107   return i;
4108 }
4109
4110 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
4111 /// MaskE correspond consecutively to elements from one of the vector operands,
4112 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4113 static
4114 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
4115                               int OpIdx, int NumElems, unsigned &OpNum) {
4116   bool SeenV1 = false;
4117   bool SeenV2 = false;
4118
4119   for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
4120     int Idx = SVOp->getMaskElt(i);
4121     // Ignore undef indicies
4122     if (Idx < 0)
4123       continue;
4124
4125     if (Idx < NumElems)
4126       SeenV1 = true;
4127     else
4128       SeenV2 = true;
4129
4130     // Only accept consecutive elements from the same vector
4131     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4132       return false;
4133   }
4134
4135   OpNum = SeenV1 ? 0 : 1;
4136   return true;
4137 }
4138
4139 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4140 /// logical left shift of a vector.
4141 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4142                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4143   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4144   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4145               false /* check zeros from right */, DAG);
4146   unsigned OpSrc;
4147
4148   if (!NumZeros)
4149     return false;
4150
4151   // Considering the elements in the mask that are not consecutive zeros,
4152   // check if they consecutively come from only one of the source vectors.
4153   //
4154   //               V1 = {X, A, B, C}     0
4155   //                         \  \  \    /
4156   //   vector_shuffle V1, V2 <1, 2, 3, X>
4157   //
4158   if (!isShuffleMaskConsecutive(SVOp,
4159             0,                   // Mask Start Index
4160             NumElems-NumZeros-1, // Mask End Index
4161             NumZeros,            // Where to start looking in the src vector
4162             NumElems,            // Number of elements in vector
4163             OpSrc))              // Which source operand ?
4164     return false;
4165
4166   isLeft = false;
4167   ShAmt = NumZeros;
4168   ShVal = SVOp->getOperand(OpSrc);
4169   return true;
4170 }
4171
4172 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4173 /// logical left shift of a vector.
4174 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4175                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4176   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4177   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4178               true /* check zeros from left */, DAG);
4179   unsigned OpSrc;
4180
4181   if (!NumZeros)
4182     return false;
4183
4184   // Considering the elements in the mask that are not consecutive zeros,
4185   // check if they consecutively come from only one of the source vectors.
4186   //
4187   //                           0    { A, B, X, X } = V2
4188   //                          / \    /  /
4189   //   vector_shuffle V1, V2 <X, X, 4, 5>
4190   //
4191   if (!isShuffleMaskConsecutive(SVOp,
4192             NumZeros,     // Mask Start Index
4193             NumElems-1,   // Mask End Index
4194             0,            // Where to start looking in the src vector
4195             NumElems,     // Number of elements in vector
4196             OpSrc))       // Which source operand ?
4197     return false;
4198
4199   isLeft = true;
4200   ShAmt = NumZeros;
4201   ShVal = SVOp->getOperand(OpSrc);
4202   return true;
4203 }
4204
4205 /// isVectorShift - Returns true if the shuffle can be implemented as a
4206 /// logical left or right shift of a vector.
4207 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4208                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4209   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4210       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4211     return true;
4212
4213   return false;
4214 }
4215
4216 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4217 ///
4218 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4219                                        unsigned NumNonZero, unsigned NumZero,
4220                                        SelectionDAG &DAG,
4221                                        const TargetLowering &TLI) {
4222   if (NumNonZero > 8)
4223     return SDValue();
4224
4225   DebugLoc dl = Op.getDebugLoc();
4226   SDValue V(0, 0);
4227   bool First = true;
4228   for (unsigned i = 0; i < 16; ++i) {
4229     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4230     if (ThisIsNonZero && First) {
4231       if (NumZero)
4232         V = getZeroVector(MVT::v8i16, true, DAG, dl);
4233       else
4234         V = DAG.getUNDEF(MVT::v8i16);
4235       First = false;
4236     }
4237
4238     if ((i & 1) != 0) {
4239       SDValue ThisElt(0, 0), LastElt(0, 0);
4240       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4241       if (LastIsNonZero) {
4242         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4243                               MVT::i16, Op.getOperand(i-1));
4244       }
4245       if (ThisIsNonZero) {
4246         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4247         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4248                               ThisElt, DAG.getConstant(8, MVT::i8));
4249         if (LastIsNonZero)
4250           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4251       } else
4252         ThisElt = LastElt;
4253
4254       if (ThisElt.getNode())
4255         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4256                         DAG.getIntPtrConstant(i/2));
4257     }
4258   }
4259
4260   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4261 }
4262
4263 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4264 ///
4265 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4266                                      unsigned NumNonZero, unsigned NumZero,
4267                                      SelectionDAG &DAG,
4268                                      const TargetLowering &TLI) {
4269   if (NumNonZero > 4)
4270     return SDValue();
4271
4272   DebugLoc dl = Op.getDebugLoc();
4273   SDValue V(0, 0);
4274   bool First = true;
4275   for (unsigned i = 0; i < 8; ++i) {
4276     bool isNonZero = (NonZeros & (1 << i)) != 0;
4277     if (isNonZero) {
4278       if (First) {
4279         if (NumZero)
4280           V = getZeroVector(MVT::v8i16, true, DAG, dl);
4281         else
4282           V = DAG.getUNDEF(MVT::v8i16);
4283         First = false;
4284       }
4285       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4286                       MVT::v8i16, V, Op.getOperand(i),
4287                       DAG.getIntPtrConstant(i));
4288     }
4289   }
4290
4291   return V;
4292 }
4293
4294 /// getVShift - Return a vector logical shift node.
4295 ///
4296 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4297                          unsigned NumBits, SelectionDAG &DAG,
4298                          const TargetLowering &TLI, DebugLoc dl) {
4299   EVT ShVT = MVT::v2i64;
4300   unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
4301   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4302   return DAG.getNode(ISD::BITCAST, dl, VT,
4303                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4304                              DAG.getConstant(NumBits,
4305                                   TLI.getShiftAmountTy(SrcOp.getValueType()))));
4306 }
4307
4308 SDValue
4309 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4310                                           SelectionDAG &DAG) const {
4311
4312   // Check if the scalar load can be widened into a vector load. And if
4313   // the address is "base + cst" see if the cst can be "absorbed" into
4314   // the shuffle mask.
4315   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4316     SDValue Ptr = LD->getBasePtr();
4317     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4318       return SDValue();
4319     EVT PVT = LD->getValueType(0);
4320     if (PVT != MVT::i32 && PVT != MVT::f32)
4321       return SDValue();
4322
4323     int FI = -1;
4324     int64_t Offset = 0;
4325     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4326       FI = FINode->getIndex();
4327       Offset = 0;
4328     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4329                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4330       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4331       Offset = Ptr.getConstantOperandVal(1);
4332       Ptr = Ptr.getOperand(0);
4333     } else {
4334       return SDValue();
4335     }
4336
4337     SDValue Chain = LD->getChain();
4338     // Make sure the stack object alignment is at least 16.
4339     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4340     if (DAG.InferPtrAlignment(Ptr) < 16) {
4341       if (MFI->isFixedObjectIndex(FI)) {
4342         // Can't change the alignment. FIXME: It's possible to compute
4343         // the exact stack offset and reference FI + adjust offset instead.
4344         // If someone *really* cares about this. That's the way to implement it.
4345         return SDValue();
4346       } else {
4347         MFI->setObjectAlignment(FI, 16);
4348       }
4349     }
4350
4351     // (Offset % 16) must be multiple of 4. Then address is then
4352     // Ptr + (Offset & ~15).
4353     if (Offset < 0)
4354       return SDValue();
4355     if ((Offset % 16) & 3)
4356       return SDValue();
4357     int64_t StartOffset = Offset & ~15;
4358     if (StartOffset)
4359       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4360                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4361
4362     int EltNo = (Offset - StartOffset) >> 2;
4363     int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
4364     EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
4365     SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,
4366                              LD->getPointerInfo().getWithOffset(StartOffset),
4367                              false, false, 0);
4368     // Canonicalize it to a v4i32 shuffle.
4369     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
4370     return DAG.getNode(ISD::BITCAST, dl, VT,
4371                        DAG.getVectorShuffle(MVT::v4i32, dl, V1,
4372                                             DAG.getUNDEF(MVT::v4i32),&Mask[0]));
4373   }
4374
4375   return SDValue();
4376 }
4377
4378 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4379 /// vector of type 'VT', see if the elements can be replaced by a single large
4380 /// load which has the same value as a build_vector whose operands are 'elts'.
4381 ///
4382 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4383 ///
4384 /// FIXME: we'd also like to handle the case where the last elements are zero
4385 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4386 /// There's even a handy isZeroNode for that purpose.
4387 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4388                                         DebugLoc &DL, SelectionDAG &DAG) {
4389   EVT EltVT = VT.getVectorElementType();
4390   unsigned NumElems = Elts.size();
4391
4392   LoadSDNode *LDBase = NULL;
4393   unsigned LastLoadedElt = -1U;
4394
4395   // For each element in the initializer, see if we've found a load or an undef.
4396   // If we don't find an initial load element, or later load elements are
4397   // non-consecutive, bail out.
4398   for (unsigned i = 0; i < NumElems; ++i) {
4399     SDValue Elt = Elts[i];
4400
4401     if (!Elt.getNode() ||
4402         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4403       return SDValue();
4404     if (!LDBase) {
4405       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4406         return SDValue();
4407       LDBase = cast<LoadSDNode>(Elt.getNode());
4408       LastLoadedElt = i;
4409       continue;
4410     }
4411     if (Elt.getOpcode() == ISD::UNDEF)
4412       continue;
4413
4414     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4415     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4416       return SDValue();
4417     LastLoadedElt = i;
4418   }
4419
4420   // If we have found an entire vector of loads and undefs, then return a large
4421   // load of the entire vector width starting at the base pointer.  If we found
4422   // consecutive loads for the low half, generate a vzext_load node.
4423   if (LastLoadedElt == NumElems - 1) {
4424     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4425       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4426                          LDBase->getPointerInfo(),
4427                          LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
4428     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4429                        LDBase->getPointerInfo(),
4430                        LDBase->isVolatile(), LDBase->isNonTemporal(),
4431                        LDBase->getAlignment());
4432   } else if (NumElems == 4 && LastLoadedElt == 1) {
4433     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4434     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4435     SDValue ResNode = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys,
4436                                               Ops, 2, MVT::i32,
4437                                               LDBase->getMemOperand());
4438     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4439   }
4440   return SDValue();
4441 }
4442
4443 SDValue
4444 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
4445   DebugLoc dl = Op.getDebugLoc();
4446
4447   EVT VT = Op.getValueType();
4448   EVT ExtVT = VT.getVectorElementType();
4449
4450   unsigned NumElems = Op.getNumOperands();
4451
4452   // For AVX-length vectors, build the individual 128-bit pieces and
4453   // use shuffles to put them in place.
4454   if (VT.getSizeInBits() > 256 &&
4455       Subtarget->hasAVX() &&
4456       !ISD::isBuildVectorAllZeros(Op.getNode())) {
4457     SmallVector<SDValue, 8> V;
4458     V.resize(NumElems);
4459     for (unsigned i = 0; i < NumElems; ++i) {
4460       V[i] = Op.getOperand(i);
4461     }
4462
4463     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
4464
4465     // Build the lower subvector.
4466     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
4467     // Build the upper subvector.
4468     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
4469                                 NumElems/2);
4470
4471     return ConcatVectors(Lower, Upper, DAG);
4472   }
4473
4474   // All zero's are handled with pxor in SSE2 and above, xorps in SSE1.
4475   // All one's are handled with pcmpeqd. In AVX, zero's are handled with
4476   // vpxor in 128-bit and xor{pd,ps} in 256-bit, but no 256 version of pcmpeqd
4477   // is present, so AllOnes is ignored.
4478   if (ISD::isBuildVectorAllZeros(Op.getNode()) ||
4479       (Op.getValueType().getSizeInBits() != 256 &&
4480        ISD::isBuildVectorAllOnes(Op.getNode()))) {
4481     // Canonicalize this to <4 x i32> (SSE) to
4482     // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
4483     // eliminated on x86-32 hosts.
4484     if (Op.getValueType() == MVT::v4i32)
4485       return Op;
4486
4487     if (ISD::isBuildVectorAllOnes(Op.getNode()))
4488       return getOnesVector(Op.getValueType(), DAG, dl);
4489     return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
4490   }
4491
4492   unsigned EVTBits = ExtVT.getSizeInBits();
4493
4494   unsigned NumZero  = 0;
4495   unsigned NumNonZero = 0;
4496   unsigned NonZeros = 0;
4497   bool IsAllConstants = true;
4498   SmallSet<SDValue, 8> Values;
4499   for (unsigned i = 0; i < NumElems; ++i) {
4500     SDValue Elt = Op.getOperand(i);
4501     if (Elt.getOpcode() == ISD::UNDEF)
4502       continue;
4503     Values.insert(Elt);
4504     if (Elt.getOpcode() != ISD::Constant &&
4505         Elt.getOpcode() != ISD::ConstantFP)
4506       IsAllConstants = false;
4507     if (X86::isZeroNode(Elt))
4508       NumZero++;
4509     else {
4510       NonZeros |= (1 << i);
4511       NumNonZero++;
4512     }
4513   }
4514
4515   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
4516   if (NumNonZero == 0)
4517     return DAG.getUNDEF(VT);
4518
4519   // Special case for single non-zero, non-undef, element.
4520   if (NumNonZero == 1) {
4521     unsigned Idx = CountTrailingZeros_32(NonZeros);
4522     SDValue Item = Op.getOperand(Idx);
4523
4524     // If this is an insertion of an i64 value on x86-32, and if the top bits of
4525     // the value are obviously zero, truncate the value to i32 and do the
4526     // insertion that way.  Only do this if the value is non-constant or if the
4527     // value is a constant being inserted into element 0.  It is cheaper to do
4528     // a constant pool load than it is to do a movd + shuffle.
4529     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
4530         (!IsAllConstants || Idx == 0)) {
4531       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
4532         // Handle SSE only.
4533         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
4534         EVT VecVT = MVT::v4i32;
4535         unsigned VecElts = 4;
4536
4537         // Truncate the value (which may itself be a constant) to i32, and
4538         // convert it to a vector with movd (S2V+shuffle to zero extend).
4539         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
4540         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
4541         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4542                                            Subtarget->hasSSE2(), DAG);
4543
4544         // Now we have our 32-bit value zero extended in the low element of
4545         // a vector.  If Idx != 0, swizzle it into place.
4546         if (Idx != 0) {
4547           SmallVector<int, 4> Mask;
4548           Mask.push_back(Idx);
4549           for (unsigned i = 1; i != VecElts; ++i)
4550             Mask.push_back(i);
4551           Item = DAG.getVectorShuffle(VecVT, dl, Item,
4552                                       DAG.getUNDEF(Item.getValueType()),
4553                                       &Mask[0]);
4554         }
4555         return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
4556       }
4557     }
4558
4559     // If we have a constant or non-constant insertion into the low element of
4560     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
4561     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
4562     // depending on what the source datatype is.
4563     if (Idx == 0) {
4564       if (NumZero == 0) {
4565         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4566       } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
4567           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
4568         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4569         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
4570         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
4571                                            DAG);
4572       } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
4573         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
4574         assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
4575         EVT MiddleVT = MVT::v4i32;
4576         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
4577         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4578                                            Subtarget->hasSSE2(), DAG);
4579         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
4580       }
4581     }
4582
4583     // Is it a vector logical left shift?
4584     if (NumElems == 2 && Idx == 1 &&
4585         X86::isZeroNode(Op.getOperand(0)) &&
4586         !X86::isZeroNode(Op.getOperand(1))) {
4587       unsigned NumBits = VT.getSizeInBits();
4588       return getVShift(true, VT,
4589                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4590                                    VT, Op.getOperand(1)),
4591                        NumBits/2, DAG, *this, dl);
4592     }
4593
4594     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
4595       return SDValue();
4596
4597     // Otherwise, if this is a vector with i32 or f32 elements, and the element
4598     // is a non-constant being inserted into an element other than the low one,
4599     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
4600     // movd/movss) to move this into the low element, then shuffle it into
4601     // place.
4602     if (EVTBits == 32) {
4603       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4604
4605       // Turn it into a shuffle of zero and zero-extended scalar to vector.
4606       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
4607                                          Subtarget->hasSSE2(), DAG);
4608       SmallVector<int, 8> MaskVec;
4609       for (unsigned i = 0; i < NumElems; i++)
4610         MaskVec.push_back(i == Idx ? 0 : 1);
4611       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
4612     }
4613   }
4614
4615   // Splat is obviously ok. Let legalizer expand it to a shuffle.
4616   if (Values.size() == 1) {
4617     if (EVTBits == 32) {
4618       // Instead of a shuffle like this:
4619       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
4620       // Check if it's possible to issue this instead.
4621       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
4622       unsigned Idx = CountTrailingZeros_32(NonZeros);
4623       SDValue Item = Op.getOperand(Idx);
4624       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
4625         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
4626     }
4627     return SDValue();
4628   }
4629
4630   // A vector full of immediates; various special cases are already
4631   // handled, so this is best done with a single constant-pool load.
4632   if (IsAllConstants)
4633     return SDValue();
4634
4635   // Let legalizer expand 2-wide build_vectors.
4636   if (EVTBits == 64) {
4637     if (NumNonZero == 1) {
4638       // One half is zero or undef.
4639       unsigned Idx = CountTrailingZeros_32(NonZeros);
4640       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
4641                                  Op.getOperand(Idx));
4642       return getShuffleVectorZeroOrUndef(V2, Idx, true,
4643                                          Subtarget->hasSSE2(), DAG);
4644     }
4645     return SDValue();
4646   }
4647
4648   // If element VT is < 32 bits, convert it to inserts into a zero vector.
4649   if (EVTBits == 8 && NumElems == 16) {
4650     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
4651                                         *this);
4652     if (V.getNode()) return V;
4653   }
4654
4655   if (EVTBits == 16 && NumElems == 8) {
4656     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
4657                                       *this);
4658     if (V.getNode()) return V;
4659   }
4660
4661   // If element VT is == 32 bits, turn it into a number of shuffles.
4662   SmallVector<SDValue, 8> V;
4663   V.resize(NumElems);
4664   if (NumElems == 4 && NumZero > 0) {
4665     for (unsigned i = 0; i < 4; ++i) {
4666       bool isZero = !(NonZeros & (1 << i));
4667       if (isZero)
4668         V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4669       else
4670         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4671     }
4672
4673     for (unsigned i = 0; i < 2; ++i) {
4674       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
4675         default: break;
4676         case 0:
4677           V[i] = V[i*2];  // Must be a zero vector.
4678           break;
4679         case 1:
4680           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
4681           break;
4682         case 2:
4683           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
4684           break;
4685         case 3:
4686           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
4687           break;
4688       }
4689     }
4690
4691     SmallVector<int, 8> MaskVec;
4692     bool Reverse = (NonZeros & 0x3) == 2;
4693     for (unsigned i = 0; i < 2; ++i)
4694       MaskVec.push_back(Reverse ? 1-i : i);
4695     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
4696     for (unsigned i = 0; i < 2; ++i)
4697       MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
4698     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
4699   }
4700
4701   if (Values.size() > 1 && VT.getSizeInBits() == 128) {
4702     // Check for a build vector of consecutive loads.
4703     for (unsigned i = 0; i < NumElems; ++i)
4704       V[i] = Op.getOperand(i);
4705
4706     // Check for elements which are consecutive loads.
4707     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
4708     if (LD.getNode())
4709       return LD;
4710
4711     // For SSE 4.1, use insertps to put the high elements into the low element.
4712     if (getSubtarget()->hasSSE41()) {
4713       SDValue Result;
4714       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
4715         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
4716       else
4717         Result = DAG.getUNDEF(VT);
4718
4719       for (unsigned i = 1; i < NumElems; ++i) {
4720         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
4721         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
4722                              Op.getOperand(i), DAG.getIntPtrConstant(i));
4723       }
4724       return Result;
4725     }
4726
4727     // Otherwise, expand into a number of unpckl*, start by extending each of
4728     // our (non-undef) elements to the full vector width with the element in the
4729     // bottom slot of the vector (which generates no code for SSE).
4730     for (unsigned i = 0; i < NumElems; ++i) {
4731       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
4732         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4733       else
4734         V[i] = DAG.getUNDEF(VT);
4735     }
4736
4737     // Next, we iteratively mix elements, e.g. for v4f32:
4738     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
4739     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
4740     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
4741     unsigned EltStride = NumElems >> 1;
4742     while (EltStride != 0) {
4743       for (unsigned i = 0; i < EltStride; ++i) {
4744         // If V[i+EltStride] is undef and this is the first round of mixing,
4745         // then it is safe to just drop this shuffle: V[i] is already in the
4746         // right place, the one element (since it's the first round) being
4747         // inserted as undef can be dropped.  This isn't safe for successive
4748         // rounds because they will permute elements within both vectors.
4749         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
4750             EltStride == NumElems/2)
4751           continue;
4752
4753         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
4754       }
4755       EltStride >>= 1;
4756     }
4757     return V[0];
4758   }
4759   return SDValue();
4760 }
4761
4762 SDValue
4763 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
4764   // We support concatenate two MMX registers and place them in a MMX
4765   // register.  This is better than doing a stack convert.
4766   DebugLoc dl = Op.getDebugLoc();
4767   EVT ResVT = Op.getValueType();
4768   assert(Op.getNumOperands() == 2);
4769   assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
4770          ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
4771   int Mask[2];
4772   SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
4773   SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4774   InVec = Op.getOperand(1);
4775   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4776     unsigned NumElts = ResVT.getVectorNumElements();
4777     VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4778     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
4779                        InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
4780   } else {
4781     InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
4782     SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4783     Mask[0] = 0; Mask[1] = 2;
4784     VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
4785   }
4786   return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4787 }
4788
4789 // v8i16 shuffles - Prefer shuffles in the following order:
4790 // 1. [all]   pshuflw, pshufhw, optional move
4791 // 2. [ssse3] 1 x pshufb
4792 // 3. [ssse3] 2 x pshufb + 1 x por
4793 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
4794 SDValue
4795 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
4796                                             SelectionDAG &DAG) const {
4797   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4798   SDValue V1 = SVOp->getOperand(0);
4799   SDValue V2 = SVOp->getOperand(1);
4800   DebugLoc dl = SVOp->getDebugLoc();
4801   SmallVector<int, 8> MaskVals;
4802
4803   // Determine if more than 1 of the words in each of the low and high quadwords
4804   // of the result come from the same quadword of one of the two inputs.  Undef
4805   // mask values count as coming from any quadword, for better codegen.
4806   SmallVector<unsigned, 4> LoQuad(4);
4807   SmallVector<unsigned, 4> HiQuad(4);
4808   BitVector InputQuads(4);
4809   for (unsigned i = 0; i < 8; ++i) {
4810     SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
4811     int EltIdx = SVOp->getMaskElt(i);
4812     MaskVals.push_back(EltIdx);
4813     if (EltIdx < 0) {
4814       ++Quad[0];
4815       ++Quad[1];
4816       ++Quad[2];
4817       ++Quad[3];
4818       continue;
4819     }
4820     ++Quad[EltIdx / 4];
4821     InputQuads.set(EltIdx / 4);
4822   }
4823
4824   int BestLoQuad = -1;
4825   unsigned MaxQuad = 1;
4826   for (unsigned i = 0; i < 4; ++i) {
4827     if (LoQuad[i] > MaxQuad) {
4828       BestLoQuad = i;
4829       MaxQuad = LoQuad[i];
4830     }
4831   }
4832
4833   int BestHiQuad = -1;
4834   MaxQuad = 1;
4835   for (unsigned i = 0; i < 4; ++i) {
4836     if (HiQuad[i] > MaxQuad) {
4837       BestHiQuad = i;
4838       MaxQuad = HiQuad[i];
4839     }
4840   }
4841
4842   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
4843   // of the two input vectors, shuffle them into one input vector so only a
4844   // single pshufb instruction is necessary. If There are more than 2 input
4845   // quads, disable the next transformation since it does not help SSSE3.
4846   bool V1Used = InputQuads[0] || InputQuads[1];
4847   bool V2Used = InputQuads[2] || InputQuads[3];
4848   if (Subtarget->hasSSSE3()) {
4849     if (InputQuads.count() == 2 && V1Used && V2Used) {
4850       BestLoQuad = InputQuads.find_first();
4851       BestHiQuad = InputQuads.find_next(BestLoQuad);
4852     }
4853     if (InputQuads.count() > 2) {
4854       BestLoQuad = -1;
4855       BestHiQuad = -1;
4856     }
4857   }
4858
4859   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
4860   // the shuffle mask.  If a quad is scored as -1, that means that it contains
4861   // words from all 4 input quadwords.
4862   SDValue NewV;
4863   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
4864     SmallVector<int, 8> MaskV;
4865     MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
4866     MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
4867     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
4868                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
4869                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
4870     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
4871
4872     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
4873     // source words for the shuffle, to aid later transformations.
4874     bool AllWordsInNewV = true;
4875     bool InOrder[2] = { true, true };
4876     for (unsigned i = 0; i != 8; ++i) {
4877       int idx = MaskVals[i];
4878       if (idx != (int)i)
4879         InOrder[i/4] = false;
4880       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
4881         continue;
4882       AllWordsInNewV = false;
4883       break;
4884     }
4885
4886     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
4887     if (AllWordsInNewV) {
4888       for (int i = 0; i != 8; ++i) {
4889         int idx = MaskVals[i];
4890         if (idx < 0)
4891           continue;
4892         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
4893         if ((idx != i) && idx < 4)
4894           pshufhw = false;
4895         if ((idx != i) && idx > 3)
4896           pshuflw = false;
4897       }
4898       V1 = NewV;
4899       V2Used = false;
4900       BestLoQuad = 0;
4901       BestHiQuad = 1;
4902     }
4903
4904     // If we've eliminated the use of V2, and the new mask is a pshuflw or
4905     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
4906     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
4907       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
4908       unsigned TargetMask = 0;
4909       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
4910                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
4911       TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
4912                              X86::getShufflePSHUFLWImmediate(NewV.getNode());
4913       V1 = NewV.getOperand(0);
4914       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
4915     }
4916   }
4917
4918   // If we have SSSE3, and all words of the result are from 1 input vector,
4919   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
4920   // is present, fall back to case 4.
4921   if (Subtarget->hasSSSE3()) {
4922     SmallVector<SDValue,16> pshufbMask;
4923
4924     // If we have elements from both input vectors, set the high bit of the
4925     // shuffle mask element to zero out elements that come from V2 in the V1
4926     // mask, and elements that come from V1 in the V2 mask, so that the two
4927     // results can be OR'd together.
4928     bool TwoInputs = V1Used && V2Used;
4929     for (unsigned i = 0; i != 8; ++i) {
4930       int EltIdx = MaskVals[i] * 2;
4931       if (TwoInputs && (EltIdx >= 16)) {
4932         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4933         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4934         continue;
4935       }
4936       pshufbMask.push_back(DAG.getConstant(EltIdx,   MVT::i8));
4937       pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
4938     }
4939     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
4940     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4941                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4942                                  MVT::v16i8, &pshufbMask[0], 16));
4943     if (!TwoInputs)
4944       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4945
4946     // Calculate the shuffle mask for the second input, shuffle it, and
4947     // OR it with the first shuffled input.
4948     pshufbMask.clear();
4949     for (unsigned i = 0; i != 8; ++i) {
4950       int EltIdx = MaskVals[i] * 2;
4951       if (EltIdx < 16) {
4952         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4953         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4954         continue;
4955       }
4956       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4957       pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
4958     }
4959     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
4960     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4961                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4962                                  MVT::v16i8, &pshufbMask[0], 16));
4963     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4964     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4965   }
4966
4967   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
4968   // and update MaskVals with new element order.
4969   BitVector InOrder(8);
4970   if (BestLoQuad >= 0) {
4971     SmallVector<int, 8> MaskV;
4972     for (int i = 0; i != 4; ++i) {
4973       int idx = MaskVals[i];
4974       if (idx < 0) {
4975         MaskV.push_back(-1);
4976         InOrder.set(i);
4977       } else if ((idx / 4) == BestLoQuad) {
4978         MaskV.push_back(idx & 3);
4979         InOrder.set(i);
4980       } else {
4981         MaskV.push_back(-1);
4982       }
4983     }
4984     for (unsigned i = 4; i != 8; ++i)
4985       MaskV.push_back(i);
4986     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4987                                 &MaskV[0]);
4988
4989     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4990       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
4991                                NewV.getOperand(0),
4992                                X86::getShufflePSHUFLWImmediate(NewV.getNode()),
4993                                DAG);
4994   }
4995
4996   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
4997   // and update MaskVals with the new element order.
4998   if (BestHiQuad >= 0) {
4999     SmallVector<int, 8> MaskV;
5000     for (unsigned i = 0; i != 4; ++i)
5001       MaskV.push_back(i);
5002     for (unsigned i = 4; i != 8; ++i) {
5003       int idx = MaskVals[i];
5004       if (idx < 0) {
5005         MaskV.push_back(-1);
5006         InOrder.set(i);
5007       } else if ((idx / 4) == BestHiQuad) {
5008         MaskV.push_back((idx & 3) + 4);
5009         InOrder.set(i);
5010       } else {
5011         MaskV.push_back(-1);
5012       }
5013     }
5014     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5015                                 &MaskV[0]);
5016
5017     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
5018       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5019                               NewV.getOperand(0),
5020                               X86::getShufflePSHUFHWImmediate(NewV.getNode()),
5021                               DAG);
5022   }
5023
5024   // In case BestHi & BestLo were both -1, which means each quadword has a word
5025   // from each of the four input quadwords, calculate the InOrder bitvector now
5026   // before falling through to the insert/extract cleanup.
5027   if (BestLoQuad == -1 && BestHiQuad == -1) {
5028     NewV = V1;
5029     for (int i = 0; i != 8; ++i)
5030       if (MaskVals[i] < 0 || MaskVals[i] == i)
5031         InOrder.set(i);
5032   }
5033
5034   // The other elements are put in the right place using pextrw and pinsrw.
5035   for (unsigned i = 0; i != 8; ++i) {
5036     if (InOrder[i])
5037       continue;
5038     int EltIdx = MaskVals[i];
5039     if (EltIdx < 0)
5040       continue;
5041     SDValue ExtOp = (EltIdx < 8)
5042     ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5043                   DAG.getIntPtrConstant(EltIdx))
5044     : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5045                   DAG.getIntPtrConstant(EltIdx - 8));
5046     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5047                        DAG.getIntPtrConstant(i));
5048   }
5049   return NewV;
5050 }
5051
5052 // v16i8 shuffles - Prefer shuffles in the following order:
5053 // 1. [ssse3] 1 x pshufb
5054 // 2. [ssse3] 2 x pshufb + 1 x por
5055 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
5056 static
5057 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5058                                  SelectionDAG &DAG,
5059                                  const X86TargetLowering &TLI) {
5060   SDValue V1 = SVOp->getOperand(0);
5061   SDValue V2 = SVOp->getOperand(1);
5062   DebugLoc dl = SVOp->getDebugLoc();
5063   SmallVector<int, 16> MaskVals;
5064   SVOp->getMask(MaskVals);
5065
5066   // If we have SSSE3, case 1 is generated when all result bytes come from
5067   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
5068   // present, fall back to case 3.
5069   // FIXME: kill V2Only once shuffles are canonizalized by getNode.
5070   bool V1Only = true;
5071   bool V2Only = true;
5072   for (unsigned i = 0; i < 16; ++i) {
5073     int EltIdx = MaskVals[i];
5074     if (EltIdx < 0)
5075       continue;
5076     if (EltIdx < 16)
5077       V2Only = false;
5078     else
5079       V1Only = false;
5080   }
5081
5082   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5083   if (TLI.getSubtarget()->hasSSSE3()) {
5084     SmallVector<SDValue,16> pshufbMask;
5085
5086     // If all result elements are from one input vector, then only translate
5087     // undef mask values to 0x80 (zero out result) in the pshufb mask.
5088     //
5089     // Otherwise, we have elements from both input vectors, and must zero out
5090     // elements that come from V2 in the first mask, and V1 in the second mask
5091     // so that we can OR them together.
5092     bool TwoInputs = !(V1Only || V2Only);
5093     for (unsigned i = 0; i != 16; ++i) {
5094       int EltIdx = MaskVals[i];
5095       if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
5096         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5097         continue;
5098       }
5099       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5100     }
5101     // If all the elements are from V2, assign it to V1 and return after
5102     // building the first pshufb.
5103     if (V2Only)
5104       V1 = V2;
5105     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5106                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5107                                  MVT::v16i8, &pshufbMask[0], 16));
5108     if (!TwoInputs)
5109       return V1;
5110
5111     // Calculate the shuffle mask for the second input, shuffle it, and
5112     // OR it with the first shuffled input.
5113     pshufbMask.clear();
5114     for (unsigned i = 0; i != 16; ++i) {
5115       int EltIdx = MaskVals[i];
5116       if (EltIdx < 16) {
5117         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5118         continue;
5119       }
5120       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5121     }
5122     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5123                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5124                                  MVT::v16i8, &pshufbMask[0], 16));
5125     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5126   }
5127
5128   // No SSSE3 - Calculate in place words and then fix all out of place words
5129   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
5130   // the 16 different words that comprise the two doublequadword input vectors.
5131   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5132   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5133   SDValue NewV = V2Only ? V2 : V1;
5134   for (int i = 0; i != 8; ++i) {
5135     int Elt0 = MaskVals[i*2];
5136     int Elt1 = MaskVals[i*2+1];
5137
5138     // This word of the result is all undef, skip it.
5139     if (Elt0 < 0 && Elt1 < 0)
5140       continue;
5141
5142     // This word of the result is already in the correct place, skip it.
5143     if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
5144       continue;
5145     if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
5146       continue;
5147
5148     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5149     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5150     SDValue InsElt;
5151
5152     // If Elt0 and Elt1 are defined, are consecutive, and can be load
5153     // using a single extract together, load it and store it.
5154     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5155       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5156                            DAG.getIntPtrConstant(Elt1 / 2));
5157       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5158                         DAG.getIntPtrConstant(i));
5159       continue;
5160     }
5161
5162     // If Elt1 is defined, extract it from the appropriate source.  If the
5163     // source byte is not also odd, shift the extracted word left 8 bits
5164     // otherwise clear the bottom 8 bits if we need to do an or.
5165     if (Elt1 >= 0) {
5166       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5167                            DAG.getIntPtrConstant(Elt1 / 2));
5168       if ((Elt1 & 1) == 0)
5169         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5170                              DAG.getConstant(8,
5171                                   TLI.getShiftAmountTy(InsElt.getValueType())));
5172       else if (Elt0 >= 0)
5173         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5174                              DAG.getConstant(0xFF00, MVT::i16));
5175     }
5176     // If Elt0 is defined, extract it from the appropriate source.  If the
5177     // source byte is not also even, shift the extracted word right 8 bits. If
5178     // Elt1 was also defined, OR the extracted values together before
5179     // inserting them in the result.
5180     if (Elt0 >= 0) {
5181       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5182                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5183       if ((Elt0 & 1) != 0)
5184         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5185                               DAG.getConstant(8,
5186                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
5187       else if (Elt1 >= 0)
5188         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5189                              DAG.getConstant(0x00FF, MVT::i16));
5190       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5191                          : InsElt0;
5192     }
5193     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5194                        DAG.getIntPtrConstant(i));
5195   }
5196   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5197 }
5198
5199 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5200 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5201 /// done when every pair / quad of shuffle mask elements point to elements in
5202 /// the right sequence. e.g.
5203 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5204 static
5205 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5206                                  SelectionDAG &DAG, DebugLoc dl) {
5207   EVT VT = SVOp->getValueType(0);
5208   SDValue V1 = SVOp->getOperand(0);
5209   SDValue V2 = SVOp->getOperand(1);
5210   unsigned NumElems = VT.getVectorNumElements();
5211   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
5212   EVT NewVT;
5213   switch (VT.getSimpleVT().SimpleTy) {
5214   default: assert(false && "Unexpected!");
5215   case MVT::v4f32: NewVT = MVT::v2f64; break;
5216   case MVT::v4i32: NewVT = MVT::v2i64; break;
5217   case MVT::v8i16: NewVT = MVT::v4i32; break;
5218   case MVT::v16i8: NewVT = MVT::v4i32; break;
5219   }
5220
5221   int Scale = NumElems / NewWidth;
5222   SmallVector<int, 8> MaskVec;
5223   for (unsigned i = 0; i < NumElems; i += Scale) {
5224     int StartIdx = -1;
5225     for (int j = 0; j < Scale; ++j) {
5226       int EltIdx = SVOp->getMaskElt(i+j);
5227       if (EltIdx < 0)
5228         continue;
5229       if (StartIdx == -1)
5230         StartIdx = EltIdx - (EltIdx % Scale);
5231       if (EltIdx != StartIdx + j)
5232         return SDValue();
5233     }
5234     if (StartIdx == -1)
5235       MaskVec.push_back(-1);
5236     else
5237       MaskVec.push_back(StartIdx / Scale);
5238   }
5239
5240   V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
5241   V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
5242   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5243 }
5244
5245 /// getVZextMovL - Return a zero-extending vector move low node.
5246 ///
5247 static SDValue getVZextMovL(EVT VT, EVT OpVT,
5248                             SDValue SrcOp, SelectionDAG &DAG,
5249                             const X86Subtarget *Subtarget, DebugLoc dl) {
5250   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
5251     LoadSDNode *LD = NULL;
5252     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
5253       LD = dyn_cast<LoadSDNode>(SrcOp);
5254     if (!LD) {
5255       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
5256       // instead.
5257       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
5258       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
5259           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5260           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
5261           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
5262         // PR2108
5263         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
5264         return DAG.getNode(ISD::BITCAST, dl, VT,
5265                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5266                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5267                                                    OpVT,
5268                                                    SrcOp.getOperand(0)
5269                                                           .getOperand(0))));
5270       }
5271     }
5272   }
5273
5274   return DAG.getNode(ISD::BITCAST, dl, VT,
5275                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5276                                  DAG.getNode(ISD::BITCAST, dl,
5277                                              OpVT, SrcOp)));
5278 }
5279
5280 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
5281 /// shuffles.
5282 static SDValue
5283 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5284   SDValue V1 = SVOp->getOperand(0);
5285   SDValue V2 = SVOp->getOperand(1);
5286   DebugLoc dl = SVOp->getDebugLoc();
5287   EVT VT = SVOp->getValueType(0);
5288
5289   SmallVector<std::pair<int, int>, 8> Locs;
5290   Locs.resize(4);
5291   SmallVector<int, 8> Mask1(4U, -1);
5292   SmallVector<int, 8> PermMask;
5293   SVOp->getMask(PermMask);
5294
5295   unsigned NumHi = 0;
5296   unsigned NumLo = 0;
5297   for (unsigned i = 0; i != 4; ++i) {
5298     int Idx = PermMask[i];
5299     if (Idx < 0) {
5300       Locs[i] = std::make_pair(-1, -1);
5301     } else {
5302       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
5303       if (Idx < 4) {
5304         Locs[i] = std::make_pair(0, NumLo);
5305         Mask1[NumLo] = Idx;
5306         NumLo++;
5307       } else {
5308         Locs[i] = std::make_pair(1, NumHi);
5309         if (2+NumHi < 4)
5310           Mask1[2+NumHi] = Idx;
5311         NumHi++;
5312       }
5313     }
5314   }
5315
5316   if (NumLo <= 2 && NumHi <= 2) {
5317     // If no more than two elements come from either vector. This can be
5318     // implemented with two shuffles. First shuffle gather the elements.
5319     // The second shuffle, which takes the first shuffle as both of its
5320     // vector operands, put the elements into the right order.
5321     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5322
5323     SmallVector<int, 8> Mask2(4U, -1);
5324
5325     for (unsigned i = 0; i != 4; ++i) {
5326       if (Locs[i].first == -1)
5327         continue;
5328       else {
5329         unsigned Idx = (i < 2) ? 0 : 4;
5330         Idx += Locs[i].first * 2 + Locs[i].second;
5331         Mask2[i] = Idx;
5332       }
5333     }
5334
5335     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
5336   } else if (NumLo == 3 || NumHi == 3) {
5337     // Otherwise, we must have three elements from one vector, call it X, and
5338     // one element from the other, call it Y.  First, use a shufps to build an
5339     // intermediate vector with the one element from Y and the element from X
5340     // that will be in the same half in the final destination (the indexes don't
5341     // matter). Then, use a shufps to build the final vector, taking the half
5342     // containing the element from Y from the intermediate, and the other half
5343     // from X.
5344     if (NumHi == 3) {
5345       // Normalize it so the 3 elements come from V1.
5346       CommuteVectorShuffleMask(PermMask, VT);
5347       std::swap(V1, V2);
5348     }
5349
5350     // Find the element from V2.
5351     unsigned HiIndex;
5352     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
5353       int Val = PermMask[HiIndex];
5354       if (Val < 0)
5355         continue;
5356       if (Val >= 4)
5357         break;
5358     }
5359
5360     Mask1[0] = PermMask[HiIndex];
5361     Mask1[1] = -1;
5362     Mask1[2] = PermMask[HiIndex^1];
5363     Mask1[3] = -1;
5364     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5365
5366     if (HiIndex >= 2) {
5367       Mask1[0] = PermMask[0];
5368       Mask1[1] = PermMask[1];
5369       Mask1[2] = HiIndex & 1 ? 6 : 4;
5370       Mask1[3] = HiIndex & 1 ? 4 : 6;
5371       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5372     } else {
5373       Mask1[0] = HiIndex & 1 ? 2 : 0;
5374       Mask1[1] = HiIndex & 1 ? 0 : 2;
5375       Mask1[2] = PermMask[2];
5376       Mask1[3] = PermMask[3];
5377       if (Mask1[2] >= 0)
5378         Mask1[2] += 4;
5379       if (Mask1[3] >= 0)
5380         Mask1[3] += 4;
5381       return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
5382     }
5383   }
5384
5385   // Break it into (shuffle shuffle_hi, shuffle_lo).
5386   Locs.clear();
5387   Locs.resize(4);
5388   SmallVector<int,8> LoMask(4U, -1);
5389   SmallVector<int,8> HiMask(4U, -1);
5390
5391   SmallVector<int,8> *MaskPtr = &LoMask;
5392   unsigned MaskIdx = 0;
5393   unsigned LoIdx = 0;
5394   unsigned HiIdx = 2;
5395   for (unsigned i = 0; i != 4; ++i) {
5396     if (i == 2) {
5397       MaskPtr = &HiMask;
5398       MaskIdx = 1;
5399       LoIdx = 0;
5400       HiIdx = 2;
5401     }
5402     int Idx = PermMask[i];
5403     if (Idx < 0) {
5404       Locs[i] = std::make_pair(-1, -1);
5405     } else if (Idx < 4) {
5406       Locs[i] = std::make_pair(MaskIdx, LoIdx);
5407       (*MaskPtr)[LoIdx] = Idx;
5408       LoIdx++;
5409     } else {
5410       Locs[i] = std::make_pair(MaskIdx, HiIdx);
5411       (*MaskPtr)[HiIdx] = Idx;
5412       HiIdx++;
5413     }
5414   }
5415
5416   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
5417   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
5418   SmallVector<int, 8> MaskOps;
5419   for (unsigned i = 0; i != 4; ++i) {
5420     if (Locs[i].first == -1) {
5421       MaskOps.push_back(-1);
5422     } else {
5423       unsigned Idx = Locs[i].first * 4 + Locs[i].second;
5424       MaskOps.push_back(Idx);
5425     }
5426   }
5427   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
5428 }
5429
5430 static bool MayFoldVectorLoad(SDValue V) {
5431   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5432     V = V.getOperand(0);
5433   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5434     V = V.getOperand(0);
5435   if (MayFoldLoad(V))
5436     return true;
5437   return false;
5438 }
5439
5440 // FIXME: the version above should always be used. Since there's
5441 // a bug where several vector shuffles can't be folded because the
5442 // DAG is not updated during lowering and a node claims to have two
5443 // uses while it only has one, use this version, and let isel match
5444 // another instruction if the load really happens to have more than
5445 // one use. Remove this version after this bug get fixed.
5446 // rdar://8434668, PR8156
5447 static bool RelaxedMayFoldVectorLoad(SDValue V) {
5448   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5449     V = V.getOperand(0);
5450   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5451     V = V.getOperand(0);
5452   if (ISD::isNormalLoad(V.getNode()))
5453     return true;
5454   return false;
5455 }
5456
5457 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
5458 /// a vector extract, and if both can be later optimized into a single load.
5459 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
5460 /// here because otherwise a target specific shuffle node is going to be
5461 /// emitted for this shuffle, and the optimization not done.
5462 /// FIXME: This is probably not the best approach, but fix the problem
5463 /// until the right path is decided.
5464 static
5465 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
5466                                          const TargetLowering &TLI) {
5467   EVT VT = V.getValueType();
5468   ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
5469
5470   // Be sure that the vector shuffle is present in a pattern like this:
5471   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
5472   if (!V.hasOneUse())
5473     return false;
5474
5475   SDNode *N = *V.getNode()->use_begin();
5476   if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5477     return false;
5478
5479   SDValue EltNo = N->getOperand(1);
5480   if (!isa<ConstantSDNode>(EltNo))
5481     return false;
5482
5483   // If the bit convert changed the number of elements, it is unsafe
5484   // to examine the mask.
5485   bool HasShuffleIntoBitcast = false;
5486   if (V.getOpcode() == ISD::BITCAST) {
5487     EVT SrcVT = V.getOperand(0).getValueType();
5488     if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
5489       return false;
5490     V = V.getOperand(0);
5491     HasShuffleIntoBitcast = true;
5492   }
5493
5494   // Select the input vector, guarding against out of range extract vector.
5495   unsigned NumElems = VT.getVectorNumElements();
5496   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5497   int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
5498   V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
5499
5500   // Skip one more bit_convert if necessary
5501   if (V.getOpcode() == ISD::BITCAST)
5502     V = V.getOperand(0);
5503
5504   if (ISD::isNormalLoad(V.getNode())) {
5505     // Is the original load suitable?
5506     LoadSDNode *LN0 = cast<LoadSDNode>(V);
5507
5508     // FIXME: avoid the multi-use bug that is preventing lots of
5509     // of foldings to be detected, this is still wrong of course, but
5510     // give the temporary desired behavior, and if it happens that
5511     // the load has real more uses, during isel it will not fold, and
5512     // will generate poor code.
5513     if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
5514       return false;
5515
5516     if (!HasShuffleIntoBitcast)
5517       return true;
5518
5519     // If there's a bitcast before the shuffle, check if the load type and
5520     // alignment is valid.
5521     unsigned Align = LN0->getAlignment();
5522     unsigned NewAlign =
5523       TLI.getTargetData()->getABITypeAlignment(
5524                                     VT.getTypeForEVT(*DAG.getContext()));
5525
5526     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
5527       return false;
5528   }
5529
5530   return true;
5531 }
5532
5533 static
5534 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
5535   EVT VT = Op.getValueType();
5536
5537   // Canonizalize to v2f64.
5538   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
5539   return DAG.getNode(ISD::BITCAST, dl, VT,
5540                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
5541                                           V1, DAG));
5542 }
5543
5544 static
5545 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
5546                         bool HasSSE2) {
5547   SDValue V1 = Op.getOperand(0);
5548   SDValue V2 = Op.getOperand(1);
5549   EVT VT = Op.getValueType();
5550
5551   assert(VT != MVT::v2i64 && "unsupported shuffle type");
5552
5553   if (HasSSE2 && VT == MVT::v2f64)
5554     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
5555
5556   // v4f32 or v4i32
5557   return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V2, DAG);
5558 }
5559
5560 static
5561 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
5562   SDValue V1 = Op.getOperand(0);
5563   SDValue V2 = Op.getOperand(1);
5564   EVT VT = Op.getValueType();
5565
5566   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
5567          "unsupported shuffle type");
5568
5569   if (V2.getOpcode() == ISD::UNDEF)
5570     V2 = V1;
5571
5572   // v4i32 or v4f32
5573   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
5574 }
5575
5576 static
5577 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
5578   SDValue V1 = Op.getOperand(0);
5579   SDValue V2 = Op.getOperand(1);
5580   EVT VT = Op.getValueType();
5581   unsigned NumElems = VT.getVectorNumElements();
5582
5583   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
5584   // operand of these instructions is only memory, so check if there's a
5585   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
5586   // same masks.
5587   bool CanFoldLoad = false;
5588
5589   // Trivial case, when V2 comes from a load.
5590   if (MayFoldVectorLoad(V2))
5591     CanFoldLoad = true;
5592
5593   // When V1 is a load, it can be folded later into a store in isel, example:
5594   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
5595   //    turns into:
5596   //  (MOVLPSmr addr:$src1, VR128:$src2)
5597   // So, recognize this potential and also use MOVLPS or MOVLPD
5598   if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
5599     CanFoldLoad = true;
5600
5601   // Both of them can't be memory operations though.
5602   if (MayFoldVectorLoad(V1) && MayFoldVectorLoad(V2))
5603     CanFoldLoad = false;
5604
5605   if (CanFoldLoad) {
5606     if (HasSSE2 && NumElems == 2)
5607       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
5608
5609     if (NumElems == 4)
5610       return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
5611   }
5612
5613   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5614   // movl and movlp will both match v2i64, but v2i64 is never matched by
5615   // movl earlier because we make it strict to avoid messing with the movlp load
5616   // folding logic (see the code above getMOVLP call). Match it here then,
5617   // this is horrible, but will stay like this until we move all shuffle
5618   // matching to x86 specific nodes. Note that for the 1st condition all
5619   // types are matched with movsd.
5620   if ((HasSSE2 && NumElems == 2) || !X86::isMOVLMask(SVOp))
5621     return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5622   else if (HasSSE2)
5623     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5624
5625
5626   assert(VT != MVT::v4i32 && "unsupported shuffle type");
5627
5628   // Invert the operand order and use SHUFPS to match it.
5629   return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V2, V1,
5630                               X86::getShuffleSHUFImmediate(SVOp), DAG);
5631 }
5632
5633 static inline unsigned getUNPCKLOpcode(EVT VT, const X86Subtarget *Subtarget) {
5634   switch(VT.getSimpleVT().SimpleTy) {
5635   case MVT::v4i32: return X86ISD::PUNPCKLDQ;
5636   case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
5637   case MVT::v4f32:
5638     return Subtarget->hasAVX() ? X86ISD::VUNPCKLPS : X86ISD::UNPCKLPS;
5639   case MVT::v2f64:
5640     return Subtarget->hasAVX() ? X86ISD::VUNPCKLPD : X86ISD::UNPCKLPD;
5641   case MVT::v8f32: return X86ISD::VUNPCKLPSY;
5642   case MVT::v4f64: return X86ISD::VUNPCKLPDY;
5643   case MVT::v16i8: return X86ISD::PUNPCKLBW;
5644   case MVT::v8i16: return X86ISD::PUNPCKLWD;
5645   default:
5646     llvm_unreachable("Unknown type for unpckl");
5647   }
5648   return 0;
5649 }
5650
5651 static inline unsigned getUNPCKHOpcode(EVT VT) {
5652   switch(VT.getSimpleVT().SimpleTy) {
5653   case MVT::v4i32: return X86ISD::PUNPCKHDQ;
5654   case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
5655   case MVT::v4f32: return X86ISD::UNPCKHPS;
5656   case MVT::v2f64: return X86ISD::UNPCKHPD;
5657   case MVT::v16i8: return X86ISD::PUNPCKHBW;
5658   case MVT::v8i16: return X86ISD::PUNPCKHWD;
5659   default:
5660     llvm_unreachable("Unknown type for unpckh");
5661   }
5662   return 0;
5663 }
5664
5665 static
5666 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
5667                                const TargetLowering &TLI,
5668                                const X86Subtarget *Subtarget) {
5669   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5670   EVT VT = Op.getValueType();
5671   DebugLoc dl = Op.getDebugLoc();
5672   SDValue V1 = Op.getOperand(0);
5673   SDValue V2 = Op.getOperand(1);
5674
5675   if (isZeroShuffle(SVOp))
5676     return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
5677
5678   // Handle splat operations
5679   if (SVOp->isSplat()) {
5680     // Special case, this is the only place now where it's
5681     // allowed to return a vector_shuffle operation without
5682     // using a target specific node, because *hopefully* it
5683     // will be optimized away by the dag combiner.
5684     if (VT.getVectorNumElements() <= 4 &&
5685         CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
5686       return Op;
5687
5688     // Handle splats by matching through known masks
5689     if (VT.getVectorNumElements() <= 4)
5690       return SDValue();
5691
5692     // Canonicalize all of the remaining to v4f32.
5693     return PromoteSplat(SVOp, DAG);
5694   }
5695
5696   // If the shuffle can be profitably rewritten as a narrower shuffle, then
5697   // do it!
5698   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
5699     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5700     if (NewOp.getNode())
5701       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
5702   } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
5703     // FIXME: Figure out a cleaner way to do this.
5704     // Try to make use of movq to zero out the top part.
5705     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
5706       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5707       if (NewOp.getNode()) {
5708         if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
5709           return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
5710                               DAG, Subtarget, dl);
5711       }
5712     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
5713       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5714       if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
5715         return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
5716                             DAG, Subtarget, dl);
5717     }
5718   }
5719   return SDValue();
5720 }
5721
5722 SDValue
5723 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
5724   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5725   SDValue V1 = Op.getOperand(0);
5726   SDValue V2 = Op.getOperand(1);
5727   EVT VT = Op.getValueType();
5728   DebugLoc dl = Op.getDebugLoc();
5729   unsigned NumElems = VT.getVectorNumElements();
5730   bool isMMX = VT.getSizeInBits() == 64;
5731   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
5732   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
5733   bool V1IsSplat = false;
5734   bool V2IsSplat = false;
5735   bool HasSSE2 = Subtarget->hasSSE2() || Subtarget->hasAVX();
5736   bool HasSSE3 = Subtarget->hasSSE3() || Subtarget->hasAVX();
5737   bool HasSSSE3 = Subtarget->hasSSSE3() || Subtarget->hasAVX();
5738   MachineFunction &MF = DAG.getMachineFunction();
5739   bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
5740
5741   // Shuffle operations on MMX not supported.
5742   if (isMMX)
5743     return Op;
5744
5745   // Vector shuffle lowering takes 3 steps:
5746   //
5747   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
5748   //    narrowing and commutation of operands should be handled.
5749   // 2) Matching of shuffles with known shuffle masks to x86 target specific
5750   //    shuffle nodes.
5751   // 3) Rewriting of unmatched masks into new generic shuffle operations,
5752   //    so the shuffle can be broken into other shuffles and the legalizer can
5753   //    try the lowering again.
5754   //
5755   // The general ideia is that no vector_shuffle operation should be left to
5756   // be matched during isel, all of them must be converted to a target specific
5757   // node here.
5758
5759   // Normalize the input vectors. Here splats, zeroed vectors, profitable
5760   // narrowing and commutation of operands should be handled. The actual code
5761   // doesn't include all of those, work in progress...
5762   SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
5763   if (NewOp.getNode())
5764     return NewOp;
5765
5766   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
5767   // unpckh_undef). Only use pshufd if speed is more important than size.
5768   if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
5769     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5770       return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()), dl, VT, V1, V1, DAG);
5771   if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
5772     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5773       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5774
5775   if (X86::isMOVDDUPMask(SVOp) && HasSSE3 && V2IsUndef &&
5776       RelaxedMayFoldVectorLoad(V1))
5777     return getMOVDDup(Op, dl, V1, DAG);
5778
5779   if (X86::isMOVHLPS_v_undef_Mask(SVOp))
5780     return getMOVHighToLow(Op, dl, DAG);
5781
5782   // Use to match splats
5783   if (HasSSE2 && X86::isUNPCKHMask(SVOp) && V2IsUndef &&
5784       (VT == MVT::v2f64 || VT == MVT::v2i64))
5785     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5786
5787   if (X86::isPSHUFDMask(SVOp)) {
5788     // The actual implementation will match the mask in the if above and then
5789     // during isel it can match several different instructions, not only pshufd
5790     // as its name says, sad but true, emulate the behavior for now...
5791     if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
5792         return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
5793
5794     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5795
5796     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
5797       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
5798
5799     if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5800       return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V1,
5801                                   TargetMask, DAG);
5802
5803     if (VT == MVT::v4f32)
5804       return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V1,
5805                                   TargetMask, DAG);
5806   }
5807
5808   // Check if this can be converted into a logical shift.
5809   bool isLeft = false;
5810   unsigned ShAmt = 0;
5811   SDValue ShVal;
5812   bool isShift = getSubtarget()->hasSSE2() &&
5813     isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
5814   if (isShift && ShVal.hasOneUse()) {
5815     // If the shifted value has multiple uses, it may be cheaper to use
5816     // v_set0 + movlhps or movhlps, etc.
5817     EVT EltVT = VT.getVectorElementType();
5818     ShAmt *= EltVT.getSizeInBits();
5819     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5820   }
5821
5822   if (X86::isMOVLMask(SVOp)) {
5823     if (V1IsUndef)
5824       return V2;
5825     if (ISD::isBuildVectorAllZeros(V1.getNode()))
5826       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
5827     if (!X86::isMOVLPMask(SVOp)) {
5828       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5829         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5830
5831       if (VT == MVT::v4i32 || VT == MVT::v4f32)
5832         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5833     }
5834   }
5835
5836   // FIXME: fold these into legal mask.
5837   if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp))
5838     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
5839
5840   if (X86::isMOVHLPSMask(SVOp))
5841     return getMOVHighToLow(Op, dl, DAG);
5842
5843   if (X86::isMOVSHDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5844     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
5845
5846   if (X86::isMOVSLDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5847     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
5848
5849   if (X86::isMOVLPMask(SVOp))
5850     return getMOVLP(Op, dl, DAG, HasSSE2);
5851
5852   if (ShouldXformToMOVHLPS(SVOp) ||
5853       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
5854     return CommuteVectorShuffle(SVOp, DAG);
5855
5856   if (isShift) {
5857     // No better options. Use a vshl / vsrl.
5858     EVT EltVT = VT.getVectorElementType();
5859     ShAmt *= EltVT.getSizeInBits();
5860     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5861   }
5862
5863   bool Commuted = false;
5864   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
5865   // 1,1,1,1 -> v8i16 though.
5866   V1IsSplat = isSplatVector(V1.getNode());
5867   V2IsSplat = isSplatVector(V2.getNode());
5868
5869   // Canonicalize the splat or undef, if present, to be on the RHS.
5870   if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
5871     Op = CommuteVectorShuffle(SVOp, DAG);
5872     SVOp = cast<ShuffleVectorSDNode>(Op);
5873     V1 = SVOp->getOperand(0);
5874     V2 = SVOp->getOperand(1);
5875     std::swap(V1IsSplat, V2IsSplat);
5876     std::swap(V1IsUndef, V2IsUndef);
5877     Commuted = true;
5878   }
5879
5880   if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
5881     // Shuffling low element of v1 into undef, just return v1.
5882     if (V2IsUndef)
5883       return V1;
5884     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
5885     // the instruction selector will not match, so get a canonical MOVL with
5886     // swapped operands to undo the commute.
5887     return getMOVL(DAG, dl, VT, V2, V1);
5888   }
5889
5890   if (X86::isUNPCKLMask(SVOp))
5891     return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
5892                                 dl, VT, V1, V2, DAG);
5893
5894   if (X86::isUNPCKHMask(SVOp))
5895     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG);
5896
5897   if (V2IsSplat) {
5898     // Normalize mask so all entries that point to V2 points to its first
5899     // element then try to match unpck{h|l} again. If match, return a
5900     // new vector_shuffle with the corrected mask.
5901     SDValue NewMask = NormalizeMask(SVOp, DAG);
5902     ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
5903     if (NSVOp != SVOp) {
5904       if (X86::isUNPCKLMask(NSVOp, true)) {
5905         return NewMask;
5906       } else if (X86::isUNPCKHMask(NSVOp, true)) {
5907         return NewMask;
5908       }
5909     }
5910   }
5911
5912   if (Commuted) {
5913     // Commute is back and try unpck* again.
5914     // FIXME: this seems wrong.
5915     SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
5916     ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
5917
5918     if (X86::isUNPCKLMask(NewSVOp))
5919       return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
5920                                   dl, VT, V2, V1, DAG);
5921
5922     if (X86::isUNPCKHMask(NewSVOp))
5923       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG);
5924   }
5925
5926   // Normalize the node to match x86 shuffle ops if needed
5927   if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
5928     return CommuteVectorShuffle(SVOp, DAG);
5929
5930   // The checks below are all present in isShuffleMaskLegal, but they are
5931   // inlined here right now to enable us to directly emit target specific
5932   // nodes, and remove one by one until they don't return Op anymore.
5933   SmallVector<int, 16> M;
5934   SVOp->getMask(M);
5935
5936   if (isPALIGNRMask(M, VT, HasSSSE3))
5937     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
5938                                 X86::getShufflePALIGNRImmediate(SVOp),
5939                                 DAG);
5940
5941   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
5942       SVOp->getSplatIndex() == 0 && V2IsUndef) {
5943     if (VT == MVT::v2f64) {
5944       X86ISD::NodeType Opcode =
5945         getSubtarget()->hasAVX() ? X86ISD::VUNPCKLPD : X86ISD::UNPCKLPD;
5946       return getTargetShuffleNode(Opcode, dl, VT, V1, V1, DAG);
5947     }
5948     if (VT == MVT::v2i64)
5949       return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
5950   }
5951
5952   if (isPSHUFHWMask(M, VT))
5953     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
5954                                 X86::getShufflePSHUFHWImmediate(SVOp),
5955                                 DAG);
5956
5957   if (isPSHUFLWMask(M, VT))
5958     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
5959                                 X86::getShufflePSHUFLWImmediate(SVOp),
5960                                 DAG);
5961
5962   if (isSHUFPMask(M, VT)) {
5963     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5964     if (VT == MVT::v4f32 || VT == MVT::v4i32)
5965       return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V2,
5966                                   TargetMask, DAG);
5967     if (VT == MVT::v2f64 || VT == MVT::v2i64)
5968       return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V2,
5969                                   TargetMask, DAG);
5970   }
5971
5972   if (X86::isUNPCKL_v_undef_Mask(SVOp))
5973     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5974       return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
5975                                   dl, VT, V1, V1, DAG);
5976   if (X86::isUNPCKH_v_undef_Mask(SVOp))
5977     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5978       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5979
5980   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
5981   if (VT == MVT::v8i16) {
5982     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
5983     if (NewOp.getNode())
5984       return NewOp;
5985   }
5986
5987   if (VT == MVT::v16i8) {
5988     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
5989     if (NewOp.getNode())
5990       return NewOp;
5991   }
5992
5993   // Handle all 4 wide cases with a number of shuffles.
5994   if (NumElems == 4)
5995     return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
5996
5997   return SDValue();
5998 }
5999
6000 SDValue
6001 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6002                                                 SelectionDAG &DAG) const {
6003   EVT VT = Op.getValueType();
6004   DebugLoc dl = Op.getDebugLoc();
6005   if (VT.getSizeInBits() == 8) {
6006     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6007                                     Op.getOperand(0), Op.getOperand(1));
6008     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6009                                     DAG.getValueType(VT));
6010     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6011   } else if (VT.getSizeInBits() == 16) {
6012     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6013     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6014     if (Idx == 0)
6015       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6016                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6017                                      DAG.getNode(ISD::BITCAST, dl,
6018                                                  MVT::v4i32,
6019                                                  Op.getOperand(0)),
6020                                      Op.getOperand(1)));
6021     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6022                                     Op.getOperand(0), Op.getOperand(1));
6023     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6024                                     DAG.getValueType(VT));
6025     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6026   } else if (VT == MVT::f32) {
6027     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6028     // the result back to FR32 register. It's only worth matching if the
6029     // result has a single use which is a store or a bitcast to i32.  And in
6030     // the case of a store, it's not worth it if the index is a constant 0,
6031     // because a MOVSSmr can be used instead, which is smaller and faster.
6032     if (!Op.hasOneUse())
6033       return SDValue();
6034     SDNode *User = *Op.getNode()->use_begin();
6035     if ((User->getOpcode() != ISD::STORE ||
6036          (isa<ConstantSDNode>(Op.getOperand(1)) &&
6037           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6038         (User->getOpcode() != ISD::BITCAST ||
6039          User->getValueType(0) != MVT::i32))
6040       return SDValue();
6041     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6042                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6043                                               Op.getOperand(0)),
6044                                               Op.getOperand(1));
6045     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6046   } else if (VT == MVT::i32) {
6047     // ExtractPS works with constant index.
6048     if (isa<ConstantSDNode>(Op.getOperand(1)))
6049       return Op;
6050   }
6051   return SDValue();
6052 }
6053
6054
6055 SDValue
6056 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6057                                            SelectionDAG &DAG) const {
6058   if (!isa<ConstantSDNode>(Op.getOperand(1)))
6059     return SDValue();
6060
6061   SDValue Vec = Op.getOperand(0);
6062   EVT VecVT = Vec.getValueType();
6063
6064   // If this is a 256-bit vector result, first extract the 128-bit
6065   // vector and then extract from the 128-bit vector.
6066   if (VecVT.getSizeInBits() > 128) {
6067     DebugLoc dl = Op.getNode()->getDebugLoc();
6068     unsigned NumElems = VecVT.getVectorNumElements();
6069     SDValue Idx = Op.getOperand(1);
6070
6071     if (!isa<ConstantSDNode>(Idx))
6072       return SDValue();
6073
6074     unsigned ExtractNumElems = NumElems / (VecVT.getSizeInBits() / 128);
6075     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6076
6077     // Get the 128-bit vector.
6078     bool Upper = IdxVal >= ExtractNumElems;
6079     Vec = Extract128BitVector(Vec, Idx, DAG, dl);
6080
6081     // Extract from it.
6082     SDValue ScaledIdx = Idx;
6083     if (Upper)
6084       ScaledIdx = DAG.getNode(ISD::SUB, dl, Idx.getValueType(), Idx,
6085                               DAG.getConstant(ExtractNumElems,
6086                                               Idx.getValueType()));
6087     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6088                        ScaledIdx);
6089   }
6090
6091   assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
6092
6093   if (Subtarget->hasSSE41()) {
6094     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6095     if (Res.getNode())
6096       return Res;
6097   }
6098
6099   EVT VT = Op.getValueType();
6100   DebugLoc dl = Op.getDebugLoc();
6101   // TODO: handle v16i8.
6102   if (VT.getSizeInBits() == 16) {
6103     SDValue Vec = Op.getOperand(0);
6104     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6105     if (Idx == 0)
6106       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6107                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6108                                      DAG.getNode(ISD::BITCAST, dl,
6109                                                  MVT::v4i32, Vec),
6110                                      Op.getOperand(1)));
6111     // Transform it so it match pextrw which produces a 32-bit result.
6112     EVT EltVT = MVT::i32;
6113     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6114                                     Op.getOperand(0), Op.getOperand(1));
6115     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6116                                     DAG.getValueType(VT));
6117     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6118   } else if (VT.getSizeInBits() == 32) {
6119     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6120     if (Idx == 0)
6121       return Op;
6122
6123     // SHUFPS the element to the lowest double word, then movss.
6124     int Mask[4] = { Idx, -1, -1, -1 };
6125     EVT VVT = Op.getOperand(0).getValueType();
6126     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6127                                        DAG.getUNDEF(VVT), Mask);
6128     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6129                        DAG.getIntPtrConstant(0));
6130   } else if (VT.getSizeInBits() == 64) {
6131     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6132     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6133     //        to match extract_elt for f64.
6134     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6135     if (Idx == 0)
6136       return Op;
6137
6138     // UNPCKHPD the element to the lowest double word, then movsd.
6139     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
6140     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
6141     int Mask[2] = { 1, -1 };
6142     EVT VVT = Op.getOperand(0).getValueType();
6143     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6144                                        DAG.getUNDEF(VVT), Mask);
6145     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6146                        DAG.getIntPtrConstant(0));
6147   }
6148
6149   return SDValue();
6150 }
6151
6152 SDValue
6153 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
6154                                                SelectionDAG &DAG) const {
6155   EVT VT = Op.getValueType();
6156   EVT EltVT = VT.getVectorElementType();
6157   DebugLoc dl = Op.getDebugLoc();
6158
6159   SDValue N0 = Op.getOperand(0);
6160   SDValue N1 = Op.getOperand(1);
6161   SDValue N2 = Op.getOperand(2);
6162
6163   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
6164       isa<ConstantSDNode>(N2)) {
6165     unsigned Opc;
6166     if (VT == MVT::v8i16)
6167       Opc = X86ISD::PINSRW;
6168     else if (VT == MVT::v16i8)
6169       Opc = X86ISD::PINSRB;
6170     else
6171       Opc = X86ISD::PINSRB;
6172
6173     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
6174     // argument.
6175     if (N1.getValueType() != MVT::i32)
6176       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6177     if (N2.getValueType() != MVT::i32)
6178       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6179     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
6180   } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
6181     // Bits [7:6] of the constant are the source select.  This will always be
6182     //  zero here.  The DAG Combiner may combine an extract_elt index into these
6183     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
6184     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
6185     // Bits [5:4] of the constant are the destination select.  This is the
6186     //  value of the incoming immediate.
6187     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
6188     //   combine either bitwise AND or insert of float 0.0 to set these bits.
6189     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
6190     // Create this as a scalar to vector..
6191     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
6192     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
6193   } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
6194     // PINSR* works with constant index.
6195     return Op;
6196   }
6197   return SDValue();
6198 }
6199
6200 SDValue
6201 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
6202   EVT VT = Op.getValueType();
6203   EVT EltVT = VT.getVectorElementType();
6204
6205   DebugLoc dl = Op.getDebugLoc();
6206   SDValue N0 = Op.getOperand(0);
6207   SDValue N1 = Op.getOperand(1);
6208   SDValue N2 = Op.getOperand(2);
6209
6210   // If this is a 256-bit vector result, first insert into a 128-bit
6211   // vector and then insert into the 256-bit vector.
6212   if (VT.getSizeInBits() > 128) {
6213     if (!isa<ConstantSDNode>(N2))
6214       return SDValue();
6215
6216     // Get the 128-bit vector.
6217     unsigned NumElems = VT.getVectorNumElements();
6218     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
6219     bool Upper = IdxVal >= NumElems / 2;
6220
6221     SDValue SubN0 = Extract128BitVector(N0, N2, DAG, dl);
6222
6223     // Insert into it.
6224     SDValue ScaledN2 = N2;
6225     if (Upper)
6226       ScaledN2 = DAG.getNode(ISD::SUB, dl, N2.getValueType(), N2,
6227                              DAG.getConstant(NumElems /
6228                                              (VT.getSizeInBits() / 128),
6229                                              N2.getValueType()));
6230     Op = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubN0.getValueType(), SubN0,
6231                      N1, ScaledN2);
6232
6233     // Insert the 128-bit vector
6234     // FIXME: Why UNDEF?
6235     return Insert128BitVector(N0, Op, N2, DAG, dl);
6236   }
6237
6238   if (Subtarget->hasSSE41())
6239     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
6240
6241   if (EltVT == MVT::i8)
6242     return SDValue();
6243
6244   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
6245     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
6246     // as its second argument.
6247     if (N1.getValueType() != MVT::i32)
6248       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6249     if (N2.getValueType() != MVT::i32)
6250       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6251     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
6252   }
6253   return SDValue();
6254 }
6255
6256 SDValue
6257 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6258   LLVMContext *Context = DAG.getContext();
6259   DebugLoc dl = Op.getDebugLoc();
6260   EVT OpVT = Op.getValueType();
6261
6262   // If this is a 256-bit vector result, first insert into a 128-bit
6263   // vector and then insert into the 256-bit vector.
6264   if (OpVT.getSizeInBits() > 128) {
6265     // Insert into a 128-bit vector.
6266     EVT VT128 = EVT::getVectorVT(*Context,
6267                                  OpVT.getVectorElementType(),
6268                                  OpVT.getVectorNumElements() / 2);
6269
6270     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
6271
6272     // Insert the 128-bit vector.
6273     return Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, OpVT), Op,
6274                               DAG.getConstant(0, MVT::i32),
6275                               DAG, dl);
6276   }
6277
6278   if (Op.getValueType() == MVT::v1i64 &&
6279       Op.getOperand(0).getValueType() == MVT::i64)
6280     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
6281
6282   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
6283   assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
6284          "Expected an SSE type!");
6285   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
6286                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
6287 }
6288
6289 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
6290 // a simple subregister reference or explicit instructions to grab
6291 // upper bits of a vector.
6292 SDValue
6293 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6294   if (Subtarget->hasAVX()) {
6295     DebugLoc dl = Op.getNode()->getDebugLoc();
6296     SDValue Vec = Op.getNode()->getOperand(0);
6297     SDValue Idx = Op.getNode()->getOperand(1);
6298
6299     if (Op.getNode()->getValueType(0).getSizeInBits() == 128
6300         && Vec.getNode()->getValueType(0).getSizeInBits() == 256) {
6301         return Extract128BitVector(Vec, Idx, DAG, dl);
6302     }
6303   }
6304   return SDValue();
6305 }
6306
6307 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
6308 // simple superregister reference or explicit instructions to insert
6309 // the upper bits of a vector.
6310 SDValue
6311 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6312   if (Subtarget->hasAVX()) {
6313     DebugLoc dl = Op.getNode()->getDebugLoc();
6314     SDValue Vec = Op.getNode()->getOperand(0);
6315     SDValue SubVec = Op.getNode()->getOperand(1);
6316     SDValue Idx = Op.getNode()->getOperand(2);
6317
6318     if (Op.getNode()->getValueType(0).getSizeInBits() == 256
6319         && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) {
6320       return Insert128BitVector(Vec, SubVec, Idx, DAG, dl);
6321     }
6322   }
6323   return SDValue();
6324 }
6325
6326 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
6327 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
6328 // one of the above mentioned nodes. It has to be wrapped because otherwise
6329 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
6330 // be used to form addressing mode. These wrapped nodes will be selected
6331 // into MOV32ri.
6332 SDValue
6333 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
6334   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
6335
6336   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6337   // global base reg.
6338   unsigned char OpFlag = 0;
6339   unsigned WrapperKind = X86ISD::Wrapper;
6340   CodeModel::Model M = getTargetMachine().getCodeModel();
6341
6342   if (Subtarget->isPICStyleRIPRel() &&
6343       (M == CodeModel::Small || M == CodeModel::Kernel))
6344     WrapperKind = X86ISD::WrapperRIP;
6345   else if (Subtarget->isPICStyleGOT())
6346     OpFlag = X86II::MO_GOTOFF;
6347   else if (Subtarget->isPICStyleStubPIC())
6348     OpFlag = X86II::MO_PIC_BASE_OFFSET;
6349
6350   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
6351                                              CP->getAlignment(),
6352                                              CP->getOffset(), OpFlag);
6353   DebugLoc DL = CP->getDebugLoc();
6354   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6355   // With PIC, the address is actually $g + Offset.
6356   if (OpFlag) {
6357     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6358                          DAG.getNode(X86ISD::GlobalBaseReg,
6359                                      DebugLoc(), getPointerTy()),
6360                          Result);
6361   }
6362
6363   return Result;
6364 }
6365
6366 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
6367   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
6368
6369   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6370   // global base reg.
6371   unsigned char OpFlag = 0;
6372   unsigned WrapperKind = X86ISD::Wrapper;
6373   CodeModel::Model M = getTargetMachine().getCodeModel();
6374
6375   if (Subtarget->isPICStyleRIPRel() &&
6376       (M == CodeModel::Small || M == CodeModel::Kernel))
6377     WrapperKind = X86ISD::WrapperRIP;
6378   else if (Subtarget->isPICStyleGOT())
6379     OpFlag = X86II::MO_GOTOFF;
6380   else if (Subtarget->isPICStyleStubPIC())
6381     OpFlag = X86II::MO_PIC_BASE_OFFSET;
6382
6383   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
6384                                           OpFlag);
6385   DebugLoc DL = JT->getDebugLoc();
6386   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6387
6388   // With PIC, the address is actually $g + Offset.
6389   if (OpFlag)
6390     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6391                          DAG.getNode(X86ISD::GlobalBaseReg,
6392                                      DebugLoc(), getPointerTy()),
6393                          Result);
6394
6395   return Result;
6396 }
6397
6398 SDValue
6399 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
6400   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
6401
6402   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6403   // global base reg.
6404   unsigned char OpFlag = 0;
6405   unsigned WrapperKind = X86ISD::Wrapper;
6406   CodeModel::Model M = getTargetMachine().getCodeModel();
6407
6408   if (Subtarget->isPICStyleRIPRel() &&
6409       (M == CodeModel::Small || M == CodeModel::Kernel))
6410     WrapperKind = X86ISD::WrapperRIP;
6411   else if (Subtarget->isPICStyleGOT())
6412     OpFlag = X86II::MO_GOTOFF;
6413   else if (Subtarget->isPICStyleStubPIC())
6414     OpFlag = X86II::MO_PIC_BASE_OFFSET;
6415
6416   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
6417
6418   DebugLoc DL = Op.getDebugLoc();
6419   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6420
6421
6422   // With PIC, the address is actually $g + Offset.
6423   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
6424       !Subtarget->is64Bit()) {
6425     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6426                          DAG.getNode(X86ISD::GlobalBaseReg,
6427                                      DebugLoc(), getPointerTy()),
6428                          Result);
6429   }
6430
6431   return Result;
6432 }
6433
6434 SDValue
6435 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
6436   // Create the TargetBlockAddressAddress node.
6437   unsigned char OpFlags =
6438     Subtarget->ClassifyBlockAddressReference();
6439   CodeModel::Model M = getTargetMachine().getCodeModel();
6440   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
6441   DebugLoc dl = Op.getDebugLoc();
6442   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
6443                                        /*isTarget=*/true, OpFlags);
6444
6445   if (Subtarget->isPICStyleRIPRel() &&
6446       (M == CodeModel::Small || M == CodeModel::Kernel))
6447     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6448   else
6449     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6450
6451   // With PIC, the address is actually $g + Offset.
6452   if (isGlobalRelativeToPICBase(OpFlags)) {
6453     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6454                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6455                          Result);
6456   }
6457
6458   return Result;
6459 }
6460
6461 SDValue
6462 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
6463                                       int64_t Offset,
6464                                       SelectionDAG &DAG) const {
6465   // Create the TargetGlobalAddress node, folding in the constant
6466   // offset if it is legal.
6467   unsigned char OpFlags =
6468     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
6469   CodeModel::Model M = getTargetMachine().getCodeModel();
6470   SDValue Result;
6471   if (OpFlags == X86II::MO_NO_FLAG &&
6472       X86::isOffsetSuitableForCodeModel(Offset, M)) {
6473     // A direct static reference to a global.
6474     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
6475     Offset = 0;
6476   } else {
6477     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
6478   }
6479
6480   if (Subtarget->isPICStyleRIPRel() &&
6481       (M == CodeModel::Small || M == CodeModel::Kernel))
6482     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6483   else
6484     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6485
6486   // With PIC, the address is actually $g + Offset.
6487   if (isGlobalRelativeToPICBase(OpFlags)) {
6488     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6489                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6490                          Result);
6491   }
6492
6493   // For globals that require a load from a stub to get the address, emit the
6494   // load.
6495   if (isGlobalStubReference(OpFlags))
6496     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
6497                          MachinePointerInfo::getGOT(), false, false, 0);
6498
6499   // If there was a non-zero offset that we didn't fold, create an explicit
6500   // addition for it.
6501   if (Offset != 0)
6502     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
6503                          DAG.getConstant(Offset, getPointerTy()));
6504
6505   return Result;
6506 }
6507
6508 SDValue
6509 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
6510   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
6511   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
6512   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
6513 }
6514
6515 static SDValue
6516 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
6517            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
6518            unsigned char OperandFlags) {
6519   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6520   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6521   DebugLoc dl = GA->getDebugLoc();
6522   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6523                                            GA->getValueType(0),
6524                                            GA->getOffset(),
6525                                            OperandFlags);
6526   if (InFlag) {
6527     SDValue Ops[] = { Chain,  TGA, *InFlag };
6528     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
6529   } else {
6530     SDValue Ops[]  = { Chain, TGA };
6531     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
6532   }
6533
6534   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
6535   MFI->setAdjustsStack(true);
6536
6537   SDValue Flag = Chain.getValue(1);
6538   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
6539 }
6540
6541 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
6542 static SDValue
6543 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6544                                 const EVT PtrVT) {
6545   SDValue InFlag;
6546   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
6547   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
6548                                      DAG.getNode(X86ISD::GlobalBaseReg,
6549                                                  DebugLoc(), PtrVT), InFlag);
6550   InFlag = Chain.getValue(1);
6551
6552   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
6553 }
6554
6555 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
6556 static SDValue
6557 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6558                                 const EVT PtrVT) {
6559   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
6560                     X86::RAX, X86II::MO_TLSGD);
6561 }
6562
6563 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
6564 // "local exec" model.
6565 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6566                                    const EVT PtrVT, TLSModel::Model model,
6567                                    bool is64Bit) {
6568   DebugLoc dl = GA->getDebugLoc();
6569
6570   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
6571   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
6572                                                          is64Bit ? 257 : 256));
6573
6574   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
6575                                       DAG.getIntPtrConstant(0),
6576                                       MachinePointerInfo(Ptr), false, false, 0);
6577
6578   unsigned char OperandFlags = 0;
6579   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
6580   // initialexec.
6581   unsigned WrapperKind = X86ISD::Wrapper;
6582   if (model == TLSModel::LocalExec) {
6583     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
6584   } else if (is64Bit) {
6585     assert(model == TLSModel::InitialExec);
6586     OperandFlags = X86II::MO_GOTTPOFF;
6587     WrapperKind = X86ISD::WrapperRIP;
6588   } else {
6589     assert(model == TLSModel::InitialExec);
6590     OperandFlags = X86II::MO_INDNTPOFF;
6591   }
6592
6593   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
6594   // exec)
6595   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6596                                            GA->getValueType(0),
6597                                            GA->getOffset(), OperandFlags);
6598   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
6599
6600   if (model == TLSModel::InitialExec)
6601     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
6602                          MachinePointerInfo::getGOT(), false, false, 0);
6603
6604   // The address of the thread local variable is the add of the thread
6605   // pointer with the offset of the variable.
6606   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
6607 }
6608
6609 SDValue
6610 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
6611
6612   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
6613   const GlobalValue *GV = GA->getGlobal();
6614
6615   if (Subtarget->isTargetELF()) {
6616     // TODO: implement the "local dynamic" model
6617     // TODO: implement the "initial exec"model for pic executables
6618
6619     // If GV is an alias then use the aliasee for determining
6620     // thread-localness.
6621     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
6622       GV = GA->resolveAliasedGlobal(false);
6623
6624     TLSModel::Model model
6625       = getTLSModel(GV, getTargetMachine().getRelocationModel());
6626
6627     switch (model) {
6628       case TLSModel::GeneralDynamic:
6629       case TLSModel::LocalDynamic: // not implemented
6630         if (Subtarget->is64Bit())
6631           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
6632         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
6633
6634       case TLSModel::InitialExec:
6635       case TLSModel::LocalExec:
6636         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
6637                                    Subtarget->is64Bit());
6638     }
6639   } else if (Subtarget->isTargetDarwin()) {
6640     // Darwin only has one model of TLS.  Lower to that.
6641     unsigned char OpFlag = 0;
6642     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
6643                            X86ISD::WrapperRIP : X86ISD::Wrapper;
6644
6645     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6646     // global base reg.
6647     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
6648                   !Subtarget->is64Bit();
6649     if (PIC32)
6650       OpFlag = X86II::MO_TLVP_PIC_BASE;
6651     else
6652       OpFlag = X86II::MO_TLVP;
6653     DebugLoc DL = Op.getDebugLoc();
6654     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
6655                                                 GA->getValueType(0),
6656                                                 GA->getOffset(), OpFlag);
6657     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6658
6659     // With PIC32, the address is actually $g + Offset.
6660     if (PIC32)
6661       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6662                            DAG.getNode(X86ISD::GlobalBaseReg,
6663                                        DebugLoc(), getPointerTy()),
6664                            Offset);
6665
6666     // Lowering the machine isd will make sure everything is in the right
6667     // location.
6668     SDValue Chain = DAG.getEntryNode();
6669     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6670     SDValue Args[] = { Chain, Offset };
6671     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
6672
6673     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
6674     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6675     MFI->setAdjustsStack(true);
6676
6677     // And our return value (tls address) is in the standard call return value
6678     // location.
6679     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
6680     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
6681   }
6682
6683   assert(false &&
6684          "TLS not implemented for this target.");
6685
6686   llvm_unreachable("Unreachable");
6687   return SDValue();
6688 }
6689
6690
6691 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values and
6692 /// take a 2 x i32 value to shift plus a shift amount.
6693 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const {
6694   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6695   EVT VT = Op.getValueType();
6696   unsigned VTBits = VT.getSizeInBits();
6697   DebugLoc dl = Op.getDebugLoc();
6698   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
6699   SDValue ShOpLo = Op.getOperand(0);
6700   SDValue ShOpHi = Op.getOperand(1);
6701   SDValue ShAmt  = Op.getOperand(2);
6702   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
6703                                      DAG.getConstant(VTBits - 1, MVT::i8))
6704                        : DAG.getConstant(0, VT);
6705
6706   SDValue Tmp2, Tmp3;
6707   if (Op.getOpcode() == ISD::SHL_PARTS) {
6708     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
6709     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
6710   } else {
6711     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
6712     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
6713   }
6714
6715   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
6716                                 DAG.getConstant(VTBits, MVT::i8));
6717   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
6718                              AndNode, DAG.getConstant(0, MVT::i8));
6719
6720   SDValue Hi, Lo;
6721   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6722   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
6723   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
6724
6725   if (Op.getOpcode() == ISD::SHL_PARTS) {
6726     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6727     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6728   } else {
6729     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6730     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6731   }
6732
6733   SDValue Ops[2] = { Lo, Hi };
6734   return DAG.getMergeValues(Ops, 2, dl);
6735 }
6736
6737 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
6738                                            SelectionDAG &DAG) const {
6739   EVT SrcVT = Op.getOperand(0).getValueType();
6740
6741   if (SrcVT.isVector())
6742     return SDValue();
6743
6744   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
6745          "Unknown SINT_TO_FP to lower!");
6746
6747   // These are really Legal; return the operand so the caller accepts it as
6748   // Legal.
6749   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
6750     return Op;
6751   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
6752       Subtarget->is64Bit()) {
6753     return Op;
6754   }
6755
6756   DebugLoc dl = Op.getDebugLoc();
6757   unsigned Size = SrcVT.getSizeInBits()/8;
6758   MachineFunction &MF = DAG.getMachineFunction();
6759   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
6760   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6761   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6762                                StackSlot,
6763                                MachinePointerInfo::getFixedStack(SSFI),
6764                                false, false, 0);
6765   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
6766 }
6767
6768 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
6769                                      SDValue StackSlot,
6770                                      SelectionDAG &DAG) const {
6771   // Build the FILD
6772   DebugLoc DL = Op.getDebugLoc();
6773   SDVTList Tys;
6774   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
6775   if (useSSE)
6776     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
6777   else
6778     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
6779
6780   unsigned ByteSize = SrcVT.getSizeInBits()/8;
6781
6782   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
6783   MachineMemOperand *MMO;
6784   if (FI) {
6785     int SSFI = FI->getIndex();
6786     MMO =
6787       DAG.getMachineFunction()
6788       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6789                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
6790   } else {
6791     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
6792     StackSlot = StackSlot.getOperand(1);
6793   }
6794   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
6795   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
6796                                            X86ISD::FILD, DL,
6797                                            Tys, Ops, array_lengthof(Ops),
6798                                            SrcVT, MMO);
6799
6800   if (useSSE) {
6801     Chain = Result.getValue(1);
6802     SDValue InFlag = Result.getValue(2);
6803
6804     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
6805     // shouldn't be necessary except that RFP cannot be live across
6806     // multiple blocks. When stackifier is fixed, they can be uncoupled.
6807     MachineFunction &MF = DAG.getMachineFunction();
6808     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
6809     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
6810     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6811     Tys = DAG.getVTList(MVT::Other);
6812     SDValue Ops[] = {
6813       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
6814     };
6815     MachineMemOperand *MMO =
6816       DAG.getMachineFunction()
6817       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6818                             MachineMemOperand::MOStore, SSFISize, SSFISize);
6819
6820     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
6821                                     Ops, array_lengthof(Ops),
6822                                     Op.getValueType(), MMO);
6823     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
6824                          MachinePointerInfo::getFixedStack(SSFI),
6825                          false, false, 0);
6826   }
6827
6828   return Result;
6829 }
6830
6831 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
6832 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
6833                                                SelectionDAG &DAG) const {
6834   // This algorithm is not obvious. Here it is in C code, more or less:
6835   /*
6836     double uint64_to_double( uint32_t hi, uint32_t lo ) {
6837       static const __m128i exp = { 0x4330000045300000ULL, 0 };
6838       static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
6839
6840       // Copy ints to xmm registers.
6841       __m128i xh = _mm_cvtsi32_si128( hi );
6842       __m128i xl = _mm_cvtsi32_si128( lo );
6843
6844       // Combine into low half of a single xmm register.
6845       __m128i x = _mm_unpacklo_epi32( xh, xl );
6846       __m128d d;
6847       double sd;
6848
6849       // Merge in appropriate exponents to give the integer bits the right
6850       // magnitude.
6851       x = _mm_unpacklo_epi32( x, exp );
6852
6853       // Subtract away the biases to deal with the IEEE-754 double precision
6854       // implicit 1.
6855       d = _mm_sub_pd( (__m128d) x, bias );
6856
6857       // All conversions up to here are exact. The correctly rounded result is
6858       // calculated using the current rounding mode using the following
6859       // horizontal add.
6860       d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
6861       _mm_store_sd( &sd, d );   // Because we are returning doubles in XMM, this
6862                                 // store doesn't really need to be here (except
6863                                 // maybe to zero the other double)
6864       return sd;
6865     }
6866   */
6867
6868   DebugLoc dl = Op.getDebugLoc();
6869   LLVMContext *Context = DAG.getContext();
6870
6871   // Build some magic constants.
6872   std::vector<Constant*> CV0;
6873   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
6874   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
6875   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6876   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6877   Constant *C0 = ConstantVector::get(CV0);
6878   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
6879
6880   std::vector<Constant*> CV1;
6881   CV1.push_back(
6882     ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
6883   CV1.push_back(
6884     ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
6885   Constant *C1 = ConstantVector::get(CV1);
6886   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
6887
6888   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6889                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6890                                         Op.getOperand(0),
6891                                         DAG.getIntPtrConstant(1)));
6892   SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6893                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6894                                         Op.getOperand(0),
6895                                         DAG.getIntPtrConstant(0)));
6896   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
6897   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
6898                               MachinePointerInfo::getConstantPool(),
6899                               false, false, 16);
6900   SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
6901   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
6902   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
6903                               MachinePointerInfo::getConstantPool(),
6904                               false, false, 16);
6905   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
6906
6907   // Add the halves; easiest way is to swap them into another reg first.
6908   int ShufMask[2] = { 1, -1 };
6909   SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
6910                                       DAG.getUNDEF(MVT::v2f64), ShufMask);
6911   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
6912   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
6913                      DAG.getIntPtrConstant(0));
6914 }
6915
6916 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
6917 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
6918                                                SelectionDAG &DAG) const {
6919   DebugLoc dl = Op.getDebugLoc();
6920   // FP constant to bias correct the final result.
6921   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
6922                                    MVT::f64);
6923
6924   // Load the 32-bit value into an XMM register.
6925   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6926                              DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6927                                          Op.getOperand(0),
6928                                          DAG.getIntPtrConstant(0)));
6929
6930   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6931                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
6932                      DAG.getIntPtrConstant(0));
6933
6934   // Or the load with the bias.
6935   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
6936                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6937                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6938                                                    MVT::v2f64, Load)),
6939                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6940                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6941                                                    MVT::v2f64, Bias)));
6942   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6943                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
6944                    DAG.getIntPtrConstant(0));
6945
6946   // Subtract the bias.
6947   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
6948
6949   // Handle final rounding.
6950   EVT DestVT = Op.getValueType();
6951
6952   if (DestVT.bitsLT(MVT::f64)) {
6953     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
6954                        DAG.getIntPtrConstant(0));
6955   } else if (DestVT.bitsGT(MVT::f64)) {
6956     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
6957   }
6958
6959   // Handle final rounding.
6960   return Sub;
6961 }
6962
6963 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
6964                                            SelectionDAG &DAG) const {
6965   SDValue N0 = Op.getOperand(0);
6966   DebugLoc dl = Op.getDebugLoc();
6967
6968   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
6969   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
6970   // the optimization here.
6971   if (DAG.SignBitIsZero(N0))
6972     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
6973
6974   EVT SrcVT = N0.getValueType();
6975   EVT DstVT = Op.getValueType();
6976   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
6977     return LowerUINT_TO_FP_i64(Op, DAG);
6978   else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
6979     return LowerUINT_TO_FP_i32(Op, DAG);
6980
6981   // Make a 64-bit buffer, and use it to build an FILD.
6982   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
6983   if (SrcVT == MVT::i32) {
6984     SDValue WordOff = DAG.getConstant(4, getPointerTy());
6985     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
6986                                      getPointerTy(), StackSlot, WordOff);
6987     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6988                                   StackSlot, MachinePointerInfo(),
6989                                   false, false, 0);
6990     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
6991                                   OffsetSlot, MachinePointerInfo(),
6992                                   false, false, 0);
6993     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
6994     return Fild;
6995   }
6996
6997   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
6998   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6999                                 StackSlot, MachinePointerInfo(),
7000                                false, false, 0);
7001   // For i64 source, we need to add the appropriate power of 2 if the input
7002   // was negative.  This is the same as the optimization in
7003   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
7004   // we must be careful to do the computation in x87 extended precision, not
7005   // in SSE. (The generic code can't know it's OK to do this, or how to.)
7006   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
7007   MachineMemOperand *MMO =
7008     DAG.getMachineFunction()
7009     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7010                           MachineMemOperand::MOLoad, 8, 8);
7011
7012   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
7013   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
7014   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
7015                                          MVT::i64, MMO);
7016
7017   APInt FF(32, 0x5F800000ULL);
7018
7019   // Check whether the sign bit is set.
7020   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
7021                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
7022                                  ISD::SETLT);
7023
7024   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
7025   SDValue FudgePtr = DAG.getConstantPool(
7026                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
7027                                          getPointerTy());
7028
7029   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
7030   SDValue Zero = DAG.getIntPtrConstant(0);
7031   SDValue Four = DAG.getIntPtrConstant(4);
7032   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
7033                                Zero, Four);
7034   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
7035
7036   // Load the value out, extending it from f32 to f80.
7037   // FIXME: Avoid the extend by constructing the right constant pool?
7038   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
7039                                  FudgePtr, MachinePointerInfo::getConstantPool(),
7040                                  MVT::f32, false, false, 4);
7041   // Extend everything to 80 bits to force it to be done on x87.
7042   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
7043   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
7044 }
7045
7046 std::pair<SDValue,SDValue> X86TargetLowering::
7047 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
7048   DebugLoc DL = Op.getDebugLoc();
7049
7050   EVT DstTy = Op.getValueType();
7051
7052   if (!IsSigned) {
7053     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
7054     DstTy = MVT::i64;
7055   }
7056
7057   assert(DstTy.getSimpleVT() <= MVT::i64 &&
7058          DstTy.getSimpleVT() >= MVT::i16 &&
7059          "Unknown FP_TO_SINT to lower!");
7060
7061   // These are really Legal.
7062   if (DstTy == MVT::i32 &&
7063       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7064     return std::make_pair(SDValue(), SDValue());
7065   if (Subtarget->is64Bit() &&
7066       DstTy == MVT::i64 &&
7067       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7068     return std::make_pair(SDValue(), SDValue());
7069
7070   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
7071   // stack slot.
7072   MachineFunction &MF = DAG.getMachineFunction();
7073   unsigned MemSize = DstTy.getSizeInBits()/8;
7074   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7075   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7076
7077
7078
7079   unsigned Opc;
7080   switch (DstTy.getSimpleVT().SimpleTy) {
7081   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
7082   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
7083   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
7084   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
7085   }
7086
7087   SDValue Chain = DAG.getEntryNode();
7088   SDValue Value = Op.getOperand(0);
7089   EVT TheVT = Op.getOperand(0).getValueType();
7090   if (isScalarFPTypeInSSEReg(TheVT)) {
7091     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
7092     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
7093                          MachinePointerInfo::getFixedStack(SSFI),
7094                          false, false, 0);
7095     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
7096     SDValue Ops[] = {
7097       Chain, StackSlot, DAG.getValueType(TheVT)
7098     };
7099
7100     MachineMemOperand *MMO =
7101       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7102                               MachineMemOperand::MOLoad, MemSize, MemSize);
7103     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
7104                                     DstTy, MMO);
7105     Chain = Value.getValue(1);
7106     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7107     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7108   }
7109
7110   MachineMemOperand *MMO =
7111     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7112                             MachineMemOperand::MOStore, MemSize, MemSize);
7113
7114   // Build the FP_TO_INT*_IN_MEM
7115   SDValue Ops[] = { Chain, Value, StackSlot };
7116   SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
7117                                          Ops, 3, DstTy, MMO);
7118
7119   return std::make_pair(FIST, StackSlot);
7120 }
7121
7122 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
7123                                            SelectionDAG &DAG) const {
7124   if (Op.getValueType().isVector())
7125     return SDValue();
7126
7127   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
7128   SDValue FIST = Vals.first, StackSlot = Vals.second;
7129   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
7130   if (FIST.getNode() == 0) return Op;
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::LowerFP_TO_UINT(SDValue Op,
7138                                            SelectionDAG &DAG) const {
7139   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
7140   SDValue FIST = Vals.first, StackSlot = Vals.second;
7141   assert(FIST.getNode() && "Unexpected failure");
7142
7143   // Load the result.
7144   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7145                      FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7146 }
7147
7148 SDValue X86TargetLowering::LowerFABS(SDValue Op,
7149                                      SelectionDAG &DAG) const {
7150   LLVMContext *Context = DAG.getContext();
7151   DebugLoc dl = Op.getDebugLoc();
7152   EVT VT = Op.getValueType();
7153   EVT EltVT = VT;
7154   if (VT.isVector())
7155     EltVT = VT.getVectorElementType();
7156   std::vector<Constant*> CV;
7157   if (EltVT == MVT::f64) {
7158     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
7159     CV.push_back(C);
7160     CV.push_back(C);
7161   } else {
7162     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
7163     CV.push_back(C);
7164     CV.push_back(C);
7165     CV.push_back(C);
7166     CV.push_back(C);
7167   }
7168   Constant *C = ConstantVector::get(CV);
7169   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7170   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7171                              MachinePointerInfo::getConstantPool(),
7172                              false, false, 16);
7173   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
7174 }
7175
7176 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
7177   LLVMContext *Context = DAG.getContext();
7178   DebugLoc dl = Op.getDebugLoc();
7179   EVT VT = Op.getValueType();
7180   EVT EltVT = VT;
7181   if (VT.isVector())
7182     EltVT = VT.getVectorElementType();
7183   std::vector<Constant*> CV;
7184   if (EltVT == MVT::f64) {
7185     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
7186     CV.push_back(C);
7187     CV.push_back(C);
7188   } else {
7189     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
7190     CV.push_back(C);
7191     CV.push_back(C);
7192     CV.push_back(C);
7193     CV.push_back(C);
7194   }
7195   Constant *C = ConstantVector::get(CV);
7196   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7197   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7198                              MachinePointerInfo::getConstantPool(),
7199                              false, false, 16);
7200   if (VT.isVector()) {
7201     return DAG.getNode(ISD::BITCAST, dl, VT,
7202                        DAG.getNode(ISD::XOR, dl, MVT::v2i64,
7203                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7204                                 Op.getOperand(0)),
7205                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask)));
7206   } else {
7207     return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
7208   }
7209 }
7210
7211 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
7212   LLVMContext *Context = DAG.getContext();
7213   SDValue Op0 = Op.getOperand(0);
7214   SDValue Op1 = Op.getOperand(1);
7215   DebugLoc dl = Op.getDebugLoc();
7216   EVT VT = Op.getValueType();
7217   EVT SrcVT = Op1.getValueType();
7218
7219   // If second operand is smaller, extend it first.
7220   if (SrcVT.bitsLT(VT)) {
7221     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
7222     SrcVT = VT;
7223   }
7224   // And if it is bigger, shrink it first.
7225   if (SrcVT.bitsGT(VT)) {
7226     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
7227     SrcVT = VT;
7228   }
7229
7230   // At this point the operands and the result should have the same
7231   // type, and that won't be f80 since that is not custom lowered.
7232
7233   // First get the sign bit of second operand.
7234   std::vector<Constant*> CV;
7235   if (SrcVT == MVT::f64) {
7236     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
7237     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7238   } else {
7239     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
7240     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7241     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7242     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7243   }
7244   Constant *C = ConstantVector::get(CV);
7245   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7246   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
7247                               MachinePointerInfo::getConstantPool(),
7248                               false, false, 16);
7249   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
7250
7251   // Shift sign bit right or left if the two operands have different types.
7252   if (SrcVT.bitsGT(VT)) {
7253     // Op0 is MVT::f32, Op1 is MVT::f64.
7254     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
7255     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
7256                           DAG.getConstant(32, MVT::i32));
7257     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
7258     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
7259                           DAG.getIntPtrConstant(0));
7260   }
7261
7262   // Clear first operand sign bit.
7263   CV.clear();
7264   if (VT == MVT::f64) {
7265     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
7266     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7267   } else {
7268     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
7269     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7270     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7271     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7272   }
7273   C = ConstantVector::get(CV);
7274   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7275   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7276                               MachinePointerInfo::getConstantPool(),
7277                               false, false, 16);
7278   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
7279
7280   // Or the value with the sign bit.
7281   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
7282 }
7283
7284 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
7285   SDValue N0 = Op.getOperand(0);
7286   DebugLoc dl = Op.getDebugLoc();
7287   EVT VT = Op.getValueType();
7288
7289   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
7290   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
7291                                   DAG.getConstant(1, VT));
7292   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
7293 }
7294
7295 /// Emit nodes that will be selected as "test Op0,Op0", or something
7296 /// equivalent.
7297 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
7298                                     SelectionDAG &DAG) const {
7299   DebugLoc dl = Op.getDebugLoc();
7300
7301   // CF and OF aren't always set the way we want. Determine which
7302   // of these we need.
7303   bool NeedCF = false;
7304   bool NeedOF = false;
7305   switch (X86CC) {
7306   default: break;
7307   case X86::COND_A: case X86::COND_AE:
7308   case X86::COND_B: case X86::COND_BE:
7309     NeedCF = true;
7310     break;
7311   case X86::COND_G: case X86::COND_GE:
7312   case X86::COND_L: case X86::COND_LE:
7313   case X86::COND_O: case X86::COND_NO:
7314     NeedOF = true;
7315     break;
7316   }
7317
7318   // See if we can use the EFLAGS value from the operand instead of
7319   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
7320   // we prove that the arithmetic won't overflow, we can't use OF or CF.
7321   if (Op.getResNo() != 0 || NeedOF || NeedCF)
7322     // Emit a CMP with 0, which is the TEST pattern.
7323     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
7324                        DAG.getConstant(0, Op.getValueType()));
7325
7326   unsigned Opcode = 0;
7327   unsigned NumOperands = 0;
7328   switch (Op.getNode()->getOpcode()) {
7329   case ISD::ADD:
7330     // Due to an isel shortcoming, be conservative if this add is likely to be
7331     // selected as part of a load-modify-store instruction. When the root node
7332     // in a match is a store, isel doesn't know how to remap non-chain non-flag
7333     // uses of other nodes in the match, such as the ADD in this case. This
7334     // leads to the ADD being left around and reselected, with the result being
7335     // two adds in the output.  Alas, even if none our users are stores, that
7336     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
7337     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
7338     // climbing the DAG back to the root, and it doesn't seem to be worth the
7339     // effort.
7340     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7341            UE = Op.getNode()->use_end(); UI != UE; ++UI)
7342       if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
7343         goto default_case;
7344
7345     if (ConstantSDNode *C =
7346         dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
7347       // An add of one will be selected as an INC.
7348       if (C->getAPIntValue() == 1) {
7349         Opcode = X86ISD::INC;
7350         NumOperands = 1;
7351         break;
7352       }
7353
7354       // An add of negative one (subtract of one) will be selected as a DEC.
7355       if (C->getAPIntValue().isAllOnesValue()) {
7356         Opcode = X86ISD::DEC;
7357         NumOperands = 1;
7358         break;
7359       }
7360     }
7361
7362     // Otherwise use a regular EFLAGS-setting add.
7363     Opcode = X86ISD::ADD;
7364     NumOperands = 2;
7365     break;
7366   case ISD::AND: {
7367     // If the primary and result isn't used, don't bother using X86ISD::AND,
7368     // because a TEST instruction will be better.
7369     bool NonFlagUse = false;
7370     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7371            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
7372       SDNode *User = *UI;
7373       unsigned UOpNo = UI.getOperandNo();
7374       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
7375         // Look pass truncate.
7376         UOpNo = User->use_begin().getOperandNo();
7377         User = *User->use_begin();
7378       }
7379
7380       if (User->getOpcode() != ISD::BRCOND &&
7381           User->getOpcode() != ISD::SETCC &&
7382           (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
7383         NonFlagUse = true;
7384         break;
7385       }
7386     }
7387
7388     if (!NonFlagUse)
7389       break;
7390   }
7391     // FALL THROUGH
7392   case ISD::SUB:
7393   case ISD::OR:
7394   case ISD::XOR:
7395     // Due to the ISEL shortcoming noted above, be conservative if this op is
7396     // likely to be selected as part of a load-modify-store instruction.
7397     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7398            UE = Op.getNode()->use_end(); UI != UE; ++UI)
7399       if (UI->getOpcode() == ISD::STORE)
7400         goto default_case;
7401
7402     // Otherwise use a regular EFLAGS-setting instruction.
7403     switch (Op.getNode()->getOpcode()) {
7404     default: llvm_unreachable("unexpected operator!");
7405     case ISD::SUB: Opcode = X86ISD::SUB; break;
7406     case ISD::OR:  Opcode = X86ISD::OR;  break;
7407     case ISD::XOR: Opcode = X86ISD::XOR; break;
7408     case ISD::AND: Opcode = X86ISD::AND; break;
7409     }
7410
7411     NumOperands = 2;
7412     break;
7413   case X86ISD::ADD:
7414   case X86ISD::SUB:
7415   case X86ISD::INC:
7416   case X86ISD::DEC:
7417   case X86ISD::OR:
7418   case X86ISD::XOR:
7419   case X86ISD::AND:
7420     return SDValue(Op.getNode(), 1);
7421   default:
7422   default_case:
7423     break;
7424   }
7425
7426   if (Opcode == 0)
7427     // Emit a CMP with 0, which is the TEST pattern.
7428     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
7429                        DAG.getConstant(0, Op.getValueType()));
7430
7431   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
7432   SmallVector<SDValue, 4> Ops;
7433   for (unsigned i = 0; i != NumOperands; ++i)
7434     Ops.push_back(Op.getOperand(i));
7435
7436   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
7437   DAG.ReplaceAllUsesWith(Op, New);
7438   return SDValue(New.getNode(), 1);
7439 }
7440
7441 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
7442 /// equivalent.
7443 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
7444                                    SelectionDAG &DAG) const {
7445   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
7446     if (C->getAPIntValue() == 0)
7447       return EmitTest(Op0, X86CC, DAG);
7448
7449   DebugLoc dl = Op0.getDebugLoc();
7450   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
7451 }
7452
7453 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
7454 /// if it's possible.
7455 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
7456                                      DebugLoc dl, SelectionDAG &DAG) const {
7457   SDValue Op0 = And.getOperand(0);
7458   SDValue Op1 = And.getOperand(1);
7459   if (Op0.getOpcode() == ISD::TRUNCATE)
7460     Op0 = Op0.getOperand(0);
7461   if (Op1.getOpcode() == ISD::TRUNCATE)
7462     Op1 = Op1.getOperand(0);
7463
7464   SDValue LHS, RHS;
7465   if (Op1.getOpcode() == ISD::SHL)
7466     std::swap(Op0, Op1);
7467   if (Op0.getOpcode() == ISD::SHL) {
7468     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
7469       if (And00C->getZExtValue() == 1) {
7470         // If we looked past a truncate, check that it's only truncating away
7471         // known zeros.
7472         unsigned BitWidth = Op0.getValueSizeInBits();
7473         unsigned AndBitWidth = And.getValueSizeInBits();
7474         if (BitWidth > AndBitWidth) {
7475           APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
7476           DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
7477           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
7478             return SDValue();
7479         }
7480         LHS = Op1;
7481         RHS = Op0.getOperand(1);
7482       }
7483   } else if (Op1.getOpcode() == ISD::Constant) {
7484     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
7485     SDValue AndLHS = Op0;
7486     if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
7487       LHS = AndLHS.getOperand(0);
7488       RHS = AndLHS.getOperand(1);
7489     }
7490   }
7491
7492   if (LHS.getNode()) {
7493     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
7494     // instruction.  Since the shift amount is in-range-or-undefined, we know
7495     // that doing a bittest on the i32 value is ok.  We extend to i32 because
7496     // the encoding for the i16 version is larger than the i32 version.
7497     // Also promote i16 to i32 for performance / code size reason.
7498     if (LHS.getValueType() == MVT::i8 ||
7499         LHS.getValueType() == MVT::i16)
7500       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
7501
7502     // If the operand types disagree, extend the shift amount to match.  Since
7503     // BT ignores high bits (like shifts) we can use anyextend.
7504     if (LHS.getValueType() != RHS.getValueType())
7505       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
7506
7507     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
7508     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
7509     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7510                        DAG.getConstant(Cond, MVT::i8), BT);
7511   }
7512
7513   return SDValue();
7514 }
7515
7516 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
7517   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
7518   SDValue Op0 = Op.getOperand(0);
7519   SDValue Op1 = Op.getOperand(1);
7520   DebugLoc dl = Op.getDebugLoc();
7521   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7522
7523   // Optimize to BT if possible.
7524   // Lower (X & (1 << N)) == 0 to BT(X, N).
7525   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
7526   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
7527   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
7528       Op1.getOpcode() == ISD::Constant &&
7529       cast<ConstantSDNode>(Op1)->isNullValue() &&
7530       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7531     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
7532     if (NewSetCC.getNode())
7533       return NewSetCC;
7534   }
7535
7536   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
7537   // these.
7538   if (Op1.getOpcode() == ISD::Constant &&
7539       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
7540        cast<ConstantSDNode>(Op1)->isNullValue()) &&
7541       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7542
7543     // If the input is a setcc, then reuse the input setcc or use a new one with
7544     // the inverted condition.
7545     if (Op0.getOpcode() == X86ISD::SETCC) {
7546       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
7547       bool Invert = (CC == ISD::SETNE) ^
7548         cast<ConstantSDNode>(Op1)->isNullValue();
7549       if (!Invert) return Op0;
7550
7551       CCode = X86::GetOppositeBranchCondition(CCode);
7552       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7553                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
7554     }
7555   }
7556
7557   bool isFP = Op1.getValueType().isFloatingPoint();
7558   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
7559   if (X86CC == X86::COND_INVALID)
7560     return SDValue();
7561
7562   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
7563   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7564                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
7565 }
7566
7567 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
7568   SDValue Cond;
7569   SDValue Op0 = Op.getOperand(0);
7570   SDValue Op1 = Op.getOperand(1);
7571   SDValue CC = Op.getOperand(2);
7572   EVT VT = Op.getValueType();
7573   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
7574   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
7575   DebugLoc dl = Op.getDebugLoc();
7576
7577   if (isFP) {
7578     unsigned SSECC = 8;
7579     EVT VT0 = Op0.getValueType();
7580     assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
7581     unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
7582     bool Swap = false;
7583
7584     switch (SetCCOpcode) {
7585     default: break;
7586     case ISD::SETOEQ:
7587     case ISD::SETEQ:  SSECC = 0; break;
7588     case ISD::SETOGT:
7589     case ISD::SETGT: Swap = true; // Fallthrough
7590     case ISD::SETLT:
7591     case ISD::SETOLT: SSECC = 1; break;
7592     case ISD::SETOGE:
7593     case ISD::SETGE: Swap = true; // Fallthrough
7594     case ISD::SETLE:
7595     case ISD::SETOLE: SSECC = 2; break;
7596     case ISD::SETUO:  SSECC = 3; break;
7597     case ISD::SETUNE:
7598     case ISD::SETNE:  SSECC = 4; break;
7599     case ISD::SETULE: Swap = true;
7600     case ISD::SETUGE: SSECC = 5; break;
7601     case ISD::SETULT: Swap = true;
7602     case ISD::SETUGT: SSECC = 6; break;
7603     case ISD::SETO:   SSECC = 7; break;
7604     }
7605     if (Swap)
7606       std::swap(Op0, Op1);
7607
7608     // In the two special cases we can't handle, emit two comparisons.
7609     if (SSECC == 8) {
7610       if (SetCCOpcode == ISD::SETUEQ) {
7611         SDValue UNORD, EQ;
7612         UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
7613         EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
7614         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
7615       }
7616       else if (SetCCOpcode == ISD::SETONE) {
7617         SDValue ORD, NEQ;
7618         ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
7619         NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
7620         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
7621       }
7622       llvm_unreachable("Illegal FP comparison");
7623     }
7624     // Handle all other FP comparisons here.
7625     return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
7626   }
7627
7628   // We are handling one of the integer comparisons here.  Since SSE only has
7629   // GT and EQ comparisons for integer, swapping operands and multiple
7630   // operations may be required for some comparisons.
7631   unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
7632   bool Swap = false, Invert = false, FlipSigns = false;
7633
7634   switch (VT.getSimpleVT().SimpleTy) {
7635   default: break;
7636   case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
7637   case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
7638   case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
7639   case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
7640   }
7641
7642   switch (SetCCOpcode) {
7643   default: break;
7644   case ISD::SETNE:  Invert = true;
7645   case ISD::SETEQ:  Opc = EQOpc; break;
7646   case ISD::SETLT:  Swap = true;
7647   case ISD::SETGT:  Opc = GTOpc; break;
7648   case ISD::SETGE:  Swap = true;
7649   case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
7650   case ISD::SETULT: Swap = true;
7651   case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
7652   case ISD::SETUGE: Swap = true;
7653   case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
7654   }
7655   if (Swap)
7656     std::swap(Op0, Op1);
7657
7658   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
7659   // bits of the inputs before performing those operations.
7660   if (FlipSigns) {
7661     EVT EltVT = VT.getVectorElementType();
7662     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
7663                                       EltVT);
7664     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
7665     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
7666                                     SignBits.size());
7667     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
7668     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
7669   }
7670
7671   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
7672
7673   // If the logical-not of the result is required, perform that now.
7674   if (Invert)
7675     Result = DAG.getNOT(dl, Result, VT);
7676
7677   return Result;
7678 }
7679
7680 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
7681 static bool isX86LogicalCmp(SDValue Op) {
7682   unsigned Opc = Op.getNode()->getOpcode();
7683   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
7684     return true;
7685   if (Op.getResNo() == 1 &&
7686       (Opc == X86ISD::ADD ||
7687        Opc == X86ISD::SUB ||
7688        Opc == X86ISD::ADC ||
7689        Opc == X86ISD::SBB ||
7690        Opc == X86ISD::SMUL ||
7691        Opc == X86ISD::UMUL ||
7692        Opc == X86ISD::INC ||
7693        Opc == X86ISD::DEC ||
7694        Opc == X86ISD::OR ||
7695        Opc == X86ISD::XOR ||
7696        Opc == X86ISD::AND))
7697     return true;
7698
7699   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
7700     return true;
7701
7702   return false;
7703 }
7704
7705 static bool isZero(SDValue V) {
7706   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7707   return C && C->isNullValue();
7708 }
7709
7710 static bool isAllOnes(SDValue V) {
7711   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7712   return C && C->isAllOnesValue();
7713 }
7714
7715 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
7716   bool addTest = true;
7717   SDValue Cond  = Op.getOperand(0);
7718   SDValue Op1 = Op.getOperand(1);
7719   SDValue Op2 = Op.getOperand(2);
7720   DebugLoc DL = Op.getDebugLoc();
7721   SDValue CC;
7722
7723   if (Cond.getOpcode() == ISD::SETCC) {
7724     SDValue NewCond = LowerSETCC(Cond, DAG);
7725     if (NewCond.getNode())
7726       Cond = NewCond;
7727   }
7728
7729   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
7730   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
7731   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
7732   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
7733   if (Cond.getOpcode() == X86ISD::SETCC &&
7734       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
7735       isZero(Cond.getOperand(1).getOperand(1))) {
7736     SDValue Cmp = Cond.getOperand(1);
7737
7738     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
7739
7740     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
7741         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
7742       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
7743
7744       SDValue CmpOp0 = Cmp.getOperand(0);
7745       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
7746                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
7747
7748       SDValue Res =   // Res = 0 or -1.
7749         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7750                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
7751
7752       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
7753         Res = DAG.getNOT(DL, Res, Res.getValueType());
7754
7755       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
7756       if (N2C == 0 || !N2C->isNullValue())
7757         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
7758       return Res;
7759     }
7760   }
7761
7762   // Look past (and (setcc_carry (cmp ...)), 1).
7763   if (Cond.getOpcode() == ISD::AND &&
7764       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7765     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7766     if (C && C->getAPIntValue() == 1)
7767       Cond = Cond.getOperand(0);
7768   }
7769
7770   // If condition flag is set by a X86ISD::CMP, then use it as the condition
7771   // setting operand in place of the X86ISD::SETCC.
7772   if (Cond.getOpcode() == X86ISD::SETCC ||
7773       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7774     CC = Cond.getOperand(0);
7775
7776     SDValue Cmp = Cond.getOperand(1);
7777     unsigned Opc = Cmp.getOpcode();
7778     EVT VT = Op.getValueType();
7779
7780     bool IllegalFPCMov = false;
7781     if (VT.isFloatingPoint() && !VT.isVector() &&
7782         !isScalarFPTypeInSSEReg(VT))  // FPStack?
7783       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
7784
7785     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
7786         Opc == X86ISD::BT) { // FIXME
7787       Cond = Cmp;
7788       addTest = false;
7789     }
7790   }
7791
7792   if (addTest) {
7793     // Look pass the truncate.
7794     if (Cond.getOpcode() == ISD::TRUNCATE)
7795       Cond = Cond.getOperand(0);
7796
7797     // We know the result of AND is compared against zero. Try to match
7798     // it to BT.
7799     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7800       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
7801       if (NewSetCC.getNode()) {
7802         CC = NewSetCC.getOperand(0);
7803         Cond = NewSetCC.getOperand(1);
7804         addTest = false;
7805       }
7806     }
7807   }
7808
7809   if (addTest) {
7810     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7811     Cond = EmitTest(Cond, X86::COND_NE, DAG);
7812   }
7813
7814   // a <  b ? -1 :  0 -> RES = ~setcc_carry
7815   // a <  b ?  0 : -1 -> RES = setcc_carry
7816   // a >= b ? -1 :  0 -> RES = setcc_carry
7817   // a >= b ?  0 : -1 -> RES = ~setcc_carry
7818   if (Cond.getOpcode() == X86ISD::CMP) {
7819     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
7820
7821     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
7822         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
7823       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7824                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
7825       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
7826         return DAG.getNOT(DL, Res, Res.getValueType());
7827       return Res;
7828     }
7829   }
7830
7831   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
7832   // condition is true.
7833   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
7834   SDValue Ops[] = { Op2, Op1, CC, Cond };
7835   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
7836 }
7837
7838 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
7839 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
7840 // from the AND / OR.
7841 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
7842   Opc = Op.getOpcode();
7843   if (Opc != ISD::OR && Opc != ISD::AND)
7844     return false;
7845   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7846           Op.getOperand(0).hasOneUse() &&
7847           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
7848           Op.getOperand(1).hasOneUse());
7849 }
7850
7851 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
7852 // 1 and that the SETCC node has a single use.
7853 static bool isXor1OfSetCC(SDValue Op) {
7854   if (Op.getOpcode() != ISD::XOR)
7855     return false;
7856   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7857   if (N1C && N1C->getAPIntValue() == 1) {
7858     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7859       Op.getOperand(0).hasOneUse();
7860   }
7861   return false;
7862 }
7863
7864 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
7865   bool addTest = true;
7866   SDValue Chain = Op.getOperand(0);
7867   SDValue Cond  = Op.getOperand(1);
7868   SDValue Dest  = Op.getOperand(2);
7869   DebugLoc dl = Op.getDebugLoc();
7870   SDValue CC;
7871
7872   if (Cond.getOpcode() == ISD::SETCC) {
7873     SDValue NewCond = LowerSETCC(Cond, DAG);
7874     if (NewCond.getNode())
7875       Cond = NewCond;
7876   }
7877 #if 0
7878   // FIXME: LowerXALUO doesn't handle these!!
7879   else if (Cond.getOpcode() == X86ISD::ADD  ||
7880            Cond.getOpcode() == X86ISD::SUB  ||
7881            Cond.getOpcode() == X86ISD::SMUL ||
7882            Cond.getOpcode() == X86ISD::UMUL)
7883     Cond = LowerXALUO(Cond, DAG);
7884 #endif
7885
7886   // Look pass (and (setcc_carry (cmp ...)), 1).
7887   if (Cond.getOpcode() == ISD::AND &&
7888       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7889     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7890     if (C && C->getAPIntValue() == 1)
7891       Cond = Cond.getOperand(0);
7892   }
7893
7894   // If condition flag is set by a X86ISD::CMP, then use it as the condition
7895   // setting operand in place of the X86ISD::SETCC.
7896   if (Cond.getOpcode() == X86ISD::SETCC ||
7897       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7898     CC = Cond.getOperand(0);
7899
7900     SDValue Cmp = Cond.getOperand(1);
7901     unsigned Opc = Cmp.getOpcode();
7902     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
7903     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
7904       Cond = Cmp;
7905       addTest = false;
7906     } else {
7907       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
7908       default: break;
7909       case X86::COND_O:
7910       case X86::COND_B:
7911         // These can only come from an arithmetic instruction with overflow,
7912         // e.g. SADDO, UADDO.
7913         Cond = Cond.getNode()->getOperand(1);
7914         addTest = false;
7915         break;
7916       }
7917     }
7918   } else {
7919     unsigned CondOpc;
7920     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
7921       SDValue Cmp = Cond.getOperand(0).getOperand(1);
7922       if (CondOpc == ISD::OR) {
7923         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
7924         // two branches instead of an explicit OR instruction with a
7925         // separate test.
7926         if (Cmp == Cond.getOperand(1).getOperand(1) &&
7927             isX86LogicalCmp(Cmp)) {
7928           CC = Cond.getOperand(0).getOperand(0);
7929           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7930                               Chain, Dest, CC, Cmp);
7931           CC = Cond.getOperand(1).getOperand(0);
7932           Cond = Cmp;
7933           addTest = false;
7934         }
7935       } else { // ISD::AND
7936         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
7937         // two branches instead of an explicit AND instruction with a
7938         // separate test. However, we only do this if this block doesn't
7939         // have a fall-through edge, because this requires an explicit
7940         // jmp when the condition is false.
7941         if (Cmp == Cond.getOperand(1).getOperand(1) &&
7942             isX86LogicalCmp(Cmp) &&
7943             Op.getNode()->hasOneUse()) {
7944           X86::CondCode CCode =
7945             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7946           CCode = X86::GetOppositeBranchCondition(CCode);
7947           CC = DAG.getConstant(CCode, MVT::i8);
7948           SDNode *User = *Op.getNode()->use_begin();
7949           // Look for an unconditional branch following this conditional branch.
7950           // We need this because we need to reverse the successors in order
7951           // to implement FCMP_OEQ.
7952           if (User->getOpcode() == ISD::BR) {
7953             SDValue FalseBB = User->getOperand(1);
7954             SDNode *NewBR =
7955               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
7956             assert(NewBR == User);
7957             (void)NewBR;
7958             Dest = FalseBB;
7959
7960             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7961                                 Chain, Dest, CC, Cmp);
7962             X86::CondCode CCode =
7963               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
7964             CCode = X86::GetOppositeBranchCondition(CCode);
7965             CC = DAG.getConstant(CCode, MVT::i8);
7966             Cond = Cmp;
7967             addTest = false;
7968           }
7969         }
7970       }
7971     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
7972       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
7973       // It should be transformed during dag combiner except when the condition
7974       // is set by a arithmetics with overflow node.
7975       X86::CondCode CCode =
7976         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7977       CCode = X86::GetOppositeBranchCondition(CCode);
7978       CC = DAG.getConstant(CCode, MVT::i8);
7979       Cond = Cond.getOperand(0).getOperand(1);
7980       addTest = false;
7981     }
7982   }
7983
7984   if (addTest) {
7985     // Look pass the truncate.
7986     if (Cond.getOpcode() == ISD::TRUNCATE)
7987       Cond = Cond.getOperand(0);
7988
7989     // We know the result of AND is compared against zero. Try to match
7990     // it to BT.
7991     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7992       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
7993       if (NewSetCC.getNode()) {
7994         CC = NewSetCC.getOperand(0);
7995         Cond = NewSetCC.getOperand(1);
7996         addTest = false;
7997       }
7998     }
7999   }
8000
8001   if (addTest) {
8002     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8003     Cond = EmitTest(Cond, X86::COND_NE, DAG);
8004   }
8005   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8006                      Chain, Dest, CC, Cond);
8007 }
8008
8009
8010 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
8011 // Calls to _alloca is needed to probe the stack when allocating more than 4k
8012 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
8013 // that the guard pages used by the OS virtual memory manager are allocated in
8014 // correct sequence.
8015 SDValue
8016 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
8017                                            SelectionDAG &DAG) const {
8018   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows()) &&
8019          "This should be used only on Windows targets");
8020   assert(!Subtarget->isTargetEnvMacho());
8021   DebugLoc dl = Op.getDebugLoc();
8022
8023   // Get the inputs.
8024   SDValue Chain = Op.getOperand(0);
8025   SDValue Size  = Op.getOperand(1);
8026   // FIXME: Ensure alignment here
8027
8028   SDValue Flag;
8029
8030   EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
8031   unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
8032
8033   Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
8034   Flag = Chain.getValue(1);
8035
8036   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8037
8038   Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
8039   Flag = Chain.getValue(1);
8040
8041   Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
8042
8043   SDValue Ops1[2] = { Chain.getValue(0), Chain };
8044   return DAG.getMergeValues(Ops1, 2, dl);
8045 }
8046
8047 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
8048   MachineFunction &MF = DAG.getMachineFunction();
8049   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
8050
8051   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
8052   DebugLoc DL = Op.getDebugLoc();
8053
8054   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
8055     // vastart just stores the address of the VarArgsFrameIndex slot into the
8056     // memory location argument.
8057     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
8058                                    getPointerTy());
8059     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
8060                         MachinePointerInfo(SV), false, false, 0);
8061   }
8062
8063   // __va_list_tag:
8064   //   gp_offset         (0 - 6 * 8)
8065   //   fp_offset         (48 - 48 + 8 * 16)
8066   //   overflow_arg_area (point to parameters coming in memory).
8067   //   reg_save_area
8068   SmallVector<SDValue, 8> MemOps;
8069   SDValue FIN = Op.getOperand(1);
8070   // Store gp_offset
8071   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
8072                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
8073                                                MVT::i32),
8074                                FIN, MachinePointerInfo(SV), false, false, 0);
8075   MemOps.push_back(Store);
8076
8077   // Store fp_offset
8078   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8079                     FIN, DAG.getIntPtrConstant(4));
8080   Store = DAG.getStore(Op.getOperand(0), DL,
8081                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
8082                                        MVT::i32),
8083                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
8084   MemOps.push_back(Store);
8085
8086   // Store ptr to overflow_arg_area
8087   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8088                     FIN, DAG.getIntPtrConstant(4));
8089   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
8090                                     getPointerTy());
8091   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
8092                        MachinePointerInfo(SV, 8),
8093                        false, false, 0);
8094   MemOps.push_back(Store);
8095
8096   // Store ptr to reg_save_area.
8097   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8098                     FIN, DAG.getIntPtrConstant(8));
8099   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
8100                                     getPointerTy());
8101   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
8102                        MachinePointerInfo(SV, 16), false, false, 0);
8103   MemOps.push_back(Store);
8104   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
8105                      &MemOps[0], MemOps.size());
8106 }
8107
8108 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
8109   assert(Subtarget->is64Bit() &&
8110          "LowerVAARG only handles 64-bit va_arg!");
8111   assert((Subtarget->isTargetLinux() ||
8112           Subtarget->isTargetDarwin()) &&
8113           "Unhandled target in LowerVAARG");
8114   assert(Op.getNode()->getNumOperands() == 4);
8115   SDValue Chain = Op.getOperand(0);
8116   SDValue SrcPtr = Op.getOperand(1);
8117   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
8118   unsigned Align = Op.getConstantOperandVal(3);
8119   DebugLoc dl = Op.getDebugLoc();
8120
8121   EVT ArgVT = Op.getNode()->getValueType(0);
8122   const Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
8123   uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
8124   uint8_t ArgMode;
8125
8126   // Decide which area this value should be read from.
8127   // TODO: Implement the AMD64 ABI in its entirety. This simple
8128   // selection mechanism works only for the basic types.
8129   if (ArgVT == MVT::f80) {
8130     llvm_unreachable("va_arg for f80 not yet implemented");
8131   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
8132     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
8133   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
8134     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
8135   } else {
8136     llvm_unreachable("Unhandled argument type in LowerVAARG");
8137   }
8138
8139   if (ArgMode == 2) {
8140     // Sanity Check: Make sure using fp_offset makes sense.
8141     assert(!UseSoftFloat &&
8142            !(DAG.getMachineFunction()
8143                 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
8144            Subtarget->hasXMM());
8145   }
8146
8147   // Insert VAARG_64 node into the DAG
8148   // VAARG_64 returns two values: Variable Argument Address, Chain
8149   SmallVector<SDValue, 11> InstOps;
8150   InstOps.push_back(Chain);
8151   InstOps.push_back(SrcPtr);
8152   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
8153   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
8154   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
8155   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
8156   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
8157                                           VTs, &InstOps[0], InstOps.size(),
8158                                           MVT::i64,
8159                                           MachinePointerInfo(SV),
8160                                           /*Align=*/0,
8161                                           /*Volatile=*/false,
8162                                           /*ReadMem=*/true,
8163                                           /*WriteMem=*/true);
8164   Chain = VAARG.getValue(1);
8165
8166   // Load the next argument and return it
8167   return DAG.getLoad(ArgVT, dl,
8168                      Chain,
8169                      VAARG,
8170                      MachinePointerInfo(),
8171                      false, false, 0);
8172 }
8173
8174 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
8175   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
8176   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
8177   SDValue Chain = Op.getOperand(0);
8178   SDValue DstPtr = Op.getOperand(1);
8179   SDValue SrcPtr = Op.getOperand(2);
8180   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
8181   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8182   DebugLoc DL = Op.getDebugLoc();
8183
8184   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
8185                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
8186                        false,
8187                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
8188 }
8189
8190 SDValue
8191 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
8192   DebugLoc dl = Op.getDebugLoc();
8193   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8194   switch (IntNo) {
8195   default: return SDValue();    // Don't custom lower most intrinsics.
8196   // Comparison intrinsics.
8197   case Intrinsic::x86_sse_comieq_ss:
8198   case Intrinsic::x86_sse_comilt_ss:
8199   case Intrinsic::x86_sse_comile_ss:
8200   case Intrinsic::x86_sse_comigt_ss:
8201   case Intrinsic::x86_sse_comige_ss:
8202   case Intrinsic::x86_sse_comineq_ss:
8203   case Intrinsic::x86_sse_ucomieq_ss:
8204   case Intrinsic::x86_sse_ucomilt_ss:
8205   case Intrinsic::x86_sse_ucomile_ss:
8206   case Intrinsic::x86_sse_ucomigt_ss:
8207   case Intrinsic::x86_sse_ucomige_ss:
8208   case Intrinsic::x86_sse_ucomineq_ss:
8209   case Intrinsic::x86_sse2_comieq_sd:
8210   case Intrinsic::x86_sse2_comilt_sd:
8211   case Intrinsic::x86_sse2_comile_sd:
8212   case Intrinsic::x86_sse2_comigt_sd:
8213   case Intrinsic::x86_sse2_comige_sd:
8214   case Intrinsic::x86_sse2_comineq_sd:
8215   case Intrinsic::x86_sse2_ucomieq_sd:
8216   case Intrinsic::x86_sse2_ucomilt_sd:
8217   case Intrinsic::x86_sse2_ucomile_sd:
8218   case Intrinsic::x86_sse2_ucomigt_sd:
8219   case Intrinsic::x86_sse2_ucomige_sd:
8220   case Intrinsic::x86_sse2_ucomineq_sd: {
8221     unsigned Opc = 0;
8222     ISD::CondCode CC = ISD::SETCC_INVALID;
8223     switch (IntNo) {
8224     default: break;
8225     case Intrinsic::x86_sse_comieq_ss:
8226     case Intrinsic::x86_sse2_comieq_sd:
8227       Opc = X86ISD::COMI;
8228       CC = ISD::SETEQ;
8229       break;
8230     case Intrinsic::x86_sse_comilt_ss:
8231     case Intrinsic::x86_sse2_comilt_sd:
8232       Opc = X86ISD::COMI;
8233       CC = ISD::SETLT;
8234       break;
8235     case Intrinsic::x86_sse_comile_ss:
8236     case Intrinsic::x86_sse2_comile_sd:
8237       Opc = X86ISD::COMI;
8238       CC = ISD::SETLE;
8239       break;
8240     case Intrinsic::x86_sse_comigt_ss:
8241     case Intrinsic::x86_sse2_comigt_sd:
8242       Opc = X86ISD::COMI;
8243       CC = ISD::SETGT;
8244       break;
8245     case Intrinsic::x86_sse_comige_ss:
8246     case Intrinsic::x86_sse2_comige_sd:
8247       Opc = X86ISD::COMI;
8248       CC = ISD::SETGE;
8249       break;
8250     case Intrinsic::x86_sse_comineq_ss:
8251     case Intrinsic::x86_sse2_comineq_sd:
8252       Opc = X86ISD::COMI;
8253       CC = ISD::SETNE;
8254       break;
8255     case Intrinsic::x86_sse_ucomieq_ss:
8256     case Intrinsic::x86_sse2_ucomieq_sd:
8257       Opc = X86ISD::UCOMI;
8258       CC = ISD::SETEQ;
8259       break;
8260     case Intrinsic::x86_sse_ucomilt_ss:
8261     case Intrinsic::x86_sse2_ucomilt_sd:
8262       Opc = X86ISD::UCOMI;
8263       CC = ISD::SETLT;
8264       break;
8265     case Intrinsic::x86_sse_ucomile_ss:
8266     case Intrinsic::x86_sse2_ucomile_sd:
8267       Opc = X86ISD::UCOMI;
8268       CC = ISD::SETLE;
8269       break;
8270     case Intrinsic::x86_sse_ucomigt_ss:
8271     case Intrinsic::x86_sse2_ucomigt_sd:
8272       Opc = X86ISD::UCOMI;
8273       CC = ISD::SETGT;
8274       break;
8275     case Intrinsic::x86_sse_ucomige_ss:
8276     case Intrinsic::x86_sse2_ucomige_sd:
8277       Opc = X86ISD::UCOMI;
8278       CC = ISD::SETGE;
8279       break;
8280     case Intrinsic::x86_sse_ucomineq_ss:
8281     case Intrinsic::x86_sse2_ucomineq_sd:
8282       Opc = X86ISD::UCOMI;
8283       CC = ISD::SETNE;
8284       break;
8285     }
8286
8287     SDValue LHS = Op.getOperand(1);
8288     SDValue RHS = Op.getOperand(2);
8289     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
8290     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
8291     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
8292     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8293                                 DAG.getConstant(X86CC, MVT::i8), Cond);
8294     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
8295   }
8296   // ptest and testp intrinsics. The intrinsic these come from are designed to
8297   // return an integer value, not just an instruction so lower it to the ptest
8298   // or testp pattern and a setcc for the result.
8299   case Intrinsic::x86_sse41_ptestz:
8300   case Intrinsic::x86_sse41_ptestc:
8301   case Intrinsic::x86_sse41_ptestnzc:
8302   case Intrinsic::x86_avx_ptestz_256:
8303   case Intrinsic::x86_avx_ptestc_256:
8304   case Intrinsic::x86_avx_ptestnzc_256:
8305   case Intrinsic::x86_avx_vtestz_ps:
8306   case Intrinsic::x86_avx_vtestc_ps:
8307   case Intrinsic::x86_avx_vtestnzc_ps:
8308   case Intrinsic::x86_avx_vtestz_pd:
8309   case Intrinsic::x86_avx_vtestc_pd:
8310   case Intrinsic::x86_avx_vtestnzc_pd:
8311   case Intrinsic::x86_avx_vtestz_ps_256:
8312   case Intrinsic::x86_avx_vtestc_ps_256:
8313   case Intrinsic::x86_avx_vtestnzc_ps_256:
8314   case Intrinsic::x86_avx_vtestz_pd_256:
8315   case Intrinsic::x86_avx_vtestc_pd_256:
8316   case Intrinsic::x86_avx_vtestnzc_pd_256: {
8317     bool IsTestPacked = false;
8318     unsigned X86CC = 0;
8319     switch (IntNo) {
8320     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
8321     case Intrinsic::x86_avx_vtestz_ps:
8322     case Intrinsic::x86_avx_vtestz_pd:
8323     case Intrinsic::x86_avx_vtestz_ps_256:
8324     case Intrinsic::x86_avx_vtestz_pd_256:
8325       IsTestPacked = true; // Fallthrough
8326     case Intrinsic::x86_sse41_ptestz:
8327     case Intrinsic::x86_avx_ptestz_256:
8328       // ZF = 1
8329       X86CC = X86::COND_E;
8330       break;
8331     case Intrinsic::x86_avx_vtestc_ps:
8332     case Intrinsic::x86_avx_vtestc_pd:
8333     case Intrinsic::x86_avx_vtestc_ps_256:
8334     case Intrinsic::x86_avx_vtestc_pd_256:
8335       IsTestPacked = true; // Fallthrough
8336     case Intrinsic::x86_sse41_ptestc:
8337     case Intrinsic::x86_avx_ptestc_256:
8338       // CF = 1
8339       X86CC = X86::COND_B;
8340       break;
8341     case Intrinsic::x86_avx_vtestnzc_ps:
8342     case Intrinsic::x86_avx_vtestnzc_pd:
8343     case Intrinsic::x86_avx_vtestnzc_ps_256:
8344     case Intrinsic::x86_avx_vtestnzc_pd_256:
8345       IsTestPacked = true; // Fallthrough
8346     case Intrinsic::x86_sse41_ptestnzc:
8347     case Intrinsic::x86_avx_ptestnzc_256:
8348       // ZF and CF = 0
8349       X86CC = X86::COND_A;
8350       break;
8351     }
8352
8353     SDValue LHS = Op.getOperand(1);
8354     SDValue RHS = Op.getOperand(2);
8355     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
8356     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
8357     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
8358     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
8359     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
8360   }
8361
8362   // Fix vector shift instructions where the last operand is a non-immediate
8363   // i32 value.
8364   case Intrinsic::x86_sse2_pslli_w:
8365   case Intrinsic::x86_sse2_pslli_d:
8366   case Intrinsic::x86_sse2_pslli_q:
8367   case Intrinsic::x86_sse2_psrli_w:
8368   case Intrinsic::x86_sse2_psrli_d:
8369   case Intrinsic::x86_sse2_psrli_q:
8370   case Intrinsic::x86_sse2_psrai_w:
8371   case Intrinsic::x86_sse2_psrai_d:
8372   case Intrinsic::x86_mmx_pslli_w:
8373   case Intrinsic::x86_mmx_pslli_d:
8374   case Intrinsic::x86_mmx_pslli_q:
8375   case Intrinsic::x86_mmx_psrli_w:
8376   case Intrinsic::x86_mmx_psrli_d:
8377   case Intrinsic::x86_mmx_psrli_q:
8378   case Intrinsic::x86_mmx_psrai_w:
8379   case Intrinsic::x86_mmx_psrai_d: {
8380     SDValue ShAmt = Op.getOperand(2);
8381     if (isa<ConstantSDNode>(ShAmt))
8382       return SDValue();
8383
8384     unsigned NewIntNo = 0;
8385     EVT ShAmtVT = MVT::v4i32;
8386     switch (IntNo) {
8387     case Intrinsic::x86_sse2_pslli_w:
8388       NewIntNo = Intrinsic::x86_sse2_psll_w;
8389       break;
8390     case Intrinsic::x86_sse2_pslli_d:
8391       NewIntNo = Intrinsic::x86_sse2_psll_d;
8392       break;
8393     case Intrinsic::x86_sse2_pslli_q:
8394       NewIntNo = Intrinsic::x86_sse2_psll_q;
8395       break;
8396     case Intrinsic::x86_sse2_psrli_w:
8397       NewIntNo = Intrinsic::x86_sse2_psrl_w;
8398       break;
8399     case Intrinsic::x86_sse2_psrli_d:
8400       NewIntNo = Intrinsic::x86_sse2_psrl_d;
8401       break;
8402     case Intrinsic::x86_sse2_psrli_q:
8403       NewIntNo = Intrinsic::x86_sse2_psrl_q;
8404       break;
8405     case Intrinsic::x86_sse2_psrai_w:
8406       NewIntNo = Intrinsic::x86_sse2_psra_w;
8407       break;
8408     case Intrinsic::x86_sse2_psrai_d:
8409       NewIntNo = Intrinsic::x86_sse2_psra_d;
8410       break;
8411     default: {
8412       ShAmtVT = MVT::v2i32;
8413       switch (IntNo) {
8414       case Intrinsic::x86_mmx_pslli_w:
8415         NewIntNo = Intrinsic::x86_mmx_psll_w;
8416         break;
8417       case Intrinsic::x86_mmx_pslli_d:
8418         NewIntNo = Intrinsic::x86_mmx_psll_d;
8419         break;
8420       case Intrinsic::x86_mmx_pslli_q:
8421         NewIntNo = Intrinsic::x86_mmx_psll_q;
8422         break;
8423       case Intrinsic::x86_mmx_psrli_w:
8424         NewIntNo = Intrinsic::x86_mmx_psrl_w;
8425         break;
8426       case Intrinsic::x86_mmx_psrli_d:
8427         NewIntNo = Intrinsic::x86_mmx_psrl_d;
8428         break;
8429       case Intrinsic::x86_mmx_psrli_q:
8430         NewIntNo = Intrinsic::x86_mmx_psrl_q;
8431         break;
8432       case Intrinsic::x86_mmx_psrai_w:
8433         NewIntNo = Intrinsic::x86_mmx_psra_w;
8434         break;
8435       case Intrinsic::x86_mmx_psrai_d:
8436         NewIntNo = Intrinsic::x86_mmx_psra_d;
8437         break;
8438       default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
8439       }
8440       break;
8441     }
8442     }
8443
8444     // The vector shift intrinsics with scalars uses 32b shift amounts but
8445     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
8446     // to be zero.
8447     SDValue ShOps[4];
8448     ShOps[0] = ShAmt;
8449     ShOps[1] = DAG.getConstant(0, MVT::i32);
8450     if (ShAmtVT == MVT::v4i32) {
8451       ShOps[2] = DAG.getUNDEF(MVT::i32);
8452       ShOps[3] = DAG.getUNDEF(MVT::i32);
8453       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
8454     } else {
8455       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
8456 // FIXME this must be lowered to get rid of the invalid type.
8457     }
8458
8459     EVT VT = Op.getValueType();
8460     ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
8461     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8462                        DAG.getConstant(NewIntNo, MVT::i32),
8463                        Op.getOperand(1), ShAmt);
8464   }
8465   }
8466 }
8467
8468 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
8469                                            SelectionDAG &DAG) const {
8470   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8471   MFI->setReturnAddressIsTaken(true);
8472
8473   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8474   DebugLoc dl = Op.getDebugLoc();
8475
8476   if (Depth > 0) {
8477     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
8478     SDValue Offset =
8479       DAG.getConstant(TD->getPointerSize(),
8480                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
8481     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8482                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
8483                                    FrameAddr, Offset),
8484                        MachinePointerInfo(), false, false, 0);
8485   }
8486
8487   // Just load the return address.
8488   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
8489   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8490                      RetAddrFI, MachinePointerInfo(), false, false, 0);
8491 }
8492
8493 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
8494   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8495   MFI->setFrameAddressIsTaken(true);
8496
8497   EVT VT = Op.getValueType();
8498   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
8499   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8500   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
8501   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
8502   while (Depth--)
8503     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
8504                             MachinePointerInfo(),
8505                             false, false, 0);
8506   return FrameAddr;
8507 }
8508
8509 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
8510                                                      SelectionDAG &DAG) const {
8511   return DAG.getIntPtrConstant(2*TD->getPointerSize());
8512 }
8513
8514 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
8515   MachineFunction &MF = DAG.getMachineFunction();
8516   SDValue Chain     = Op.getOperand(0);
8517   SDValue Offset    = Op.getOperand(1);
8518   SDValue Handler   = Op.getOperand(2);
8519   DebugLoc dl       = Op.getDebugLoc();
8520
8521   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
8522                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
8523                                      getPointerTy());
8524   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
8525
8526   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
8527                                   DAG.getIntPtrConstant(TD->getPointerSize()));
8528   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
8529   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
8530                        false, false, 0);
8531   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
8532   MF.getRegInfo().addLiveOut(StoreAddrReg);
8533
8534   return DAG.getNode(X86ISD::EH_RETURN, dl,
8535                      MVT::Other,
8536                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
8537 }
8538
8539 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
8540                                              SelectionDAG &DAG) const {
8541   SDValue Root = Op.getOperand(0);
8542   SDValue Trmp = Op.getOperand(1); // trampoline
8543   SDValue FPtr = Op.getOperand(2); // nested function
8544   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
8545   DebugLoc dl  = Op.getDebugLoc();
8546
8547   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8548
8549   if (Subtarget->is64Bit()) {
8550     SDValue OutChains[6];
8551
8552     // Large code-model.
8553     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
8554     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
8555
8556     const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
8557     const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
8558
8559     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
8560
8561     // Load the pointer to the nested function into R11.
8562     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
8563     SDValue Addr = Trmp;
8564     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8565                                 Addr, MachinePointerInfo(TrmpAddr),
8566                                 false, false, 0);
8567
8568     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8569                        DAG.getConstant(2, MVT::i64));
8570     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
8571                                 MachinePointerInfo(TrmpAddr, 2),
8572                                 false, false, 2);
8573
8574     // Load the 'nest' parameter value into R10.
8575     // R10 is specified in X86CallingConv.td
8576     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
8577     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8578                        DAG.getConstant(10, MVT::i64));
8579     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8580                                 Addr, MachinePointerInfo(TrmpAddr, 10),
8581                                 false, false, 0);
8582
8583     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8584                        DAG.getConstant(12, MVT::i64));
8585     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
8586                                 MachinePointerInfo(TrmpAddr, 12),
8587                                 false, false, 2);
8588
8589     // Jump to the nested function.
8590     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
8591     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8592                        DAG.getConstant(20, MVT::i64));
8593     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8594                                 Addr, MachinePointerInfo(TrmpAddr, 20),
8595                                 false, false, 0);
8596
8597     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
8598     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8599                        DAG.getConstant(22, MVT::i64));
8600     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
8601                                 MachinePointerInfo(TrmpAddr, 22),
8602                                 false, false, 0);
8603
8604     SDValue Ops[] =
8605       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
8606     return DAG.getMergeValues(Ops, 2, dl);
8607   } else {
8608     const Function *Func =
8609       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
8610     CallingConv::ID CC = Func->getCallingConv();
8611     unsigned NestReg;
8612
8613     switch (CC) {
8614     default:
8615       llvm_unreachable("Unsupported calling convention");
8616     case CallingConv::C:
8617     case CallingConv::X86_StdCall: {
8618       // Pass 'nest' parameter in ECX.
8619       // Must be kept in sync with X86CallingConv.td
8620       NestReg = X86::ECX;
8621
8622       // Check that ECX wasn't needed by an 'inreg' parameter.
8623       const FunctionType *FTy = Func->getFunctionType();
8624       const AttrListPtr &Attrs = Func->getAttributes();
8625
8626       if (!Attrs.isEmpty() && !Func->isVarArg()) {
8627         unsigned InRegCount = 0;
8628         unsigned Idx = 1;
8629
8630         for (FunctionType::param_iterator I = FTy->param_begin(),
8631              E = FTy->param_end(); I != E; ++I, ++Idx)
8632           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
8633             // FIXME: should only count parameters that are lowered to integers.
8634             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
8635
8636         if (InRegCount > 2) {
8637           report_fatal_error("Nest register in use - reduce number of inreg"
8638                              " parameters!");
8639         }
8640       }
8641       break;
8642     }
8643     case CallingConv::X86_FastCall:
8644     case CallingConv::X86_ThisCall:
8645     case CallingConv::Fast:
8646       // Pass 'nest' parameter in EAX.
8647       // Must be kept in sync with X86CallingConv.td
8648       NestReg = X86::EAX;
8649       break;
8650     }
8651
8652     SDValue OutChains[4];
8653     SDValue Addr, Disp;
8654
8655     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8656                        DAG.getConstant(10, MVT::i32));
8657     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
8658
8659     // This is storing the opcode for MOV32ri.
8660     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
8661     const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
8662     OutChains[0] = DAG.getStore(Root, dl,
8663                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
8664                                 Trmp, MachinePointerInfo(TrmpAddr),
8665                                 false, false, 0);
8666
8667     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8668                        DAG.getConstant(1, MVT::i32));
8669     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
8670                                 MachinePointerInfo(TrmpAddr, 1),
8671                                 false, false, 1);
8672
8673     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
8674     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8675                        DAG.getConstant(5, MVT::i32));
8676     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
8677                                 MachinePointerInfo(TrmpAddr, 5),
8678                                 false, false, 1);
8679
8680     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8681                        DAG.getConstant(6, MVT::i32));
8682     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
8683                                 MachinePointerInfo(TrmpAddr, 6),
8684                                 false, false, 1);
8685
8686     SDValue Ops[] =
8687       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
8688     return DAG.getMergeValues(Ops, 2, dl);
8689   }
8690 }
8691
8692 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8693                                             SelectionDAG &DAG) const {
8694   /*
8695    The rounding mode is in bits 11:10 of FPSR, and has the following
8696    settings:
8697      00 Round to nearest
8698      01 Round to -inf
8699      10 Round to +inf
8700      11 Round to 0
8701
8702   FLT_ROUNDS, on the other hand, expects the following:
8703     -1 Undefined
8704      0 Round to 0
8705      1 Round to nearest
8706      2 Round to +inf
8707      3 Round to -inf
8708
8709   To perform the conversion, we do:
8710     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
8711   */
8712
8713   MachineFunction &MF = DAG.getMachineFunction();
8714   const TargetMachine &TM = MF.getTarget();
8715   const TargetFrameLowering &TFI = *TM.getFrameLowering();
8716   unsigned StackAlignment = TFI.getStackAlignment();
8717   EVT VT = Op.getValueType();
8718   DebugLoc DL = Op.getDebugLoc();
8719
8720   // Save FP Control Word to stack slot
8721   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
8722   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8723
8724
8725   MachineMemOperand *MMO =
8726    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8727                            MachineMemOperand::MOStore, 2, 2);
8728
8729   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
8730   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
8731                                           DAG.getVTList(MVT::Other),
8732                                           Ops, 2, MVT::i16, MMO);
8733
8734   // Load FP Control Word from stack slot
8735   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
8736                             MachinePointerInfo(), false, false, 0);
8737
8738   // Transform as necessary
8739   SDValue CWD1 =
8740     DAG.getNode(ISD::SRL, DL, MVT::i16,
8741                 DAG.getNode(ISD::AND, DL, MVT::i16,
8742                             CWD, DAG.getConstant(0x800, MVT::i16)),
8743                 DAG.getConstant(11, MVT::i8));
8744   SDValue CWD2 =
8745     DAG.getNode(ISD::SRL, DL, MVT::i16,
8746                 DAG.getNode(ISD::AND, DL, MVT::i16,
8747                             CWD, DAG.getConstant(0x400, MVT::i16)),
8748                 DAG.getConstant(9, MVT::i8));
8749
8750   SDValue RetVal =
8751     DAG.getNode(ISD::AND, DL, MVT::i16,
8752                 DAG.getNode(ISD::ADD, DL, MVT::i16,
8753                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
8754                             DAG.getConstant(1, MVT::i16)),
8755                 DAG.getConstant(3, MVT::i16));
8756
8757
8758   return DAG.getNode((VT.getSizeInBits() < 16 ?
8759                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
8760 }
8761
8762 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
8763   EVT VT = Op.getValueType();
8764   EVT OpVT = VT;
8765   unsigned NumBits = VT.getSizeInBits();
8766   DebugLoc dl = Op.getDebugLoc();
8767
8768   Op = Op.getOperand(0);
8769   if (VT == MVT::i8) {
8770     // Zero extend to i32 since there is not an i8 bsr.
8771     OpVT = MVT::i32;
8772     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8773   }
8774
8775   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
8776   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8777   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
8778
8779   // If src is zero (i.e. bsr sets ZF), returns NumBits.
8780   SDValue Ops[] = {
8781     Op,
8782     DAG.getConstant(NumBits+NumBits-1, OpVT),
8783     DAG.getConstant(X86::COND_E, MVT::i8),
8784     Op.getValue(1)
8785   };
8786   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8787
8788   // Finally xor with NumBits-1.
8789   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
8790
8791   if (VT == MVT::i8)
8792     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8793   return Op;
8794 }
8795
8796 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
8797   EVT VT = Op.getValueType();
8798   EVT OpVT = VT;
8799   unsigned NumBits = VT.getSizeInBits();
8800   DebugLoc dl = Op.getDebugLoc();
8801
8802   Op = Op.getOperand(0);
8803   if (VT == MVT::i8) {
8804     OpVT = MVT::i32;
8805     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8806   }
8807
8808   // Issue a bsf (scan bits forward) which also sets EFLAGS.
8809   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8810   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
8811
8812   // If src is zero (i.e. bsf sets ZF), returns NumBits.
8813   SDValue Ops[] = {
8814     Op,
8815     DAG.getConstant(NumBits, OpVT),
8816     DAG.getConstant(X86::COND_E, MVT::i8),
8817     Op.getValue(1)
8818   };
8819   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8820
8821   if (VT == MVT::i8)
8822     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8823   return Op;
8824 }
8825
8826 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) const {
8827   EVT VT = Op.getValueType();
8828   assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
8829   DebugLoc dl = Op.getDebugLoc();
8830
8831   //  ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
8832   //  ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
8833   //  ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
8834   //  ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
8835   //  ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
8836   //
8837   //  AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
8838   //  AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
8839   //  return AloBlo + AloBhi + AhiBlo;
8840
8841   SDValue A = Op.getOperand(0);
8842   SDValue B = Op.getOperand(1);
8843
8844   SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8845                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8846                        A, DAG.getConstant(32, MVT::i32));
8847   SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8848                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8849                        B, DAG.getConstant(32, MVT::i32));
8850   SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8851                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8852                        A, B);
8853   SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8854                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8855                        A, Bhi);
8856   SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8857                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8858                        Ahi, B);
8859   AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8860                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8861                        AloBhi, DAG.getConstant(32, MVT::i32));
8862   AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8863                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8864                        AhiBlo, DAG.getConstant(32, MVT::i32));
8865   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
8866   Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
8867   return Res;
8868 }
8869
8870 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
8871
8872   EVT VT = Op.getValueType();
8873   DebugLoc dl = Op.getDebugLoc();
8874   SDValue R = Op.getOperand(0);
8875   SDValue Amt = Op.getOperand(1);
8876
8877   LLVMContext *Context = DAG.getContext();
8878
8879   // Must have SSE2.
8880   if (!Subtarget->hasSSE2()) return SDValue();
8881
8882   // Optimize shl/srl/sra with constant shift amount.
8883   if (isSplatVector(Amt.getNode())) {
8884     SDValue SclrAmt = Amt->getOperand(0);
8885     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
8886       uint64_t ShiftAmt = C->getZExtValue();
8887
8888       if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SHL)
8889        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8890                      DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8891                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8892
8893       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SHL)
8894        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8895                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8896                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8897
8898       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SHL)
8899        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8900                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8901                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8902
8903       if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SRL)
8904        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8905                      DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8906                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8907
8908       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRL)
8909        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8910                      DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
8911                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8912
8913       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRL)
8914        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8915                      DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
8916                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8917
8918       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRA)
8919        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8920                      DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
8921                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8922
8923       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRA)
8924        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8925                      DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
8926                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8927     }
8928   }
8929
8930   // Lower SHL with variable shift amount.
8931   // Cannot lower SHL without SSE4.1 or later.
8932   if (!Subtarget->hasSSE41()) return SDValue();
8933
8934   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
8935     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8936                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8937                      Op.getOperand(1), DAG.getConstant(23, MVT::i32));
8938
8939     ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
8940
8941     std::vector<Constant*> CV(4, CI);
8942     Constant *C = ConstantVector::get(CV);
8943     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8944     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8945                                  MachinePointerInfo::getConstantPool(),
8946                                  false, false, 16);
8947
8948     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
8949     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
8950     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
8951     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
8952   }
8953   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
8954     // a = a << 5;
8955     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8956                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8957                      Op.getOperand(1), DAG.getConstant(5, MVT::i32));
8958
8959     ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
8960     ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
8961
8962     std::vector<Constant*> CVM1(16, CM1);
8963     std::vector<Constant*> CVM2(16, CM2);
8964     Constant *C = ConstantVector::get(CVM1);
8965     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8966     SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8967                             MachinePointerInfo::getConstantPool(),
8968                             false, false, 16);
8969
8970     // r = pblendv(r, psllw(r & (char16)15, 4), a);
8971     M = DAG.getNode(ISD::AND, dl, VT, R, M);
8972     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8973                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8974                     DAG.getConstant(4, MVT::i32));
8975     R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
8976     // a += a
8977     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8978
8979     C = ConstantVector::get(CVM2);
8980     CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8981     M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8982                     MachinePointerInfo::getConstantPool(),
8983                     false, false, 16);
8984
8985     // r = pblendv(r, psllw(r & (char16)63, 2), a);
8986     M = DAG.getNode(ISD::AND, dl, VT, R, M);
8987     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8988                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8989                     DAG.getConstant(2, MVT::i32));
8990     R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
8991     // a += a
8992     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8993
8994     // return pblendv(r, r+r, a);
8995     R = DAG.getNode(X86ISD::PBLENDVB, dl, VT,
8996                     R, DAG.getNode(ISD::ADD, dl, VT, R, R), Op);
8997     return R;
8998   }
8999   return SDValue();
9000 }
9001
9002 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
9003   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
9004   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
9005   // looks for this combo and may remove the "setcc" instruction if the "setcc"
9006   // has only one use.
9007   SDNode *N = Op.getNode();
9008   SDValue LHS = N->getOperand(0);
9009   SDValue RHS = N->getOperand(1);
9010   unsigned BaseOp = 0;
9011   unsigned Cond = 0;
9012   DebugLoc DL = Op.getDebugLoc();
9013   switch (Op.getOpcode()) {
9014   default: llvm_unreachable("Unknown ovf instruction!");
9015   case ISD::SADDO:
9016     // A subtract of one will be selected as a INC. Note that INC doesn't
9017     // set CF, so we can't do this for UADDO.
9018     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
9019       if (C->isOne()) {
9020         BaseOp = X86ISD::INC;
9021         Cond = X86::COND_O;
9022         break;
9023       }
9024     BaseOp = X86ISD::ADD;
9025     Cond = X86::COND_O;
9026     break;
9027   case ISD::UADDO:
9028     BaseOp = X86ISD::ADD;
9029     Cond = X86::COND_B;
9030     break;
9031   case ISD::SSUBO:
9032     // A subtract of one will be selected as a DEC. Note that DEC doesn't
9033     // set CF, so we can't do this for USUBO.
9034     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
9035       if (C->isOne()) {
9036         BaseOp = X86ISD::DEC;
9037         Cond = X86::COND_O;
9038         break;
9039       }
9040     BaseOp = X86ISD::SUB;
9041     Cond = X86::COND_O;
9042     break;
9043   case ISD::USUBO:
9044     BaseOp = X86ISD::SUB;
9045     Cond = X86::COND_B;
9046     break;
9047   case ISD::SMULO:
9048     BaseOp = X86ISD::SMUL;
9049     Cond = X86::COND_O;
9050     break;
9051   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
9052     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
9053                                  MVT::i32);
9054     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
9055
9056     SDValue SetCC =
9057       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9058                   DAG.getConstant(X86::COND_O, MVT::i32),
9059                   SDValue(Sum.getNode(), 2));
9060
9061     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
9062     return Sum;
9063   }
9064   }
9065
9066   // Also sets EFLAGS.
9067   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
9068   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
9069
9070   SDValue SetCC =
9071     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
9072                 DAG.getConstant(Cond, MVT::i32),
9073                 SDValue(Sum.getNode(), 1));
9074
9075   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
9076   return Sum;
9077 }
9078
9079 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
9080   DebugLoc dl = Op.getDebugLoc();
9081
9082   // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
9083   // There isn't any reason to disable it if the target processor supports it.
9084   if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
9085     SDValue Chain = Op.getOperand(0);
9086     SDValue Zero = DAG.getConstant(0, MVT::i32);
9087     SDValue Ops[] = {
9088       DAG.getRegister(X86::ESP, MVT::i32), // Base
9089       DAG.getTargetConstant(1, MVT::i8),   // Scale
9090       DAG.getRegister(0, MVT::i32),        // Index
9091       DAG.getTargetConstant(0, MVT::i32),  // Disp
9092       DAG.getRegister(0, MVT::i32),        // Segment.
9093       Zero,
9094       Chain
9095     };
9096     SDNode *Res =
9097       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
9098                           array_lengthof(Ops));
9099     return SDValue(Res, 0);
9100   }
9101
9102   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
9103   if (!isDev)
9104     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
9105
9106   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9107   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
9108   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
9109   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
9110
9111   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
9112   if (!Op1 && !Op2 && !Op3 && Op4)
9113     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
9114
9115   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
9116   if (Op1 && !Op2 && !Op3 && !Op4)
9117     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
9118
9119   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
9120   //           (MFENCE)>;
9121   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
9122 }
9123
9124 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
9125   EVT T = Op.getValueType();
9126   DebugLoc DL = Op.getDebugLoc();
9127   unsigned Reg = 0;
9128   unsigned size = 0;
9129   switch(T.getSimpleVT().SimpleTy) {
9130   default:
9131     assert(false && "Invalid value type!");
9132   case MVT::i8:  Reg = X86::AL;  size = 1; break;
9133   case MVT::i16: Reg = X86::AX;  size = 2; break;
9134   case MVT::i32: Reg = X86::EAX; size = 4; break;
9135   case MVT::i64:
9136     assert(Subtarget->is64Bit() && "Node not type legal!");
9137     Reg = X86::RAX; size = 8;
9138     break;
9139   }
9140   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
9141                                     Op.getOperand(2), SDValue());
9142   SDValue Ops[] = { cpIn.getValue(0),
9143                     Op.getOperand(1),
9144                     Op.getOperand(3),
9145                     DAG.getTargetConstant(size, MVT::i8),
9146                     cpIn.getValue(1) };
9147   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9148   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
9149   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
9150                                            Ops, 5, T, MMO);
9151   SDValue cpOut =
9152     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
9153   return cpOut;
9154 }
9155
9156 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
9157                                                  SelectionDAG &DAG) const {
9158   assert(Subtarget->is64Bit() && "Result not type legalized?");
9159   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9160   SDValue TheChain = Op.getOperand(0);
9161   DebugLoc dl = Op.getDebugLoc();
9162   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
9163   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
9164   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
9165                                    rax.getValue(2));
9166   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
9167                             DAG.getConstant(32, MVT::i8));
9168   SDValue Ops[] = {
9169     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
9170     rdx.getValue(1)
9171   };
9172   return DAG.getMergeValues(Ops, 2, dl);
9173 }
9174
9175 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
9176                                             SelectionDAG &DAG) const {
9177   EVT SrcVT = Op.getOperand(0).getValueType();
9178   EVT DstVT = Op.getValueType();
9179   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
9180          Subtarget->hasMMX() && "Unexpected custom BITCAST");
9181   assert((DstVT == MVT::i64 ||
9182           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
9183          "Unexpected custom BITCAST");
9184   // i64 <=> MMX conversions are Legal.
9185   if (SrcVT==MVT::i64 && DstVT.isVector())
9186     return Op;
9187   if (DstVT==MVT::i64 && SrcVT.isVector())
9188     return Op;
9189   // MMX <=> MMX conversions are Legal.
9190   if (SrcVT.isVector() && DstVT.isVector())
9191     return Op;
9192   // All other conversions need to be expanded.
9193   return SDValue();
9194 }
9195
9196 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
9197   SDNode *Node = Op.getNode();
9198   DebugLoc dl = Node->getDebugLoc();
9199   EVT T = Node->getValueType(0);
9200   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
9201                               DAG.getConstant(0, T), Node->getOperand(2));
9202   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
9203                        cast<AtomicSDNode>(Node)->getMemoryVT(),
9204                        Node->getOperand(0),
9205                        Node->getOperand(1), negOp,
9206                        cast<AtomicSDNode>(Node)->getSrcValue(),
9207                        cast<AtomicSDNode>(Node)->getAlignment());
9208 }
9209
9210 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
9211   EVT VT = Op.getNode()->getValueType(0);
9212
9213   // Let legalize expand this if it isn't a legal type yet.
9214   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9215     return SDValue();
9216
9217   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
9218
9219   unsigned Opc;
9220   bool ExtraOp = false;
9221   switch (Op.getOpcode()) {
9222   default: assert(0 && "Invalid code");
9223   case ISD::ADDC: Opc = X86ISD::ADD; break;
9224   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
9225   case ISD::SUBC: Opc = X86ISD::SUB; break;
9226   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
9227   }
9228
9229   if (!ExtraOp)
9230     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
9231                        Op.getOperand(1));
9232   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
9233                      Op.getOperand(1), Op.getOperand(2));
9234 }
9235
9236 /// LowerOperation - Provide custom lowering hooks for some operations.
9237 ///
9238 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9239   switch (Op.getOpcode()) {
9240   default: llvm_unreachable("Should not custom lower this!");
9241   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op,DAG);
9242   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
9243   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
9244   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
9245   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
9246   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
9247   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
9248   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
9249   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op, DAG);
9250   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, DAG);
9251   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
9252   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
9253   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
9254   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
9255   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
9256   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
9257   case ISD::SHL_PARTS:
9258   case ISD::SRA_PARTS:
9259   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
9260   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
9261   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
9262   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
9263   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
9264   case ISD::FABS:               return LowerFABS(Op, DAG);
9265   case ISD::FNEG:               return LowerFNEG(Op, DAG);
9266   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
9267   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
9268   case ISD::SETCC:              return LowerSETCC(Op, DAG);
9269   case ISD::VSETCC:             return LowerVSETCC(Op, DAG);
9270   case ISD::SELECT:             return LowerSELECT(Op, DAG);
9271   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
9272   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
9273   case ISD::VASTART:            return LowerVASTART(Op, DAG);
9274   case ISD::VAARG:              return LowerVAARG(Op, DAG);
9275   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
9276   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
9277   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
9278   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
9279   case ISD::FRAME_TO_ARGS_OFFSET:
9280                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
9281   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
9282   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
9283   case ISD::TRAMPOLINE:         return LowerTRAMPOLINE(Op, DAG);
9284   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
9285   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
9286   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
9287   case ISD::MUL:                return LowerMUL_V2I64(Op, DAG);
9288   case ISD::SRA:
9289   case ISD::SRL:
9290   case ISD::SHL:                return LowerShift(Op, DAG);
9291   case ISD::SADDO:
9292   case ISD::UADDO:
9293   case ISD::SSUBO:
9294   case ISD::USUBO:
9295   case ISD::SMULO:
9296   case ISD::UMULO:              return LowerXALUO(Op, DAG);
9297   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
9298   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
9299   case ISD::ADDC:
9300   case ISD::ADDE:
9301   case ISD::SUBC:
9302   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
9303   }
9304 }
9305
9306 void X86TargetLowering::
9307 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
9308                         SelectionDAG &DAG, unsigned NewOp) const {
9309   EVT T = Node->getValueType(0);
9310   DebugLoc dl = Node->getDebugLoc();
9311   assert (T == MVT::i64 && "Only know how to expand i64 atomics");
9312
9313   SDValue Chain = Node->getOperand(0);
9314   SDValue In1 = Node->getOperand(1);
9315   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9316                              Node->getOperand(2), DAG.getIntPtrConstant(0));
9317   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9318                              Node->getOperand(2), DAG.getIntPtrConstant(1));
9319   SDValue Ops[] = { Chain, In1, In2L, In2H };
9320   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
9321   SDValue Result =
9322     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
9323                             cast<MemSDNode>(Node)->getMemOperand());
9324   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
9325   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
9326   Results.push_back(Result.getValue(2));
9327 }
9328
9329 /// ReplaceNodeResults - Replace a node with an illegal result type
9330 /// with a new node built out of custom code.
9331 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
9332                                            SmallVectorImpl<SDValue>&Results,
9333                                            SelectionDAG &DAG) const {
9334   DebugLoc dl = N->getDebugLoc();
9335   switch (N->getOpcode()) {
9336   default:
9337     assert(false && "Do not know how to custom type legalize this operation!");
9338     return;
9339   case ISD::ADDC:
9340   case ISD::ADDE:
9341   case ISD::SUBC:
9342   case ISD::SUBE:
9343     // We don't want to expand or promote these.
9344     return;
9345   case ISD::FP_TO_SINT: {
9346     std::pair<SDValue,SDValue> Vals =
9347         FP_TO_INTHelper(SDValue(N, 0), DAG, true);
9348     SDValue FIST = Vals.first, StackSlot = Vals.second;
9349     if (FIST.getNode() != 0) {
9350       EVT VT = N->getValueType(0);
9351       // Return a load from the stack slot.
9352       Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
9353                                     MachinePointerInfo(), false, false, 0));
9354     }
9355     return;
9356   }
9357   case ISD::READCYCLECOUNTER: {
9358     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9359     SDValue TheChain = N->getOperand(0);
9360     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
9361     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
9362                                      rd.getValue(1));
9363     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
9364                                      eax.getValue(2));
9365     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
9366     SDValue Ops[] = { eax, edx };
9367     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
9368     Results.push_back(edx.getValue(1));
9369     return;
9370   }
9371   case ISD::ATOMIC_CMP_SWAP: {
9372     EVT T = N->getValueType(0);
9373     assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
9374     SDValue cpInL, cpInH;
9375     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
9376                         DAG.getConstant(0, MVT::i32));
9377     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
9378                         DAG.getConstant(1, MVT::i32));
9379     cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
9380     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
9381                              cpInL.getValue(1));
9382     SDValue swapInL, swapInH;
9383     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
9384                           DAG.getConstant(0, MVT::i32));
9385     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
9386                           DAG.getConstant(1, MVT::i32));
9387     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
9388                                cpInH.getValue(1));
9389     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
9390                                swapInL.getValue(1));
9391     SDValue Ops[] = { swapInH.getValue(0),
9392                       N->getOperand(1),
9393                       swapInH.getValue(1) };
9394     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9395     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
9396     SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG8_DAG, dl, Tys,
9397                                              Ops, 3, T, MMO);
9398     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
9399                                         MVT::i32, Result.getValue(1));
9400     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
9401                                         MVT::i32, cpOutL.getValue(2));
9402     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
9403     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
9404     Results.push_back(cpOutH.getValue(1));
9405     return;
9406   }
9407   case ISD::ATOMIC_LOAD_ADD:
9408     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
9409     return;
9410   case ISD::ATOMIC_LOAD_AND:
9411     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
9412     return;
9413   case ISD::ATOMIC_LOAD_NAND:
9414     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
9415     return;
9416   case ISD::ATOMIC_LOAD_OR:
9417     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
9418     return;
9419   case ISD::ATOMIC_LOAD_SUB:
9420     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
9421     return;
9422   case ISD::ATOMIC_LOAD_XOR:
9423     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
9424     return;
9425   case ISD::ATOMIC_SWAP:
9426     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
9427     return;
9428   }
9429 }
9430
9431 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
9432   switch (Opcode) {
9433   default: return NULL;
9434   case X86ISD::BSF:                return "X86ISD::BSF";
9435   case X86ISD::BSR:                return "X86ISD::BSR";
9436   case X86ISD::SHLD:               return "X86ISD::SHLD";
9437   case X86ISD::SHRD:               return "X86ISD::SHRD";
9438   case X86ISD::FAND:               return "X86ISD::FAND";
9439   case X86ISD::FOR:                return "X86ISD::FOR";
9440   case X86ISD::FXOR:               return "X86ISD::FXOR";
9441   case X86ISD::FSRL:               return "X86ISD::FSRL";
9442   case X86ISD::FILD:               return "X86ISD::FILD";
9443   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
9444   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
9445   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
9446   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
9447   case X86ISD::FLD:                return "X86ISD::FLD";
9448   case X86ISD::FST:                return "X86ISD::FST";
9449   case X86ISD::CALL:               return "X86ISD::CALL";
9450   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
9451   case X86ISD::BT:                 return "X86ISD::BT";
9452   case X86ISD::CMP:                return "X86ISD::CMP";
9453   case X86ISD::COMI:               return "X86ISD::COMI";
9454   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
9455   case X86ISD::SETCC:              return "X86ISD::SETCC";
9456   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
9457   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
9458   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
9459   case X86ISD::CMOV:               return "X86ISD::CMOV";
9460   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
9461   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
9462   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
9463   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
9464   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
9465   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
9466   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
9467   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
9468   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
9469   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
9470   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
9471   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
9472   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
9473   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
9474   case X86ISD::PSIGNB:             return "X86ISD::PSIGNB";
9475   case X86ISD::PSIGNW:             return "X86ISD::PSIGNW";
9476   case X86ISD::PSIGND:             return "X86ISD::PSIGND";
9477   case X86ISD::PBLENDVB:           return "X86ISD::PBLENDVB";
9478   case X86ISD::FMAX:               return "X86ISD::FMAX";
9479   case X86ISD::FMIN:               return "X86ISD::FMIN";
9480   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
9481   case X86ISD::FRCP:               return "X86ISD::FRCP";
9482   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
9483   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
9484   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
9485   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
9486   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
9487   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
9488   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
9489   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
9490   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
9491   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
9492   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
9493   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
9494   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
9495   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
9496   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
9497   case X86ISD::VSHL:               return "X86ISD::VSHL";
9498   case X86ISD::VSRL:               return "X86ISD::VSRL";
9499   case X86ISD::CMPPD:              return "X86ISD::CMPPD";
9500   case X86ISD::CMPPS:              return "X86ISD::CMPPS";
9501   case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
9502   case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
9503   case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
9504   case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
9505   case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
9506   case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
9507   case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
9508   case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
9509   case X86ISD::ADD:                return "X86ISD::ADD";
9510   case X86ISD::SUB:                return "X86ISD::SUB";
9511   case X86ISD::ADC:                return "X86ISD::ADC";
9512   case X86ISD::SBB:                return "X86ISD::SBB";
9513   case X86ISD::SMUL:               return "X86ISD::SMUL";
9514   case X86ISD::UMUL:               return "X86ISD::UMUL";
9515   case X86ISD::INC:                return "X86ISD::INC";
9516   case X86ISD::DEC:                return "X86ISD::DEC";
9517   case X86ISD::OR:                 return "X86ISD::OR";
9518   case X86ISD::XOR:                return "X86ISD::XOR";
9519   case X86ISD::AND:                return "X86ISD::AND";
9520   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
9521   case X86ISD::PTEST:              return "X86ISD::PTEST";
9522   case X86ISD::TESTP:              return "X86ISD::TESTP";
9523   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
9524   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
9525   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
9526   case X86ISD::PSHUFHW_LD:         return "X86ISD::PSHUFHW_LD";
9527   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
9528   case X86ISD::PSHUFLW_LD:         return "X86ISD::PSHUFLW_LD";
9529   case X86ISD::SHUFPS:             return "X86ISD::SHUFPS";
9530   case X86ISD::SHUFPD:             return "X86ISD::SHUFPD";
9531   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
9532   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
9533   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
9534   case X86ISD::MOVHLPD:            return "X86ISD::MOVHLPD";
9535   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
9536   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
9537   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
9538   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
9539   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
9540   case X86ISD::MOVSHDUP_LD:        return "X86ISD::MOVSHDUP_LD";
9541   case X86ISD::MOVSLDUP_LD:        return "X86ISD::MOVSLDUP_LD";
9542   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
9543   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
9544   case X86ISD::UNPCKLPS:           return "X86ISD::UNPCKLPS";
9545   case X86ISD::UNPCKLPD:           return "X86ISD::UNPCKLPD";
9546   case X86ISD::VUNPCKLPS:          return "X86ISD::VUNPCKLPS";
9547   case X86ISD::VUNPCKLPD:          return "X86ISD::VUNPCKLPD";
9548   case X86ISD::VUNPCKLPSY:         return "X86ISD::VUNPCKLPSY";
9549   case X86ISD::VUNPCKLPDY:         return "X86ISD::VUNPCKLPDY";
9550   case X86ISD::UNPCKHPS:           return "X86ISD::UNPCKHPS";
9551   case X86ISD::UNPCKHPD:           return "X86ISD::UNPCKHPD";
9552   case X86ISD::PUNPCKLBW:          return "X86ISD::PUNPCKLBW";
9553   case X86ISD::PUNPCKLWD:          return "X86ISD::PUNPCKLWD";
9554   case X86ISD::PUNPCKLDQ:          return "X86ISD::PUNPCKLDQ";
9555   case X86ISD::PUNPCKLQDQ:         return "X86ISD::PUNPCKLQDQ";
9556   case X86ISD::PUNPCKHBW:          return "X86ISD::PUNPCKHBW";
9557   case X86ISD::PUNPCKHWD:          return "X86ISD::PUNPCKHWD";
9558   case X86ISD::PUNPCKHDQ:          return "X86ISD::PUNPCKHDQ";
9559   case X86ISD::PUNPCKHQDQ:         return "X86ISD::PUNPCKHQDQ";
9560   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
9561   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
9562   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
9563   }
9564 }
9565
9566 // isLegalAddressingMode - Return true if the addressing mode represented
9567 // by AM is legal for this target, for a load/store of the specified type.
9568 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
9569                                               const Type *Ty) const {
9570   // X86 supports extremely general addressing modes.
9571   CodeModel::Model M = getTargetMachine().getCodeModel();
9572   Reloc::Model R = getTargetMachine().getRelocationModel();
9573
9574   // X86 allows a sign-extended 32-bit immediate field as a displacement.
9575   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
9576     return false;
9577
9578   if (AM.BaseGV) {
9579     unsigned GVFlags =
9580       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
9581
9582     // If a reference to this global requires an extra load, we can't fold it.
9583     if (isGlobalStubReference(GVFlags))
9584       return false;
9585
9586     // If BaseGV requires a register for the PIC base, we cannot also have a
9587     // BaseReg specified.
9588     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
9589       return false;
9590
9591     // If lower 4G is not available, then we must use rip-relative addressing.
9592     if ((M != CodeModel::Small || R != Reloc::Static) &&
9593         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
9594       return false;
9595   }
9596
9597   switch (AM.Scale) {
9598   case 0:
9599   case 1:
9600   case 2:
9601   case 4:
9602   case 8:
9603     // These scales always work.
9604     break;
9605   case 3:
9606   case 5:
9607   case 9:
9608     // These scales are formed with basereg+scalereg.  Only accept if there is
9609     // no basereg yet.
9610     if (AM.HasBaseReg)
9611       return false;
9612     break;
9613   default:  // Other stuff never works.
9614     return false;
9615   }
9616
9617   return true;
9618 }
9619
9620
9621 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
9622   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9623     return false;
9624   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
9625   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
9626   if (NumBits1 <= NumBits2)
9627     return false;
9628   return true;
9629 }
9630
9631 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
9632   if (!VT1.isInteger() || !VT2.isInteger())
9633     return false;
9634   unsigned NumBits1 = VT1.getSizeInBits();
9635   unsigned NumBits2 = VT2.getSizeInBits();
9636   if (NumBits1 <= NumBits2)
9637     return false;
9638   return true;
9639 }
9640
9641 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
9642   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9643   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
9644 }
9645
9646 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
9647   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9648   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
9649 }
9650
9651 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
9652   // i16 instructions are longer (0x66 prefix) and potentially slower.
9653   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
9654 }
9655
9656 /// isShuffleMaskLegal - Targets can use this to indicate that they only
9657 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
9658 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
9659 /// are assumed to be legal.
9660 bool
9661 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
9662                                       EVT VT) const {
9663   // Very little shuffling can be done for 64-bit vectors right now.
9664   if (VT.getSizeInBits() == 64)
9665     return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
9666
9667   // FIXME: pshufb, blends, shifts.
9668   return (VT.getVectorNumElements() == 2 ||
9669           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
9670           isMOVLMask(M, VT) ||
9671           isSHUFPMask(M, VT) ||
9672           isPSHUFDMask(M, VT) ||
9673           isPSHUFHWMask(M, VT) ||
9674           isPSHUFLWMask(M, VT) ||
9675           isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
9676           isUNPCKLMask(M, VT) ||
9677           isUNPCKHMask(M, VT) ||
9678           isUNPCKL_v_undef_Mask(M, VT) ||
9679           isUNPCKH_v_undef_Mask(M, VT));
9680 }
9681
9682 bool
9683 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
9684                                           EVT VT) const {
9685   unsigned NumElts = VT.getVectorNumElements();
9686   // FIXME: This collection of masks seems suspect.
9687   if (NumElts == 2)
9688     return true;
9689   if (NumElts == 4 && VT.getSizeInBits() == 128) {
9690     return (isMOVLMask(Mask, VT)  ||
9691             isCommutedMOVLMask(Mask, VT, true) ||
9692             isSHUFPMask(Mask, VT) ||
9693             isCommutedSHUFPMask(Mask, VT));
9694   }
9695   return false;
9696 }
9697
9698 //===----------------------------------------------------------------------===//
9699 //                           X86 Scheduler Hooks
9700 //===----------------------------------------------------------------------===//
9701
9702 // private utility function
9703 MachineBasicBlock *
9704 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
9705                                                        MachineBasicBlock *MBB,
9706                                                        unsigned regOpc,
9707                                                        unsigned immOpc,
9708                                                        unsigned LoadOpc,
9709                                                        unsigned CXchgOpc,
9710                                                        unsigned notOpc,
9711                                                        unsigned EAXreg,
9712                                                        TargetRegisterClass *RC,
9713                                                        bool invSrc) const {
9714   // For the atomic bitwise operator, we generate
9715   //   thisMBB:
9716   //   newMBB:
9717   //     ld  t1 = [bitinstr.addr]
9718   //     op  t2 = t1, [bitinstr.val]
9719   //     mov EAX = t1
9720   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
9721   //     bz  newMBB
9722   //     fallthrough -->nextMBB
9723   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9724   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9725   MachineFunction::iterator MBBIter = MBB;
9726   ++MBBIter;
9727
9728   /// First build the CFG
9729   MachineFunction *F = MBB->getParent();
9730   MachineBasicBlock *thisMBB = MBB;
9731   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9732   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9733   F->insert(MBBIter, newMBB);
9734   F->insert(MBBIter, nextMBB);
9735
9736   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9737   nextMBB->splice(nextMBB->begin(), thisMBB,
9738                   llvm::next(MachineBasicBlock::iterator(bInstr)),
9739                   thisMBB->end());
9740   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9741
9742   // Update thisMBB to fall through to newMBB
9743   thisMBB->addSuccessor(newMBB);
9744
9745   // newMBB jumps to itself and fall through to nextMBB
9746   newMBB->addSuccessor(nextMBB);
9747   newMBB->addSuccessor(newMBB);
9748
9749   // Insert instructions into newMBB based on incoming instruction
9750   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9751          "unexpected number of operands");
9752   DebugLoc dl = bInstr->getDebugLoc();
9753   MachineOperand& destOper = bInstr->getOperand(0);
9754   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9755   int numArgs = bInstr->getNumOperands() - 1;
9756   for (int i=0; i < numArgs; ++i)
9757     argOpers[i] = &bInstr->getOperand(i+1);
9758
9759   // x86 address has 4 operands: base, index, scale, and displacement
9760   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9761   int valArgIndx = lastAddrIndx + 1;
9762
9763   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9764   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
9765   for (int i=0; i <= lastAddrIndx; ++i)
9766     (*MIB).addOperand(*argOpers[i]);
9767
9768   unsigned tt = F->getRegInfo().createVirtualRegister(RC);
9769   if (invSrc) {
9770     MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
9771   }
9772   else
9773     tt = t1;
9774
9775   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9776   assert((argOpers[valArgIndx]->isReg() ||
9777           argOpers[valArgIndx]->isImm()) &&
9778          "invalid operand");
9779   if (argOpers[valArgIndx]->isReg())
9780     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
9781   else
9782     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
9783   MIB.addReg(tt);
9784   (*MIB).addOperand(*argOpers[valArgIndx]);
9785
9786   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
9787   MIB.addReg(t1);
9788
9789   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
9790   for (int i=0; i <= lastAddrIndx; ++i)
9791     (*MIB).addOperand(*argOpers[i]);
9792   MIB.addReg(t2);
9793   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9794   (*MIB).setMemRefs(bInstr->memoperands_begin(),
9795                     bInstr->memoperands_end());
9796
9797   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9798   MIB.addReg(EAXreg);
9799
9800   // insert branch
9801   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9802
9803   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
9804   return nextMBB;
9805 }
9806
9807 // private utility function:  64 bit atomics on 32 bit host.
9808 MachineBasicBlock *
9809 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
9810                                                        MachineBasicBlock *MBB,
9811                                                        unsigned regOpcL,
9812                                                        unsigned regOpcH,
9813                                                        unsigned immOpcL,
9814                                                        unsigned immOpcH,
9815                                                        bool invSrc) const {
9816   // For the atomic bitwise operator, we generate
9817   //   thisMBB (instructions are in pairs, except cmpxchg8b)
9818   //     ld t1,t2 = [bitinstr.addr]
9819   //   newMBB:
9820   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
9821   //     op  t5, t6 <- out1, out2, [bitinstr.val]
9822   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
9823   //     mov ECX, EBX <- t5, t6
9824   //     mov EAX, EDX <- t1, t2
9825   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
9826   //     mov t3, t4 <- EAX, EDX
9827   //     bz  newMBB
9828   //     result in out1, out2
9829   //     fallthrough -->nextMBB
9830
9831   const TargetRegisterClass *RC = X86::GR32RegisterClass;
9832   const unsigned LoadOpc = X86::MOV32rm;
9833   const unsigned NotOpc = X86::NOT32r;
9834   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9835   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9836   MachineFunction::iterator MBBIter = MBB;
9837   ++MBBIter;
9838
9839   /// First build the CFG
9840   MachineFunction *F = MBB->getParent();
9841   MachineBasicBlock *thisMBB = MBB;
9842   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9843   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9844   F->insert(MBBIter, newMBB);
9845   F->insert(MBBIter, nextMBB);
9846
9847   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9848   nextMBB->splice(nextMBB->begin(), thisMBB,
9849                   llvm::next(MachineBasicBlock::iterator(bInstr)),
9850                   thisMBB->end());
9851   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9852
9853   // Update thisMBB to fall through to newMBB
9854   thisMBB->addSuccessor(newMBB);
9855
9856   // newMBB jumps to itself and fall through to nextMBB
9857   newMBB->addSuccessor(nextMBB);
9858   newMBB->addSuccessor(newMBB);
9859
9860   DebugLoc dl = bInstr->getDebugLoc();
9861   // Insert instructions into newMBB based on incoming instruction
9862   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
9863   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
9864          "unexpected number of operands");
9865   MachineOperand& dest1Oper = bInstr->getOperand(0);
9866   MachineOperand& dest2Oper = bInstr->getOperand(1);
9867   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9868   for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
9869     argOpers[i] = &bInstr->getOperand(i+2);
9870
9871     // We use some of the operands multiple times, so conservatively just
9872     // clear any kill flags that might be present.
9873     if (argOpers[i]->isReg() && argOpers[i]->isUse())
9874       argOpers[i]->setIsKill(false);
9875   }
9876
9877   // x86 address has 5 operands: base, index, scale, displacement, and segment.
9878   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9879
9880   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9881   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
9882   for (int i=0; i <= lastAddrIndx; ++i)
9883     (*MIB).addOperand(*argOpers[i]);
9884   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9885   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
9886   // add 4 to displacement.
9887   for (int i=0; i <= lastAddrIndx-2; ++i)
9888     (*MIB).addOperand(*argOpers[i]);
9889   MachineOperand newOp3 = *(argOpers[3]);
9890   if (newOp3.isImm())
9891     newOp3.setImm(newOp3.getImm()+4);
9892   else
9893     newOp3.setOffset(newOp3.getOffset()+4);
9894   (*MIB).addOperand(newOp3);
9895   (*MIB).addOperand(*argOpers[lastAddrIndx]);
9896
9897   // t3/4 are defined later, at the bottom of the loop
9898   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
9899   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
9900   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
9901     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
9902   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
9903     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
9904
9905   // The subsequent operations should be using the destination registers of
9906   //the PHI instructions.
9907   if (invSrc) {
9908     t1 = F->getRegInfo().createVirtualRegister(RC);
9909     t2 = F->getRegInfo().createVirtualRegister(RC);
9910     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
9911     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
9912   } else {
9913     t1 = dest1Oper.getReg();
9914     t2 = dest2Oper.getReg();
9915   }
9916
9917   int valArgIndx = lastAddrIndx + 1;
9918   assert((argOpers[valArgIndx]->isReg() ||
9919           argOpers[valArgIndx]->isImm()) &&
9920          "invalid operand");
9921   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
9922   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
9923   if (argOpers[valArgIndx]->isReg())
9924     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
9925   else
9926     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
9927   if (regOpcL != X86::MOV32rr)
9928     MIB.addReg(t1);
9929   (*MIB).addOperand(*argOpers[valArgIndx]);
9930   assert(argOpers[valArgIndx + 1]->isReg() ==
9931          argOpers[valArgIndx]->isReg());
9932   assert(argOpers[valArgIndx + 1]->isImm() ==
9933          argOpers[valArgIndx]->isImm());
9934   if (argOpers[valArgIndx + 1]->isReg())
9935     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
9936   else
9937     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
9938   if (regOpcH != X86::MOV32rr)
9939     MIB.addReg(t2);
9940   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
9941
9942   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9943   MIB.addReg(t1);
9944   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
9945   MIB.addReg(t2);
9946
9947   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
9948   MIB.addReg(t5);
9949   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
9950   MIB.addReg(t6);
9951
9952   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
9953   for (int i=0; i <= lastAddrIndx; ++i)
9954     (*MIB).addOperand(*argOpers[i]);
9955
9956   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9957   (*MIB).setMemRefs(bInstr->memoperands_begin(),
9958                     bInstr->memoperands_end());
9959
9960   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
9961   MIB.addReg(X86::EAX);
9962   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
9963   MIB.addReg(X86::EDX);
9964
9965   // insert branch
9966   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9967
9968   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
9969   return nextMBB;
9970 }
9971
9972 // private utility function
9973 MachineBasicBlock *
9974 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
9975                                                       MachineBasicBlock *MBB,
9976                                                       unsigned cmovOpc) const {
9977   // For the atomic min/max operator, we generate
9978   //   thisMBB:
9979   //   newMBB:
9980   //     ld t1 = [min/max.addr]
9981   //     mov t2 = [min/max.val]
9982   //     cmp  t1, t2
9983   //     cmov[cond] t2 = t1
9984   //     mov EAX = t1
9985   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
9986   //     bz   newMBB
9987   //     fallthrough -->nextMBB
9988   //
9989   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9990   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9991   MachineFunction::iterator MBBIter = MBB;
9992   ++MBBIter;
9993
9994   /// First build the CFG
9995   MachineFunction *F = MBB->getParent();
9996   MachineBasicBlock *thisMBB = MBB;
9997   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9998   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9999   F->insert(MBBIter, newMBB);
10000   F->insert(MBBIter, nextMBB);
10001
10002   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
10003   nextMBB->splice(nextMBB->begin(), thisMBB,
10004                   llvm::next(MachineBasicBlock::iterator(mInstr)),
10005                   thisMBB->end());
10006   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
10007
10008   // Update thisMBB to fall through to newMBB
10009   thisMBB->addSuccessor(newMBB);
10010
10011   // newMBB jumps to newMBB and fall through to nextMBB
10012   newMBB->addSuccessor(nextMBB);
10013   newMBB->addSuccessor(newMBB);
10014
10015   DebugLoc dl = mInstr->getDebugLoc();
10016   // Insert instructions into newMBB based on incoming instruction
10017   assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
10018          "unexpected number of operands");
10019   MachineOperand& destOper = mInstr->getOperand(0);
10020   MachineOperand* argOpers[2 + X86::AddrNumOperands];
10021   int numArgs = mInstr->getNumOperands() - 1;
10022   for (int i=0; i < numArgs; ++i)
10023     argOpers[i] = &mInstr->getOperand(i+1);
10024
10025   // x86 address has 4 operands: base, index, scale, and displacement
10026   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
10027   int valArgIndx = lastAddrIndx + 1;
10028
10029   unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
10030   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
10031   for (int i=0; i <= lastAddrIndx; ++i)
10032     (*MIB).addOperand(*argOpers[i]);
10033
10034   // We only support register and immediate values
10035   assert((argOpers[valArgIndx]->isReg() ||
10036           argOpers[valArgIndx]->isImm()) &&
10037          "invalid operand");
10038
10039   unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
10040   if (argOpers[valArgIndx]->isReg())
10041     MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
10042   else
10043     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
10044   (*MIB).addOperand(*argOpers[valArgIndx]);
10045
10046   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
10047   MIB.addReg(t1);
10048
10049   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
10050   MIB.addReg(t1);
10051   MIB.addReg(t2);
10052
10053   // Generate movc
10054   unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
10055   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
10056   MIB.addReg(t2);
10057   MIB.addReg(t1);
10058
10059   // Cmp and exchange if none has modified the memory location
10060   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
10061   for (int i=0; i <= lastAddrIndx; ++i)
10062     (*MIB).addOperand(*argOpers[i]);
10063   MIB.addReg(t3);
10064   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
10065   (*MIB).setMemRefs(mInstr->memoperands_begin(),
10066                     mInstr->memoperands_end());
10067
10068   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
10069   MIB.addReg(X86::EAX);
10070
10071   // insert branch
10072   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
10073
10074   mInstr->eraseFromParent();   // The pseudo instruction is gone now.
10075   return nextMBB;
10076 }
10077
10078 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
10079 // or XMM0_V32I8 in AVX all of this code can be replaced with that
10080 // in the .td file.
10081 MachineBasicBlock *
10082 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
10083                             unsigned numArgs, bool memArg) const {
10084   assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
10085          "Target must have SSE4.2 or AVX features enabled");
10086
10087   DebugLoc dl = MI->getDebugLoc();
10088   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10089   unsigned Opc;
10090   if (!Subtarget->hasAVX()) {
10091     if (memArg)
10092       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
10093     else
10094       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
10095   } else {
10096     if (memArg)
10097       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
10098     else
10099       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
10100   }
10101
10102   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
10103   for (unsigned i = 0; i < numArgs; ++i) {
10104     MachineOperand &Op = MI->getOperand(i+1);
10105     if (!(Op.isReg() && Op.isImplicit()))
10106       MIB.addOperand(Op);
10107   }
10108   BuildMI(*BB, MI, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
10109     .addReg(X86::XMM0);
10110
10111   MI->eraseFromParent();
10112   return BB;
10113 }
10114
10115 MachineBasicBlock *
10116 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
10117   DebugLoc dl = MI->getDebugLoc();
10118   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10119
10120   // Address into RAX/EAX, other two args into ECX, EDX.
10121   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
10122   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
10123   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
10124   for (int i = 0; i < X86::AddrNumOperands; ++i)
10125     MIB.addOperand(MI->getOperand(i));
10126
10127   unsigned ValOps = X86::AddrNumOperands;
10128   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
10129     .addReg(MI->getOperand(ValOps).getReg());
10130   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
10131     .addReg(MI->getOperand(ValOps+1).getReg());
10132
10133   // The instruction doesn't actually take any operands though.
10134   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
10135
10136   MI->eraseFromParent(); // The pseudo is gone now.
10137   return BB;
10138 }
10139
10140 MachineBasicBlock *
10141 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
10142   DebugLoc dl = MI->getDebugLoc();
10143   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10144
10145   // First arg in ECX, the second in EAX.
10146   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
10147     .addReg(MI->getOperand(0).getReg());
10148   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
10149     .addReg(MI->getOperand(1).getReg());
10150
10151   // The instruction doesn't actually take any operands though.
10152   BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
10153
10154   MI->eraseFromParent(); // The pseudo is gone now.
10155   return BB;
10156 }
10157
10158 MachineBasicBlock *
10159 X86TargetLowering::EmitVAARG64WithCustomInserter(
10160                    MachineInstr *MI,
10161                    MachineBasicBlock *MBB) const {
10162   // Emit va_arg instruction on X86-64.
10163
10164   // Operands to this pseudo-instruction:
10165   // 0  ) Output        : destination address (reg)
10166   // 1-5) Input         : va_list address (addr, i64mem)
10167   // 6  ) ArgSize       : Size (in bytes) of vararg type
10168   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
10169   // 8  ) Align         : Alignment of type
10170   // 9  ) EFLAGS (implicit-def)
10171
10172   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
10173   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
10174
10175   unsigned DestReg = MI->getOperand(0).getReg();
10176   MachineOperand &Base = MI->getOperand(1);
10177   MachineOperand &Scale = MI->getOperand(2);
10178   MachineOperand &Index = MI->getOperand(3);
10179   MachineOperand &Disp = MI->getOperand(4);
10180   MachineOperand &Segment = MI->getOperand(5);
10181   unsigned ArgSize = MI->getOperand(6).getImm();
10182   unsigned ArgMode = MI->getOperand(7).getImm();
10183   unsigned Align = MI->getOperand(8).getImm();
10184
10185   // Memory Reference
10186   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
10187   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
10188   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
10189
10190   // Machine Information
10191   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10192   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
10193   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
10194   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
10195   DebugLoc DL = MI->getDebugLoc();
10196
10197   // struct va_list {
10198   //   i32   gp_offset
10199   //   i32   fp_offset
10200   //   i64   overflow_area (address)
10201   //   i64   reg_save_area (address)
10202   // }
10203   // sizeof(va_list) = 24
10204   // alignment(va_list) = 8
10205
10206   unsigned TotalNumIntRegs = 6;
10207   unsigned TotalNumXMMRegs = 8;
10208   bool UseGPOffset = (ArgMode == 1);
10209   bool UseFPOffset = (ArgMode == 2);
10210   unsigned MaxOffset = TotalNumIntRegs * 8 +
10211                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
10212
10213   /* Align ArgSize to a multiple of 8 */
10214   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
10215   bool NeedsAlign = (Align > 8);
10216
10217   MachineBasicBlock *thisMBB = MBB;
10218   MachineBasicBlock *overflowMBB;
10219   MachineBasicBlock *offsetMBB;
10220   MachineBasicBlock *endMBB;
10221
10222   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
10223   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
10224   unsigned OffsetReg = 0;
10225
10226   if (!UseGPOffset && !UseFPOffset) {
10227     // If we only pull from the overflow region, we don't create a branch.
10228     // We don't need to alter control flow.
10229     OffsetDestReg = 0; // unused
10230     OverflowDestReg = DestReg;
10231
10232     offsetMBB = NULL;
10233     overflowMBB = thisMBB;
10234     endMBB = thisMBB;
10235   } else {
10236     // First emit code to check if gp_offset (or fp_offset) is below the bound.
10237     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
10238     // If not, pull from overflow_area. (branch to overflowMBB)
10239     //
10240     //       thisMBB
10241     //         |     .
10242     //         |        .
10243     //     offsetMBB   overflowMBB
10244     //         |        .
10245     //         |     .
10246     //        endMBB
10247
10248     // Registers for the PHI in endMBB
10249     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
10250     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
10251
10252     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10253     MachineFunction *MF = MBB->getParent();
10254     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10255     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10256     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10257
10258     MachineFunction::iterator MBBIter = MBB;
10259     ++MBBIter;
10260
10261     // Insert the new basic blocks
10262     MF->insert(MBBIter, offsetMBB);
10263     MF->insert(MBBIter, overflowMBB);
10264     MF->insert(MBBIter, endMBB);
10265
10266     // Transfer the remainder of MBB and its successor edges to endMBB.
10267     endMBB->splice(endMBB->begin(), thisMBB,
10268                     llvm::next(MachineBasicBlock::iterator(MI)),
10269                     thisMBB->end());
10270     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
10271
10272     // Make offsetMBB and overflowMBB successors of thisMBB
10273     thisMBB->addSuccessor(offsetMBB);
10274     thisMBB->addSuccessor(overflowMBB);
10275
10276     // endMBB is a successor of both offsetMBB and overflowMBB
10277     offsetMBB->addSuccessor(endMBB);
10278     overflowMBB->addSuccessor(endMBB);
10279
10280     // Load the offset value into a register
10281     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
10282     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
10283       .addOperand(Base)
10284       .addOperand(Scale)
10285       .addOperand(Index)
10286       .addDisp(Disp, UseFPOffset ? 4 : 0)
10287       .addOperand(Segment)
10288       .setMemRefs(MMOBegin, MMOEnd);
10289
10290     // Check if there is enough room left to pull this argument.
10291     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
10292       .addReg(OffsetReg)
10293       .addImm(MaxOffset + 8 - ArgSizeA8);
10294
10295     // Branch to "overflowMBB" if offset >= max
10296     // Fall through to "offsetMBB" otherwise
10297     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
10298       .addMBB(overflowMBB);
10299   }
10300
10301   // In offsetMBB, emit code to use the reg_save_area.
10302   if (offsetMBB) {
10303     assert(OffsetReg != 0);
10304
10305     // Read the reg_save_area address.
10306     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
10307     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
10308       .addOperand(Base)
10309       .addOperand(Scale)
10310       .addOperand(Index)
10311       .addDisp(Disp, 16)
10312       .addOperand(Segment)
10313       .setMemRefs(MMOBegin, MMOEnd);
10314
10315     // Zero-extend the offset
10316     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
10317       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
10318         .addImm(0)
10319         .addReg(OffsetReg)
10320         .addImm(X86::sub_32bit);
10321
10322     // Add the offset to the reg_save_area to get the final address.
10323     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
10324       .addReg(OffsetReg64)
10325       .addReg(RegSaveReg);
10326
10327     // Compute the offset for the next argument
10328     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
10329     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
10330       .addReg(OffsetReg)
10331       .addImm(UseFPOffset ? 16 : 8);
10332
10333     // Store it back into the va_list.
10334     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
10335       .addOperand(Base)
10336       .addOperand(Scale)
10337       .addOperand(Index)
10338       .addDisp(Disp, UseFPOffset ? 4 : 0)
10339       .addOperand(Segment)
10340       .addReg(NextOffsetReg)
10341       .setMemRefs(MMOBegin, MMOEnd);
10342
10343     // Jump to endMBB
10344     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
10345       .addMBB(endMBB);
10346   }
10347
10348   //
10349   // Emit code to use overflow area
10350   //
10351
10352   // Load the overflow_area address into a register.
10353   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
10354   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
10355     .addOperand(Base)
10356     .addOperand(Scale)
10357     .addOperand(Index)
10358     .addDisp(Disp, 8)
10359     .addOperand(Segment)
10360     .setMemRefs(MMOBegin, MMOEnd);
10361
10362   // If we need to align it, do so. Otherwise, just copy the address
10363   // to OverflowDestReg.
10364   if (NeedsAlign) {
10365     // Align the overflow address
10366     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
10367     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
10368
10369     // aligned_addr = (addr + (align-1)) & ~(align-1)
10370     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
10371       .addReg(OverflowAddrReg)
10372       .addImm(Align-1);
10373
10374     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
10375       .addReg(TmpReg)
10376       .addImm(~(uint64_t)(Align-1));
10377   } else {
10378     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
10379       .addReg(OverflowAddrReg);
10380   }
10381
10382   // Compute the next overflow address after this argument.
10383   // (the overflow address should be kept 8-byte aligned)
10384   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
10385   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
10386     .addReg(OverflowDestReg)
10387     .addImm(ArgSizeA8);
10388
10389   // Store the new overflow address.
10390   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
10391     .addOperand(Base)
10392     .addOperand(Scale)
10393     .addOperand(Index)
10394     .addDisp(Disp, 8)
10395     .addOperand(Segment)
10396     .addReg(NextAddrReg)
10397     .setMemRefs(MMOBegin, MMOEnd);
10398
10399   // If we branched, emit the PHI to the front of endMBB.
10400   if (offsetMBB) {
10401     BuildMI(*endMBB, endMBB->begin(), DL,
10402             TII->get(X86::PHI), DestReg)
10403       .addReg(OffsetDestReg).addMBB(offsetMBB)
10404       .addReg(OverflowDestReg).addMBB(overflowMBB);
10405   }
10406
10407   // Erase the pseudo instruction
10408   MI->eraseFromParent();
10409
10410   return endMBB;
10411 }
10412
10413 MachineBasicBlock *
10414 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
10415                                                  MachineInstr *MI,
10416                                                  MachineBasicBlock *MBB) const {
10417   // Emit code to save XMM registers to the stack. The ABI says that the
10418   // number of registers to save is given in %al, so it's theoretically
10419   // possible to do an indirect jump trick to avoid saving all of them,
10420   // however this code takes a simpler approach and just executes all
10421   // of the stores if %al is non-zero. It's less code, and it's probably
10422   // easier on the hardware branch predictor, and stores aren't all that
10423   // expensive anyway.
10424
10425   // Create the new basic blocks. One block contains all the XMM stores,
10426   // and one block is the final destination regardless of whether any
10427   // stores were performed.
10428   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10429   MachineFunction *F = MBB->getParent();
10430   MachineFunction::iterator MBBIter = MBB;
10431   ++MBBIter;
10432   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
10433   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
10434   F->insert(MBBIter, XMMSaveMBB);
10435   F->insert(MBBIter, EndMBB);
10436
10437   // Transfer the remainder of MBB and its successor edges to EndMBB.
10438   EndMBB->splice(EndMBB->begin(), MBB,
10439                  llvm::next(MachineBasicBlock::iterator(MI)),
10440                  MBB->end());
10441   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
10442
10443   // The original block will now fall through to the XMM save block.
10444   MBB->addSuccessor(XMMSaveMBB);
10445   // The XMMSaveMBB will fall through to the end block.
10446   XMMSaveMBB->addSuccessor(EndMBB);
10447
10448   // Now add the instructions.
10449   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10450   DebugLoc DL = MI->getDebugLoc();
10451
10452   unsigned CountReg = MI->getOperand(0).getReg();
10453   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
10454   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
10455
10456   if (!Subtarget->isTargetWin64()) {
10457     // If %al is 0, branch around the XMM save block.
10458     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
10459     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
10460     MBB->addSuccessor(EndMBB);
10461   }
10462
10463   // In the XMM save block, save all the XMM argument registers.
10464   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
10465     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
10466     MachineMemOperand *MMO =
10467       F->getMachineMemOperand(
10468           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
10469         MachineMemOperand::MOStore,
10470         /*Size=*/16, /*Align=*/16);
10471     BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
10472       .addFrameIndex(RegSaveFrameIndex)
10473       .addImm(/*Scale=*/1)
10474       .addReg(/*IndexReg=*/0)
10475       .addImm(/*Disp=*/Offset)
10476       .addReg(/*Segment=*/0)
10477       .addReg(MI->getOperand(i).getReg())
10478       .addMemOperand(MMO);
10479   }
10480
10481   MI->eraseFromParent();   // The pseudo instruction is gone now.
10482
10483   return EndMBB;
10484 }
10485
10486 MachineBasicBlock *
10487 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
10488                                      MachineBasicBlock *BB) const {
10489   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10490   DebugLoc DL = MI->getDebugLoc();
10491
10492   // To "insert" a SELECT_CC instruction, we actually have to insert the
10493   // diamond control-flow pattern.  The incoming instruction knows the
10494   // destination vreg to set, the condition code register to branch on, the
10495   // true/false values to select between, and a branch opcode to use.
10496   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10497   MachineFunction::iterator It = BB;
10498   ++It;
10499
10500   //  thisMBB:
10501   //  ...
10502   //   TrueVal = ...
10503   //   cmpTY ccX, r1, r2
10504   //   bCC copy1MBB
10505   //   fallthrough --> copy0MBB
10506   MachineBasicBlock *thisMBB = BB;
10507   MachineFunction *F = BB->getParent();
10508   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
10509   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
10510   F->insert(It, copy0MBB);
10511   F->insert(It, sinkMBB);
10512
10513   // If the EFLAGS register isn't dead in the terminator, then claim that it's
10514   // live into the sink and copy blocks.
10515   const MachineFunction *MF = BB->getParent();
10516   const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
10517   BitVector ReservedRegs = TRI->getReservedRegs(*MF);
10518
10519   for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
10520     const MachineOperand &MO = MI->getOperand(I);
10521     if (!MO.isReg() || !MO.isUse() || MO.isKill()) continue;
10522     unsigned Reg = MO.getReg();
10523     if (Reg != X86::EFLAGS) continue;
10524     copy0MBB->addLiveIn(Reg);
10525     sinkMBB->addLiveIn(Reg);
10526   }
10527
10528   // Transfer the remainder of BB and its successor edges to sinkMBB.
10529   sinkMBB->splice(sinkMBB->begin(), BB,
10530                   llvm::next(MachineBasicBlock::iterator(MI)),
10531                   BB->end());
10532   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
10533
10534   // Add the true and fallthrough blocks as its successors.
10535   BB->addSuccessor(copy0MBB);
10536   BB->addSuccessor(sinkMBB);
10537
10538   // Create the conditional branch instruction.
10539   unsigned Opc =
10540     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
10541   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
10542
10543   //  copy0MBB:
10544   //   %FalseValue = ...
10545   //   # fallthrough to sinkMBB
10546   copy0MBB->addSuccessor(sinkMBB);
10547
10548   //  sinkMBB:
10549   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
10550   //  ...
10551   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
10552           TII->get(X86::PHI), MI->getOperand(0).getReg())
10553     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
10554     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
10555
10556   MI->eraseFromParent();   // The pseudo instruction is gone now.
10557   return sinkMBB;
10558 }
10559
10560 MachineBasicBlock *
10561 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
10562                                           MachineBasicBlock *BB) const {
10563   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10564   DebugLoc DL = MI->getDebugLoc();
10565
10566   assert(!Subtarget->isTargetEnvMacho());
10567
10568   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
10569   // non-trivial part is impdef of ESP.
10570
10571   if (Subtarget->isTargetWin64()) {
10572     if (Subtarget->isTargetCygMing()) {
10573       // ___chkstk(Mingw64):
10574       // Clobbers R10, R11, RAX and EFLAGS.
10575       // Updates RSP.
10576       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
10577         .addExternalSymbol("___chkstk")
10578         .addReg(X86::RAX, RegState::Implicit)
10579         .addReg(X86::RSP, RegState::Implicit)
10580         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
10581         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
10582         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10583     } else {
10584       // __chkstk(MSVCRT): does not update stack pointer.
10585       // Clobbers R10, R11 and EFLAGS.
10586       // FIXME: RAX(allocated size) might be reused and not killed.
10587       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
10588         .addExternalSymbol("__chkstk")
10589         .addReg(X86::RAX, RegState::Implicit)
10590         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10591       // RAX has the offset to subtracted from RSP.
10592       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
10593         .addReg(X86::RSP)
10594         .addReg(X86::RAX);
10595     }
10596   } else {
10597     const char *StackProbeSymbol =
10598       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
10599
10600     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
10601       .addExternalSymbol(StackProbeSymbol)
10602       .addReg(X86::EAX, RegState::Implicit)
10603       .addReg(X86::ESP, RegState::Implicit)
10604       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
10605       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
10606       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10607   }
10608
10609   MI->eraseFromParent();   // The pseudo instruction is gone now.
10610   return BB;
10611 }
10612
10613 MachineBasicBlock *
10614 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
10615                                       MachineBasicBlock *BB) const {
10616   // This is pretty easy.  We're taking the value that we received from
10617   // our load from the relocation, sticking it in either RDI (x86-64)
10618   // or EAX and doing an indirect call.  The return value will then
10619   // be in the normal return register.
10620   const X86InstrInfo *TII
10621     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
10622   DebugLoc DL = MI->getDebugLoc();
10623   MachineFunction *F = BB->getParent();
10624
10625   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
10626   assert(MI->getOperand(3).isGlobal() && "This should be a global");
10627
10628   if (Subtarget->is64Bit()) {
10629     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10630                                       TII->get(X86::MOV64rm), X86::RDI)
10631     .addReg(X86::RIP)
10632     .addImm(0).addReg(0)
10633     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10634                       MI->getOperand(3).getTargetFlags())
10635     .addReg(0);
10636     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
10637     addDirectMem(MIB, X86::RDI);
10638   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
10639     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10640                                       TII->get(X86::MOV32rm), X86::EAX)
10641     .addReg(0)
10642     .addImm(0).addReg(0)
10643     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10644                       MI->getOperand(3).getTargetFlags())
10645     .addReg(0);
10646     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10647     addDirectMem(MIB, X86::EAX);
10648   } else {
10649     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10650                                       TII->get(X86::MOV32rm), X86::EAX)
10651     .addReg(TII->getGlobalBaseReg(F))
10652     .addImm(0).addReg(0)
10653     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10654                       MI->getOperand(3).getTargetFlags())
10655     .addReg(0);
10656     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10657     addDirectMem(MIB, X86::EAX);
10658   }
10659
10660   MI->eraseFromParent(); // The pseudo instruction is gone now.
10661   return BB;
10662 }
10663
10664 MachineBasicBlock *
10665 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
10666                                                MachineBasicBlock *BB) const {
10667   switch (MI->getOpcode()) {
10668   default: assert(false && "Unexpected instr type to insert");
10669   case X86::TAILJMPd64:
10670   case X86::TAILJMPr64:
10671   case X86::TAILJMPm64:
10672     assert(!"TAILJMP64 would not be touched here.");
10673   case X86::TCRETURNdi64:
10674   case X86::TCRETURNri64:
10675   case X86::TCRETURNmi64:
10676     // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset.
10677     // On AMD64, additional defs should be added before register allocation.
10678     if (!Subtarget->isTargetWin64()) {
10679       MI->addRegisterDefined(X86::RSI);
10680       MI->addRegisterDefined(X86::RDI);
10681       MI->addRegisterDefined(X86::XMM6);
10682       MI->addRegisterDefined(X86::XMM7);
10683       MI->addRegisterDefined(X86::XMM8);
10684       MI->addRegisterDefined(X86::XMM9);
10685       MI->addRegisterDefined(X86::XMM10);
10686       MI->addRegisterDefined(X86::XMM11);
10687       MI->addRegisterDefined(X86::XMM12);
10688       MI->addRegisterDefined(X86::XMM13);
10689       MI->addRegisterDefined(X86::XMM14);
10690       MI->addRegisterDefined(X86::XMM15);
10691     }
10692     return BB;
10693   case X86::WIN_ALLOCA:
10694     return EmitLoweredWinAlloca(MI, BB);
10695   case X86::TLSCall_32:
10696   case X86::TLSCall_64:
10697     return EmitLoweredTLSCall(MI, BB);
10698   case X86::CMOV_GR8:
10699   case X86::CMOV_FR32:
10700   case X86::CMOV_FR64:
10701   case X86::CMOV_V4F32:
10702   case X86::CMOV_V2F64:
10703   case X86::CMOV_V2I64:
10704   case X86::CMOV_GR16:
10705   case X86::CMOV_GR32:
10706   case X86::CMOV_RFP32:
10707   case X86::CMOV_RFP64:
10708   case X86::CMOV_RFP80:
10709     return EmitLoweredSelect(MI, BB);
10710
10711   case X86::FP32_TO_INT16_IN_MEM:
10712   case X86::FP32_TO_INT32_IN_MEM:
10713   case X86::FP32_TO_INT64_IN_MEM:
10714   case X86::FP64_TO_INT16_IN_MEM:
10715   case X86::FP64_TO_INT32_IN_MEM:
10716   case X86::FP64_TO_INT64_IN_MEM:
10717   case X86::FP80_TO_INT16_IN_MEM:
10718   case X86::FP80_TO_INT32_IN_MEM:
10719   case X86::FP80_TO_INT64_IN_MEM: {
10720     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10721     DebugLoc DL = MI->getDebugLoc();
10722
10723     // Change the floating point control register to use "round towards zero"
10724     // mode when truncating to an integer value.
10725     MachineFunction *F = BB->getParent();
10726     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
10727     addFrameReference(BuildMI(*BB, MI, DL,
10728                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
10729
10730     // Load the old value of the high byte of the control word...
10731     unsigned OldCW =
10732       F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
10733     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
10734                       CWFrameIdx);
10735
10736     // Set the high part to be round to zero...
10737     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
10738       .addImm(0xC7F);
10739
10740     // Reload the modified control word now...
10741     addFrameReference(BuildMI(*BB, MI, DL,
10742                               TII->get(X86::FLDCW16m)), CWFrameIdx);
10743
10744     // Restore the memory image of control word to original value
10745     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
10746       .addReg(OldCW);
10747
10748     // Get the X86 opcode to use.
10749     unsigned Opc;
10750     switch (MI->getOpcode()) {
10751     default: llvm_unreachable("illegal opcode!");
10752     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
10753     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
10754     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
10755     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
10756     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
10757     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
10758     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
10759     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
10760     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
10761     }
10762
10763     X86AddressMode AM;
10764     MachineOperand &Op = MI->getOperand(0);
10765     if (Op.isReg()) {
10766       AM.BaseType = X86AddressMode::RegBase;
10767       AM.Base.Reg = Op.getReg();
10768     } else {
10769       AM.BaseType = X86AddressMode::FrameIndexBase;
10770       AM.Base.FrameIndex = Op.getIndex();
10771     }
10772     Op = MI->getOperand(1);
10773     if (Op.isImm())
10774       AM.Scale = Op.getImm();
10775     Op = MI->getOperand(2);
10776     if (Op.isImm())
10777       AM.IndexReg = Op.getImm();
10778     Op = MI->getOperand(3);
10779     if (Op.isGlobal()) {
10780       AM.GV = Op.getGlobal();
10781     } else {
10782       AM.Disp = Op.getImm();
10783     }
10784     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
10785                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
10786
10787     // Reload the original control word now.
10788     addFrameReference(BuildMI(*BB, MI, DL,
10789                               TII->get(X86::FLDCW16m)), CWFrameIdx);
10790
10791     MI->eraseFromParent();   // The pseudo instruction is gone now.
10792     return BB;
10793   }
10794     // String/text processing lowering.
10795   case X86::PCMPISTRM128REG:
10796   case X86::VPCMPISTRM128REG:
10797     return EmitPCMP(MI, BB, 3, false /* in-mem */);
10798   case X86::PCMPISTRM128MEM:
10799   case X86::VPCMPISTRM128MEM:
10800     return EmitPCMP(MI, BB, 3, true /* in-mem */);
10801   case X86::PCMPESTRM128REG:
10802   case X86::VPCMPESTRM128REG:
10803     return EmitPCMP(MI, BB, 5, false /* in mem */);
10804   case X86::PCMPESTRM128MEM:
10805   case X86::VPCMPESTRM128MEM:
10806     return EmitPCMP(MI, BB, 5, true /* in mem */);
10807
10808     // Thread synchronization.
10809   case X86::MONITOR:
10810     return EmitMonitor(MI, BB);
10811   case X86::MWAIT:
10812     return EmitMwait(MI, BB);
10813
10814     // Atomic Lowering.
10815   case X86::ATOMAND32:
10816     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10817                                                X86::AND32ri, X86::MOV32rm,
10818                                                X86::LCMPXCHG32,
10819                                                X86::NOT32r, X86::EAX,
10820                                                X86::GR32RegisterClass);
10821   case X86::ATOMOR32:
10822     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
10823                                                X86::OR32ri, X86::MOV32rm,
10824                                                X86::LCMPXCHG32,
10825                                                X86::NOT32r, X86::EAX,
10826                                                X86::GR32RegisterClass);
10827   case X86::ATOMXOR32:
10828     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
10829                                                X86::XOR32ri, X86::MOV32rm,
10830                                                X86::LCMPXCHG32,
10831                                                X86::NOT32r, X86::EAX,
10832                                                X86::GR32RegisterClass);
10833   case X86::ATOMNAND32:
10834     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10835                                                X86::AND32ri, X86::MOV32rm,
10836                                                X86::LCMPXCHG32,
10837                                                X86::NOT32r, X86::EAX,
10838                                                X86::GR32RegisterClass, true);
10839   case X86::ATOMMIN32:
10840     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
10841   case X86::ATOMMAX32:
10842     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
10843   case X86::ATOMUMIN32:
10844     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
10845   case X86::ATOMUMAX32:
10846     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
10847
10848   case X86::ATOMAND16:
10849     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10850                                                X86::AND16ri, X86::MOV16rm,
10851                                                X86::LCMPXCHG16,
10852                                                X86::NOT16r, X86::AX,
10853                                                X86::GR16RegisterClass);
10854   case X86::ATOMOR16:
10855     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
10856                                                X86::OR16ri, X86::MOV16rm,
10857                                                X86::LCMPXCHG16,
10858                                                X86::NOT16r, X86::AX,
10859                                                X86::GR16RegisterClass);
10860   case X86::ATOMXOR16:
10861     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
10862                                                X86::XOR16ri, X86::MOV16rm,
10863                                                X86::LCMPXCHG16,
10864                                                X86::NOT16r, X86::AX,
10865                                                X86::GR16RegisterClass);
10866   case X86::ATOMNAND16:
10867     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10868                                                X86::AND16ri, X86::MOV16rm,
10869                                                X86::LCMPXCHG16,
10870                                                X86::NOT16r, X86::AX,
10871                                                X86::GR16RegisterClass, true);
10872   case X86::ATOMMIN16:
10873     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
10874   case X86::ATOMMAX16:
10875     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
10876   case X86::ATOMUMIN16:
10877     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
10878   case X86::ATOMUMAX16:
10879     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
10880
10881   case X86::ATOMAND8:
10882     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10883                                                X86::AND8ri, X86::MOV8rm,
10884                                                X86::LCMPXCHG8,
10885                                                X86::NOT8r, X86::AL,
10886                                                X86::GR8RegisterClass);
10887   case X86::ATOMOR8:
10888     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
10889                                                X86::OR8ri, X86::MOV8rm,
10890                                                X86::LCMPXCHG8,
10891                                                X86::NOT8r, X86::AL,
10892                                                X86::GR8RegisterClass);
10893   case X86::ATOMXOR8:
10894     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
10895                                                X86::XOR8ri, X86::MOV8rm,
10896                                                X86::LCMPXCHG8,
10897                                                X86::NOT8r, X86::AL,
10898                                                X86::GR8RegisterClass);
10899   case X86::ATOMNAND8:
10900     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10901                                                X86::AND8ri, X86::MOV8rm,
10902                                                X86::LCMPXCHG8,
10903                                                X86::NOT8r, X86::AL,
10904                                                X86::GR8RegisterClass, true);
10905   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
10906   // This group is for 64-bit host.
10907   case X86::ATOMAND64:
10908     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10909                                                X86::AND64ri32, X86::MOV64rm,
10910                                                X86::LCMPXCHG64,
10911                                                X86::NOT64r, X86::RAX,
10912                                                X86::GR64RegisterClass);
10913   case X86::ATOMOR64:
10914     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
10915                                                X86::OR64ri32, X86::MOV64rm,
10916                                                X86::LCMPXCHG64,
10917                                                X86::NOT64r, X86::RAX,
10918                                                X86::GR64RegisterClass);
10919   case X86::ATOMXOR64:
10920     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
10921                                                X86::XOR64ri32, X86::MOV64rm,
10922                                                X86::LCMPXCHG64,
10923                                                X86::NOT64r, X86::RAX,
10924                                                X86::GR64RegisterClass);
10925   case X86::ATOMNAND64:
10926     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10927                                                X86::AND64ri32, X86::MOV64rm,
10928                                                X86::LCMPXCHG64,
10929                                                X86::NOT64r, X86::RAX,
10930                                                X86::GR64RegisterClass, true);
10931   case X86::ATOMMIN64:
10932     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
10933   case X86::ATOMMAX64:
10934     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
10935   case X86::ATOMUMIN64:
10936     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
10937   case X86::ATOMUMAX64:
10938     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
10939
10940   // This group does 64-bit operations on a 32-bit host.
10941   case X86::ATOMAND6432:
10942     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10943                                                X86::AND32rr, X86::AND32rr,
10944                                                X86::AND32ri, X86::AND32ri,
10945                                                false);
10946   case X86::ATOMOR6432:
10947     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10948                                                X86::OR32rr, X86::OR32rr,
10949                                                X86::OR32ri, X86::OR32ri,
10950                                                false);
10951   case X86::ATOMXOR6432:
10952     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10953                                                X86::XOR32rr, X86::XOR32rr,
10954                                                X86::XOR32ri, X86::XOR32ri,
10955                                                false);
10956   case X86::ATOMNAND6432:
10957     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10958                                                X86::AND32rr, X86::AND32rr,
10959                                                X86::AND32ri, X86::AND32ri,
10960                                                true);
10961   case X86::ATOMADD6432:
10962     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10963                                                X86::ADD32rr, X86::ADC32rr,
10964                                                X86::ADD32ri, X86::ADC32ri,
10965                                                false);
10966   case X86::ATOMSUB6432:
10967     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10968                                                X86::SUB32rr, X86::SBB32rr,
10969                                                X86::SUB32ri, X86::SBB32ri,
10970                                                false);
10971   case X86::ATOMSWAP6432:
10972     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10973                                                X86::MOV32rr, X86::MOV32rr,
10974                                                X86::MOV32ri, X86::MOV32ri,
10975                                                false);
10976   case X86::VASTART_SAVE_XMM_REGS:
10977     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
10978
10979   case X86::VAARG_64:
10980     return EmitVAARG64WithCustomInserter(MI, BB);
10981   }
10982 }
10983
10984 //===----------------------------------------------------------------------===//
10985 //                           X86 Optimization Hooks
10986 //===----------------------------------------------------------------------===//
10987
10988 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
10989                                                        const APInt &Mask,
10990                                                        APInt &KnownZero,
10991                                                        APInt &KnownOne,
10992                                                        const SelectionDAG &DAG,
10993                                                        unsigned Depth) const {
10994   unsigned Opc = Op.getOpcode();
10995   assert((Opc >= ISD::BUILTIN_OP_END ||
10996           Opc == ISD::INTRINSIC_WO_CHAIN ||
10997           Opc == ISD::INTRINSIC_W_CHAIN ||
10998           Opc == ISD::INTRINSIC_VOID) &&
10999          "Should use MaskedValueIsZero if you don't know whether Op"
11000          " is a target node!");
11001
11002   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
11003   switch (Opc) {
11004   default: break;
11005   case X86ISD::ADD:
11006   case X86ISD::SUB:
11007   case X86ISD::ADC:
11008   case X86ISD::SBB:
11009   case X86ISD::SMUL:
11010   case X86ISD::UMUL:
11011   case X86ISD::INC:
11012   case X86ISD::DEC:
11013   case X86ISD::OR:
11014   case X86ISD::XOR:
11015   case X86ISD::AND:
11016     // These nodes' second result is a boolean.
11017     if (Op.getResNo() == 0)
11018       break;
11019     // Fallthrough
11020   case X86ISD::SETCC:
11021     KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
11022                                        Mask.getBitWidth() - 1);
11023     break;
11024   }
11025 }
11026
11027 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
11028                                                          unsigned Depth) const {
11029   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
11030   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
11031     return Op.getValueType().getScalarType().getSizeInBits();
11032
11033   // Fallback case.
11034   return 1;
11035 }
11036
11037 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
11038 /// node is a GlobalAddress + offset.
11039 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
11040                                        const GlobalValue* &GA,
11041                                        int64_t &Offset) const {
11042   if (N->getOpcode() == X86ISD::Wrapper) {
11043     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
11044       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
11045       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
11046       return true;
11047     }
11048   }
11049   return TargetLowering::isGAPlusOffset(N, GA, Offset);
11050 }
11051
11052 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
11053 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
11054 /// if the load addresses are consecutive, non-overlapping, and in the right
11055 /// order.
11056 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
11057                                      TargetLowering::DAGCombinerInfo &DCI) {
11058   DebugLoc dl = N->getDebugLoc();
11059   EVT VT = N->getValueType(0);
11060
11061   if (VT.getSizeInBits() != 128)
11062     return SDValue();
11063
11064   // Don't create instructions with illegal types after legalize types has run.
11065   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11066   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
11067     return SDValue();
11068
11069   SmallVector<SDValue, 16> Elts;
11070   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
11071     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
11072
11073   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
11074 }
11075
11076 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
11077 /// generation and convert it from being a bunch of shuffles and extracts
11078 /// to a simple store and scalar loads to extract the elements.
11079 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
11080                                                 const TargetLowering &TLI) {
11081   SDValue InputVector = N->getOperand(0);
11082
11083   // Only operate on vectors of 4 elements, where the alternative shuffling
11084   // gets to be more expensive.
11085   if (InputVector.getValueType() != MVT::v4i32)
11086     return SDValue();
11087
11088   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
11089   // single use which is a sign-extend or zero-extend, and all elements are
11090   // used.
11091   SmallVector<SDNode *, 4> Uses;
11092   unsigned ExtractedElements = 0;
11093   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
11094        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
11095     if (UI.getUse().getResNo() != InputVector.getResNo())
11096       return SDValue();
11097
11098     SDNode *Extract = *UI;
11099     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11100       return SDValue();
11101
11102     if (Extract->getValueType(0) != MVT::i32)
11103       return SDValue();
11104     if (!Extract->hasOneUse())
11105       return SDValue();
11106     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
11107         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
11108       return SDValue();
11109     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
11110       return SDValue();
11111
11112     // Record which element was extracted.
11113     ExtractedElements |=
11114       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
11115
11116     Uses.push_back(Extract);
11117   }
11118
11119   // If not all the elements were used, this may not be worthwhile.
11120   if (ExtractedElements != 15)
11121     return SDValue();
11122
11123   // Ok, we've now decided to do the transformation.
11124   DebugLoc dl = InputVector.getDebugLoc();
11125
11126   // Store the value to a temporary stack slot.
11127   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
11128   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
11129                             MachinePointerInfo(), false, false, 0);
11130
11131   // Replace each use (extract) with a load of the appropriate element.
11132   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
11133        UE = Uses.end(); UI != UE; ++UI) {
11134     SDNode *Extract = *UI;
11135
11136     // cOMpute the element's address.
11137     SDValue Idx = Extract->getOperand(1);
11138     unsigned EltSize =
11139         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
11140     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
11141     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
11142
11143     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
11144                                      StackPtr, OffsetVal);
11145
11146     // Load the scalar.
11147     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
11148                                      ScalarAddr, MachinePointerInfo(),
11149                                      false, false, 0);
11150
11151     // Replace the exact with the load.
11152     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
11153   }
11154
11155   // The replacement was made in place; don't return anything.
11156   return SDValue();
11157 }
11158
11159 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
11160 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
11161                                     const X86Subtarget *Subtarget) {
11162   DebugLoc DL = N->getDebugLoc();
11163   SDValue Cond = N->getOperand(0);
11164   // Get the LHS/RHS of the select.
11165   SDValue LHS = N->getOperand(1);
11166   SDValue RHS = N->getOperand(2);
11167
11168   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
11169   // instructions match the semantics of the common C idiom x<y?x:y but not
11170   // x<=y?x:y, because of how they handle negative zero (which can be
11171   // ignored in unsafe-math mode).
11172   if (Subtarget->hasSSE2() &&
11173       (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
11174       Cond.getOpcode() == ISD::SETCC) {
11175     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
11176
11177     unsigned Opcode = 0;
11178     // Check for x CC y ? x : y.
11179     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
11180         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
11181       switch (CC) {
11182       default: break;
11183       case ISD::SETULT:
11184         // Converting this to a min would handle NaNs incorrectly, and swapping
11185         // the operands would cause it to handle comparisons between positive
11186         // and negative zero incorrectly.
11187         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
11188           if (!UnsafeFPMath &&
11189               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
11190             break;
11191           std::swap(LHS, RHS);
11192         }
11193         Opcode = X86ISD::FMIN;
11194         break;
11195       case ISD::SETOLE:
11196         // Converting this to a min would handle comparisons between positive
11197         // and negative zero incorrectly.
11198         if (!UnsafeFPMath &&
11199             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
11200           break;
11201         Opcode = X86ISD::FMIN;
11202         break;
11203       case ISD::SETULE:
11204         // Converting this to a min would handle both negative zeros and NaNs
11205         // incorrectly, but we can swap the operands to fix both.
11206         std::swap(LHS, RHS);
11207       case ISD::SETOLT:
11208       case ISD::SETLT:
11209       case ISD::SETLE:
11210         Opcode = X86ISD::FMIN;
11211         break;
11212
11213       case ISD::SETOGE:
11214         // Converting this to a max would handle comparisons between positive
11215         // and negative zero incorrectly.
11216         if (!UnsafeFPMath &&
11217             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS))
11218           break;
11219         Opcode = X86ISD::FMAX;
11220         break;
11221       case ISD::SETUGT:
11222         // Converting this to a max would handle NaNs incorrectly, and swapping
11223         // the operands would cause it to handle comparisons between positive
11224         // and negative zero incorrectly.
11225         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
11226           if (!UnsafeFPMath &&
11227               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
11228             break;
11229           std::swap(LHS, RHS);
11230         }
11231         Opcode = X86ISD::FMAX;
11232         break;
11233       case ISD::SETUGE:
11234         // Converting this to a max would handle both negative zeros and NaNs
11235         // incorrectly, but we can swap the operands to fix both.
11236         std::swap(LHS, RHS);
11237       case ISD::SETOGT:
11238       case ISD::SETGT:
11239       case ISD::SETGE:
11240         Opcode = X86ISD::FMAX;
11241         break;
11242       }
11243     // Check for x CC y ? y : x -- a min/max with reversed arms.
11244     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
11245                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
11246       switch (CC) {
11247       default: break;
11248       case ISD::SETOGE:
11249         // Converting this to a min would handle comparisons between positive
11250         // and negative zero incorrectly, and swapping the operands would
11251         // cause it to handle NaNs incorrectly.
11252         if (!UnsafeFPMath &&
11253             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
11254           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11255             break;
11256           std::swap(LHS, RHS);
11257         }
11258         Opcode = X86ISD::FMIN;
11259         break;
11260       case ISD::SETUGT:
11261         // Converting this to a min would handle NaNs incorrectly.
11262         if (!UnsafeFPMath &&
11263             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
11264           break;
11265         Opcode = X86ISD::FMIN;
11266         break;
11267       case ISD::SETUGE:
11268         // Converting this to a min would handle both negative zeros and NaNs
11269         // incorrectly, but we can swap the operands to fix both.
11270         std::swap(LHS, RHS);
11271       case ISD::SETOGT:
11272       case ISD::SETGT:
11273       case ISD::SETGE:
11274         Opcode = X86ISD::FMIN;
11275         break;
11276
11277       case ISD::SETULT:
11278         // Converting this to a max would handle NaNs incorrectly.
11279         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11280           break;
11281         Opcode = X86ISD::FMAX;
11282         break;
11283       case ISD::SETOLE:
11284         // Converting this to a max would handle comparisons between positive
11285         // and negative zero incorrectly, and swapping the operands would
11286         // cause it to handle NaNs incorrectly.
11287         if (!UnsafeFPMath &&
11288             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
11289           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11290             break;
11291           std::swap(LHS, RHS);
11292         }
11293         Opcode = X86ISD::FMAX;
11294         break;
11295       case ISD::SETULE:
11296         // Converting this to a max would handle both negative zeros and NaNs
11297         // incorrectly, but we can swap the operands to fix both.
11298         std::swap(LHS, RHS);
11299       case ISD::SETOLT:
11300       case ISD::SETLT:
11301       case ISD::SETLE:
11302         Opcode = X86ISD::FMAX;
11303         break;
11304       }
11305     }
11306
11307     if (Opcode)
11308       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
11309   }
11310
11311   // If this is a select between two integer constants, try to do some
11312   // optimizations.
11313   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
11314     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
11315       // Don't do this for crazy integer types.
11316       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
11317         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
11318         // so that TrueC (the true value) is larger than FalseC.
11319         bool NeedsCondInvert = false;
11320
11321         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
11322             // Efficiently invertible.
11323             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
11324              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
11325               isa<ConstantSDNode>(Cond.getOperand(1))))) {
11326           NeedsCondInvert = true;
11327           std::swap(TrueC, FalseC);
11328         }
11329
11330         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
11331         if (FalseC->getAPIntValue() == 0 &&
11332             TrueC->getAPIntValue().isPowerOf2()) {
11333           if (NeedsCondInvert) // Invert the condition if needed.
11334             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11335                                DAG.getConstant(1, Cond.getValueType()));
11336
11337           // Zero extend the condition if needed.
11338           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
11339
11340           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
11341           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
11342                              DAG.getConstant(ShAmt, MVT::i8));
11343         }
11344
11345         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
11346         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
11347           if (NeedsCondInvert) // Invert the condition if needed.
11348             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11349                                DAG.getConstant(1, Cond.getValueType()));
11350
11351           // Zero extend the condition if needed.
11352           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
11353                              FalseC->getValueType(0), Cond);
11354           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11355                              SDValue(FalseC, 0));
11356         }
11357
11358         // Optimize cases that will turn into an LEA instruction.  This requires
11359         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
11360         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
11361           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
11362           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
11363
11364           bool isFastMultiplier = false;
11365           if (Diff < 10) {
11366             switch ((unsigned char)Diff) {
11367               default: break;
11368               case 1:  // result = add base, cond
11369               case 2:  // result = lea base(    , cond*2)
11370               case 3:  // result = lea base(cond, cond*2)
11371               case 4:  // result = lea base(    , cond*4)
11372               case 5:  // result = lea base(cond, cond*4)
11373               case 8:  // result = lea base(    , cond*8)
11374               case 9:  // result = lea base(cond, cond*8)
11375                 isFastMultiplier = true;
11376                 break;
11377             }
11378           }
11379
11380           if (isFastMultiplier) {
11381             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
11382             if (NeedsCondInvert) // Invert the condition if needed.
11383               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11384                                  DAG.getConstant(1, Cond.getValueType()));
11385
11386             // Zero extend the condition if needed.
11387             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
11388                                Cond);
11389             // Scale the condition by the difference.
11390             if (Diff != 1)
11391               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
11392                                  DAG.getConstant(Diff, Cond.getValueType()));
11393
11394             // Add the base if non-zero.
11395             if (FalseC->getAPIntValue() != 0)
11396               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11397                                  SDValue(FalseC, 0));
11398             return Cond;
11399           }
11400         }
11401       }
11402   }
11403
11404   return SDValue();
11405 }
11406
11407 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
11408 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
11409                                   TargetLowering::DAGCombinerInfo &DCI) {
11410   DebugLoc DL = N->getDebugLoc();
11411
11412   // If the flag operand isn't dead, don't touch this CMOV.
11413   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
11414     return SDValue();
11415
11416   SDValue FalseOp = N->getOperand(0);
11417   SDValue TrueOp = N->getOperand(1);
11418   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
11419   SDValue Cond = N->getOperand(3);
11420   if (CC == X86::COND_E || CC == X86::COND_NE) {
11421     switch (Cond.getOpcode()) {
11422     default: break;
11423     case X86ISD::BSR:
11424     case X86ISD::BSF:
11425       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
11426       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
11427         return (CC == X86::COND_E) ? FalseOp : TrueOp;
11428     }
11429   }
11430
11431   // If this is a select between two integer constants, try to do some
11432   // optimizations.  Note that the operands are ordered the opposite of SELECT
11433   // operands.
11434   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
11435     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
11436       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
11437       // larger than FalseC (the false value).
11438       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
11439         CC = X86::GetOppositeBranchCondition(CC);
11440         std::swap(TrueC, FalseC);
11441       }
11442
11443       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
11444       // This is efficient for any integer data type (including i8/i16) and
11445       // shift amount.
11446       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
11447         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11448                            DAG.getConstant(CC, MVT::i8), Cond);
11449
11450         // Zero extend the condition if needed.
11451         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
11452
11453         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
11454         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
11455                            DAG.getConstant(ShAmt, MVT::i8));
11456         if (N->getNumValues() == 2)  // Dead flag value?
11457           return DCI.CombineTo(N, Cond, SDValue());
11458         return Cond;
11459       }
11460
11461       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
11462       // for any integer data type, including i8/i16.
11463       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
11464         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11465                            DAG.getConstant(CC, MVT::i8), Cond);
11466
11467         // Zero extend the condition if needed.
11468         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
11469                            FalseC->getValueType(0), Cond);
11470         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11471                            SDValue(FalseC, 0));
11472
11473         if (N->getNumValues() == 2)  // Dead flag value?
11474           return DCI.CombineTo(N, Cond, SDValue());
11475         return Cond;
11476       }
11477
11478       // Optimize cases that will turn into an LEA instruction.  This requires
11479       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
11480       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
11481         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
11482         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
11483
11484         bool isFastMultiplier = false;
11485         if (Diff < 10) {
11486           switch ((unsigned char)Diff) {
11487           default: break;
11488           case 1:  // result = add base, cond
11489           case 2:  // result = lea base(    , cond*2)
11490           case 3:  // result = lea base(cond, cond*2)
11491           case 4:  // result = lea base(    , cond*4)
11492           case 5:  // result = lea base(cond, cond*4)
11493           case 8:  // result = lea base(    , cond*8)
11494           case 9:  // result = lea base(cond, cond*8)
11495             isFastMultiplier = true;
11496             break;
11497           }
11498         }
11499
11500         if (isFastMultiplier) {
11501           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
11502           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11503                              DAG.getConstant(CC, MVT::i8), Cond);
11504           // Zero extend the condition if needed.
11505           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
11506                              Cond);
11507           // Scale the condition by the difference.
11508           if (Diff != 1)
11509             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
11510                                DAG.getConstant(Diff, Cond.getValueType()));
11511
11512           // Add the base if non-zero.
11513           if (FalseC->getAPIntValue() != 0)
11514             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11515                                SDValue(FalseC, 0));
11516           if (N->getNumValues() == 2)  // Dead flag value?
11517             return DCI.CombineTo(N, Cond, SDValue());
11518           return Cond;
11519         }
11520       }
11521     }
11522   }
11523   return SDValue();
11524 }
11525
11526
11527 /// PerformMulCombine - Optimize a single multiply with constant into two
11528 /// in order to implement it with two cheaper instructions, e.g.
11529 /// LEA + SHL, LEA + LEA.
11530 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
11531                                  TargetLowering::DAGCombinerInfo &DCI) {
11532   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11533     return SDValue();
11534
11535   EVT VT = N->getValueType(0);
11536   if (VT != MVT::i64)
11537     return SDValue();
11538
11539   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
11540   if (!C)
11541     return SDValue();
11542   uint64_t MulAmt = C->getZExtValue();
11543   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
11544     return SDValue();
11545
11546   uint64_t MulAmt1 = 0;
11547   uint64_t MulAmt2 = 0;
11548   if ((MulAmt % 9) == 0) {
11549     MulAmt1 = 9;
11550     MulAmt2 = MulAmt / 9;
11551   } else if ((MulAmt % 5) == 0) {
11552     MulAmt1 = 5;
11553     MulAmt2 = MulAmt / 5;
11554   } else if ((MulAmt % 3) == 0) {
11555     MulAmt1 = 3;
11556     MulAmt2 = MulAmt / 3;
11557   }
11558   if (MulAmt2 &&
11559       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
11560     DebugLoc DL = N->getDebugLoc();
11561
11562     if (isPowerOf2_64(MulAmt2) &&
11563         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
11564       // If second multiplifer is pow2, issue it first. We want the multiply by
11565       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
11566       // is an add.
11567       std::swap(MulAmt1, MulAmt2);
11568
11569     SDValue NewMul;
11570     if (isPowerOf2_64(MulAmt1))
11571       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
11572                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
11573     else
11574       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
11575                            DAG.getConstant(MulAmt1, VT));
11576
11577     if (isPowerOf2_64(MulAmt2))
11578       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
11579                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
11580     else
11581       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
11582                            DAG.getConstant(MulAmt2, VT));
11583
11584     // Do not add new nodes to DAG combiner worklist.
11585     DCI.CombineTo(N, NewMul, false);
11586   }
11587   return SDValue();
11588 }
11589
11590 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
11591   SDValue N0 = N->getOperand(0);
11592   SDValue N1 = N->getOperand(1);
11593   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
11594   EVT VT = N0.getValueType();
11595
11596   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
11597   // since the result of setcc_c is all zero's or all ones.
11598   if (N1C && N0.getOpcode() == ISD::AND &&
11599       N0.getOperand(1).getOpcode() == ISD::Constant) {
11600     SDValue N00 = N0.getOperand(0);
11601     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
11602         ((N00.getOpcode() == ISD::ANY_EXTEND ||
11603           N00.getOpcode() == ISD::ZERO_EXTEND) &&
11604          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
11605       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
11606       APInt ShAmt = N1C->getAPIntValue();
11607       Mask = Mask.shl(ShAmt);
11608       if (Mask != 0)
11609         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
11610                            N00, DAG.getConstant(Mask, VT));
11611     }
11612   }
11613
11614   return SDValue();
11615 }
11616
11617 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
11618 ///                       when possible.
11619 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
11620                                    const X86Subtarget *Subtarget) {
11621   EVT VT = N->getValueType(0);
11622   if (!VT.isVector() && VT.isInteger() &&
11623       N->getOpcode() == ISD::SHL)
11624     return PerformSHLCombine(N, DAG);
11625
11626   // On X86 with SSE2 support, we can transform this to a vector shift if
11627   // all elements are shifted by the same amount.  We can't do this in legalize
11628   // because the a constant vector is typically transformed to a constant pool
11629   // so we have no knowledge of the shift amount.
11630   if (!Subtarget->hasSSE2())
11631     return SDValue();
11632
11633   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
11634     return SDValue();
11635
11636   SDValue ShAmtOp = N->getOperand(1);
11637   EVT EltVT = VT.getVectorElementType();
11638   DebugLoc DL = N->getDebugLoc();
11639   SDValue BaseShAmt = SDValue();
11640   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
11641     unsigned NumElts = VT.getVectorNumElements();
11642     unsigned i = 0;
11643     for (; i != NumElts; ++i) {
11644       SDValue Arg = ShAmtOp.getOperand(i);
11645       if (Arg.getOpcode() == ISD::UNDEF) continue;
11646       BaseShAmt = Arg;
11647       break;
11648     }
11649     for (; i != NumElts; ++i) {
11650       SDValue Arg = ShAmtOp.getOperand(i);
11651       if (Arg.getOpcode() == ISD::UNDEF) continue;
11652       if (Arg != BaseShAmt) {
11653         return SDValue();
11654       }
11655     }
11656   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
11657              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
11658     SDValue InVec = ShAmtOp.getOperand(0);
11659     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
11660       unsigned NumElts = InVec.getValueType().getVectorNumElements();
11661       unsigned i = 0;
11662       for (; i != NumElts; ++i) {
11663         SDValue Arg = InVec.getOperand(i);
11664         if (Arg.getOpcode() == ISD::UNDEF) continue;
11665         BaseShAmt = Arg;
11666         break;
11667       }
11668     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
11669        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
11670          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
11671          if (C->getZExtValue() == SplatIdx)
11672            BaseShAmt = InVec.getOperand(1);
11673        }
11674     }
11675     if (BaseShAmt.getNode() == 0)
11676       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
11677                               DAG.getIntPtrConstant(0));
11678   } else
11679     return SDValue();
11680
11681   // The shift amount is an i32.
11682   if (EltVT.bitsGT(MVT::i32))
11683     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
11684   else if (EltVT.bitsLT(MVT::i32))
11685     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
11686
11687   // The shift amount is identical so we can do a vector shift.
11688   SDValue  ValOp = N->getOperand(0);
11689   switch (N->getOpcode()) {
11690   default:
11691     llvm_unreachable("Unknown shift opcode!");
11692     break;
11693   case ISD::SHL:
11694     if (VT == MVT::v2i64)
11695       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11696                          DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
11697                          ValOp, BaseShAmt);
11698     if (VT == MVT::v4i32)
11699       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11700                          DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
11701                          ValOp, BaseShAmt);
11702     if (VT == MVT::v8i16)
11703       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11704                          DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
11705                          ValOp, BaseShAmt);
11706     break;
11707   case ISD::SRA:
11708     if (VT == MVT::v4i32)
11709       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11710                          DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
11711                          ValOp, BaseShAmt);
11712     if (VT == MVT::v8i16)
11713       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11714                          DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
11715                          ValOp, BaseShAmt);
11716     break;
11717   case ISD::SRL:
11718     if (VT == MVT::v2i64)
11719       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11720                          DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
11721                          ValOp, BaseShAmt);
11722     if (VT == MVT::v4i32)
11723       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11724                          DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
11725                          ValOp, BaseShAmt);
11726     if (VT ==  MVT::v8i16)
11727       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11728                          DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
11729                          ValOp, BaseShAmt);
11730     break;
11731   }
11732   return SDValue();
11733 }
11734
11735
11736 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
11737 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
11738 // and friends.  Likewise for OR -> CMPNEQSS.
11739 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
11740                             TargetLowering::DAGCombinerInfo &DCI,
11741                             const X86Subtarget *Subtarget) {
11742   unsigned opcode;
11743
11744   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
11745   // we're requiring SSE2 for both.
11746   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
11747     SDValue N0 = N->getOperand(0);
11748     SDValue N1 = N->getOperand(1);
11749     SDValue CMP0 = N0->getOperand(1);
11750     SDValue CMP1 = N1->getOperand(1);
11751     DebugLoc DL = N->getDebugLoc();
11752
11753     // The SETCCs should both refer to the same CMP.
11754     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
11755       return SDValue();
11756
11757     SDValue CMP00 = CMP0->getOperand(0);
11758     SDValue CMP01 = CMP0->getOperand(1);
11759     EVT     VT    = CMP00.getValueType();
11760
11761     if (VT == MVT::f32 || VT == MVT::f64) {
11762       bool ExpectingFlags = false;
11763       // Check for any users that want flags:
11764       for (SDNode::use_iterator UI = N->use_begin(),
11765              UE = N->use_end();
11766            !ExpectingFlags && UI != UE; ++UI)
11767         switch (UI->getOpcode()) {
11768         default:
11769         case ISD::BR_CC:
11770         case ISD::BRCOND:
11771         case ISD::SELECT:
11772           ExpectingFlags = true;
11773           break;
11774         case ISD::CopyToReg:
11775         case ISD::SIGN_EXTEND:
11776         case ISD::ZERO_EXTEND:
11777         case ISD::ANY_EXTEND:
11778           break;
11779         }
11780
11781       if (!ExpectingFlags) {
11782         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
11783         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
11784
11785         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
11786           X86::CondCode tmp = cc0;
11787           cc0 = cc1;
11788           cc1 = tmp;
11789         }
11790
11791         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
11792             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
11793           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
11794           X86ISD::NodeType NTOperator = is64BitFP ?
11795             X86ISD::FSETCCsd : X86ISD::FSETCCss;
11796           // FIXME: need symbolic constants for these magic numbers.
11797           // See X86ATTInstPrinter.cpp:printSSECC().
11798           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
11799           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
11800                                               DAG.getConstant(x86cc, MVT::i8));
11801           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
11802                                               OnesOrZeroesF);
11803           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
11804                                       DAG.getConstant(1, MVT::i32));
11805           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
11806           return OneBitOfTruth;
11807         }
11808       }
11809     }
11810   }
11811   return SDValue();
11812 }
11813
11814 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
11815                                  TargetLowering::DAGCombinerInfo &DCI,
11816                                  const X86Subtarget *Subtarget) {
11817   if (DCI.isBeforeLegalizeOps())
11818     return SDValue();
11819
11820   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
11821   if (R.getNode())
11822     return R;
11823
11824   // Want to form ANDNP nodes:
11825   // 1) In the hopes of then easily combining them with OR and AND nodes
11826   //    to form PBLEND/PSIGN.
11827   // 2) To match ANDN packed intrinsics
11828   EVT VT = N->getValueType(0);
11829   if (VT != MVT::v2i64 && VT != MVT::v4i64)
11830     return SDValue();
11831
11832   SDValue N0 = N->getOperand(0);
11833   SDValue N1 = N->getOperand(1);
11834   DebugLoc DL = N->getDebugLoc();
11835
11836   // Check LHS for vnot
11837   if (N0.getOpcode() == ISD::XOR &&
11838       ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
11839     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
11840
11841   // Check RHS for vnot
11842   if (N1.getOpcode() == ISD::XOR &&
11843       ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
11844     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
11845
11846   return SDValue();
11847 }
11848
11849 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
11850                                 TargetLowering::DAGCombinerInfo &DCI,
11851                                 const X86Subtarget *Subtarget) {
11852   if (DCI.isBeforeLegalizeOps())
11853     return SDValue();
11854
11855   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
11856   if (R.getNode())
11857     return R;
11858
11859   EVT VT = N->getValueType(0);
11860   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64 && VT != MVT::v2i64)
11861     return SDValue();
11862
11863   SDValue N0 = N->getOperand(0);
11864   SDValue N1 = N->getOperand(1);
11865
11866   // look for psign/blend
11867   if (Subtarget->hasSSSE3()) {
11868     if (VT == MVT::v2i64) {
11869       // Canonicalize pandn to RHS
11870       if (N0.getOpcode() == X86ISD::ANDNP)
11871         std::swap(N0, N1);
11872       // or (and (m, x), (pandn m, y))
11873       if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
11874         SDValue Mask = N1.getOperand(0);
11875         SDValue X    = N1.getOperand(1);
11876         SDValue Y;
11877         if (N0.getOperand(0) == Mask)
11878           Y = N0.getOperand(1);
11879         if (N0.getOperand(1) == Mask)
11880           Y = N0.getOperand(0);
11881
11882         // Check to see if the mask appeared in both the AND and ANDNP and
11883         if (!Y.getNode())
11884           return SDValue();
11885
11886         // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
11887         if (Mask.getOpcode() != ISD::BITCAST ||
11888             X.getOpcode() != ISD::BITCAST ||
11889             Y.getOpcode() != ISD::BITCAST)
11890           return SDValue();
11891
11892         // Look through mask bitcast.
11893         Mask = Mask.getOperand(0);
11894         EVT MaskVT = Mask.getValueType();
11895
11896         // Validate that the Mask operand is a vector sra node.  The sra node
11897         // will be an intrinsic.
11898         if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
11899           return SDValue();
11900
11901         // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
11902         // there is no psrai.b
11903         switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
11904         case Intrinsic::x86_sse2_psrai_w:
11905         case Intrinsic::x86_sse2_psrai_d:
11906           break;
11907         default: return SDValue();
11908         }
11909
11910         // Check that the SRA is all signbits.
11911         SDValue SraC = Mask.getOperand(2);
11912         unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
11913         unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
11914         if ((SraAmt + 1) != EltBits)
11915           return SDValue();
11916
11917         DebugLoc DL = N->getDebugLoc();
11918
11919         // Now we know we at least have a plendvb with the mask val.  See if
11920         // we can form a psignb/w/d.
11921         // psign = x.type == y.type == mask.type && y = sub(0, x);
11922         X = X.getOperand(0);
11923         Y = Y.getOperand(0);
11924         if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
11925             ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
11926             X.getValueType() == MaskVT && X.getValueType() == Y.getValueType()){
11927           unsigned Opc = 0;
11928           switch (EltBits) {
11929           case 8: Opc = X86ISD::PSIGNB; break;
11930           case 16: Opc = X86ISD::PSIGNW; break;
11931           case 32: Opc = X86ISD::PSIGND; break;
11932           default: break;
11933           }
11934           if (Opc) {
11935             SDValue Sign = DAG.getNode(Opc, DL, MaskVT, X, Mask.getOperand(1));
11936             return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Sign);
11937           }
11938         }
11939         // PBLENDVB only available on SSE 4.1
11940         if (!Subtarget->hasSSE41())
11941           return SDValue();
11942
11943         X = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, X);
11944         Y = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Y);
11945         Mask = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Mask);
11946         Mask = DAG.getNode(X86ISD::PBLENDVB, DL, MVT::v16i8, X, Y, Mask);
11947         return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Mask);
11948       }
11949     }
11950   }
11951
11952   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
11953   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
11954     std::swap(N0, N1);
11955   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
11956     return SDValue();
11957   if (!N0.hasOneUse() || !N1.hasOneUse())
11958     return SDValue();
11959
11960   SDValue ShAmt0 = N0.getOperand(1);
11961   if (ShAmt0.getValueType() != MVT::i8)
11962     return SDValue();
11963   SDValue ShAmt1 = N1.getOperand(1);
11964   if (ShAmt1.getValueType() != MVT::i8)
11965     return SDValue();
11966   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
11967     ShAmt0 = ShAmt0.getOperand(0);
11968   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
11969     ShAmt1 = ShAmt1.getOperand(0);
11970
11971   DebugLoc DL = N->getDebugLoc();
11972   unsigned Opc = X86ISD::SHLD;
11973   SDValue Op0 = N0.getOperand(0);
11974   SDValue Op1 = N1.getOperand(0);
11975   if (ShAmt0.getOpcode() == ISD::SUB) {
11976     Opc = X86ISD::SHRD;
11977     std::swap(Op0, Op1);
11978     std::swap(ShAmt0, ShAmt1);
11979   }
11980
11981   unsigned Bits = VT.getSizeInBits();
11982   if (ShAmt1.getOpcode() == ISD::SUB) {
11983     SDValue Sum = ShAmt1.getOperand(0);
11984     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
11985       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
11986       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
11987         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
11988       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
11989         return DAG.getNode(Opc, DL, VT,
11990                            Op0, Op1,
11991                            DAG.getNode(ISD::TRUNCATE, DL,
11992                                        MVT::i8, ShAmt0));
11993     }
11994   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
11995     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
11996     if (ShAmt0C &&
11997         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
11998       return DAG.getNode(Opc, DL, VT,
11999                          N0.getOperand(0), N1.getOperand(0),
12000                          DAG.getNode(ISD::TRUNCATE, DL,
12001                                        MVT::i8, ShAmt0));
12002   }
12003
12004   return SDValue();
12005 }
12006
12007 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
12008 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
12009                                    const X86Subtarget *Subtarget) {
12010   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
12011   // the FP state in cases where an emms may be missing.
12012   // A preferable solution to the general problem is to figure out the right
12013   // places to insert EMMS.  This qualifies as a quick hack.
12014
12015   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
12016   StoreSDNode *St = cast<StoreSDNode>(N);
12017   EVT VT = St->getValue().getValueType();
12018   if (VT.getSizeInBits() != 64)
12019     return SDValue();
12020
12021   const Function *F = DAG.getMachineFunction().getFunction();
12022   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
12023   bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
12024     && Subtarget->hasSSE2();
12025   if ((VT.isVector() ||
12026        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
12027       isa<LoadSDNode>(St->getValue()) &&
12028       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
12029       St->getChain().hasOneUse() && !St->isVolatile()) {
12030     SDNode* LdVal = St->getValue().getNode();
12031     LoadSDNode *Ld = 0;
12032     int TokenFactorIndex = -1;
12033     SmallVector<SDValue, 8> Ops;
12034     SDNode* ChainVal = St->getChain().getNode();
12035     // Must be a store of a load.  We currently handle two cases:  the load
12036     // is a direct child, and it's under an intervening TokenFactor.  It is
12037     // possible to dig deeper under nested TokenFactors.
12038     if (ChainVal == LdVal)
12039       Ld = cast<LoadSDNode>(St->getChain());
12040     else if (St->getValue().hasOneUse() &&
12041              ChainVal->getOpcode() == ISD::TokenFactor) {
12042       for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
12043         if (ChainVal->getOperand(i).getNode() == LdVal) {
12044           TokenFactorIndex = i;
12045           Ld = cast<LoadSDNode>(St->getValue());
12046         } else
12047           Ops.push_back(ChainVal->getOperand(i));
12048       }
12049     }
12050
12051     if (!Ld || !ISD::isNormalLoad(Ld))
12052       return SDValue();
12053
12054     // If this is not the MMX case, i.e. we are just turning i64 load/store
12055     // into f64 load/store, avoid the transformation if there are multiple
12056     // uses of the loaded value.
12057     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
12058       return SDValue();
12059
12060     DebugLoc LdDL = Ld->getDebugLoc();
12061     DebugLoc StDL = N->getDebugLoc();
12062     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
12063     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
12064     // pair instead.
12065     if (Subtarget->is64Bit() || F64IsLegal) {
12066       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
12067       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
12068                                   Ld->getPointerInfo(), Ld->isVolatile(),
12069                                   Ld->isNonTemporal(), Ld->getAlignment());
12070       SDValue NewChain = NewLd.getValue(1);
12071       if (TokenFactorIndex != -1) {
12072         Ops.push_back(NewChain);
12073         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
12074                                Ops.size());
12075       }
12076       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
12077                           St->getPointerInfo(),
12078                           St->isVolatile(), St->isNonTemporal(),
12079                           St->getAlignment());
12080     }
12081
12082     // Otherwise, lower to two pairs of 32-bit loads / stores.
12083     SDValue LoAddr = Ld->getBasePtr();
12084     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
12085                                  DAG.getConstant(4, MVT::i32));
12086
12087     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
12088                                Ld->getPointerInfo(),
12089                                Ld->isVolatile(), Ld->isNonTemporal(),
12090                                Ld->getAlignment());
12091     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
12092                                Ld->getPointerInfo().getWithOffset(4),
12093                                Ld->isVolatile(), Ld->isNonTemporal(),
12094                                MinAlign(Ld->getAlignment(), 4));
12095
12096     SDValue NewChain = LoLd.getValue(1);
12097     if (TokenFactorIndex != -1) {
12098       Ops.push_back(LoLd);
12099       Ops.push_back(HiLd);
12100       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
12101                              Ops.size());
12102     }
12103
12104     LoAddr = St->getBasePtr();
12105     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
12106                          DAG.getConstant(4, MVT::i32));
12107
12108     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
12109                                 St->getPointerInfo(),
12110                                 St->isVolatile(), St->isNonTemporal(),
12111                                 St->getAlignment());
12112     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
12113                                 St->getPointerInfo().getWithOffset(4),
12114                                 St->isVolatile(),
12115                                 St->isNonTemporal(),
12116                                 MinAlign(St->getAlignment(), 4));
12117     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
12118   }
12119   return SDValue();
12120 }
12121
12122 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
12123 /// X86ISD::FXOR nodes.
12124 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
12125   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
12126   // F[X]OR(0.0, x) -> x
12127   // F[X]OR(x, 0.0) -> x
12128   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
12129     if (C->getValueAPF().isPosZero())
12130       return N->getOperand(1);
12131   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
12132     if (C->getValueAPF().isPosZero())
12133       return N->getOperand(0);
12134   return SDValue();
12135 }
12136
12137 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
12138 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
12139   // FAND(0.0, x) -> 0.0
12140   // FAND(x, 0.0) -> 0.0
12141   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
12142     if (C->getValueAPF().isPosZero())
12143       return N->getOperand(0);
12144   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
12145     if (C->getValueAPF().isPosZero())
12146       return N->getOperand(1);
12147   return SDValue();
12148 }
12149
12150 static SDValue PerformBTCombine(SDNode *N,
12151                                 SelectionDAG &DAG,
12152                                 TargetLowering::DAGCombinerInfo &DCI) {
12153   // BT ignores high bits in the bit index operand.
12154   SDValue Op1 = N->getOperand(1);
12155   if (Op1.hasOneUse()) {
12156     unsigned BitWidth = Op1.getValueSizeInBits();
12157     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
12158     APInt KnownZero, KnownOne;
12159     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
12160                                           !DCI.isBeforeLegalizeOps());
12161     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12162     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
12163         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
12164       DCI.CommitTargetLoweringOpt(TLO);
12165   }
12166   return SDValue();
12167 }
12168
12169 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
12170   SDValue Op = N->getOperand(0);
12171   if (Op.getOpcode() == ISD::BITCAST)
12172     Op = Op.getOperand(0);
12173   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
12174   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
12175       VT.getVectorElementType().getSizeInBits() ==
12176       OpVT.getVectorElementType().getSizeInBits()) {
12177     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
12178   }
12179   return SDValue();
12180 }
12181
12182 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
12183   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
12184   //           (and (i32 x86isd::setcc_carry), 1)
12185   // This eliminates the zext. This transformation is necessary because
12186   // ISD::SETCC is always legalized to i8.
12187   DebugLoc dl = N->getDebugLoc();
12188   SDValue N0 = N->getOperand(0);
12189   EVT VT = N->getValueType(0);
12190   if (N0.getOpcode() == ISD::AND &&
12191       N0.hasOneUse() &&
12192       N0.getOperand(0).hasOneUse()) {
12193     SDValue N00 = N0.getOperand(0);
12194     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
12195       return SDValue();
12196     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
12197     if (!C || C->getZExtValue() != 1)
12198       return SDValue();
12199     return DAG.getNode(ISD::AND, dl, VT,
12200                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
12201                                    N00.getOperand(0), N00.getOperand(1)),
12202                        DAG.getConstant(1, VT));
12203   }
12204
12205   return SDValue();
12206 }
12207
12208 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
12209 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
12210   unsigned X86CC = N->getConstantOperandVal(0);
12211   SDValue EFLAG = N->getOperand(1);
12212   DebugLoc DL = N->getDebugLoc();
12213
12214   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
12215   // a zext and produces an all-ones bit which is more useful than 0/1 in some
12216   // cases.
12217   if (X86CC == X86::COND_B)
12218     return DAG.getNode(ISD::AND, DL, MVT::i8,
12219                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
12220                                    DAG.getConstant(X86CC, MVT::i8), EFLAG),
12221                        DAG.getConstant(1, MVT::i8));
12222
12223   return SDValue();
12224 }
12225
12226 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
12227                                         const X86TargetLowering *XTLI) {
12228   SDValue Op0 = N->getOperand(0);
12229   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
12230   // a 32-bit target where SSE doesn't support i64->FP operations.
12231   if (Op0.getOpcode() == ISD::LOAD) {
12232     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
12233     EVT VT = Ld->getValueType(0);
12234     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
12235         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
12236         !XTLI->getSubtarget()->is64Bit() &&
12237         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
12238       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
12239                                           Ld->getChain(), Op0, DAG);
12240       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
12241       return FILDChain;
12242     }
12243   }
12244   return SDValue();
12245 }
12246
12247 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
12248 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
12249                                  X86TargetLowering::DAGCombinerInfo &DCI) {
12250   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
12251   // the result is either zero or one (depending on the input carry bit).
12252   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
12253   if (X86::isZeroNode(N->getOperand(0)) &&
12254       X86::isZeroNode(N->getOperand(1)) &&
12255       // We don't have a good way to replace an EFLAGS use, so only do this when
12256       // dead right now.
12257       SDValue(N, 1).use_empty()) {
12258     DebugLoc DL = N->getDebugLoc();
12259     EVT VT = N->getValueType(0);
12260     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
12261     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
12262                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
12263                                            DAG.getConstant(X86::COND_B,MVT::i8),
12264                                            N->getOperand(2)),
12265                                DAG.getConstant(1, VT));
12266     return DCI.CombineTo(N, Res1, CarryOut);
12267   }
12268
12269   return SDValue();
12270 }
12271
12272 // fold (add Y, (sete  X, 0)) -> adc  0, Y
12273 //      (add Y, (setne X, 0)) -> sbb -1, Y
12274 //      (sub (sete  X, 0), Y) -> sbb  0, Y
12275 //      (sub (setne X, 0), Y) -> adc -1, Y
12276 static SDValue OptimizeConditonalInDecrement(SDNode *N, SelectionDAG &DAG) {
12277   DebugLoc DL = N->getDebugLoc();
12278
12279   // Look through ZExts.
12280   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
12281   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
12282     return SDValue();
12283
12284   SDValue SetCC = Ext.getOperand(0);
12285   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
12286     return SDValue();
12287
12288   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
12289   if (CC != X86::COND_E && CC != X86::COND_NE)
12290     return SDValue();
12291
12292   SDValue Cmp = SetCC.getOperand(1);
12293   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
12294       !X86::isZeroNode(Cmp.getOperand(1)) ||
12295       !Cmp.getOperand(0).getValueType().isInteger())
12296     return SDValue();
12297
12298   SDValue CmpOp0 = Cmp.getOperand(0);
12299   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
12300                                DAG.getConstant(1, CmpOp0.getValueType()));
12301
12302   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
12303   if (CC == X86::COND_NE)
12304     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
12305                        DL, OtherVal.getValueType(), OtherVal,
12306                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
12307   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
12308                      DL, OtherVal.getValueType(), OtherVal,
12309                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
12310 }
12311
12312 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
12313                                              DAGCombinerInfo &DCI) const {
12314   SelectionDAG &DAG = DCI.DAG;
12315   switch (N->getOpcode()) {
12316   default: break;
12317   case ISD::EXTRACT_VECTOR_ELT:
12318     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
12319   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
12320   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
12321   case ISD::ADD:
12322   case ISD::SUB:            return OptimizeConditonalInDecrement(N, DAG);
12323   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
12324   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
12325   case ISD::SHL:
12326   case ISD::SRA:
12327   case ISD::SRL:            return PerformShiftCombine(N, DAG, Subtarget);
12328   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
12329   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
12330   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
12331   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
12332   case X86ISD::FXOR:
12333   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
12334   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
12335   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
12336   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
12337   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG);
12338   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG);
12339   case X86ISD::SHUFPS:      // Handle all target specific shuffles
12340   case X86ISD::SHUFPD:
12341   case X86ISD::PALIGN:
12342   case X86ISD::PUNPCKHBW:
12343   case X86ISD::PUNPCKHWD:
12344   case X86ISD::PUNPCKHDQ:
12345   case X86ISD::PUNPCKHQDQ:
12346   case X86ISD::UNPCKHPS:
12347   case X86ISD::UNPCKHPD:
12348   case X86ISD::PUNPCKLBW:
12349   case X86ISD::PUNPCKLWD:
12350   case X86ISD::PUNPCKLDQ:
12351   case X86ISD::PUNPCKLQDQ:
12352   case X86ISD::UNPCKLPS:
12353   case X86ISD::UNPCKLPD:
12354   case X86ISD::VUNPCKLPS:
12355   case X86ISD::VUNPCKLPD:
12356   case X86ISD::VUNPCKLPSY:
12357   case X86ISD::VUNPCKLPDY:
12358   case X86ISD::MOVHLPS:
12359   case X86ISD::MOVLHPS:
12360   case X86ISD::PSHUFD:
12361   case X86ISD::PSHUFHW:
12362   case X86ISD::PSHUFLW:
12363   case X86ISD::MOVSS:
12364   case X86ISD::MOVSD:
12365   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI);
12366   }
12367
12368   return SDValue();
12369 }
12370
12371 /// isTypeDesirableForOp - Return true if the target has native support for
12372 /// the specified value type and it is 'desirable' to use the type for the
12373 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
12374 /// instruction encodings are longer and some i16 instructions are slow.
12375 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
12376   if (!isTypeLegal(VT))
12377     return false;
12378   if (VT != MVT::i16)
12379     return true;
12380
12381   switch (Opc) {
12382   default:
12383     return true;
12384   case ISD::LOAD:
12385   case ISD::SIGN_EXTEND:
12386   case ISD::ZERO_EXTEND:
12387   case ISD::ANY_EXTEND:
12388   case ISD::SHL:
12389   case ISD::SRL:
12390   case ISD::SUB:
12391   case ISD::ADD:
12392   case ISD::MUL:
12393   case ISD::AND:
12394   case ISD::OR:
12395   case ISD::XOR:
12396     return false;
12397   }
12398 }
12399
12400 /// IsDesirableToPromoteOp - This method query the target whether it is
12401 /// beneficial for dag combiner to promote the specified node. If true, it
12402 /// should return the desired promotion type by reference.
12403 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
12404   EVT VT = Op.getValueType();
12405   if (VT != MVT::i16)
12406     return false;
12407
12408   bool Promote = false;
12409   bool Commute = false;
12410   switch (Op.getOpcode()) {
12411   default: break;
12412   case ISD::LOAD: {
12413     LoadSDNode *LD = cast<LoadSDNode>(Op);
12414     // If the non-extending load has a single use and it's not live out, then it
12415     // might be folded.
12416     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
12417                                                      Op.hasOneUse()*/) {
12418       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12419              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
12420         // The only case where we'd want to promote LOAD (rather then it being
12421         // promoted as an operand is when it's only use is liveout.
12422         if (UI->getOpcode() != ISD::CopyToReg)
12423           return false;
12424       }
12425     }
12426     Promote = true;
12427     break;
12428   }
12429   case ISD::SIGN_EXTEND:
12430   case ISD::ZERO_EXTEND:
12431   case ISD::ANY_EXTEND:
12432     Promote = true;
12433     break;
12434   case ISD::SHL:
12435   case ISD::SRL: {
12436     SDValue N0 = Op.getOperand(0);
12437     // Look out for (store (shl (load), x)).
12438     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
12439       return false;
12440     Promote = true;
12441     break;
12442   }
12443   case ISD::ADD:
12444   case ISD::MUL:
12445   case ISD::AND:
12446   case ISD::OR:
12447   case ISD::XOR:
12448     Commute = true;
12449     // fallthrough
12450   case ISD::SUB: {
12451     SDValue N0 = Op.getOperand(0);
12452     SDValue N1 = Op.getOperand(1);
12453     if (!Commute && MayFoldLoad(N1))
12454       return false;
12455     // Avoid disabling potential load folding opportunities.
12456     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
12457       return false;
12458     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
12459       return false;
12460     Promote = true;
12461   }
12462   }
12463
12464   PVT = MVT::i32;
12465   return Promote;
12466 }
12467
12468 //===----------------------------------------------------------------------===//
12469 //                           X86 Inline Assembly Support
12470 //===----------------------------------------------------------------------===//
12471
12472 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
12473   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
12474
12475   std::string AsmStr = IA->getAsmString();
12476
12477   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
12478   SmallVector<StringRef, 4> AsmPieces;
12479   SplitString(AsmStr, AsmPieces, ";\n");
12480
12481   switch (AsmPieces.size()) {
12482   default: return false;
12483   case 1:
12484     AsmStr = AsmPieces[0];
12485     AsmPieces.clear();
12486     SplitString(AsmStr, AsmPieces, " \t");  // Split with whitespace.
12487
12488     // FIXME: this should verify that we are targeting a 486 or better.  If not,
12489     // we will turn this bswap into something that will be lowered to logical ops
12490     // instead of emitting the bswap asm.  For now, we don't support 486 or lower
12491     // so don't worry about this.
12492     // bswap $0
12493     if (AsmPieces.size() == 2 &&
12494         (AsmPieces[0] == "bswap" ||
12495          AsmPieces[0] == "bswapq" ||
12496          AsmPieces[0] == "bswapl") &&
12497         (AsmPieces[1] == "$0" ||
12498          AsmPieces[1] == "${0:q}")) {
12499       // No need to check constraints, nothing other than the equivalent of
12500       // "=r,0" would be valid here.
12501       const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12502       if (!Ty || Ty->getBitWidth() % 16 != 0)
12503         return false;
12504       return IntrinsicLowering::LowerToByteSwap(CI);
12505     }
12506     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
12507     if (CI->getType()->isIntegerTy(16) &&
12508         AsmPieces.size() == 3 &&
12509         (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
12510         AsmPieces[1] == "$$8," &&
12511         AsmPieces[2] == "${0:w}" &&
12512         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
12513       AsmPieces.clear();
12514       const std::string &ConstraintsStr = IA->getConstraintString();
12515       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
12516       std::sort(AsmPieces.begin(), AsmPieces.end());
12517       if (AsmPieces.size() == 4 &&
12518           AsmPieces[0] == "~{cc}" &&
12519           AsmPieces[1] == "~{dirflag}" &&
12520           AsmPieces[2] == "~{flags}" &&
12521           AsmPieces[3] == "~{fpsr}") {
12522         const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12523         if (!Ty || Ty->getBitWidth() % 16 != 0)
12524           return false;
12525         return IntrinsicLowering::LowerToByteSwap(CI);
12526       }
12527     }
12528     break;
12529   case 3:
12530     if (CI->getType()->isIntegerTy(32) &&
12531         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
12532       SmallVector<StringRef, 4> Words;
12533       SplitString(AsmPieces[0], Words, " \t,");
12534       if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
12535           Words[2] == "${0:w}") {
12536         Words.clear();
12537         SplitString(AsmPieces[1], Words, " \t,");
12538         if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" &&
12539             Words[2] == "$0") {
12540           Words.clear();
12541           SplitString(AsmPieces[2], Words, " \t,");
12542           if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
12543               Words[2] == "${0:w}") {
12544             AsmPieces.clear();
12545             const std::string &ConstraintsStr = IA->getConstraintString();
12546             SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
12547             std::sort(AsmPieces.begin(), AsmPieces.end());
12548             if (AsmPieces.size() == 4 &&
12549                 AsmPieces[0] == "~{cc}" &&
12550                 AsmPieces[1] == "~{dirflag}" &&
12551                 AsmPieces[2] == "~{flags}" &&
12552                 AsmPieces[3] == "~{fpsr}") {
12553               const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12554               if (!Ty || Ty->getBitWidth() % 16 != 0)
12555                 return false;
12556               return IntrinsicLowering::LowerToByteSwap(CI);
12557             }
12558           }
12559         }
12560       }
12561     }
12562
12563     if (CI->getType()->isIntegerTy(64)) {
12564       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
12565       if (Constraints.size() >= 2 &&
12566           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
12567           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
12568         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
12569         SmallVector<StringRef, 4> Words;
12570         SplitString(AsmPieces[0], Words, " \t");
12571         if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
12572           Words.clear();
12573           SplitString(AsmPieces[1], Words, " \t");
12574           if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
12575             Words.clear();
12576             SplitString(AsmPieces[2], Words, " \t,");
12577             if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
12578                 Words[2] == "%edx") {
12579               const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12580               if (!Ty || Ty->getBitWidth() % 16 != 0)
12581                 return false;
12582               return IntrinsicLowering::LowerToByteSwap(CI);
12583             }
12584           }
12585         }
12586       }
12587     }
12588     break;
12589   }
12590   return false;
12591 }
12592
12593
12594
12595 /// getConstraintType - Given a constraint letter, return the type of
12596 /// constraint it is for this target.
12597 X86TargetLowering::ConstraintType
12598 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
12599   if (Constraint.size() == 1) {
12600     switch (Constraint[0]) {
12601     case 'R':
12602     case 'q':
12603     case 'Q':
12604     case 'f':
12605     case 't':
12606     case 'u':
12607     case 'y':
12608     case 'x':
12609     case 'Y':
12610     case 'l':
12611       return C_RegisterClass;
12612     case 'a':
12613     case 'b':
12614     case 'c':
12615     case 'd':
12616     case 'S':
12617     case 'D':
12618     case 'A':
12619       return C_Register;
12620     case 'I':
12621     case 'J':
12622     case 'K':
12623     case 'L':
12624     case 'M':
12625     case 'N':
12626     case 'G':
12627     case 'C':
12628     case 'e':
12629     case 'Z':
12630       return C_Other;
12631     default:
12632       break;
12633     }
12634   }
12635   return TargetLowering::getConstraintType(Constraint);
12636 }
12637
12638 /// Examine constraint type and operand type and determine a weight value.
12639 /// This object must already have been set up with the operand type
12640 /// and the current alternative constraint selected.
12641 TargetLowering::ConstraintWeight
12642   X86TargetLowering::getSingleConstraintMatchWeight(
12643     AsmOperandInfo &info, const char *constraint) const {
12644   ConstraintWeight weight = CW_Invalid;
12645   Value *CallOperandVal = info.CallOperandVal;
12646     // If we don't have a value, we can't do a match,
12647     // but allow it at the lowest weight.
12648   if (CallOperandVal == NULL)
12649     return CW_Default;
12650   const Type *type = CallOperandVal->getType();
12651   // Look at the constraint type.
12652   switch (*constraint) {
12653   default:
12654     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
12655   case 'R':
12656   case 'q':
12657   case 'Q':
12658   case 'a':
12659   case 'b':
12660   case 'c':
12661   case 'd':
12662   case 'S':
12663   case 'D':
12664   case 'A':
12665     if (CallOperandVal->getType()->isIntegerTy())
12666       weight = CW_SpecificReg;
12667     break;
12668   case 'f':
12669   case 't':
12670   case 'u':
12671       if (type->isFloatingPointTy())
12672         weight = CW_SpecificReg;
12673       break;
12674   case 'y':
12675       if (type->isX86_MMXTy() && Subtarget->hasMMX())
12676         weight = CW_SpecificReg;
12677       break;
12678   case 'x':
12679   case 'Y':
12680     if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
12681       weight = CW_Register;
12682     break;
12683   case 'I':
12684     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
12685       if (C->getZExtValue() <= 31)
12686         weight = CW_Constant;
12687     }
12688     break;
12689   case 'J':
12690     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12691       if (C->getZExtValue() <= 63)
12692         weight = CW_Constant;
12693     }
12694     break;
12695   case 'K':
12696     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12697       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
12698         weight = CW_Constant;
12699     }
12700     break;
12701   case 'L':
12702     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12703       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
12704         weight = CW_Constant;
12705     }
12706     break;
12707   case 'M':
12708     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12709       if (C->getZExtValue() <= 3)
12710         weight = CW_Constant;
12711     }
12712     break;
12713   case 'N':
12714     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12715       if (C->getZExtValue() <= 0xff)
12716         weight = CW_Constant;
12717     }
12718     break;
12719   case 'G':
12720   case 'C':
12721     if (dyn_cast<ConstantFP>(CallOperandVal)) {
12722       weight = CW_Constant;
12723     }
12724     break;
12725   case 'e':
12726     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12727       if ((C->getSExtValue() >= -0x80000000LL) &&
12728           (C->getSExtValue() <= 0x7fffffffLL))
12729         weight = CW_Constant;
12730     }
12731     break;
12732   case 'Z':
12733     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12734       if (C->getZExtValue() <= 0xffffffff)
12735         weight = CW_Constant;
12736     }
12737     break;
12738   }
12739   return weight;
12740 }
12741
12742 /// LowerXConstraint - try to replace an X constraint, which matches anything,
12743 /// with another that has more specific requirements based on the type of the
12744 /// corresponding operand.
12745 const char *X86TargetLowering::
12746 LowerXConstraint(EVT ConstraintVT) const {
12747   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
12748   // 'f' like normal targets.
12749   if (ConstraintVT.isFloatingPoint()) {
12750     if (Subtarget->hasXMMInt())
12751       return "Y";
12752     if (Subtarget->hasXMM())
12753       return "x";
12754   }
12755
12756   return TargetLowering::LowerXConstraint(ConstraintVT);
12757 }
12758
12759 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
12760 /// vector.  If it is invalid, don't add anything to Ops.
12761 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
12762                                                      std::string &Constraint,
12763                                                      std::vector<SDValue>&Ops,
12764                                                      SelectionDAG &DAG) const {
12765   SDValue Result(0, 0);
12766
12767   // Only support length 1 constraints for now.
12768   if (Constraint.length() > 1) return;
12769
12770   char ConstraintLetter = Constraint[0];
12771   switch (ConstraintLetter) {
12772   default: break;
12773   case 'I':
12774     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12775       if (C->getZExtValue() <= 31) {
12776         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12777         break;
12778       }
12779     }
12780     return;
12781   case 'J':
12782     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12783       if (C->getZExtValue() <= 63) {
12784         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12785         break;
12786       }
12787     }
12788     return;
12789   case 'K':
12790     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12791       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
12792         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12793         break;
12794       }
12795     }
12796     return;
12797   case 'N':
12798     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12799       if (C->getZExtValue() <= 255) {
12800         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12801         break;
12802       }
12803     }
12804     return;
12805   case 'e': {
12806     // 32-bit signed value
12807     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12808       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
12809                                            C->getSExtValue())) {
12810         // Widen to 64 bits here to get it sign extended.
12811         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
12812         break;
12813       }
12814     // FIXME gcc accepts some relocatable values here too, but only in certain
12815     // memory models; it's complicated.
12816     }
12817     return;
12818   }
12819   case 'Z': {
12820     // 32-bit unsigned value
12821     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12822       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
12823                                            C->getZExtValue())) {
12824         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12825         break;
12826       }
12827     }
12828     // FIXME gcc accepts some relocatable values here too, but only in certain
12829     // memory models; it's complicated.
12830     return;
12831   }
12832   case 'i': {
12833     // Literal immediates are always ok.
12834     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
12835       // Widen to 64 bits here to get it sign extended.
12836       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
12837       break;
12838     }
12839
12840     // In any sort of PIC mode addresses need to be computed at runtime by
12841     // adding in a register or some sort of table lookup.  These can't
12842     // be used as immediates.
12843     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
12844       return;
12845
12846     // If we are in non-pic codegen mode, we allow the address of a global (with
12847     // an optional displacement) to be used with 'i'.
12848     GlobalAddressSDNode *GA = 0;
12849     int64_t Offset = 0;
12850
12851     // Match either (GA), (GA+C), (GA+C1+C2), etc.
12852     while (1) {
12853       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
12854         Offset += GA->getOffset();
12855         break;
12856       } else if (Op.getOpcode() == ISD::ADD) {
12857         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
12858           Offset += C->getZExtValue();
12859           Op = Op.getOperand(0);
12860           continue;
12861         }
12862       } else if (Op.getOpcode() == ISD::SUB) {
12863         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
12864           Offset += -C->getZExtValue();
12865           Op = Op.getOperand(0);
12866           continue;
12867         }
12868       }
12869
12870       // Otherwise, this isn't something we can handle, reject it.
12871       return;
12872     }
12873
12874     const GlobalValue *GV = GA->getGlobal();
12875     // If we require an extra load to get this address, as in PIC mode, we
12876     // can't accept it.
12877     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
12878                                                         getTargetMachine())))
12879       return;
12880
12881     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
12882                                         GA->getValueType(0), Offset);
12883     break;
12884   }
12885   }
12886
12887   if (Result.getNode()) {
12888     Ops.push_back(Result);
12889     return;
12890   }
12891   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
12892 }
12893
12894 std::pair<unsigned, const TargetRegisterClass*>
12895 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
12896                                                 EVT VT) const {
12897   // First, see if this is a constraint that directly corresponds to an LLVM
12898   // register class.
12899   if (Constraint.size() == 1) {
12900     // GCC Constraint Letters
12901     switch (Constraint[0]) {
12902     default: break;
12903       // TODO: Slight differences here in allocation order and leaving
12904       // RIP in the class. Do they matter any more here than they do
12905       // in the normal allocation?
12906     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
12907       if (Subtarget->is64Bit()) {
12908         if (VT == MVT::i32 || VT == MVT::f32)
12909           return std::make_pair(0U, X86::GR32RegisterClass);
12910         else if (VT == MVT::i16)
12911           return std::make_pair(0U, X86::GR16RegisterClass);
12912         else if (VT == MVT::i8)
12913           return std::make_pair(0U, X86::GR8RegisterClass);
12914         else if (VT == MVT::i64 || VT == MVT::f64)
12915           return std::make_pair(0U, X86::GR64RegisterClass);
12916         break;
12917       }
12918       // 32-bit fallthrough
12919     case 'Q':   // Q_REGS
12920       if (VT == MVT::i32 || VT == MVT::f32)
12921         return std::make_pair(0U, X86::GR32_ABCDRegisterClass);
12922       else if (VT == MVT::i16)
12923         return std::make_pair(0U, X86::GR16_ABCDRegisterClass);
12924       else if (VT == MVT::i8)
12925         return std::make_pair(0U, X86::GR8_ABCD_LRegisterClass);
12926       else if (VT == MVT::i64)
12927         return std::make_pair(0U, X86::GR64_ABCDRegisterClass);
12928       break;
12929     case 'r':   // GENERAL_REGS
12930     case 'l':   // INDEX_REGS
12931       if (VT == MVT::i8)
12932         return std::make_pair(0U, X86::GR8RegisterClass);
12933       if (VT == MVT::i16)
12934         return std::make_pair(0U, X86::GR16RegisterClass);
12935       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
12936         return std::make_pair(0U, X86::GR32RegisterClass);
12937       return std::make_pair(0U, X86::GR64RegisterClass);
12938     case 'R':   // LEGACY_REGS
12939       if (VT == MVT::i8)
12940         return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
12941       if (VT == MVT::i16)
12942         return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
12943       if (VT == MVT::i32 || !Subtarget->is64Bit())
12944         return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
12945       return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
12946     case 'f':  // FP Stack registers.
12947       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
12948       // value to the correct fpstack register class.
12949       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
12950         return std::make_pair(0U, X86::RFP32RegisterClass);
12951       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
12952         return std::make_pair(0U, X86::RFP64RegisterClass);
12953       return std::make_pair(0U, X86::RFP80RegisterClass);
12954     case 'y':   // MMX_REGS if MMX allowed.
12955       if (!Subtarget->hasMMX()) break;
12956       return std::make_pair(0U, X86::VR64RegisterClass);
12957     case 'Y':   // SSE_REGS if SSE2 allowed
12958       if (!Subtarget->hasXMMInt()) break;
12959       // FALL THROUGH.
12960     case 'x':   // SSE_REGS if SSE1 allowed
12961       if (!Subtarget->hasXMM()) break;
12962
12963       switch (VT.getSimpleVT().SimpleTy) {
12964       default: break;
12965       // Scalar SSE types.
12966       case MVT::f32:
12967       case MVT::i32:
12968         return std::make_pair(0U, X86::FR32RegisterClass);
12969       case MVT::f64:
12970       case MVT::i64:
12971         return std::make_pair(0U, X86::FR64RegisterClass);
12972       // Vector types.
12973       case MVT::v16i8:
12974       case MVT::v8i16:
12975       case MVT::v4i32:
12976       case MVT::v2i64:
12977       case MVT::v4f32:
12978       case MVT::v2f64:
12979         return std::make_pair(0U, X86::VR128RegisterClass);
12980       }
12981       break;
12982     }
12983   }
12984
12985   // Use the default implementation in TargetLowering to convert the register
12986   // constraint into a member of a register class.
12987   std::pair<unsigned, const TargetRegisterClass*> Res;
12988   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
12989
12990   // Not found as a standard register?
12991   if (Res.second == 0) {
12992     // Map st(0) -> st(7) -> ST0
12993     if (Constraint.size() == 7 && Constraint[0] == '{' &&
12994         tolower(Constraint[1]) == 's' &&
12995         tolower(Constraint[2]) == 't' &&
12996         Constraint[3] == '(' &&
12997         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
12998         Constraint[5] == ')' &&
12999         Constraint[6] == '}') {
13000
13001       Res.first = X86::ST0+Constraint[4]-'0';
13002       Res.second = X86::RFP80RegisterClass;
13003       return Res;
13004     }
13005
13006     // GCC allows "st(0)" to be called just plain "st".
13007     if (StringRef("{st}").equals_lower(Constraint)) {
13008       Res.first = X86::ST0;
13009       Res.second = X86::RFP80RegisterClass;
13010       return Res;
13011     }
13012
13013     // flags -> EFLAGS
13014     if (StringRef("{flags}").equals_lower(Constraint)) {
13015       Res.first = X86::EFLAGS;
13016       Res.second = X86::CCRRegisterClass;
13017       return Res;
13018     }
13019
13020     // 'A' means EAX + EDX.
13021     if (Constraint == "A") {
13022       Res.first = X86::EAX;
13023       Res.second = X86::GR32_ADRegisterClass;
13024       return Res;
13025     }
13026     return Res;
13027   }
13028
13029   // Otherwise, check to see if this is a register class of the wrong value
13030   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
13031   // turn into {ax},{dx}.
13032   if (Res.second->hasType(VT))
13033     return Res;   // Correct type already, nothing to do.
13034
13035   // All of the single-register GCC register classes map their values onto
13036   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
13037   // really want an 8-bit or 32-bit register, map to the appropriate register
13038   // class and return the appropriate register.
13039   if (Res.second == X86::GR16RegisterClass) {
13040     if (VT == MVT::i8) {
13041       unsigned DestReg = 0;
13042       switch (Res.first) {
13043       default: break;
13044       case X86::AX: DestReg = X86::AL; break;
13045       case X86::DX: DestReg = X86::DL; break;
13046       case X86::CX: DestReg = X86::CL; break;
13047       case X86::BX: DestReg = X86::BL; break;
13048       }
13049       if (DestReg) {
13050         Res.first = DestReg;
13051         Res.second = X86::GR8RegisterClass;
13052       }
13053     } else if (VT == MVT::i32) {
13054       unsigned DestReg = 0;
13055       switch (Res.first) {
13056       default: break;
13057       case X86::AX: DestReg = X86::EAX; break;
13058       case X86::DX: DestReg = X86::EDX; break;
13059       case X86::CX: DestReg = X86::ECX; break;
13060       case X86::BX: DestReg = X86::EBX; break;
13061       case X86::SI: DestReg = X86::ESI; break;
13062       case X86::DI: DestReg = X86::EDI; break;
13063       case X86::BP: DestReg = X86::EBP; break;
13064       case X86::SP: DestReg = X86::ESP; break;
13065       }
13066       if (DestReg) {
13067         Res.first = DestReg;
13068         Res.second = X86::GR32RegisterClass;
13069       }
13070     } else if (VT == MVT::i64) {
13071       unsigned DestReg = 0;
13072       switch (Res.first) {
13073       default: break;
13074       case X86::AX: DestReg = X86::RAX; break;
13075       case X86::DX: DestReg = X86::RDX; break;
13076       case X86::CX: DestReg = X86::RCX; break;
13077       case X86::BX: DestReg = X86::RBX; break;
13078       case X86::SI: DestReg = X86::RSI; break;
13079       case X86::DI: DestReg = X86::RDI; break;
13080       case X86::BP: DestReg = X86::RBP; break;
13081       case X86::SP: DestReg = X86::RSP; break;
13082       }
13083       if (DestReg) {
13084         Res.first = DestReg;
13085         Res.second = X86::GR64RegisterClass;
13086       }
13087     }
13088   } else if (Res.second == X86::FR32RegisterClass ||
13089              Res.second == X86::FR64RegisterClass ||
13090              Res.second == X86::VR128RegisterClass) {
13091     // Handle references to XMM physical registers that got mapped into the
13092     // wrong class.  This can happen with constraints like {xmm0} where the
13093     // target independent register mapper will just pick the first match it can
13094     // find, ignoring the required type.
13095     if (VT == MVT::f32)
13096       Res.second = X86::FR32RegisterClass;
13097     else if (VT == MVT::f64)
13098       Res.second = X86::FR64RegisterClass;
13099     else if (X86::VR128RegisterClass->hasType(VT))
13100       Res.second = X86::VR128RegisterClass;
13101   }
13102
13103   return Res;
13104 }