Extend VPBLENDVB and VPSIGN lowering to work for AVX2.
[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/MC/MCAsmInfo.h"
39 #include "llvm/MC/MCContext.h"
40 #include "llvm/MC/MCExpr.h"
41 #include "llvm/MC/MCSymbol.h"
42 #include "llvm/ADT/BitVector.h"
43 #include "llvm/ADT/SmallSet.h"
44 #include "llvm/ADT/Statistic.h"
45 #include "llvm/ADT/StringExtras.h"
46 #include "llvm/ADT/VectorExtras.h"
47 #include "llvm/Support/CallSite.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/Dwarf.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/MathExtras.h"
52 #include "llvm/Support/raw_ostream.h"
53 #include "llvm/Target/TargetOptions.h"
54 using namespace llvm;
55 using namespace dwarf;
56
57 STATISTIC(NumTailCalls, "Number of tail calls");
58
59 // Forward declarations.
60 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
61                        SDValue V2);
62
63 static SDValue Insert128BitVector(SDValue Result,
64                                   SDValue Vec,
65                                   SDValue Idx,
66                                   SelectionDAG &DAG,
67                                   DebugLoc dl);
68
69 static SDValue Extract128BitVector(SDValue Vec,
70                                    SDValue Idx,
71                                    SelectionDAG &DAG,
72                                    DebugLoc dl);
73
74 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
75 /// sets things up to match to an AVX VEXTRACTF128 instruction or a
76 /// simple subregister reference.  Idx is an index in the 128 bits we
77 /// want.  It need not be aligned to a 128-bit bounday.  That makes
78 /// lowering EXTRACT_VECTOR_ELT operations easier.
79 static SDValue Extract128BitVector(SDValue Vec,
80                                    SDValue Idx,
81                                    SelectionDAG &DAG,
82                                    DebugLoc dl) {
83   EVT VT = Vec.getValueType();
84   assert(VT.getSizeInBits() == 256 && "Unexpected vector size!");
85   EVT ElVT = VT.getVectorElementType();
86   int Factor = VT.getSizeInBits()/128;
87   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
88                                   VT.getVectorNumElements()/Factor);
89
90   // Extract from UNDEF is UNDEF.
91   if (Vec.getOpcode() == ISD::UNDEF)
92     return DAG.getNode(ISD::UNDEF, dl, ResultVT);
93
94   if (isa<ConstantSDNode>(Idx)) {
95     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
96
97     // Extract the relevant 128 bits.  Generate an EXTRACT_SUBVECTOR
98     // we can match to VEXTRACTF128.
99     unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
100
101     // This is the index of the first element of the 128-bit chunk
102     // we want.
103     unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
104                                  * ElemsPerChunk);
105
106     SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
107     SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
108                                  VecIdx);
109
110     return Result;
111   }
112
113   return SDValue();
114 }
115
116 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
117 /// sets things up to match to an AVX VINSERTF128 instruction or a
118 /// simple superregister reference.  Idx is an index in the 128 bits
119 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
120 /// lowering INSERT_VECTOR_ELT operations easier.
121 static SDValue Insert128BitVector(SDValue Result,
122                                   SDValue Vec,
123                                   SDValue Idx,
124                                   SelectionDAG &DAG,
125                                   DebugLoc dl) {
126   if (isa<ConstantSDNode>(Idx)) {
127     EVT VT = Vec.getValueType();
128     assert(VT.getSizeInBits() == 128 && "Unexpected vector size!");
129
130     EVT ElVT = VT.getVectorElementType();
131     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
132     EVT ResultVT = Result.getValueType();
133
134     // Insert the relevant 128 bits.
135     unsigned ElemsPerChunk = 128/ElVT.getSizeInBits();
136
137     // This is the index of the first element of the 128-bit chunk
138     // we want.
139     unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/128)
140                                  * ElemsPerChunk);
141
142     SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
143     Result = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
144                          VecIdx);
145     return Result;
146   }
147
148   return SDValue();
149 }
150
151 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
152   const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
153   bool is64Bit = Subtarget->is64Bit();
154
155   if (Subtarget->isTargetEnvMacho()) {
156     if (is64Bit)
157       return new X8664_MachoTargetObjectFile();
158     return new TargetLoweringObjectFileMachO();
159   }
160
161   if (Subtarget->isTargetELF())
162     return new TargetLoweringObjectFileELF();
163   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
164     return new TargetLoweringObjectFileCOFF();
165   llvm_unreachable("unknown subtarget type");
166 }
167
168 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
169   : TargetLowering(TM, createTLOF(TM)) {
170   Subtarget = &TM.getSubtarget<X86Subtarget>();
171   X86ScalarSSEf64 = Subtarget->hasXMMInt();
172   X86ScalarSSEf32 = Subtarget->hasXMM();
173   X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
174
175   RegInfo = TM.getRegisterInfo();
176   TD = getTargetData();
177
178   // Set up the TargetLowering object.
179   static MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
180
181   // X86 is weird, it always uses i8 for shift amounts and setcc results.
182   setBooleanContents(ZeroOrOneBooleanContent);
183   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
184   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
185
186   // For 64-bit since we have so many registers use the ILP scheduler, for
187   // 32-bit code use the register pressure specific scheduling.
188   if (Subtarget->is64Bit())
189     setSchedulingPreference(Sched::ILP);
190   else
191     setSchedulingPreference(Sched::RegPressure);
192   setStackPointerRegisterToSaveRestore(X86StackPtr);
193
194   if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
195     // Setup Windows compiler runtime calls.
196     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
197     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
198     setLibcallName(RTLIB::SREM_I64, "_allrem");
199     setLibcallName(RTLIB::UREM_I64, "_aullrem");
200     setLibcallName(RTLIB::MUL_I64, "_allmul");
201     setLibcallName(RTLIB::FPTOUINT_F64_I64, "_ftol2");
202     setLibcallName(RTLIB::FPTOUINT_F32_I64, "_ftol2");
203     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
204     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
205     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
206     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
207     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
208     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::C);
209     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::C);
210   }
211
212   if (Subtarget->isTargetDarwin()) {
213     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
214     setUseUnderscoreSetJmp(false);
215     setUseUnderscoreLongJmp(false);
216   } else if (Subtarget->isTargetMingw()) {
217     // MS runtime is weird: it exports _setjmp, but longjmp!
218     setUseUnderscoreSetJmp(true);
219     setUseUnderscoreLongJmp(false);
220   } else {
221     setUseUnderscoreSetJmp(true);
222     setUseUnderscoreLongJmp(true);
223   }
224
225   // Set up the register classes.
226   addRegisterClass(MVT::i8, X86::GR8RegisterClass);
227   addRegisterClass(MVT::i16, X86::GR16RegisterClass);
228   addRegisterClass(MVT::i32, X86::GR32RegisterClass);
229   if (Subtarget->is64Bit())
230     addRegisterClass(MVT::i64, X86::GR64RegisterClass);
231
232   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
233
234   // We don't accept any truncstore of integer registers.
235   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
236   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
237   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
238   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
239   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
240   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
241
242   // SETOEQ and SETUNE require checking two conditions.
243   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
244   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
245   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
246   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
247   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
248   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
249
250   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
251   // operation.
252   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
253   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
254   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
255
256   if (Subtarget->is64Bit()) {
257     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
258     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Expand);
259   } else if (!UseSoftFloat) {
260     // We have an algorithm for SSE2->double, and we turn this into a
261     // 64-bit FILD followed by conditional FADD for other targets.
262     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
263     // We have an algorithm for SSE2, and we turn this into a 64-bit
264     // FILD for other targets.
265     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
266   }
267
268   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
269   // this operation.
270   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
271   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
272
273   if (!UseSoftFloat) {
274     // SSE has no i16 to fp conversion, only i32
275     if (X86ScalarSSEf32) {
276       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
277       // f32 and f64 cases are Legal, f80 case is not
278       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
279     } else {
280       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
281       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
282     }
283   } else {
284     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
285     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
286   }
287
288   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
289   // are Legal, f80 is custom lowered.
290   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
291   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
292
293   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
294   // this operation.
295   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
296   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
297
298   if (X86ScalarSSEf32) {
299     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
300     // f32 and f64 cases are Legal, f80 case is not
301     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
302   } else {
303     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
304     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
305   }
306
307   // Handle FP_TO_UINT by promoting the destination to a larger signed
308   // conversion.
309   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
310   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
311   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
312
313   if (Subtarget->is64Bit()) {
314     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
315     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
316   } else if (!UseSoftFloat) {
317     // Since AVX is a superset of SSE3, only check for SSE here.
318     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
319       // Expand FP_TO_UINT into a select.
320       // FIXME: We would like to use a Custom expander here eventually to do
321       // the optimal thing for SSE vs. the default expansion in the legalizer.
322       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
323     else
324       // With SSE3 we can use fisttpll to convert to a signed i64; without
325       // SSE, we're stuck with a fistpll.
326       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
327   }
328
329   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
330   if (!X86ScalarSSEf64) {
331     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
332     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
333     if (Subtarget->is64Bit()) {
334       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
335       // Without SSE, i64->f64 goes through memory.
336       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
337     }
338   }
339
340   // Scalar integer divide and remainder are lowered to use operations that
341   // produce two results, to match the available instructions. This exposes
342   // the two-result form to trivial CSE, which is able to combine x/y and x%y
343   // into a single instruction.
344   //
345   // Scalar integer multiply-high is also lowered to use two-result
346   // operations, to match the available instructions. However, plain multiply
347   // (low) operations are left as Legal, as there are single-result
348   // instructions for this in x86. Using the two-result multiply instructions
349   // when both high and low results are needed must be arranged by dagcombine.
350   for (unsigned i = 0, e = 4; i != e; ++i) {
351     MVT VT = IntVTs[i];
352     setOperationAction(ISD::MULHS, VT, Expand);
353     setOperationAction(ISD::MULHU, VT, Expand);
354     setOperationAction(ISD::SDIV, VT, Expand);
355     setOperationAction(ISD::UDIV, VT, Expand);
356     setOperationAction(ISD::SREM, VT, Expand);
357     setOperationAction(ISD::UREM, VT, Expand);
358
359     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
360     setOperationAction(ISD::ADDC, VT, Custom);
361     setOperationAction(ISD::ADDE, VT, Custom);
362     setOperationAction(ISD::SUBC, VT, Custom);
363     setOperationAction(ISD::SUBE, VT, Custom);
364   }
365
366   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
367   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
368   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
369   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
370   if (Subtarget->is64Bit())
371     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
372   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
373   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
374   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
375   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
376   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
377   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
378   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
379   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
380
381   if (Subtarget->hasBMI()) {
382     setOperationAction(ISD::CTTZ           , MVT::i8   , Promote);
383   } else {
384     setOperationAction(ISD::CTTZ           , MVT::i8   , Custom);
385     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
386     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
387     if (Subtarget->is64Bit())
388       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
389   }
390
391   if (Subtarget->hasLZCNT()) {
392     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
393   } else {
394     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
395     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
396     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
397     if (Subtarget->is64Bit())
398       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
399   }
400
401   if (Subtarget->hasPOPCNT()) {
402     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
403   } else {
404     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
405     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
406     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
407     if (Subtarget->is64Bit())
408       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
409   }
410
411   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
412   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
413
414   // These should be promoted to a larger select which is supported.
415   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
416   // X86 wants to expand cmov itself.
417   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
418   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
419   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
420   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
421   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
422   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
423   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
424   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
425   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
426   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
427   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
428   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
429   if (Subtarget->is64Bit()) {
430     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
431     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
432   }
433   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
434
435   // Darwin ABI issue.
436   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
437   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
438   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
439   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
440   if (Subtarget->is64Bit())
441     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
442   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
443   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
444   if (Subtarget->is64Bit()) {
445     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
446     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
447     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
448     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
449     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
450   }
451   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
452   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
453   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
454   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
455   if (Subtarget->is64Bit()) {
456     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
457     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
458     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
459   }
460
461   if (Subtarget->hasXMM())
462     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
463
464   setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
465   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
466
467   // On X86 and X86-64, atomic operations are lowered to locked instructions.
468   // Locked instructions, in turn, have implicit fence semantics (all memory
469   // operations are flushed before issuing the locked instruction, and they
470   // are not buffered), so we can fold away the common pattern of
471   // fence-atomic-fence.
472   setShouldFoldAtomicFences(true);
473
474   // Expand certain atomics
475   for (unsigned i = 0, e = 4; i != e; ++i) {
476     MVT VT = IntVTs[i];
477     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
478     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
479     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
480   }
481
482   if (!Subtarget->is64Bit()) {
483     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
484     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
485     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
486     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
487     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
488     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
489     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
490     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
491   }
492
493   if (Subtarget->hasCmpxchg16b()) {
494     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
495   }
496
497   // FIXME - use subtarget debug flags
498   if (!Subtarget->isTargetDarwin() &&
499       !Subtarget->isTargetELF() &&
500       !Subtarget->isTargetCygMing()) {
501     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
502   }
503
504   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
505   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
506   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
507   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
508   if (Subtarget->is64Bit()) {
509     setExceptionPointerRegister(X86::RAX);
510     setExceptionSelectorRegister(X86::RDX);
511   } else {
512     setExceptionPointerRegister(X86::EAX);
513     setExceptionSelectorRegister(X86::EDX);
514   }
515   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
516   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
517
518   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
519   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
520
521   setOperationAction(ISD::TRAP, MVT::Other, Legal);
522
523   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
524   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
525   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
526   if (Subtarget->is64Bit()) {
527     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
528     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
529   } else {
530     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
531     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
532   }
533
534   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
535   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
536
537   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
538     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
539                        MVT::i64 : MVT::i32, Custom);
540   else if (EnableSegmentedStacks)
541     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
542                        MVT::i64 : MVT::i32, Custom);
543   else
544     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
545                        MVT::i64 : MVT::i32, Expand);
546
547   if (!UseSoftFloat && X86ScalarSSEf64) {
548     // f32 and f64 use SSE.
549     // Set up the FP register classes.
550     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
551     addRegisterClass(MVT::f64, X86::FR64RegisterClass);
552
553     // Use ANDPD to simulate FABS.
554     setOperationAction(ISD::FABS , MVT::f64, Custom);
555     setOperationAction(ISD::FABS , MVT::f32, Custom);
556
557     // Use XORP to simulate FNEG.
558     setOperationAction(ISD::FNEG , MVT::f64, Custom);
559     setOperationAction(ISD::FNEG , MVT::f32, Custom);
560
561     // Use ANDPD and ORPD to simulate FCOPYSIGN.
562     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
563     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
564
565     // Lower this to FGETSIGNx86 plus an AND.
566     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
567     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
568
569     // We don't support sin/cos/fmod
570     setOperationAction(ISD::FSIN , MVT::f64, Expand);
571     setOperationAction(ISD::FCOS , MVT::f64, Expand);
572     setOperationAction(ISD::FSIN , MVT::f32, Expand);
573     setOperationAction(ISD::FCOS , MVT::f32, Expand);
574
575     // Expand FP immediates into loads from the stack, except for the special
576     // cases we handle.
577     addLegalFPImmediate(APFloat(+0.0)); // xorpd
578     addLegalFPImmediate(APFloat(+0.0f)); // xorps
579   } else if (!UseSoftFloat && X86ScalarSSEf32) {
580     // Use SSE for f32, x87 for f64.
581     // Set up the FP register classes.
582     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
583     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
584
585     // Use ANDPS to simulate FABS.
586     setOperationAction(ISD::FABS , MVT::f32, Custom);
587
588     // Use XORP to simulate FNEG.
589     setOperationAction(ISD::FNEG , MVT::f32, Custom);
590
591     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
592
593     // Use ANDPS and ORPS to simulate FCOPYSIGN.
594     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
595     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
596
597     // We don't support sin/cos/fmod
598     setOperationAction(ISD::FSIN , MVT::f32, Expand);
599     setOperationAction(ISD::FCOS , MVT::f32, Expand);
600
601     // Special cases we handle for FP constants.
602     addLegalFPImmediate(APFloat(+0.0f)); // xorps
603     addLegalFPImmediate(APFloat(+0.0)); // FLD0
604     addLegalFPImmediate(APFloat(+1.0)); // FLD1
605     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
606     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
607
608     if (!UnsafeFPMath) {
609       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
610       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
611     }
612   } else if (!UseSoftFloat) {
613     // f32 and f64 in x87.
614     // Set up the FP register classes.
615     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
616     addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
617
618     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
619     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
620     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
621     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
622
623     if (!UnsafeFPMath) {
624       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
625       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
626     }
627     addLegalFPImmediate(APFloat(+0.0)); // FLD0
628     addLegalFPImmediate(APFloat(+1.0)); // FLD1
629     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
630     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
631     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
632     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
633     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
634     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
635   }
636
637   // We don't support FMA.
638   setOperationAction(ISD::FMA, MVT::f64, Expand);
639   setOperationAction(ISD::FMA, MVT::f32, Expand);
640
641   // Long double always uses X87.
642   if (!UseSoftFloat) {
643     addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
644     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
645     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
646     {
647       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
648       addLegalFPImmediate(TmpFlt);  // FLD0
649       TmpFlt.changeSign();
650       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
651
652       bool ignored;
653       APFloat TmpFlt2(+1.0);
654       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
655                       &ignored);
656       addLegalFPImmediate(TmpFlt2);  // FLD1
657       TmpFlt2.changeSign();
658       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
659     }
660
661     if (!UnsafeFPMath) {
662       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
663       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
664     }
665
666     setOperationAction(ISD::FMA, MVT::f80, Expand);
667   }
668
669   // Always use a library call for pow.
670   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
671   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
672   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
673
674   setOperationAction(ISD::FLOG, MVT::f80, Expand);
675   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
676   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
677   setOperationAction(ISD::FEXP, MVT::f80, Expand);
678   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
679
680   // First set operation action for all vector types to either promote
681   // (for widening) or expand (for scalarization). Then we will selectively
682   // turn on ones that can be effectively codegen'd.
683   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
684        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
685     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
686     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
687     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
688     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
689     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
690     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
691     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
692     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
693     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
694     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
695     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
696     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
697     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
698     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
699     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
700     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
701     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
702     setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
703     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
704     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
705     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
706     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
707     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
708     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
709     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
710     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
711     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
712     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
713     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
714     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
715     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
716     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
717     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
718     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
719     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
720     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
721     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
722     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
723     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
724     setOperationAction(ISD::SETCC, (MVT::SimpleValueType)VT, Expand);
725     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
726     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
727     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
728     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
729     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
730     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
731     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
732     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
733     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
734     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
735     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
736     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
737     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
738     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
739     setOperationAction(ISD::VSELECT,  (MVT::SimpleValueType)VT, Expand);
740     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
741          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
742       setTruncStoreAction((MVT::SimpleValueType)VT,
743                           (MVT::SimpleValueType)InnerVT, Expand);
744     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
745     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
746     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
747   }
748
749   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
750   // with -msoft-float, disable use of MMX as well.
751   if (!UseSoftFloat && Subtarget->hasMMX()) {
752     addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass);
753     // No operations on x86mmx supported, everything uses intrinsics.
754   }
755
756   // MMX-sized vectors (other than x86mmx) are expected to be expanded
757   // into smaller operations.
758   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
759   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
760   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
761   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
762   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
763   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
764   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
765   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
766   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
767   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
768   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
769   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
770   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
771   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
772   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
773   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
774   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
775   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
776   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
777   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
778   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
779   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
780   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
781   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
782   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
783   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
784   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
785   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
786   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
787
788   if (!UseSoftFloat && Subtarget->hasXMM()) {
789     addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
790
791     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
792     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
793     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
794     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
795     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
796     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
797     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
798     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
799     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
800     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
801     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
802     setOperationAction(ISD::SETCC,              MVT::v4f32, Custom);
803   }
804
805   if (!UseSoftFloat && Subtarget->hasXMMInt()) {
806     addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
807
808     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
809     // registers cannot be used even for integer operations.
810     addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
811     addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
812     addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
813     addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
814
815     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
816     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
817     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
818     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
819     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
820     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
821     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
822     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
823     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
824     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
825     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
826     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
827     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
828     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
829     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
830     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
831
832     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
833     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
834     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
835     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
836
837     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
838     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
839     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
840     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
841     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
842
843     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2f64, Custom);
844     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2i64, Custom);
845     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i8, Custom);
846     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i16, Custom);
847     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i32, Custom);
848
849     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
850     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
851       EVT VT = (MVT::SimpleValueType)i;
852       // Do not attempt to custom lower non-power-of-2 vectors
853       if (!isPowerOf2_32(VT.getVectorNumElements()))
854         continue;
855       // Do not attempt to custom lower non-128-bit vectors
856       if (!VT.is128BitVector())
857         continue;
858       setOperationAction(ISD::BUILD_VECTOR,
859                          VT.getSimpleVT().SimpleTy, Custom);
860       setOperationAction(ISD::VECTOR_SHUFFLE,
861                          VT.getSimpleVT().SimpleTy, Custom);
862       setOperationAction(ISD::EXTRACT_VECTOR_ELT,
863                          VT.getSimpleVT().SimpleTy, Custom);
864     }
865
866     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
867     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
868     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
869     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
870     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
871     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
872
873     if (Subtarget->is64Bit()) {
874       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
875       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
876     }
877
878     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
879     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
880       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
881       EVT VT = SVT;
882
883       // Do not attempt to promote non-128-bit vectors
884       if (!VT.is128BitVector())
885         continue;
886
887       setOperationAction(ISD::AND,    SVT, Promote);
888       AddPromotedToType (ISD::AND,    SVT, MVT::v2i64);
889       setOperationAction(ISD::OR,     SVT, Promote);
890       AddPromotedToType (ISD::OR,     SVT, MVT::v2i64);
891       setOperationAction(ISD::XOR,    SVT, Promote);
892       AddPromotedToType (ISD::XOR,    SVT, MVT::v2i64);
893       setOperationAction(ISD::LOAD,   SVT, Promote);
894       AddPromotedToType (ISD::LOAD,   SVT, MVT::v2i64);
895       setOperationAction(ISD::SELECT, SVT, Promote);
896       AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
897     }
898
899     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
900
901     // Custom lower v2i64 and v2f64 selects.
902     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
903     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
904     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
905     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
906
907     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
908     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
909   }
910
911   if (Subtarget->hasSSE41() || Subtarget->hasAVX()) {
912     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
913     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
914     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
915     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
916     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
917     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
918     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
919     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
920     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
921     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
922
923     // FIXME: Do we need to handle scalar-to-vector here?
924     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
925
926     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
927     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
928     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
929     setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
930     setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
931
932     // i8 and i16 vectors are custom , because the source register and source
933     // source memory operand types are not the same width.  f32 vectors are
934     // custom since the immediate controlling the insert encodes additional
935     // information.
936     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
937     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
938     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
939     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
940
941     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
942     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
943     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
944     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
945
946     // FIXME: these should be Legal but thats only for the case where
947     // the index is constant.  For now custom expand to deal with that
948     if (Subtarget->is64Bit()) {
949       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
950       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
951     }
952   }
953
954   if (Subtarget->hasXMMInt()) {
955     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
956     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
957
958     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
959     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
960
961     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
962     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
963
964     if (Subtarget->hasAVX2()) {
965       setOperationAction(ISD::SRL,             MVT::v2i64, Legal);
966       setOperationAction(ISD::SRL,             MVT::v4i32, Legal);
967
968       setOperationAction(ISD::SHL,             MVT::v2i64, Legal);
969       setOperationAction(ISD::SHL,             MVT::v4i32, Legal);
970
971       setOperationAction(ISD::SRA,             MVT::v4i32, Legal);
972     } else {
973       setOperationAction(ISD::SRL,             MVT::v2i64, Custom);
974       setOperationAction(ISD::SRL,             MVT::v4i32, Custom);
975
976       setOperationAction(ISD::SHL,             MVT::v2i64, Custom);
977       setOperationAction(ISD::SHL,             MVT::v4i32, Custom);
978
979       setOperationAction(ISD::SRA,             MVT::v4i32, Custom);
980     }
981   }
982
983   if (Subtarget->hasSSE42() || Subtarget->hasAVX())
984     setOperationAction(ISD::SETCC,             MVT::v2i64, Custom);
985
986   if (!UseSoftFloat && Subtarget->hasAVX()) {
987     addRegisterClass(MVT::v32i8,  X86::VR256RegisterClass);
988     addRegisterClass(MVT::v16i16, X86::VR256RegisterClass);
989     addRegisterClass(MVT::v8i32,  X86::VR256RegisterClass);
990     addRegisterClass(MVT::v8f32,  X86::VR256RegisterClass);
991     addRegisterClass(MVT::v4i64,  X86::VR256RegisterClass);
992     addRegisterClass(MVT::v4f64,  X86::VR256RegisterClass);
993
994     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
995     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
996     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
997
998     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
999     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1000     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1001     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1002     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1003     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1004
1005     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1006     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1007     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1008     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1009     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1010     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1011
1012     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1013     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1014     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1015
1016     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4f64,  Custom);
1017     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i64,  Custom);
1018     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f32,  Custom);
1019     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i32,  Custom);
1020     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i8,  Custom);
1021     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i16, Custom);
1022
1023     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1024     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1025
1026     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1027     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1028
1029     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1030     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1031
1032     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1033     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1034     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1035     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1036
1037     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1038     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1039     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1040
1041     setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1042     setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1043     setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1044     setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1045
1046     if (Subtarget->hasAVX2()) {
1047       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1048       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1049       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1050       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1051
1052       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1053       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1054       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1055       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1056
1057       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1058       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1059       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1060       // Don't lower v32i8 because there is no 128-bit byte mul
1061
1062       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1063
1064       setOperationAction(ISD::SRL,             MVT::v4i64, Legal);
1065       setOperationAction(ISD::SRL,             MVT::v8i32, Legal);
1066
1067       setOperationAction(ISD::SHL,             MVT::v4i64, Legal);
1068       setOperationAction(ISD::SHL,             MVT::v8i32, Legal);
1069
1070       setOperationAction(ISD::SRA,             MVT::v8i32, Legal);
1071     } else {
1072       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1073       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1074       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1075       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1076
1077       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1078       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1079       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1080       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1081
1082       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1083       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1084       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1085       // Don't lower v32i8 because there is no 128-bit byte mul
1086
1087       setOperationAction(ISD::SRL,             MVT::v4i64, Custom);
1088       setOperationAction(ISD::SRL,             MVT::v8i32, Custom);
1089
1090       setOperationAction(ISD::SHL,             MVT::v4i64, Custom);
1091       setOperationAction(ISD::SHL,             MVT::v8i32, Custom);
1092
1093       setOperationAction(ISD::SRA,             MVT::v8i32, Custom);
1094     }
1095
1096     // Custom lower several nodes for 256-bit types.
1097     for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1098                   i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
1099       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1100       EVT VT = SVT;
1101
1102       // Extract subvector is special because the value type
1103       // (result) is 128-bit but the source is 256-bit wide.
1104       if (VT.is128BitVector())
1105         setOperationAction(ISD::EXTRACT_SUBVECTOR, SVT, Custom);
1106
1107       // Do not attempt to custom lower other non-256-bit vectors
1108       if (!VT.is256BitVector())
1109         continue;
1110
1111       setOperationAction(ISD::BUILD_VECTOR,       SVT, Custom);
1112       setOperationAction(ISD::VECTOR_SHUFFLE,     SVT, Custom);
1113       setOperationAction(ISD::INSERT_VECTOR_ELT,  SVT, Custom);
1114       setOperationAction(ISD::EXTRACT_VECTOR_ELT, SVT, Custom);
1115       setOperationAction(ISD::SCALAR_TO_VECTOR,   SVT, Custom);
1116       setOperationAction(ISD::INSERT_SUBVECTOR,   SVT, Custom);
1117     }
1118
1119     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1120     for (unsigned i = (unsigned)MVT::v32i8; i != (unsigned)MVT::v4i64; ++i) {
1121       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1122       EVT VT = SVT;
1123
1124       // Do not attempt to promote non-256-bit vectors
1125       if (!VT.is256BitVector())
1126         continue;
1127
1128       setOperationAction(ISD::AND,    SVT, Promote);
1129       AddPromotedToType (ISD::AND,    SVT, MVT::v4i64);
1130       setOperationAction(ISD::OR,     SVT, Promote);
1131       AddPromotedToType (ISD::OR,     SVT, MVT::v4i64);
1132       setOperationAction(ISD::XOR,    SVT, Promote);
1133       AddPromotedToType (ISD::XOR,    SVT, MVT::v4i64);
1134       setOperationAction(ISD::LOAD,   SVT, Promote);
1135       AddPromotedToType (ISD::LOAD,   SVT, MVT::v4i64);
1136       setOperationAction(ISD::SELECT, SVT, Promote);
1137       AddPromotedToType (ISD::SELECT, SVT, MVT::v4i64);
1138     }
1139   }
1140
1141   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1142   // of this type with custom code.
1143   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1144          VT != (unsigned)MVT::LAST_VECTOR_VALUETYPE; VT++) {
1145     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT, Custom);
1146   }
1147
1148   // We want to custom lower some of our intrinsics.
1149   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1150
1151
1152   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1153   // handle type legalization for these operations here.
1154   //
1155   // FIXME: We really should do custom legalization for addition and
1156   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1157   // than generic legalization for 64-bit multiplication-with-overflow, though.
1158   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1159     // Add/Sub/Mul with overflow operations are custom lowered.
1160     MVT VT = IntVTs[i];
1161     setOperationAction(ISD::SADDO, VT, Custom);
1162     setOperationAction(ISD::UADDO, VT, Custom);
1163     setOperationAction(ISD::SSUBO, VT, Custom);
1164     setOperationAction(ISD::USUBO, VT, Custom);
1165     setOperationAction(ISD::SMULO, VT, Custom);
1166     setOperationAction(ISD::UMULO, VT, Custom);
1167   }
1168
1169   // There are no 8-bit 3-address imul/mul instructions
1170   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1171   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1172
1173   if (!Subtarget->is64Bit()) {
1174     // These libcalls are not available in 32-bit.
1175     setLibcallName(RTLIB::SHL_I128, 0);
1176     setLibcallName(RTLIB::SRL_I128, 0);
1177     setLibcallName(RTLIB::SRA_I128, 0);
1178   }
1179
1180   // We have target-specific dag combine patterns for the following nodes:
1181   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1182   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1183   setTargetDAGCombine(ISD::BUILD_VECTOR);
1184   setTargetDAGCombine(ISD::VSELECT);
1185   setTargetDAGCombine(ISD::SELECT);
1186   setTargetDAGCombine(ISD::SHL);
1187   setTargetDAGCombine(ISD::SRA);
1188   setTargetDAGCombine(ISD::SRL);
1189   setTargetDAGCombine(ISD::OR);
1190   setTargetDAGCombine(ISD::AND);
1191   setTargetDAGCombine(ISD::ADD);
1192   setTargetDAGCombine(ISD::FADD);
1193   setTargetDAGCombine(ISD::FSUB);
1194   setTargetDAGCombine(ISD::SUB);
1195   setTargetDAGCombine(ISD::LOAD);
1196   setTargetDAGCombine(ISD::STORE);
1197   setTargetDAGCombine(ISD::ZERO_EXTEND);
1198   setTargetDAGCombine(ISD::SINT_TO_FP);
1199   if (Subtarget->is64Bit())
1200     setTargetDAGCombine(ISD::MUL);
1201   if (Subtarget->hasBMI())
1202     setTargetDAGCombine(ISD::XOR);
1203
1204   computeRegisterProperties();
1205
1206   // On Darwin, -Os means optimize for size without hurting performance,
1207   // do not reduce the limit.
1208   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1209   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1210   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1211   maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1212   maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1213   maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1214   setPrefLoopAlignment(16);
1215   benefitFromCodePlacementOpt = true;
1216
1217   setPrefFunctionAlignment(4);
1218 }
1219
1220
1221 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1222   if (!VT.isVector()) return MVT::i8;
1223   return VT.changeVectorElementTypeToInteger();
1224 }
1225
1226
1227 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1228 /// the desired ByVal argument alignment.
1229 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1230   if (MaxAlign == 16)
1231     return;
1232   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1233     if (VTy->getBitWidth() == 128)
1234       MaxAlign = 16;
1235   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1236     unsigned EltAlign = 0;
1237     getMaxByValAlign(ATy->getElementType(), EltAlign);
1238     if (EltAlign > MaxAlign)
1239       MaxAlign = EltAlign;
1240   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1241     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1242       unsigned EltAlign = 0;
1243       getMaxByValAlign(STy->getElementType(i), EltAlign);
1244       if (EltAlign > MaxAlign)
1245         MaxAlign = EltAlign;
1246       if (MaxAlign == 16)
1247         break;
1248     }
1249   }
1250   return;
1251 }
1252
1253 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1254 /// function arguments in the caller parameter area. For X86, aggregates
1255 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1256 /// are at 4-byte boundaries.
1257 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1258   if (Subtarget->is64Bit()) {
1259     // Max of 8 and alignment of type.
1260     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1261     if (TyAlign > 8)
1262       return TyAlign;
1263     return 8;
1264   }
1265
1266   unsigned Align = 4;
1267   if (Subtarget->hasXMM())
1268     getMaxByValAlign(Ty, Align);
1269   return Align;
1270 }
1271
1272 /// getOptimalMemOpType - Returns the target specific optimal type for load
1273 /// and store operations as a result of memset, memcpy, and memmove
1274 /// lowering. If DstAlign is zero that means it's safe to destination
1275 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1276 /// means there isn't a need to check it against alignment requirement,
1277 /// probably because the source does not need to be loaded. If
1278 /// 'IsZeroVal' is true, that means it's safe to return a
1279 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1280 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1281 /// constant so it does not need to be loaded.
1282 /// It returns EVT::Other if the type should be determined using generic
1283 /// target-independent logic.
1284 EVT
1285 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1286                                        unsigned DstAlign, unsigned SrcAlign,
1287                                        bool IsZeroVal,
1288                                        bool MemcpyStrSrc,
1289                                        MachineFunction &MF) const {
1290   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1291   // linux.  This is because the stack realignment code can't handle certain
1292   // cases like PR2962.  This should be removed when PR2962 is fixed.
1293   const Function *F = MF.getFunction();
1294   if (IsZeroVal &&
1295       !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1296     if (Size >= 16 &&
1297         (Subtarget->isUnalignedMemAccessFast() ||
1298          ((DstAlign == 0 || DstAlign >= 16) &&
1299           (SrcAlign == 0 || SrcAlign >= 16))) &&
1300         Subtarget->getStackAlignment() >= 16) {
1301       if (Subtarget->hasAVX() &&
1302           Subtarget->getStackAlignment() >= 32)
1303         return MVT::v8f32;
1304       if (Subtarget->hasXMMInt())
1305         return MVT::v4i32;
1306       if (Subtarget->hasXMM())
1307         return MVT::v4f32;
1308     } else if (!MemcpyStrSrc && Size >= 8 &&
1309                !Subtarget->is64Bit() &&
1310                Subtarget->getStackAlignment() >= 8 &&
1311                Subtarget->hasXMMInt()) {
1312       // Do not use f64 to lower memcpy if source is string constant. It's
1313       // better to use i32 to avoid the loads.
1314       return MVT::f64;
1315     }
1316   }
1317   if (Subtarget->is64Bit() && Size >= 8)
1318     return MVT::i64;
1319   return MVT::i32;
1320 }
1321
1322 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1323 /// current function.  The returned value is a member of the
1324 /// MachineJumpTableInfo::JTEntryKind enum.
1325 unsigned X86TargetLowering::getJumpTableEncoding() const {
1326   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1327   // symbol.
1328   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1329       Subtarget->isPICStyleGOT())
1330     return MachineJumpTableInfo::EK_Custom32;
1331
1332   // Otherwise, use the normal jump table encoding heuristics.
1333   return TargetLowering::getJumpTableEncoding();
1334 }
1335
1336 const MCExpr *
1337 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1338                                              const MachineBasicBlock *MBB,
1339                                              unsigned uid,MCContext &Ctx) const{
1340   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1341          Subtarget->isPICStyleGOT());
1342   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1343   // entries.
1344   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1345                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1346 }
1347
1348 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1349 /// jumptable.
1350 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1351                                                     SelectionDAG &DAG) const {
1352   if (!Subtarget->is64Bit())
1353     // This doesn't have DebugLoc associated with it, but is not really the
1354     // same as a Register.
1355     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1356   return Table;
1357 }
1358
1359 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1360 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1361 /// MCExpr.
1362 const MCExpr *X86TargetLowering::
1363 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1364                              MCContext &Ctx) const {
1365   // X86-64 uses RIP relative addressing based on the jump table label.
1366   if (Subtarget->isPICStyleRIPRel())
1367     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1368
1369   // Otherwise, the reference is relative to the PIC base.
1370   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1371 }
1372
1373 // FIXME: Why this routine is here? Move to RegInfo!
1374 std::pair<const TargetRegisterClass*, uint8_t>
1375 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1376   const TargetRegisterClass *RRC = 0;
1377   uint8_t Cost = 1;
1378   switch (VT.getSimpleVT().SimpleTy) {
1379   default:
1380     return TargetLowering::findRepresentativeClass(VT);
1381   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1382     RRC = (Subtarget->is64Bit()
1383            ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1384     break;
1385   case MVT::x86mmx:
1386     RRC = X86::VR64RegisterClass;
1387     break;
1388   case MVT::f32: case MVT::f64:
1389   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1390   case MVT::v4f32: case MVT::v2f64:
1391   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1392   case MVT::v4f64:
1393     RRC = X86::VR128RegisterClass;
1394     break;
1395   }
1396   return std::make_pair(RRC, Cost);
1397 }
1398
1399 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1400                                                unsigned &Offset) const {
1401   if (!Subtarget->isTargetLinux())
1402     return false;
1403
1404   if (Subtarget->is64Bit()) {
1405     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1406     Offset = 0x28;
1407     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1408       AddressSpace = 256;
1409     else
1410       AddressSpace = 257;
1411   } else {
1412     // %gs:0x14 on i386
1413     Offset = 0x14;
1414     AddressSpace = 256;
1415   }
1416   return true;
1417 }
1418
1419
1420 //===----------------------------------------------------------------------===//
1421 //               Return Value Calling Convention Implementation
1422 //===----------------------------------------------------------------------===//
1423
1424 #include "X86GenCallingConv.inc"
1425
1426 bool
1427 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1428                                   MachineFunction &MF, bool isVarArg,
1429                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1430                         LLVMContext &Context) const {
1431   SmallVector<CCValAssign, 16> RVLocs;
1432   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1433                  RVLocs, Context);
1434   return CCInfo.CheckReturn(Outs, RetCC_X86);
1435 }
1436
1437 SDValue
1438 X86TargetLowering::LowerReturn(SDValue Chain,
1439                                CallingConv::ID CallConv, bool isVarArg,
1440                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1441                                const SmallVectorImpl<SDValue> &OutVals,
1442                                DebugLoc dl, SelectionDAG &DAG) const {
1443   MachineFunction &MF = DAG.getMachineFunction();
1444   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1445
1446   SmallVector<CCValAssign, 16> RVLocs;
1447   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1448                  RVLocs, *DAG.getContext());
1449   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1450
1451   // Add the regs to the liveout set for the function.
1452   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1453   for (unsigned i = 0; i != RVLocs.size(); ++i)
1454     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1455       MRI.addLiveOut(RVLocs[i].getLocReg());
1456
1457   SDValue Flag;
1458
1459   SmallVector<SDValue, 6> RetOps;
1460   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1461   // Operand #1 = Bytes To Pop
1462   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1463                    MVT::i16));
1464
1465   // Copy the result values into the output registers.
1466   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1467     CCValAssign &VA = RVLocs[i];
1468     assert(VA.isRegLoc() && "Can only return in registers!");
1469     SDValue ValToCopy = OutVals[i];
1470     EVT ValVT = ValToCopy.getValueType();
1471
1472     // If this is x86-64, and we disabled SSE, we can't return FP values,
1473     // or SSE or MMX vectors.
1474     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1475          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1476           (Subtarget->is64Bit() && !Subtarget->hasXMM())) {
1477       report_fatal_error("SSE register return with SSE disabled");
1478     }
1479     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1480     // llvm-gcc has never done it right and no one has noticed, so this
1481     // should be OK for now.
1482     if (ValVT == MVT::f64 &&
1483         (Subtarget->is64Bit() && !Subtarget->hasXMMInt()))
1484       report_fatal_error("SSE2 register return with SSE2 disabled");
1485
1486     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1487     // the RET instruction and handled by the FP Stackifier.
1488     if (VA.getLocReg() == X86::ST0 ||
1489         VA.getLocReg() == X86::ST1) {
1490       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1491       // change the value to the FP stack register class.
1492       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1493         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1494       RetOps.push_back(ValToCopy);
1495       // Don't emit a copytoreg.
1496       continue;
1497     }
1498
1499     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1500     // which is returned in RAX / RDX.
1501     if (Subtarget->is64Bit()) {
1502       if (ValVT == MVT::x86mmx) {
1503         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1504           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1505           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1506                                   ValToCopy);
1507           // If we don't have SSE2 available, convert to v4f32 so the generated
1508           // register is legal.
1509           if (!Subtarget->hasXMMInt())
1510             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1511         }
1512       }
1513     }
1514
1515     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1516     Flag = Chain.getValue(1);
1517   }
1518
1519   // The x86-64 ABI for returning structs by value requires that we copy
1520   // the sret argument into %rax for the return. We saved the argument into
1521   // a virtual register in the entry block, so now we copy the value out
1522   // and into %rax.
1523   if (Subtarget->is64Bit() &&
1524       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1525     MachineFunction &MF = DAG.getMachineFunction();
1526     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1527     unsigned Reg = FuncInfo->getSRetReturnReg();
1528     assert(Reg &&
1529            "SRetReturnReg should have been set in LowerFormalArguments().");
1530     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1531
1532     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1533     Flag = Chain.getValue(1);
1534
1535     // RAX now acts like a return value.
1536     MRI.addLiveOut(X86::RAX);
1537   }
1538
1539   RetOps[0] = Chain;  // Update chain.
1540
1541   // Add the flag if we have it.
1542   if (Flag.getNode())
1543     RetOps.push_back(Flag);
1544
1545   return DAG.getNode(X86ISD::RET_FLAG, dl,
1546                      MVT::Other, &RetOps[0], RetOps.size());
1547 }
1548
1549 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1550   if (N->getNumValues() != 1)
1551     return false;
1552   if (!N->hasNUsesOfValue(1, 0))
1553     return false;
1554
1555   SDNode *Copy = *N->use_begin();
1556   if (Copy->getOpcode() != ISD::CopyToReg &&
1557       Copy->getOpcode() != ISD::FP_EXTEND)
1558     return false;
1559
1560   bool HasRet = false;
1561   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1562        UI != UE; ++UI) {
1563     if (UI->getOpcode() != X86ISD::RET_FLAG)
1564       return false;
1565     HasRet = true;
1566   }
1567
1568   return HasRet;
1569 }
1570
1571 EVT
1572 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1573                                             ISD::NodeType ExtendKind) const {
1574   MVT ReturnMVT;
1575   // TODO: Is this also valid on 32-bit?
1576   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1577     ReturnMVT = MVT::i8;
1578   else
1579     ReturnMVT = MVT::i32;
1580
1581   EVT MinVT = getRegisterType(Context, ReturnMVT);
1582   return VT.bitsLT(MinVT) ? MinVT : VT;
1583 }
1584
1585 /// LowerCallResult - Lower the result values of a call into the
1586 /// appropriate copies out of appropriate physical registers.
1587 ///
1588 SDValue
1589 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1590                                    CallingConv::ID CallConv, bool isVarArg,
1591                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1592                                    DebugLoc dl, SelectionDAG &DAG,
1593                                    SmallVectorImpl<SDValue> &InVals) const {
1594
1595   // Assign locations to each value returned by this call.
1596   SmallVector<CCValAssign, 16> RVLocs;
1597   bool Is64Bit = Subtarget->is64Bit();
1598   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1599                  getTargetMachine(), RVLocs, *DAG.getContext());
1600   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1601
1602   // Copy all of the result registers out of their specified physreg.
1603   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1604     CCValAssign &VA = RVLocs[i];
1605     EVT CopyVT = VA.getValVT();
1606
1607     // If this is x86-64, and we disabled SSE, we can't return FP values
1608     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1609         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) {
1610       report_fatal_error("SSE register return with SSE disabled");
1611     }
1612
1613     SDValue Val;
1614
1615     // If this is a call to a function that returns an fp value on the floating
1616     // point stack, we must guarantee the the value is popped from the stack, so
1617     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1618     // if the return value is not used. We use the FpPOP_RETVAL instruction
1619     // instead.
1620     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1621       // If we prefer to use the value in xmm registers, copy it out as f80 and
1622       // use a truncate to move it from fp stack reg to xmm reg.
1623       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1624       SDValue Ops[] = { Chain, InFlag };
1625       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1626                                          MVT::Other, MVT::Glue, Ops, 2), 1);
1627       Val = Chain.getValue(0);
1628
1629       // Round the f80 to the right size, which also moves it to the appropriate
1630       // xmm register.
1631       if (CopyVT != VA.getValVT())
1632         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1633                           // This truncation won't change the value.
1634                           DAG.getIntPtrConstant(1));
1635     } else {
1636       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1637                                  CopyVT, InFlag).getValue(1);
1638       Val = Chain.getValue(0);
1639     }
1640     InFlag = Chain.getValue(2);
1641     InVals.push_back(Val);
1642   }
1643
1644   return Chain;
1645 }
1646
1647
1648 //===----------------------------------------------------------------------===//
1649 //                C & StdCall & Fast Calling Convention implementation
1650 //===----------------------------------------------------------------------===//
1651 //  StdCall calling convention seems to be standard for many Windows' API
1652 //  routines and around. It differs from C calling convention just a little:
1653 //  callee should clean up the stack, not caller. Symbols should be also
1654 //  decorated in some fancy way :) It doesn't support any vector arguments.
1655 //  For info on fast calling convention see Fast Calling Convention (tail call)
1656 //  implementation LowerX86_32FastCCCallTo.
1657
1658 /// CallIsStructReturn - Determines whether a call uses struct return
1659 /// semantics.
1660 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1661   if (Outs.empty())
1662     return false;
1663
1664   return Outs[0].Flags.isSRet();
1665 }
1666
1667 /// ArgsAreStructReturn - Determines whether a function uses struct
1668 /// return semantics.
1669 static bool
1670 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1671   if (Ins.empty())
1672     return false;
1673
1674   return Ins[0].Flags.isSRet();
1675 }
1676
1677 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1678 /// by "Src" to address "Dst" with size and alignment information specified by
1679 /// the specific parameter attribute. The copy will be passed as a byval
1680 /// function parameter.
1681 static SDValue
1682 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1683                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1684                           DebugLoc dl) {
1685   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1686
1687   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1688                        /*isVolatile*/false, /*AlwaysInline=*/true,
1689                        MachinePointerInfo(), MachinePointerInfo());
1690 }
1691
1692 /// IsTailCallConvention - Return true if the calling convention is one that
1693 /// supports tail call optimization.
1694 static bool IsTailCallConvention(CallingConv::ID CC) {
1695   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1696 }
1697
1698 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1699   if (!CI->isTailCall())
1700     return false;
1701
1702   CallSite CS(CI);
1703   CallingConv::ID CalleeCC = CS.getCallingConv();
1704   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1705     return false;
1706
1707   return true;
1708 }
1709
1710 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1711 /// a tailcall target by changing its ABI.
1712 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1713   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1714 }
1715
1716 SDValue
1717 X86TargetLowering::LowerMemArgument(SDValue Chain,
1718                                     CallingConv::ID CallConv,
1719                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1720                                     DebugLoc dl, SelectionDAG &DAG,
1721                                     const CCValAssign &VA,
1722                                     MachineFrameInfo *MFI,
1723                                     unsigned i) const {
1724   // Create the nodes corresponding to a load from this parameter slot.
1725   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1726   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1727   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1728   EVT ValVT;
1729
1730   // If value is passed by pointer we have address passed instead of the value
1731   // itself.
1732   if (VA.getLocInfo() == CCValAssign::Indirect)
1733     ValVT = VA.getLocVT();
1734   else
1735     ValVT = VA.getValVT();
1736
1737   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1738   // changed with more analysis.
1739   // In case of tail call optimization mark all arguments mutable. Since they
1740   // could be overwritten by lowering of arguments in case of a tail call.
1741   if (Flags.isByVal()) {
1742     unsigned Bytes = Flags.getByValSize();
1743     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1744     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1745     return DAG.getFrameIndex(FI, getPointerTy());
1746   } else {
1747     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1748                                     VA.getLocMemOffset(), isImmutable);
1749     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1750     return DAG.getLoad(ValVT, dl, Chain, FIN,
1751                        MachinePointerInfo::getFixedStack(FI),
1752                        false, false, false, 0);
1753   }
1754 }
1755
1756 SDValue
1757 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1758                                         CallingConv::ID CallConv,
1759                                         bool isVarArg,
1760                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1761                                         DebugLoc dl,
1762                                         SelectionDAG &DAG,
1763                                         SmallVectorImpl<SDValue> &InVals)
1764                                           const {
1765   MachineFunction &MF = DAG.getMachineFunction();
1766   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1767
1768   const Function* Fn = MF.getFunction();
1769   if (Fn->hasExternalLinkage() &&
1770       Subtarget->isTargetCygMing() &&
1771       Fn->getName() == "main")
1772     FuncInfo->setForceFramePointer(true);
1773
1774   MachineFrameInfo *MFI = MF.getFrameInfo();
1775   bool Is64Bit = Subtarget->is64Bit();
1776   bool IsWin64 = Subtarget->isTargetWin64();
1777
1778   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1779          "Var args not supported with calling convention fastcc or ghc");
1780
1781   // Assign locations to all of the incoming arguments.
1782   SmallVector<CCValAssign, 16> ArgLocs;
1783   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1784                  ArgLocs, *DAG.getContext());
1785
1786   // Allocate shadow area for Win64
1787   if (IsWin64) {
1788     CCInfo.AllocateStack(32, 8);
1789   }
1790
1791   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1792
1793   unsigned LastVal = ~0U;
1794   SDValue ArgValue;
1795   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1796     CCValAssign &VA = ArgLocs[i];
1797     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1798     // places.
1799     assert(VA.getValNo() != LastVal &&
1800            "Don't support value assigned to multiple locs yet");
1801     (void)LastVal;
1802     LastVal = VA.getValNo();
1803
1804     if (VA.isRegLoc()) {
1805       EVT RegVT = VA.getLocVT();
1806       TargetRegisterClass *RC = NULL;
1807       if (RegVT == MVT::i32)
1808         RC = X86::GR32RegisterClass;
1809       else if (Is64Bit && RegVT == MVT::i64)
1810         RC = X86::GR64RegisterClass;
1811       else if (RegVT == MVT::f32)
1812         RC = X86::FR32RegisterClass;
1813       else if (RegVT == MVT::f64)
1814         RC = X86::FR64RegisterClass;
1815       else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1816         RC = X86::VR256RegisterClass;
1817       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1818         RC = X86::VR128RegisterClass;
1819       else if (RegVT == MVT::x86mmx)
1820         RC = X86::VR64RegisterClass;
1821       else
1822         llvm_unreachable("Unknown argument type!");
1823
1824       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1825       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1826
1827       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1828       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1829       // right size.
1830       if (VA.getLocInfo() == CCValAssign::SExt)
1831         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1832                                DAG.getValueType(VA.getValVT()));
1833       else if (VA.getLocInfo() == CCValAssign::ZExt)
1834         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1835                                DAG.getValueType(VA.getValVT()));
1836       else if (VA.getLocInfo() == CCValAssign::BCvt)
1837         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1838
1839       if (VA.isExtInLoc()) {
1840         // Handle MMX values passed in XMM regs.
1841         if (RegVT.isVector()) {
1842           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1843                                  ArgValue);
1844         } else
1845           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1846       }
1847     } else {
1848       assert(VA.isMemLoc());
1849       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1850     }
1851
1852     // If value is passed via pointer - do a load.
1853     if (VA.getLocInfo() == CCValAssign::Indirect)
1854       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1855                              MachinePointerInfo(), false, false, false, 0);
1856
1857     InVals.push_back(ArgValue);
1858   }
1859
1860   // The x86-64 ABI for returning structs by value requires that we copy
1861   // the sret argument into %rax for the return. Save the argument into
1862   // a virtual register so that we can access it from the return points.
1863   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1864     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1865     unsigned Reg = FuncInfo->getSRetReturnReg();
1866     if (!Reg) {
1867       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1868       FuncInfo->setSRetReturnReg(Reg);
1869     }
1870     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1871     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1872   }
1873
1874   unsigned StackSize = CCInfo.getNextStackOffset();
1875   // Align stack specially for tail calls.
1876   if (FuncIsMadeTailCallSafe(CallConv))
1877     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1878
1879   // If the function takes variable number of arguments, make a frame index for
1880   // the start of the first vararg value... for expansion of llvm.va_start.
1881   if (isVarArg) {
1882     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1883                     CallConv != CallingConv::X86_ThisCall)) {
1884       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1885     }
1886     if (Is64Bit) {
1887       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1888
1889       // FIXME: We should really autogenerate these arrays
1890       static const unsigned GPR64ArgRegsWin64[] = {
1891         X86::RCX, X86::RDX, X86::R8,  X86::R9
1892       };
1893       static const unsigned GPR64ArgRegs64Bit[] = {
1894         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1895       };
1896       static const unsigned XMMArgRegs64Bit[] = {
1897         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1898         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1899       };
1900       const unsigned *GPR64ArgRegs;
1901       unsigned NumXMMRegs = 0;
1902
1903       if (IsWin64) {
1904         // The XMM registers which might contain var arg parameters are shadowed
1905         // in their paired GPR.  So we only need to save the GPR to their home
1906         // slots.
1907         TotalNumIntRegs = 4;
1908         GPR64ArgRegs = GPR64ArgRegsWin64;
1909       } else {
1910         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1911         GPR64ArgRegs = GPR64ArgRegs64Bit;
1912
1913         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1914       }
1915       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1916                                                        TotalNumIntRegs);
1917
1918       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1919       assert(!(NumXMMRegs && !Subtarget->hasXMM()) &&
1920              "SSE register cannot be used when SSE is disabled!");
1921       assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1922              "SSE register cannot be used when SSE is disabled!");
1923       if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasXMM())
1924         // Kernel mode asks for SSE to be disabled, so don't push them
1925         // on the stack.
1926         TotalNumXMMRegs = 0;
1927
1928       if (IsWin64) {
1929         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1930         // Get to the caller-allocated home save location.  Add 8 to account
1931         // for the return address.
1932         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1933         FuncInfo->setRegSaveFrameIndex(
1934           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1935         // Fixup to set vararg frame on shadow area (4 x i64).
1936         if (NumIntRegs < 4)
1937           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1938       } else {
1939         // For X86-64, if there are vararg parameters that are passed via
1940         // registers, then we must store them to their spots on the stack so they
1941         // may be loaded by deferencing the result of va_next.
1942         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1943         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1944         FuncInfo->setRegSaveFrameIndex(
1945           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1946                                false));
1947       }
1948
1949       // Store the integer parameter registers.
1950       SmallVector<SDValue, 8> MemOps;
1951       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1952                                         getPointerTy());
1953       unsigned Offset = FuncInfo->getVarArgsGPOffset();
1954       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1955         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1956                                   DAG.getIntPtrConstant(Offset));
1957         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1958                                      X86::GR64RegisterClass);
1959         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1960         SDValue Store =
1961           DAG.getStore(Val.getValue(1), dl, Val, FIN,
1962                        MachinePointerInfo::getFixedStack(
1963                          FuncInfo->getRegSaveFrameIndex(), Offset),
1964                        false, false, 0);
1965         MemOps.push_back(Store);
1966         Offset += 8;
1967       }
1968
1969       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1970         // Now store the XMM (fp + vector) parameter registers.
1971         SmallVector<SDValue, 11> SaveXMMOps;
1972         SaveXMMOps.push_back(Chain);
1973
1974         unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1975         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1976         SaveXMMOps.push_back(ALVal);
1977
1978         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1979                                FuncInfo->getRegSaveFrameIndex()));
1980         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1981                                FuncInfo->getVarArgsFPOffset()));
1982
1983         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1984           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
1985                                        X86::VR128RegisterClass);
1986           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1987           SaveXMMOps.push_back(Val);
1988         }
1989         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1990                                      MVT::Other,
1991                                      &SaveXMMOps[0], SaveXMMOps.size()));
1992       }
1993
1994       if (!MemOps.empty())
1995         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1996                             &MemOps[0], MemOps.size());
1997     }
1998   }
1999
2000   // Some CCs need callee pop.
2001   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt)) {
2002     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2003   } else {
2004     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2005     // If this is an sret function, the return should pop the hidden pointer.
2006     if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
2007       FuncInfo->setBytesToPopOnReturn(4);
2008   }
2009
2010   if (!Is64Bit) {
2011     // RegSaveFrameIndex is X86-64 only.
2012     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2013     if (CallConv == CallingConv::X86_FastCall ||
2014         CallConv == CallingConv::X86_ThisCall)
2015       // fastcc functions can't have varargs.
2016       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2017   }
2018
2019   FuncInfo->setArgumentStackSize(StackSize);
2020
2021   return Chain;
2022 }
2023
2024 SDValue
2025 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2026                                     SDValue StackPtr, SDValue Arg,
2027                                     DebugLoc dl, SelectionDAG &DAG,
2028                                     const CCValAssign &VA,
2029                                     ISD::ArgFlagsTy Flags) const {
2030   unsigned LocMemOffset = VA.getLocMemOffset();
2031   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2032   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2033   if (Flags.isByVal())
2034     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2035
2036   return DAG.getStore(Chain, dl, Arg, PtrOff,
2037                       MachinePointerInfo::getStack(LocMemOffset),
2038                       false, false, 0);
2039 }
2040
2041 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2042 /// optimization is performed and it is required.
2043 SDValue
2044 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2045                                            SDValue &OutRetAddr, SDValue Chain,
2046                                            bool IsTailCall, bool Is64Bit,
2047                                            int FPDiff, DebugLoc dl) const {
2048   // Adjust the Return address stack slot.
2049   EVT VT = getPointerTy();
2050   OutRetAddr = getReturnAddressFrameIndex(DAG);
2051
2052   // Load the "old" Return address.
2053   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2054                            false, false, false, 0);
2055   return SDValue(OutRetAddr.getNode(), 1);
2056 }
2057
2058 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2059 /// optimization is performed and it is required (FPDiff!=0).
2060 static SDValue
2061 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2062                          SDValue Chain, SDValue RetAddrFrIdx,
2063                          bool Is64Bit, int FPDiff, DebugLoc dl) {
2064   // Store the return address to the appropriate stack slot.
2065   if (!FPDiff) return Chain;
2066   // Calculate the new stack slot for the return address.
2067   int SlotSize = Is64Bit ? 8 : 4;
2068   int NewReturnAddrFI =
2069     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2070   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2071   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
2072   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2073                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2074                        false, false, 0);
2075   return Chain;
2076 }
2077
2078 SDValue
2079 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
2080                              CallingConv::ID CallConv, bool isVarArg,
2081                              bool &isTailCall,
2082                              const SmallVectorImpl<ISD::OutputArg> &Outs,
2083                              const SmallVectorImpl<SDValue> &OutVals,
2084                              const SmallVectorImpl<ISD::InputArg> &Ins,
2085                              DebugLoc dl, SelectionDAG &DAG,
2086                              SmallVectorImpl<SDValue> &InVals) const {
2087   MachineFunction &MF = DAG.getMachineFunction();
2088   bool Is64Bit        = Subtarget->is64Bit();
2089   bool IsWin64        = Subtarget->isTargetWin64();
2090   bool IsStructRet    = CallIsStructReturn(Outs);
2091   bool IsSibcall      = false;
2092
2093   if (isTailCall) {
2094     // Check if it's really possible to do a tail call.
2095     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2096                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
2097                                                    Outs, OutVals, Ins, DAG);
2098
2099     // Sibcalls are automatically detected tailcalls which do not require
2100     // ABI changes.
2101     if (!GuaranteedTailCallOpt && isTailCall)
2102       IsSibcall = true;
2103
2104     if (isTailCall)
2105       ++NumTailCalls;
2106   }
2107
2108   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2109          "Var args not supported with calling convention fastcc or ghc");
2110
2111   // Analyze operands of the call, assigning locations to each operand.
2112   SmallVector<CCValAssign, 16> ArgLocs;
2113   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2114                  ArgLocs, *DAG.getContext());
2115
2116   // Allocate shadow area for Win64
2117   if (IsWin64) {
2118     CCInfo.AllocateStack(32, 8);
2119   }
2120
2121   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2122
2123   // Get a count of how many bytes are to be pushed on the stack.
2124   unsigned NumBytes = CCInfo.getNextStackOffset();
2125   if (IsSibcall)
2126     // This is a sibcall. The memory operands are available in caller's
2127     // own caller's stack.
2128     NumBytes = 0;
2129   else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
2130     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2131
2132   int FPDiff = 0;
2133   if (isTailCall && !IsSibcall) {
2134     // Lower arguments at fp - stackoffset + fpdiff.
2135     unsigned NumBytesCallerPushed =
2136       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2137     FPDiff = NumBytesCallerPushed - NumBytes;
2138
2139     // Set the delta of movement of the returnaddr stackslot.
2140     // But only set if delta is greater than previous delta.
2141     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2142       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2143   }
2144
2145   if (!IsSibcall)
2146     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2147
2148   SDValue RetAddrFrIdx;
2149   // Load return address for tail calls.
2150   if (isTailCall && FPDiff)
2151     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2152                                     Is64Bit, FPDiff, dl);
2153
2154   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2155   SmallVector<SDValue, 8> MemOpChains;
2156   SDValue StackPtr;
2157
2158   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2159   // of tail call optimization arguments are handle later.
2160   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2161     CCValAssign &VA = ArgLocs[i];
2162     EVT RegVT = VA.getLocVT();
2163     SDValue Arg = OutVals[i];
2164     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2165     bool isByVal = Flags.isByVal();
2166
2167     // Promote the value if needed.
2168     switch (VA.getLocInfo()) {
2169     default: llvm_unreachable("Unknown loc info!");
2170     case CCValAssign::Full: break;
2171     case CCValAssign::SExt:
2172       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2173       break;
2174     case CCValAssign::ZExt:
2175       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2176       break;
2177     case CCValAssign::AExt:
2178       if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2179         // Special case: passing MMX values in XMM registers.
2180         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2181         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2182         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2183       } else
2184         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2185       break;
2186     case CCValAssign::BCvt:
2187       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2188       break;
2189     case CCValAssign::Indirect: {
2190       // Store the argument.
2191       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2192       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2193       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2194                            MachinePointerInfo::getFixedStack(FI),
2195                            false, false, 0);
2196       Arg = SpillSlot;
2197       break;
2198     }
2199     }
2200
2201     if (VA.isRegLoc()) {
2202       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2203       if (isVarArg && IsWin64) {
2204         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2205         // shadow reg if callee is a varargs function.
2206         unsigned ShadowReg = 0;
2207         switch (VA.getLocReg()) {
2208         case X86::XMM0: ShadowReg = X86::RCX; break;
2209         case X86::XMM1: ShadowReg = X86::RDX; break;
2210         case X86::XMM2: ShadowReg = X86::R8; break;
2211         case X86::XMM3: ShadowReg = X86::R9; break;
2212         }
2213         if (ShadowReg)
2214           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2215       }
2216     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2217       assert(VA.isMemLoc());
2218       if (StackPtr.getNode() == 0)
2219         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2220       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2221                                              dl, DAG, VA, Flags));
2222     }
2223   }
2224
2225   if (!MemOpChains.empty())
2226     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2227                         &MemOpChains[0], MemOpChains.size());
2228
2229   // Build a sequence of copy-to-reg nodes chained together with token chain
2230   // and flag operands which copy the outgoing args into registers.
2231   SDValue InFlag;
2232   // Tail call byval lowering might overwrite argument registers so in case of
2233   // tail call optimization the copies to registers are lowered later.
2234   if (!isTailCall)
2235     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2236       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2237                                RegsToPass[i].second, InFlag);
2238       InFlag = Chain.getValue(1);
2239     }
2240
2241   if (Subtarget->isPICStyleGOT()) {
2242     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2243     // GOT pointer.
2244     if (!isTailCall) {
2245       Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2246                                DAG.getNode(X86ISD::GlobalBaseReg,
2247                                            DebugLoc(), getPointerTy()),
2248                                InFlag);
2249       InFlag = Chain.getValue(1);
2250     } else {
2251       // If we are tail calling and generating PIC/GOT style code load the
2252       // address of the callee into ECX. The value in ecx is used as target of
2253       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2254       // for tail calls on PIC/GOT architectures. Normally we would just put the
2255       // address of GOT into ebx and then call target@PLT. But for tail calls
2256       // ebx would be restored (since ebx is callee saved) before jumping to the
2257       // target@PLT.
2258
2259       // Note: The actual moving to ECX is done further down.
2260       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2261       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2262           !G->getGlobal()->hasProtectedVisibility())
2263         Callee = LowerGlobalAddress(Callee, DAG);
2264       else if (isa<ExternalSymbolSDNode>(Callee))
2265         Callee = LowerExternalSymbol(Callee, DAG);
2266     }
2267   }
2268
2269   if (Is64Bit && isVarArg && !IsWin64) {
2270     // From AMD64 ABI document:
2271     // For calls that may call functions that use varargs or stdargs
2272     // (prototype-less calls or calls to functions containing ellipsis (...) in
2273     // the declaration) %al is used as hidden argument to specify the number
2274     // of SSE registers used. The contents of %al do not need to match exactly
2275     // the number of registers, but must be an ubound on the number of SSE
2276     // registers used and is in the range 0 - 8 inclusive.
2277
2278     // Count the number of XMM registers allocated.
2279     static const unsigned XMMArgRegs[] = {
2280       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2281       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2282     };
2283     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2284     assert((Subtarget->hasXMM() || !NumXMMRegs)
2285            && "SSE registers cannot be used when SSE is disabled");
2286
2287     Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2288                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2289     InFlag = Chain.getValue(1);
2290   }
2291
2292
2293   // For tail calls lower the arguments to the 'real' stack slot.
2294   if (isTailCall) {
2295     // Force all the incoming stack arguments to be loaded from the stack
2296     // before any new outgoing arguments are stored to the stack, because the
2297     // outgoing stack slots may alias the incoming argument stack slots, and
2298     // the alias isn't otherwise explicit. This is slightly more conservative
2299     // than necessary, because it means that each store effectively depends
2300     // on every argument instead of just those arguments it would clobber.
2301     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2302
2303     SmallVector<SDValue, 8> MemOpChains2;
2304     SDValue FIN;
2305     int FI = 0;
2306     // Do not flag preceding copytoreg stuff together with the following stuff.
2307     InFlag = SDValue();
2308     if (GuaranteedTailCallOpt) {
2309       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2310         CCValAssign &VA = ArgLocs[i];
2311         if (VA.isRegLoc())
2312           continue;
2313         assert(VA.isMemLoc());
2314         SDValue Arg = OutVals[i];
2315         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2316         // Create frame index.
2317         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2318         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2319         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2320         FIN = DAG.getFrameIndex(FI, getPointerTy());
2321
2322         if (Flags.isByVal()) {
2323           // Copy relative to framepointer.
2324           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2325           if (StackPtr.getNode() == 0)
2326             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2327                                           getPointerTy());
2328           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2329
2330           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2331                                                            ArgChain,
2332                                                            Flags, DAG, dl));
2333         } else {
2334           // Store relative to framepointer.
2335           MemOpChains2.push_back(
2336             DAG.getStore(ArgChain, dl, Arg, FIN,
2337                          MachinePointerInfo::getFixedStack(FI),
2338                          false, false, 0));
2339         }
2340       }
2341     }
2342
2343     if (!MemOpChains2.empty())
2344       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2345                           &MemOpChains2[0], MemOpChains2.size());
2346
2347     // Copy arguments to their registers.
2348     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2349       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2350                                RegsToPass[i].second, InFlag);
2351       InFlag = Chain.getValue(1);
2352     }
2353     InFlag =SDValue();
2354
2355     // Store the return address to the appropriate stack slot.
2356     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2357                                      FPDiff, dl);
2358   }
2359
2360   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2361     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2362     // In the 64-bit large code model, we have to make all calls
2363     // through a register, since the call instruction's 32-bit
2364     // pc-relative offset may not be large enough to hold the whole
2365     // address.
2366   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2367     // If the callee is a GlobalAddress node (quite common, every direct call
2368     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2369     // it.
2370
2371     // We should use extra load for direct calls to dllimported functions in
2372     // non-JIT mode.
2373     const GlobalValue *GV = G->getGlobal();
2374     if (!GV->hasDLLImportLinkage()) {
2375       unsigned char OpFlags = 0;
2376       bool ExtraLoad = false;
2377       unsigned WrapperKind = ISD::DELETED_NODE;
2378
2379       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2380       // external symbols most go through the PLT in PIC mode.  If the symbol
2381       // has hidden or protected visibility, or if it is static or local, then
2382       // we don't need to use the PLT - we can directly call it.
2383       if (Subtarget->isTargetELF() &&
2384           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2385           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2386         OpFlags = X86II::MO_PLT;
2387       } else if (Subtarget->isPICStyleStubAny() &&
2388                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2389                  (!Subtarget->getTargetTriple().isMacOSX() ||
2390                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2391         // PC-relative references to external symbols should go through $stub,
2392         // unless we're building with the leopard linker or later, which
2393         // automatically synthesizes these stubs.
2394         OpFlags = X86II::MO_DARWIN_STUB;
2395       } else if (Subtarget->isPICStyleRIPRel() &&
2396                  isa<Function>(GV) &&
2397                  cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2398         // If the function is marked as non-lazy, generate an indirect call
2399         // which loads from the GOT directly. This avoids runtime overhead
2400         // at the cost of eager binding (and one extra byte of encoding).
2401         OpFlags = X86II::MO_GOTPCREL;
2402         WrapperKind = X86ISD::WrapperRIP;
2403         ExtraLoad = true;
2404       }
2405
2406       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2407                                           G->getOffset(), OpFlags);
2408
2409       // Add a wrapper if needed.
2410       if (WrapperKind != ISD::DELETED_NODE)
2411         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2412       // Add extra indirection if needed.
2413       if (ExtraLoad)
2414         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2415                              MachinePointerInfo::getGOT(),
2416                              false, false, false, 0);
2417     }
2418   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2419     unsigned char OpFlags = 0;
2420
2421     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2422     // external symbols should go through the PLT.
2423     if (Subtarget->isTargetELF() &&
2424         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2425       OpFlags = X86II::MO_PLT;
2426     } else if (Subtarget->isPICStyleStubAny() &&
2427                (!Subtarget->getTargetTriple().isMacOSX() ||
2428                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2429       // PC-relative references to external symbols should go through $stub,
2430       // unless we're building with the leopard linker or later, which
2431       // automatically synthesizes these stubs.
2432       OpFlags = X86II::MO_DARWIN_STUB;
2433     }
2434
2435     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2436                                          OpFlags);
2437   }
2438
2439   // Returns a chain & a flag for retval copy to use.
2440   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2441   SmallVector<SDValue, 8> Ops;
2442
2443   if (!IsSibcall && isTailCall) {
2444     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2445                            DAG.getIntPtrConstant(0, true), InFlag);
2446     InFlag = Chain.getValue(1);
2447   }
2448
2449   Ops.push_back(Chain);
2450   Ops.push_back(Callee);
2451
2452   if (isTailCall)
2453     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2454
2455   // Add argument registers to the end of the list so that they are known live
2456   // into the call.
2457   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2458     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2459                                   RegsToPass[i].second.getValueType()));
2460
2461   // Add an implicit use GOT pointer in EBX.
2462   if (!isTailCall && Subtarget->isPICStyleGOT())
2463     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2464
2465   // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2466   if (Is64Bit && isVarArg && !IsWin64)
2467     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2468
2469   if (InFlag.getNode())
2470     Ops.push_back(InFlag);
2471
2472   if (isTailCall) {
2473     // We used to do:
2474     //// If this is the first return lowered for this function, add the regs
2475     //// to the liveout set for the function.
2476     // This isn't right, although it's probably harmless on x86; liveouts
2477     // should be computed from returns not tail calls.  Consider a void
2478     // function making a tail call to a function returning int.
2479     return DAG.getNode(X86ISD::TC_RETURN, dl,
2480                        NodeTys, &Ops[0], Ops.size());
2481   }
2482
2483   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2484   InFlag = Chain.getValue(1);
2485
2486   // Create the CALLSEQ_END node.
2487   unsigned NumBytesForCalleeToPush;
2488   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt))
2489     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2490   else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2491     // If this is a call to a struct-return function, the callee
2492     // pops the hidden struct pointer, so we have to push it back.
2493     // This is common for Darwin/X86, Linux & Mingw32 targets.
2494     NumBytesForCalleeToPush = 4;
2495   else
2496     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2497
2498   // Returns a flag for retval copy to use.
2499   if (!IsSibcall) {
2500     Chain = DAG.getCALLSEQ_END(Chain,
2501                                DAG.getIntPtrConstant(NumBytes, true),
2502                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2503                                                      true),
2504                                InFlag);
2505     InFlag = Chain.getValue(1);
2506   }
2507
2508   // Handle result values, copying them out of physregs into vregs that we
2509   // return.
2510   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2511                          Ins, dl, DAG, InVals);
2512 }
2513
2514
2515 //===----------------------------------------------------------------------===//
2516 //                Fast Calling Convention (tail call) implementation
2517 //===----------------------------------------------------------------------===//
2518
2519 //  Like std call, callee cleans arguments, convention except that ECX is
2520 //  reserved for storing the tail called function address. Only 2 registers are
2521 //  free for argument passing (inreg). Tail call optimization is performed
2522 //  provided:
2523 //                * tailcallopt is enabled
2524 //                * caller/callee are fastcc
2525 //  On X86_64 architecture with GOT-style position independent code only local
2526 //  (within module) calls are supported at the moment.
2527 //  To keep the stack aligned according to platform abi the function
2528 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2529 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2530 //  If a tail called function callee has more arguments than the caller the
2531 //  caller needs to make sure that there is room to move the RETADDR to. This is
2532 //  achieved by reserving an area the size of the argument delta right after the
2533 //  original REtADDR, but before the saved framepointer or the spilled registers
2534 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2535 //  stack layout:
2536 //    arg1
2537 //    arg2
2538 //    RETADDR
2539 //    [ new RETADDR
2540 //      move area ]
2541 //    (possible EBP)
2542 //    ESI
2543 //    EDI
2544 //    local1 ..
2545
2546 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2547 /// for a 16 byte align requirement.
2548 unsigned
2549 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2550                                                SelectionDAG& DAG) const {
2551   MachineFunction &MF = DAG.getMachineFunction();
2552   const TargetMachine &TM = MF.getTarget();
2553   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2554   unsigned StackAlignment = TFI.getStackAlignment();
2555   uint64_t AlignMask = StackAlignment - 1;
2556   int64_t Offset = StackSize;
2557   uint64_t SlotSize = TD->getPointerSize();
2558   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2559     // Number smaller than 12 so just add the difference.
2560     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2561   } else {
2562     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2563     Offset = ((~AlignMask) & Offset) + StackAlignment +
2564       (StackAlignment-SlotSize);
2565   }
2566   return Offset;
2567 }
2568
2569 /// MatchingStackOffset - Return true if the given stack call argument is
2570 /// already available in the same position (relatively) of the caller's
2571 /// incoming argument stack.
2572 static
2573 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2574                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2575                          const X86InstrInfo *TII) {
2576   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2577   int FI = INT_MAX;
2578   if (Arg.getOpcode() == ISD::CopyFromReg) {
2579     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2580     if (!TargetRegisterInfo::isVirtualRegister(VR))
2581       return false;
2582     MachineInstr *Def = MRI->getVRegDef(VR);
2583     if (!Def)
2584       return false;
2585     if (!Flags.isByVal()) {
2586       if (!TII->isLoadFromStackSlot(Def, FI))
2587         return false;
2588     } else {
2589       unsigned Opcode = Def->getOpcode();
2590       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2591           Def->getOperand(1).isFI()) {
2592         FI = Def->getOperand(1).getIndex();
2593         Bytes = Flags.getByValSize();
2594       } else
2595         return false;
2596     }
2597   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2598     if (Flags.isByVal())
2599       // ByVal argument is passed in as a pointer but it's now being
2600       // dereferenced. e.g.
2601       // define @foo(%struct.X* %A) {
2602       //   tail call @bar(%struct.X* byval %A)
2603       // }
2604       return false;
2605     SDValue Ptr = Ld->getBasePtr();
2606     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2607     if (!FINode)
2608       return false;
2609     FI = FINode->getIndex();
2610   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2611     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2612     FI = FINode->getIndex();
2613     Bytes = Flags.getByValSize();
2614   } else
2615     return false;
2616
2617   assert(FI != INT_MAX);
2618   if (!MFI->isFixedObjectIndex(FI))
2619     return false;
2620   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2621 }
2622
2623 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2624 /// for tail call optimization. Targets which want to do tail call
2625 /// optimization should implement this function.
2626 bool
2627 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2628                                                      CallingConv::ID CalleeCC,
2629                                                      bool isVarArg,
2630                                                      bool isCalleeStructRet,
2631                                                      bool isCallerStructRet,
2632                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2633                                     const SmallVectorImpl<SDValue> &OutVals,
2634                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2635                                                      SelectionDAG& DAG) const {
2636   if (!IsTailCallConvention(CalleeCC) &&
2637       CalleeCC != CallingConv::C)
2638     return false;
2639
2640   // If -tailcallopt is specified, make fastcc functions tail-callable.
2641   const MachineFunction &MF = DAG.getMachineFunction();
2642   const Function *CallerF = DAG.getMachineFunction().getFunction();
2643   CallingConv::ID CallerCC = CallerF->getCallingConv();
2644   bool CCMatch = CallerCC == CalleeCC;
2645
2646   if (GuaranteedTailCallOpt) {
2647     if (IsTailCallConvention(CalleeCC) && CCMatch)
2648       return true;
2649     return false;
2650   }
2651
2652   // Look for obvious safe cases to perform tail call optimization that do not
2653   // require ABI changes. This is what gcc calls sibcall.
2654
2655   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2656   // emit a special epilogue.
2657   if (RegInfo->needsStackRealignment(MF))
2658     return false;
2659
2660   // Also avoid sibcall optimization if either caller or callee uses struct
2661   // return semantics.
2662   if (isCalleeStructRet || isCallerStructRet)
2663     return false;
2664
2665   // An stdcall caller is expected to clean up its arguments; the callee
2666   // isn't going to do that.
2667   if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2668     return false;
2669
2670   // Do not sibcall optimize vararg calls unless all arguments are passed via
2671   // registers.
2672   if (isVarArg && !Outs.empty()) {
2673
2674     // Optimizing for varargs on Win64 is unlikely to be safe without
2675     // additional testing.
2676     if (Subtarget->isTargetWin64())
2677       return false;
2678
2679     SmallVector<CCValAssign, 16> ArgLocs;
2680     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2681                    getTargetMachine(), ArgLocs, *DAG.getContext());
2682
2683     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2684     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2685       if (!ArgLocs[i].isRegLoc())
2686         return false;
2687   }
2688
2689   // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2690   // Therefore if it's not used by the call it is not safe to optimize this into
2691   // a sibcall.
2692   bool Unused = false;
2693   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2694     if (!Ins[i].Used) {
2695       Unused = true;
2696       break;
2697     }
2698   }
2699   if (Unused) {
2700     SmallVector<CCValAssign, 16> RVLocs;
2701     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2702                    getTargetMachine(), RVLocs, *DAG.getContext());
2703     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2704     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2705       CCValAssign &VA = RVLocs[i];
2706       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2707         return false;
2708     }
2709   }
2710
2711   // If the calling conventions do not match, then we'd better make sure the
2712   // results are returned in the same way as what the caller expects.
2713   if (!CCMatch) {
2714     SmallVector<CCValAssign, 16> RVLocs1;
2715     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2716                     getTargetMachine(), RVLocs1, *DAG.getContext());
2717     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2718
2719     SmallVector<CCValAssign, 16> RVLocs2;
2720     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2721                     getTargetMachine(), RVLocs2, *DAG.getContext());
2722     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2723
2724     if (RVLocs1.size() != RVLocs2.size())
2725       return false;
2726     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2727       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2728         return false;
2729       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2730         return false;
2731       if (RVLocs1[i].isRegLoc()) {
2732         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2733           return false;
2734       } else {
2735         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2736           return false;
2737       }
2738     }
2739   }
2740
2741   // If the callee takes no arguments then go on to check the results of the
2742   // call.
2743   if (!Outs.empty()) {
2744     // Check if stack adjustment is needed. For now, do not do this if any
2745     // argument is passed on the stack.
2746     SmallVector<CCValAssign, 16> ArgLocs;
2747     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2748                    getTargetMachine(), ArgLocs, *DAG.getContext());
2749
2750     // Allocate shadow area for Win64
2751     if (Subtarget->isTargetWin64()) {
2752       CCInfo.AllocateStack(32, 8);
2753     }
2754
2755     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2756     if (CCInfo.getNextStackOffset()) {
2757       MachineFunction &MF = DAG.getMachineFunction();
2758       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2759         return false;
2760
2761       // Check if the arguments are already laid out in the right way as
2762       // the caller's fixed stack objects.
2763       MachineFrameInfo *MFI = MF.getFrameInfo();
2764       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2765       const X86InstrInfo *TII =
2766         ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2767       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2768         CCValAssign &VA = ArgLocs[i];
2769         SDValue Arg = OutVals[i];
2770         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2771         if (VA.getLocInfo() == CCValAssign::Indirect)
2772           return false;
2773         if (!VA.isRegLoc()) {
2774           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2775                                    MFI, MRI, TII))
2776             return false;
2777         }
2778       }
2779     }
2780
2781     // If the tailcall address may be in a register, then make sure it's
2782     // possible to register allocate for it. In 32-bit, the call address can
2783     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2784     // callee-saved registers are restored. These happen to be the same
2785     // registers used to pass 'inreg' arguments so watch out for those.
2786     if (!Subtarget->is64Bit() &&
2787         !isa<GlobalAddressSDNode>(Callee) &&
2788         !isa<ExternalSymbolSDNode>(Callee)) {
2789       unsigned NumInRegs = 0;
2790       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2791         CCValAssign &VA = ArgLocs[i];
2792         if (!VA.isRegLoc())
2793           continue;
2794         unsigned Reg = VA.getLocReg();
2795         switch (Reg) {
2796         default: break;
2797         case X86::EAX: case X86::EDX: case X86::ECX:
2798           if (++NumInRegs == 3)
2799             return false;
2800           break;
2801         }
2802       }
2803     }
2804   }
2805
2806   return true;
2807 }
2808
2809 FastISel *
2810 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2811   return X86::createFastISel(funcInfo);
2812 }
2813
2814
2815 //===----------------------------------------------------------------------===//
2816 //                           Other Lowering Hooks
2817 //===----------------------------------------------------------------------===//
2818
2819 static bool MayFoldLoad(SDValue Op) {
2820   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2821 }
2822
2823 static bool MayFoldIntoStore(SDValue Op) {
2824   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2825 }
2826
2827 static bool isTargetShuffle(unsigned Opcode) {
2828   switch(Opcode) {
2829   default: return false;
2830   case X86ISD::PSHUFD:
2831   case X86ISD::PSHUFHW:
2832   case X86ISD::PSHUFLW:
2833   case X86ISD::SHUFPD:
2834   case X86ISD::PALIGN:
2835   case X86ISD::SHUFPS:
2836   case X86ISD::MOVLHPS:
2837   case X86ISD::MOVLHPD:
2838   case X86ISD::MOVHLPS:
2839   case X86ISD::MOVLPS:
2840   case X86ISD::MOVLPD:
2841   case X86ISD::MOVSHDUP:
2842   case X86ISD::MOVSLDUP:
2843   case X86ISD::MOVDDUP:
2844   case X86ISD::MOVSS:
2845   case X86ISD::MOVSD:
2846   case X86ISD::UNPCKLPS:
2847   case X86ISD::UNPCKLPD:
2848   case X86ISD::VUNPCKLPSY:
2849   case X86ISD::VUNPCKLPDY:
2850   case X86ISD::PUNPCKLWD:
2851   case X86ISD::PUNPCKLBW:
2852   case X86ISD::PUNPCKLDQ:
2853   case X86ISD::PUNPCKLQDQ:
2854   case X86ISD::UNPCKHPS:
2855   case X86ISD::UNPCKHPD:
2856   case X86ISD::VUNPCKHPSY:
2857   case X86ISD::VUNPCKHPDY:
2858   case X86ISD::PUNPCKHWD:
2859   case X86ISD::PUNPCKHBW:
2860   case X86ISD::PUNPCKHDQ:
2861   case X86ISD::PUNPCKHQDQ:
2862   case X86ISD::VPERMILPS:
2863   case X86ISD::VPERMILPSY:
2864   case X86ISD::VPERMILPD:
2865   case X86ISD::VPERMILPDY:
2866   case X86ISD::VPERM2F128:
2867     return true;
2868   }
2869   return false;
2870 }
2871
2872 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2873                                                SDValue V1, SelectionDAG &DAG) {
2874   switch(Opc) {
2875   default: llvm_unreachable("Unknown x86 shuffle node");
2876   case X86ISD::MOVSHDUP:
2877   case X86ISD::MOVSLDUP:
2878   case X86ISD::MOVDDUP:
2879     return DAG.getNode(Opc, dl, VT, V1);
2880   }
2881
2882   return SDValue();
2883 }
2884
2885 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2886                           SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2887   switch(Opc) {
2888   default: llvm_unreachable("Unknown x86 shuffle node");
2889   case X86ISD::PSHUFD:
2890   case X86ISD::PSHUFHW:
2891   case X86ISD::PSHUFLW:
2892   case X86ISD::VPERMILPS:
2893   case X86ISD::VPERMILPSY:
2894   case X86ISD::VPERMILPD:
2895   case X86ISD::VPERMILPDY:
2896     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2897   }
2898
2899   return SDValue();
2900 }
2901
2902 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2903                SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2904   switch(Opc) {
2905   default: llvm_unreachable("Unknown x86 shuffle node");
2906   case X86ISD::PALIGN:
2907   case X86ISD::SHUFPD:
2908   case X86ISD::SHUFPS:
2909   case X86ISD::VPERM2F128:
2910     return DAG.getNode(Opc, dl, VT, V1, V2,
2911                        DAG.getConstant(TargetMask, MVT::i8));
2912   }
2913   return SDValue();
2914 }
2915
2916 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2917                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
2918   switch(Opc) {
2919   default: llvm_unreachable("Unknown x86 shuffle node");
2920   case X86ISD::MOVLHPS:
2921   case X86ISD::MOVLHPD:
2922   case X86ISD::MOVHLPS:
2923   case X86ISD::MOVLPS:
2924   case X86ISD::MOVLPD:
2925   case X86ISD::MOVSS:
2926   case X86ISD::MOVSD:
2927   case X86ISD::UNPCKLPS:
2928   case X86ISD::UNPCKLPD:
2929   case X86ISD::VUNPCKLPSY:
2930   case X86ISD::VUNPCKLPDY:
2931   case X86ISD::PUNPCKLWD:
2932   case X86ISD::PUNPCKLBW:
2933   case X86ISD::PUNPCKLDQ:
2934   case X86ISD::PUNPCKLQDQ:
2935   case X86ISD::UNPCKHPS:
2936   case X86ISD::UNPCKHPD:
2937   case X86ISD::VUNPCKHPSY:
2938   case X86ISD::VUNPCKHPDY:
2939   case X86ISD::PUNPCKHWD:
2940   case X86ISD::PUNPCKHBW:
2941   case X86ISD::PUNPCKHDQ:
2942   case X86ISD::PUNPCKHQDQ:
2943     return DAG.getNode(Opc, dl, VT, V1, V2);
2944   }
2945   return SDValue();
2946 }
2947
2948 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2949   MachineFunction &MF = DAG.getMachineFunction();
2950   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2951   int ReturnAddrIndex = FuncInfo->getRAIndex();
2952
2953   if (ReturnAddrIndex == 0) {
2954     // Set up a frame object for the return address.
2955     uint64_t SlotSize = TD->getPointerSize();
2956     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2957                                                            false);
2958     FuncInfo->setRAIndex(ReturnAddrIndex);
2959   }
2960
2961   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2962 }
2963
2964
2965 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2966                                        bool hasSymbolicDisplacement) {
2967   // Offset should fit into 32 bit immediate field.
2968   if (!isInt<32>(Offset))
2969     return false;
2970
2971   // If we don't have a symbolic displacement - we don't have any extra
2972   // restrictions.
2973   if (!hasSymbolicDisplacement)
2974     return true;
2975
2976   // FIXME: Some tweaks might be needed for medium code model.
2977   if (M != CodeModel::Small && M != CodeModel::Kernel)
2978     return false;
2979
2980   // For small code model we assume that latest object is 16MB before end of 31
2981   // bits boundary. We may also accept pretty large negative constants knowing
2982   // that all objects are in the positive half of address space.
2983   if (M == CodeModel::Small && Offset < 16*1024*1024)
2984     return true;
2985
2986   // For kernel code model we know that all object resist in the negative half
2987   // of 32bits address space. We may not accept negative offsets, since they may
2988   // be just off and we may accept pretty large positive ones.
2989   if (M == CodeModel::Kernel && Offset > 0)
2990     return true;
2991
2992   return false;
2993 }
2994
2995 /// isCalleePop - Determines whether the callee is required to pop its
2996 /// own arguments. Callee pop is necessary to support tail calls.
2997 bool X86::isCalleePop(CallingConv::ID CallingConv,
2998                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
2999   if (IsVarArg)
3000     return false;
3001
3002   switch (CallingConv) {
3003   default:
3004     return false;
3005   case CallingConv::X86_StdCall:
3006     return !is64Bit;
3007   case CallingConv::X86_FastCall:
3008     return !is64Bit;
3009   case CallingConv::X86_ThisCall:
3010     return !is64Bit;
3011   case CallingConv::Fast:
3012     return TailCallOpt;
3013   case CallingConv::GHC:
3014     return TailCallOpt;
3015   }
3016 }
3017
3018 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3019 /// specific condition code, returning the condition code and the LHS/RHS of the
3020 /// comparison to make.
3021 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3022                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3023   if (!isFP) {
3024     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3025       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3026         // X > -1   -> X == 0, jump !sign.
3027         RHS = DAG.getConstant(0, RHS.getValueType());
3028         return X86::COND_NS;
3029       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3030         // X < 0   -> X == 0, jump on sign.
3031         return X86::COND_S;
3032       } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3033         // X < 1   -> X <= 0
3034         RHS = DAG.getConstant(0, RHS.getValueType());
3035         return X86::COND_LE;
3036       }
3037     }
3038
3039     switch (SetCCOpcode) {
3040     default: llvm_unreachable("Invalid integer condition!");
3041     case ISD::SETEQ:  return X86::COND_E;
3042     case ISD::SETGT:  return X86::COND_G;
3043     case ISD::SETGE:  return X86::COND_GE;
3044     case ISD::SETLT:  return X86::COND_L;
3045     case ISD::SETLE:  return X86::COND_LE;
3046     case ISD::SETNE:  return X86::COND_NE;
3047     case ISD::SETULT: return X86::COND_B;
3048     case ISD::SETUGT: return X86::COND_A;
3049     case ISD::SETULE: return X86::COND_BE;
3050     case ISD::SETUGE: return X86::COND_AE;
3051     }
3052   }
3053
3054   // First determine if it is required or is profitable to flip the operands.
3055
3056   // If LHS is a foldable load, but RHS is not, flip the condition.
3057   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3058       !ISD::isNON_EXTLoad(RHS.getNode())) {
3059     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3060     std::swap(LHS, RHS);
3061   }
3062
3063   switch (SetCCOpcode) {
3064   default: break;
3065   case ISD::SETOLT:
3066   case ISD::SETOLE:
3067   case ISD::SETUGT:
3068   case ISD::SETUGE:
3069     std::swap(LHS, RHS);
3070     break;
3071   }
3072
3073   // On a floating point condition, the flags are set as follows:
3074   // ZF  PF  CF   op
3075   //  0 | 0 | 0 | X > Y
3076   //  0 | 0 | 1 | X < Y
3077   //  1 | 0 | 0 | X == Y
3078   //  1 | 1 | 1 | unordered
3079   switch (SetCCOpcode) {
3080   default: llvm_unreachable("Condcode should be pre-legalized away");
3081   case ISD::SETUEQ:
3082   case ISD::SETEQ:   return X86::COND_E;
3083   case ISD::SETOLT:              // flipped
3084   case ISD::SETOGT:
3085   case ISD::SETGT:   return X86::COND_A;
3086   case ISD::SETOLE:              // flipped
3087   case ISD::SETOGE:
3088   case ISD::SETGE:   return X86::COND_AE;
3089   case ISD::SETUGT:              // flipped
3090   case ISD::SETULT:
3091   case ISD::SETLT:   return X86::COND_B;
3092   case ISD::SETUGE:              // flipped
3093   case ISD::SETULE:
3094   case ISD::SETLE:   return X86::COND_BE;
3095   case ISD::SETONE:
3096   case ISD::SETNE:   return X86::COND_NE;
3097   case ISD::SETUO:   return X86::COND_P;
3098   case ISD::SETO:    return X86::COND_NP;
3099   case ISD::SETOEQ:
3100   case ISD::SETUNE:  return X86::COND_INVALID;
3101   }
3102 }
3103
3104 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3105 /// code. Current x86 isa includes the following FP cmov instructions:
3106 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3107 static bool hasFPCMov(unsigned X86CC) {
3108   switch (X86CC) {
3109   default:
3110     return false;
3111   case X86::COND_B:
3112   case X86::COND_BE:
3113   case X86::COND_E:
3114   case X86::COND_P:
3115   case X86::COND_A:
3116   case X86::COND_AE:
3117   case X86::COND_NE:
3118   case X86::COND_NP:
3119     return true;
3120   }
3121 }
3122
3123 /// isFPImmLegal - Returns true if the target can instruction select the
3124 /// specified FP immediate natively. If false, the legalizer will
3125 /// materialize the FP immediate as a load from a constant pool.
3126 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3127   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3128     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3129       return true;
3130   }
3131   return false;
3132 }
3133
3134 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3135 /// the specified range (L, H].
3136 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3137   return (Val < 0) || (Val >= Low && Val < Hi);
3138 }
3139
3140 /// isUndefOrInRange - Return true if every element in Mask, begining
3141 /// from position Pos and ending in Pos+Size, falls within the specified
3142 /// range (L, L+Pos]. or is undef.
3143 static bool isUndefOrInRange(const SmallVectorImpl<int> &Mask,
3144                              int Pos, int Size, int Low, int Hi) {
3145   for (int i = Pos, e = Pos+Size; i != e; ++i)
3146     if (!isUndefOrInRange(Mask[i], Low, Hi))
3147       return false;
3148   return true;
3149 }
3150
3151 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3152 /// specified value.
3153 static bool isUndefOrEqual(int Val, int CmpVal) {
3154   if (Val < 0 || Val == CmpVal)
3155     return true;
3156   return false;
3157 }
3158
3159 /// isSequentialOrUndefInRange - Return true if every element in Mask, begining
3160 /// from position Pos and ending in Pos+Size, falls within the specified
3161 /// sequential range (L, L+Pos]. or is undef.
3162 static bool isSequentialOrUndefInRange(const SmallVectorImpl<int> &Mask,
3163                                        int Pos, int Size, int Low) {
3164   for (int i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3165     if (!isUndefOrEqual(Mask[i], Low))
3166       return false;
3167   return true;
3168 }
3169
3170 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3171 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3172 /// the second operand.
3173 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3174   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3175     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3176   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3177     return (Mask[0] < 2 && Mask[1] < 2);
3178   return false;
3179 }
3180
3181 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
3182   SmallVector<int, 8> M;
3183   N->getMask(M);
3184   return ::isPSHUFDMask(M, N->getValueType(0));
3185 }
3186
3187 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3188 /// is suitable for input to PSHUFHW.
3189 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3190   if (VT != MVT::v8i16)
3191     return false;
3192
3193   // Lower quadword copied in order or undef.
3194   for (int i = 0; i != 4; ++i)
3195     if (Mask[i] >= 0 && Mask[i] != i)
3196       return false;
3197
3198   // Upper quadword shuffled.
3199   for (int i = 4; i != 8; ++i)
3200     if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
3201       return false;
3202
3203   return true;
3204 }
3205
3206 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
3207   SmallVector<int, 8> M;
3208   N->getMask(M);
3209   return ::isPSHUFHWMask(M, N->getValueType(0));
3210 }
3211
3212 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3213 /// is suitable for input to PSHUFLW.
3214 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3215   if (VT != MVT::v8i16)
3216     return false;
3217
3218   // Upper quadword copied in order.
3219   for (int i = 4; i != 8; ++i)
3220     if (Mask[i] >= 0 && Mask[i] != i)
3221       return false;
3222
3223   // Lower quadword shuffled.
3224   for (int i = 0; i != 4; ++i)
3225     if (Mask[i] >= 4)
3226       return false;
3227
3228   return true;
3229 }
3230
3231 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
3232   SmallVector<int, 8> M;
3233   N->getMask(M);
3234   return ::isPSHUFLWMask(M, N->getValueType(0));
3235 }
3236
3237 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3238 /// is suitable for input to PALIGNR.
3239 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
3240                           bool hasSSSE3OrAVX) {
3241   int i, e = VT.getVectorNumElements();
3242   if (VT.getSizeInBits() != 128 && VT.getSizeInBits() != 64)
3243     return false;
3244
3245   // Do not handle v2i64 / v2f64 shuffles with palignr.
3246   if (e < 4 || !hasSSSE3OrAVX)
3247     return false;
3248
3249   for (i = 0; i != e; ++i)
3250     if (Mask[i] >= 0)
3251       break;
3252
3253   // All undef, not a palignr.
3254   if (i == e)
3255     return false;
3256
3257   // Make sure we're shifting in the right direction.
3258   if (Mask[i] <= i)
3259     return false;
3260
3261   int s = Mask[i] - i;
3262
3263   // Check the rest of the elements to see if they are consecutive.
3264   for (++i; i != e; ++i) {
3265     int m = Mask[i];
3266     if (m >= 0 && m != s+i)
3267       return false;
3268   }
3269   return true;
3270 }
3271
3272 /// isVSHUFPSYMask - Return true if the specified VECTOR_SHUFFLE operand
3273 /// specifies a shuffle of elements that is suitable for input to 256-bit
3274 /// VSHUFPSY.
3275 static bool isVSHUFPSYMask(const SmallVectorImpl<int> &Mask, EVT VT,
3276                           const X86Subtarget *Subtarget) {
3277   int NumElems = VT.getVectorNumElements();
3278
3279   if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256)
3280     return false;
3281
3282   if (NumElems != 8)
3283     return false;
3284
3285   // VSHUFPSY divides the resulting vector into 4 chunks.
3286   // The sources are also splitted into 4 chunks, and each destination
3287   // chunk must come from a different source chunk.
3288   //
3289   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3290   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3291   //
3292   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3293   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3294   //
3295   int QuarterSize = NumElems/4;
3296   int HalfSize = QuarterSize*2;
3297   for (int i = 0; i < QuarterSize; ++i)
3298     if (!isUndefOrInRange(Mask[i], 0, HalfSize))
3299       return false;
3300   for (int i = QuarterSize; i < QuarterSize*2; ++i)
3301     if (!isUndefOrInRange(Mask[i], NumElems, NumElems+HalfSize))
3302       return false;
3303
3304   // The mask of the second half must be the same as the first but with
3305   // the appropriate offsets. This works in the same way as VPERMILPS
3306   // works with masks.
3307   for (int i = QuarterSize*2; i < QuarterSize*3; ++i) {
3308     if (!isUndefOrInRange(Mask[i], HalfSize, NumElems))
3309       return false;
3310     int FstHalfIdx = i-HalfSize;
3311     if (Mask[FstHalfIdx] < 0)
3312       continue;
3313     if (!isUndefOrEqual(Mask[i], Mask[FstHalfIdx]+HalfSize))
3314       return false;
3315   }
3316   for (int i = QuarterSize*3; i < NumElems; ++i) {
3317     if (!isUndefOrInRange(Mask[i], NumElems+HalfSize, NumElems*2))
3318       return false;
3319     int FstHalfIdx = i-HalfSize;
3320     if (Mask[FstHalfIdx] < 0)
3321       continue;
3322     if (!isUndefOrEqual(Mask[i], Mask[FstHalfIdx]+HalfSize))
3323       return false;
3324
3325   }
3326
3327   return true;
3328 }
3329
3330 /// getShuffleVSHUFPSYImmediate - Return the appropriate immediate to shuffle
3331 /// the specified VECTOR_MASK mask with VSHUFPSY instruction.
3332 static unsigned getShuffleVSHUFPSYImmediate(SDNode *N) {
3333   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3334   EVT VT = SVOp->getValueType(0);
3335   int NumElems = VT.getVectorNumElements();
3336
3337   assert(NumElems == 8 && VT.getSizeInBits() == 256 &&
3338          "Only supports v8i32 and v8f32 types");
3339
3340   int HalfSize = NumElems/2;
3341   unsigned Mask = 0;
3342   for (int i = 0; i != NumElems ; ++i) {
3343     if (SVOp->getMaskElt(i) < 0)
3344       continue;
3345     // The mask of the first half must be equal to the second one.
3346     unsigned Shamt = (i%HalfSize)*2;
3347     unsigned Elt = SVOp->getMaskElt(i) % HalfSize;
3348     Mask |= Elt << Shamt;
3349   }
3350
3351   return Mask;
3352 }
3353
3354 /// isVSHUFPDYMask - Return true if the specified VECTOR_SHUFFLE operand
3355 /// specifies a shuffle of elements that is suitable for input to 256-bit
3356 /// VSHUFPDY. This shuffle doesn't have the same restriction as the PS
3357 /// version and the mask of the second half isn't binded with the first
3358 /// one.
3359 static bool isVSHUFPDYMask(const SmallVectorImpl<int> &Mask, EVT VT,
3360                            const X86Subtarget *Subtarget) {
3361   int NumElems = VT.getVectorNumElements();
3362
3363   if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256)
3364     return false;
3365
3366   if (NumElems != 4)
3367     return false;
3368
3369   // VSHUFPSY divides the resulting vector into 4 chunks.
3370   // The sources are also splitted into 4 chunks, and each destination
3371   // chunk must come from a different source chunk.
3372   //
3373   //  SRC1 =>      X3       X2       X1       X0
3374   //  SRC2 =>      Y3       Y2       Y1       Y0
3375   //
3376   //  DST  =>  Y2..Y3,  X2..X3,  Y1..Y0,  X1..X0
3377   //
3378   int QuarterSize = NumElems/4;
3379   int HalfSize = QuarterSize*2;
3380   for (int i = 0; i < QuarterSize; ++i)
3381     if (!isUndefOrInRange(Mask[i], 0, HalfSize))
3382       return false;
3383   for (int i = QuarterSize; i < QuarterSize*2; ++i)
3384     if (!isUndefOrInRange(Mask[i], NumElems, NumElems+HalfSize))
3385       return false;
3386   for (int i = QuarterSize*2; i < QuarterSize*3; ++i)
3387     if (!isUndefOrInRange(Mask[i], HalfSize, NumElems))
3388       return false;
3389   for (int i = QuarterSize*3; i < NumElems; ++i)
3390     if (!isUndefOrInRange(Mask[i], NumElems+HalfSize, NumElems*2))
3391       return false;
3392
3393   return true;
3394 }
3395
3396 /// getShuffleVSHUFPDYImmediate - Return the appropriate immediate to shuffle
3397 /// the specified VECTOR_MASK mask with VSHUFPDY instruction.
3398 static unsigned getShuffleVSHUFPDYImmediate(SDNode *N) {
3399   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3400   EVT VT = SVOp->getValueType(0);
3401   int NumElems = VT.getVectorNumElements();
3402
3403   assert(NumElems == 4 && VT.getSizeInBits() == 256 &&
3404          "Only supports v4i64 and v4f64 types");
3405
3406   int HalfSize = NumElems/2;
3407   unsigned Mask = 0;
3408   for (int i = 0; i != NumElems ; ++i) {
3409     if (SVOp->getMaskElt(i) < 0)
3410       continue;
3411     int Elt = SVOp->getMaskElt(i) % HalfSize;
3412     Mask |= Elt << i;
3413   }
3414
3415   return Mask;
3416 }
3417
3418 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3419 /// specifies a shuffle of elements that is suitable for input to 128-bit
3420 /// SHUFPS and SHUFPD.
3421 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3422   int NumElems = VT.getVectorNumElements();
3423
3424   if (VT.getSizeInBits() != 128)
3425     return false;
3426
3427   if (NumElems != 2 && NumElems != 4)
3428     return false;
3429
3430   int Half = NumElems / 2;
3431   for (int i = 0; i < Half; ++i)
3432     if (!isUndefOrInRange(Mask[i], 0, NumElems))
3433       return false;
3434   for (int i = Half; i < NumElems; ++i)
3435     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3436       return false;
3437
3438   return true;
3439 }
3440
3441 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
3442   SmallVector<int, 8> M;
3443   N->getMask(M);
3444   return ::isSHUFPMask(M, N->getValueType(0));
3445 }
3446
3447 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
3448 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
3449 /// half elements to come from vector 1 (which would equal the dest.) and
3450 /// the upper half to come from vector 2.
3451 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3452   int NumElems = VT.getVectorNumElements();
3453
3454   if (NumElems != 2 && NumElems != 4)
3455     return false;
3456
3457   int Half = NumElems / 2;
3458   for (int i = 0; i < Half; ++i)
3459     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3460       return false;
3461   for (int i = Half; i < NumElems; ++i)
3462     if (!isUndefOrInRange(Mask[i], 0, NumElems))
3463       return false;
3464   return true;
3465 }
3466
3467 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
3468   SmallVector<int, 8> M;
3469   N->getMask(M);
3470   return isCommutedSHUFPMask(M, N->getValueType(0));
3471 }
3472
3473 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3474 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3475 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3476   EVT VT = N->getValueType(0);
3477   unsigned NumElems = VT.getVectorNumElements();
3478
3479   if (VT.getSizeInBits() != 128)
3480     return false;
3481
3482   if (NumElems != 4)
3483     return false;
3484
3485   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3486   return isUndefOrEqual(N->getMaskElt(0), 6) &&
3487          isUndefOrEqual(N->getMaskElt(1), 7) &&
3488          isUndefOrEqual(N->getMaskElt(2), 2) &&
3489          isUndefOrEqual(N->getMaskElt(3), 3);
3490 }
3491
3492 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3493 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3494 /// <2, 3, 2, 3>
3495 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3496   EVT VT = N->getValueType(0);
3497   unsigned NumElems = VT.getVectorNumElements();
3498
3499   if (VT.getSizeInBits() != 128)
3500     return false;
3501
3502   if (NumElems != 4)
3503     return false;
3504
3505   return isUndefOrEqual(N->getMaskElt(0), 2) &&
3506          isUndefOrEqual(N->getMaskElt(1), 3) &&
3507          isUndefOrEqual(N->getMaskElt(2), 2) &&
3508          isUndefOrEqual(N->getMaskElt(3), 3);
3509 }
3510
3511 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3512 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3513 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3514   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3515
3516   if (NumElems != 2 && NumElems != 4)
3517     return false;
3518
3519   for (unsigned i = 0; i < NumElems/2; ++i)
3520     if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3521       return false;
3522
3523   for (unsigned i = NumElems/2; i < NumElems; ++i)
3524     if (!isUndefOrEqual(N->getMaskElt(i), i))
3525       return false;
3526
3527   return true;
3528 }
3529
3530 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3531 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3532 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3533   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3534
3535   if ((NumElems != 2 && NumElems != 4)
3536       || N->getValueType(0).getSizeInBits() > 128)
3537     return false;
3538
3539   for (unsigned i = 0; i < NumElems/2; ++i)
3540     if (!isUndefOrEqual(N->getMaskElt(i), i))
3541       return false;
3542
3543   for (unsigned i = 0; i < NumElems/2; ++i)
3544     if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3545       return false;
3546
3547   return true;
3548 }
3549
3550 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3551 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3552 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3553                          bool V2IsSplat = false) {
3554   int NumElts = VT.getVectorNumElements();
3555
3556   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3557          "Unsupported vector type for unpckh");
3558
3559   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8)
3560     return false;
3561
3562   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3563   // independently on 128-bit lanes.
3564   unsigned NumLanes = VT.getSizeInBits()/128;
3565   unsigned NumLaneElts = NumElts/NumLanes;
3566
3567   unsigned Start = 0;
3568   unsigned End = NumLaneElts;
3569   for (unsigned s = 0; s < NumLanes; ++s) {
3570     for (unsigned i = Start, j = s * NumLaneElts;
3571          i != End;
3572          i += 2, ++j) {
3573       int BitI  = Mask[i];
3574       int BitI1 = Mask[i+1];
3575       if (!isUndefOrEqual(BitI, j))
3576         return false;
3577       if (V2IsSplat) {
3578         if (!isUndefOrEqual(BitI1, NumElts))
3579           return false;
3580       } else {
3581         if (!isUndefOrEqual(BitI1, j + NumElts))
3582           return false;
3583       }
3584     }
3585     // Process the next 128 bits.
3586     Start += NumLaneElts;
3587     End += NumLaneElts;
3588   }
3589
3590   return true;
3591 }
3592
3593 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3594   SmallVector<int, 8> M;
3595   N->getMask(M);
3596   return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
3597 }
3598
3599 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3600 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3601 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3602                          bool V2IsSplat = false) {
3603   int NumElts = VT.getVectorNumElements();
3604
3605   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3606          "Unsupported vector type for unpckh");
3607
3608   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8)
3609     return false;
3610
3611   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3612   // independently on 128-bit lanes.
3613   unsigned NumLanes = VT.getSizeInBits()/128;
3614   unsigned NumLaneElts = NumElts/NumLanes;
3615
3616   unsigned Start = 0;
3617   unsigned End = NumLaneElts;
3618   for (unsigned l = 0; l != NumLanes; ++l) {
3619     for (unsigned i = Start, j = (l*NumLaneElts)+NumLaneElts/2;
3620                              i != End; i += 2, ++j) {
3621       int BitI  = Mask[i];
3622       int BitI1 = Mask[i+1];
3623       if (!isUndefOrEqual(BitI, j))
3624         return false;
3625       if (V2IsSplat) {
3626         if (isUndefOrEqual(BitI1, NumElts))
3627           return false;
3628       } else {
3629         if (!isUndefOrEqual(BitI1, j+NumElts))
3630           return false;
3631       }
3632     }
3633     // Process the next 128 bits.
3634     Start += NumLaneElts;
3635     End += NumLaneElts;
3636   }
3637   return true;
3638 }
3639
3640 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3641   SmallVector<int, 8> M;
3642   N->getMask(M);
3643   return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
3644 }
3645
3646 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3647 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3648 /// <0, 0, 1, 1>
3649 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3650   int NumElems = VT.getVectorNumElements();
3651   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3652     return false;
3653
3654   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3655   // FIXME: Need a better way to get rid of this, there's no latency difference
3656   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3657   // the former later. We should also remove the "_undef" special mask.
3658   if (NumElems == 4 && VT.getSizeInBits() == 256)
3659     return false;
3660
3661   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3662   // independently on 128-bit lanes.
3663   unsigned NumLanes = VT.getSizeInBits() / 128;
3664   unsigned NumLaneElts = NumElems / NumLanes;
3665
3666   for (unsigned s = 0; s < NumLanes; ++s) {
3667     for (unsigned i = s * NumLaneElts, j = s * NumLaneElts;
3668          i != NumLaneElts * (s + 1);
3669          i += 2, ++j) {
3670       int BitI  = Mask[i];
3671       int BitI1 = Mask[i+1];
3672
3673       if (!isUndefOrEqual(BitI, j))
3674         return false;
3675       if (!isUndefOrEqual(BitI1, j))
3676         return false;
3677     }
3678   }
3679
3680   return true;
3681 }
3682
3683 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3684   SmallVector<int, 8> M;
3685   N->getMask(M);
3686   return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3687 }
3688
3689 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3690 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3691 /// <2, 2, 3, 3>
3692 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3693   int NumElems = VT.getVectorNumElements();
3694   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3695     return false;
3696
3697   for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3698     int BitI  = Mask[i];
3699     int BitI1 = Mask[i+1];
3700     if (!isUndefOrEqual(BitI, j))
3701       return false;
3702     if (!isUndefOrEqual(BitI1, j))
3703       return false;
3704   }
3705   return true;
3706 }
3707
3708 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3709   SmallVector<int, 8> M;
3710   N->getMask(M);
3711   return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3712 }
3713
3714 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3715 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3716 /// MOVSD, and MOVD, i.e. setting the lowest element.
3717 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3718   if (VT.getVectorElementType().getSizeInBits() < 32)
3719     return false;
3720
3721   int NumElts = VT.getVectorNumElements();
3722
3723   if (!isUndefOrEqual(Mask[0], NumElts))
3724     return false;
3725
3726   for (int i = 1; i < NumElts; ++i)
3727     if (!isUndefOrEqual(Mask[i], i))
3728       return false;
3729
3730   return true;
3731 }
3732
3733 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3734   SmallVector<int, 8> M;
3735   N->getMask(M);
3736   return ::isMOVLMask(M, N->getValueType(0));
3737 }
3738
3739 /// isVPERM2F128Mask - Match 256-bit shuffles where the elements are considered
3740 /// as permutations between 128-bit chunks or halves. As an example: this
3741 /// shuffle bellow:
3742 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3743 /// The first half comes from the second half of V1 and the second half from the
3744 /// the second half of V2.
3745 static bool isVPERM2F128Mask(const SmallVectorImpl<int> &Mask, EVT VT,
3746                              const X86Subtarget *Subtarget) {
3747   if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256)
3748     return false;
3749
3750   // The shuffle result is divided into half A and half B. In total the two
3751   // sources have 4 halves, namely: C, D, E, F. The final values of A and
3752   // B must come from C, D, E or F.
3753   int HalfSize = VT.getVectorNumElements()/2;
3754   bool MatchA = false, MatchB = false;
3755
3756   // Check if A comes from one of C, D, E, F.
3757   for (int Half = 0; Half < 4; ++Half) {
3758     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3759       MatchA = true;
3760       break;
3761     }
3762   }
3763
3764   // Check if B comes from one of C, D, E, F.
3765   for (int Half = 0; Half < 4; ++Half) {
3766     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3767       MatchB = true;
3768       break;
3769     }
3770   }
3771
3772   return MatchA && MatchB;
3773 }
3774
3775 /// getShuffleVPERM2F128Immediate - Return the appropriate immediate to shuffle
3776 /// the specified VECTOR_MASK mask with VPERM2F128 instructions.
3777 static unsigned getShuffleVPERM2F128Immediate(SDNode *N) {
3778   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3779   EVT VT = SVOp->getValueType(0);
3780
3781   int HalfSize = VT.getVectorNumElements()/2;
3782
3783   int FstHalf = 0, SndHalf = 0;
3784   for (int i = 0; i < HalfSize; ++i) {
3785     if (SVOp->getMaskElt(i) > 0) {
3786       FstHalf = SVOp->getMaskElt(i)/HalfSize;
3787       break;
3788     }
3789   }
3790   for (int i = HalfSize; i < HalfSize*2; ++i) {
3791     if (SVOp->getMaskElt(i) > 0) {
3792       SndHalf = SVOp->getMaskElt(i)/HalfSize;
3793       break;
3794     }
3795   }
3796
3797   return (FstHalf | (SndHalf << 4));
3798 }
3799
3800 /// isVPERMILPDMask - Return true if the specified VECTOR_SHUFFLE operand
3801 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3802 /// Note that VPERMIL mask matching is different depending whether theunderlying
3803 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3804 /// to the same elements of the low, but to the higher half of the source.
3805 /// In VPERMILPD the two lanes could be shuffled independently of each other
3806 /// with the same restriction that lanes can't be crossed.
3807 static bool isVPERMILPDMask(const SmallVectorImpl<int> &Mask, EVT VT,
3808                             const X86Subtarget *Subtarget) {
3809   int NumElts = VT.getVectorNumElements();
3810   int NumLanes = VT.getSizeInBits()/128;
3811
3812   if (!Subtarget->hasAVX())
3813     return false;
3814
3815   // Only match 256-bit with 64-bit types
3816   if (VT.getSizeInBits() != 256 || NumElts != 4)
3817     return false;
3818
3819   // The mask on the high lane is independent of the low. Both can match
3820   // any element in inside its own lane, but can't cross.
3821   int LaneSize = NumElts/NumLanes;
3822   for (int l = 0; l < NumLanes; ++l)
3823     for (int i = l*LaneSize; i < LaneSize*(l+1); ++i) {
3824       int LaneStart = l*LaneSize;
3825       if (!isUndefOrInRange(Mask[i], LaneStart, LaneStart+LaneSize))
3826         return false;
3827     }
3828
3829   return true;
3830 }
3831
3832 /// isVPERMILPSMask - Return true if the specified VECTOR_SHUFFLE operand
3833 /// specifies a shuffle of elements that is suitable for input to VPERMILPS*.
3834 /// Note that VPERMIL mask matching is different depending whether theunderlying
3835 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3836 /// to the same elements of the low, but to the higher half of the source.
3837 /// In VPERMILPD the two lanes could be shuffled independently of each other
3838 /// with the same restriction that lanes can't be crossed.
3839 static bool isVPERMILPSMask(const SmallVectorImpl<int> &Mask, EVT VT,
3840                             const X86Subtarget *Subtarget) {
3841   unsigned NumElts = VT.getVectorNumElements();
3842   unsigned NumLanes = VT.getSizeInBits()/128;
3843
3844   if (!Subtarget->hasAVX())
3845     return false;
3846
3847   // Only match 256-bit with 32-bit types
3848   if (VT.getSizeInBits() != 256 || NumElts != 8)
3849     return false;
3850
3851   // The mask on the high lane should be the same as the low. Actually,
3852   // they can differ if any of the corresponding index in a lane is undef
3853   // and the other stays in range.
3854   int LaneSize = NumElts/NumLanes;
3855   for (int i = 0; i < LaneSize; ++i) {
3856     int HighElt = i+LaneSize;
3857     bool HighValid = isUndefOrInRange(Mask[HighElt], LaneSize, NumElts);
3858     bool LowValid = isUndefOrInRange(Mask[i], 0, LaneSize);
3859
3860     if (!HighValid || !LowValid)
3861       return false;
3862     if (Mask[i] < 0 || Mask[HighElt] < 0)
3863       continue;
3864     if (Mask[HighElt]-Mask[i] != LaneSize)
3865       return false;
3866   }
3867
3868   return true;
3869 }
3870
3871 /// getShuffleVPERMILPSImmediate - Return the appropriate immediate to shuffle
3872 /// the specified VECTOR_MASK mask with VPERMILPS* instructions.
3873 static unsigned getShuffleVPERMILPSImmediate(SDNode *N) {
3874   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3875   EVT VT = SVOp->getValueType(0);
3876
3877   int NumElts = VT.getVectorNumElements();
3878   int NumLanes = VT.getSizeInBits()/128;
3879   int LaneSize = NumElts/NumLanes;
3880
3881   // Although the mask is equal for both lanes do it twice to get the cases
3882   // where a mask will match because the same mask element is undef on the
3883   // first half but valid on the second. This would get pathological cases
3884   // such as: shuffle <u, 0, 1, 2, 4, 4, 5, 6>, which is completely valid.
3885   unsigned Mask = 0;
3886   for (int l = 0; l < NumLanes; ++l) {
3887     for (int i = 0; i < LaneSize; ++i) {
3888       int MaskElt = SVOp->getMaskElt(i+(l*LaneSize));
3889       if (MaskElt < 0)
3890         continue;
3891       if (MaskElt >= LaneSize)
3892         MaskElt -= LaneSize;
3893       Mask |= MaskElt << (i*2);
3894     }
3895   }
3896
3897   return Mask;
3898 }
3899
3900 /// getShuffleVPERMILPDImmediate - Return the appropriate immediate to shuffle
3901 /// the specified VECTOR_MASK mask with VPERMILPD* instructions.
3902 static unsigned getShuffleVPERMILPDImmediate(SDNode *N) {
3903   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3904   EVT VT = SVOp->getValueType(0);
3905
3906   int NumElts = VT.getVectorNumElements();
3907   int NumLanes = VT.getSizeInBits()/128;
3908
3909   unsigned Mask = 0;
3910   int LaneSize = NumElts/NumLanes;
3911   for (int l = 0; l < NumLanes; ++l)
3912     for (int i = l*LaneSize; i < LaneSize*(l+1); ++i) {
3913       int MaskElt = SVOp->getMaskElt(i);
3914       if (MaskElt < 0)
3915         continue;
3916       Mask |= (MaskElt-l*LaneSize) << i;
3917     }
3918
3919   return Mask;
3920 }
3921
3922 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3923 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3924 /// element of vector 2 and the other elements to come from vector 1 in order.
3925 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3926                                bool V2IsSplat = false, bool V2IsUndef = false) {
3927   int NumOps = VT.getVectorNumElements();
3928   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3929     return false;
3930
3931   if (!isUndefOrEqual(Mask[0], 0))
3932     return false;
3933
3934   for (int i = 1; i < NumOps; ++i)
3935     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3936           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3937           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3938       return false;
3939
3940   return true;
3941 }
3942
3943 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3944                            bool V2IsUndef = false) {
3945   SmallVector<int, 8> M;
3946   N->getMask(M);
3947   return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3948 }
3949
3950 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3951 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3952 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3953 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N,
3954                          const X86Subtarget *Subtarget) {
3955   if (!Subtarget->hasSSE3() && !Subtarget->hasAVX())
3956     return false;
3957
3958   // The second vector must be undef
3959   if (N->getOperand(1).getOpcode() != ISD::UNDEF)
3960     return false;
3961
3962   EVT VT = N->getValueType(0);
3963   unsigned NumElems = VT.getVectorNumElements();
3964
3965   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3966       (VT.getSizeInBits() == 256 && NumElems != 8))
3967     return false;
3968
3969   // "i+1" is the value the indexed mask element must have
3970   for (unsigned i = 0; i < NumElems; i += 2)
3971     if (!isUndefOrEqual(N->getMaskElt(i), i+1) ||
3972         !isUndefOrEqual(N->getMaskElt(i+1), i+1))
3973       return false;
3974
3975   return true;
3976 }
3977
3978 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3979 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3980 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3981 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N,
3982                          const X86Subtarget *Subtarget) {
3983   if (!Subtarget->hasSSE3() && !Subtarget->hasAVX())
3984     return false;
3985
3986   // The second vector must be undef
3987   if (N->getOperand(1).getOpcode() != ISD::UNDEF)
3988     return false;
3989
3990   EVT VT = N->getValueType(0);
3991   unsigned NumElems = VT.getVectorNumElements();
3992
3993   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3994       (VT.getSizeInBits() == 256 && NumElems != 8))
3995     return false;
3996
3997   // "i" is the value the indexed mask element must have
3998   for (unsigned i = 0; i < NumElems; i += 2)
3999     if (!isUndefOrEqual(N->getMaskElt(i), i) ||
4000         !isUndefOrEqual(N->getMaskElt(i+1), i))
4001       return false;
4002
4003   return true;
4004 }
4005
4006 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4007 /// specifies a shuffle of elements that is suitable for input to 256-bit
4008 /// version of MOVDDUP.
4009 static bool isMOVDDUPYMask(ShuffleVectorSDNode *N,
4010                            const X86Subtarget *Subtarget) {
4011   EVT VT = N->getValueType(0);
4012   int NumElts = VT.getVectorNumElements();
4013   bool V2IsUndef = N->getOperand(1).getOpcode() == ISD::UNDEF;
4014
4015   if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256 ||
4016       !V2IsUndef || NumElts != 4)
4017     return false;
4018
4019   for (int i = 0; i != NumElts/2; ++i)
4020     if (!isUndefOrEqual(N->getMaskElt(i), 0))
4021       return false;
4022   for (int i = NumElts/2; i != NumElts; ++i)
4023     if (!isUndefOrEqual(N->getMaskElt(i), NumElts/2))
4024       return false;
4025   return true;
4026 }
4027
4028 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4029 /// specifies a shuffle of elements that is suitable for input to 128-bit
4030 /// version of MOVDDUP.
4031 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
4032   EVT VT = N->getValueType(0);
4033
4034   if (VT.getSizeInBits() != 128)
4035     return false;
4036
4037   int e = VT.getVectorNumElements() / 2;
4038   for (int i = 0; i < e; ++i)
4039     if (!isUndefOrEqual(N->getMaskElt(i), i))
4040       return false;
4041   for (int i = 0; i < e; ++i)
4042     if (!isUndefOrEqual(N->getMaskElt(e+i), i))
4043       return false;
4044   return true;
4045 }
4046
4047 /// isVEXTRACTF128Index - Return true if the specified
4048 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4049 /// suitable for input to VEXTRACTF128.
4050 bool X86::isVEXTRACTF128Index(SDNode *N) {
4051   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4052     return false;
4053
4054   // The index should be aligned on a 128-bit boundary.
4055   uint64_t Index =
4056     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4057
4058   unsigned VL = N->getValueType(0).getVectorNumElements();
4059   unsigned VBits = N->getValueType(0).getSizeInBits();
4060   unsigned ElSize = VBits / VL;
4061   bool Result = (Index * ElSize) % 128 == 0;
4062
4063   return Result;
4064 }
4065
4066 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
4067 /// operand specifies a subvector insert that is suitable for input to
4068 /// VINSERTF128.
4069 bool X86::isVINSERTF128Index(SDNode *N) {
4070   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4071     return false;
4072
4073   // The index should be aligned on a 128-bit boundary.
4074   uint64_t Index =
4075     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4076
4077   unsigned VL = N->getValueType(0).getVectorNumElements();
4078   unsigned VBits = N->getValueType(0).getSizeInBits();
4079   unsigned ElSize = VBits / VL;
4080   bool Result = (Index * ElSize) % 128 == 0;
4081
4082   return Result;
4083 }
4084
4085 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4086 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4087 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
4088   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4089   int NumOperands = SVOp->getValueType(0).getVectorNumElements();
4090
4091   unsigned Shift = (NumOperands == 4) ? 2 : 1;
4092   unsigned Mask = 0;
4093   for (int i = 0; i < NumOperands; ++i) {
4094     int Val = SVOp->getMaskElt(NumOperands-i-1);
4095     if (Val < 0) Val = 0;
4096     if (Val >= NumOperands) Val -= NumOperands;
4097     Mask |= Val;
4098     if (i != NumOperands - 1)
4099       Mask <<= Shift;
4100   }
4101   return Mask;
4102 }
4103
4104 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4105 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4106 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
4107   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4108   unsigned Mask = 0;
4109   // 8 nodes, but we only care about the last 4.
4110   for (unsigned i = 7; i >= 4; --i) {
4111     int Val = SVOp->getMaskElt(i);
4112     if (Val >= 0)
4113       Mask |= (Val - 4);
4114     if (i != 4)
4115       Mask <<= 2;
4116   }
4117   return Mask;
4118 }
4119
4120 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4121 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4122 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
4123   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4124   unsigned Mask = 0;
4125   // 8 nodes, but we only care about the first 4.
4126   for (int i = 3; i >= 0; --i) {
4127     int Val = SVOp->getMaskElt(i);
4128     if (Val >= 0)
4129       Mask |= Val;
4130     if (i != 0)
4131       Mask <<= 2;
4132   }
4133   return Mask;
4134 }
4135
4136 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4137 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4138 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
4139   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4140   EVT VVT = N->getValueType(0);
4141   unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
4142   int Val = 0;
4143
4144   unsigned i, e;
4145   for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
4146     Val = SVOp->getMaskElt(i);
4147     if (Val >= 0)
4148       break;
4149   }
4150   assert(Val - i > 0 && "PALIGNR imm should be positive");
4151   return (Val - i) * EltSize;
4152 }
4153
4154 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4155 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4156 /// instructions.
4157 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4158   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4159     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4160
4161   uint64_t Index =
4162     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4163
4164   EVT VecVT = N->getOperand(0).getValueType();
4165   EVT ElVT = VecVT.getVectorElementType();
4166
4167   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4168   return Index / NumElemsPerChunk;
4169 }
4170
4171 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4172 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4173 /// instructions.
4174 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4175   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4176     llvm_unreachable("Illegal insert subvector for VINSERTF128");
4177
4178   uint64_t Index =
4179     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4180
4181   EVT VecVT = N->getValueType(0);
4182   EVT ElVT = VecVT.getVectorElementType();
4183
4184   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4185   return Index / NumElemsPerChunk;
4186 }
4187
4188 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4189 /// constant +0.0.
4190 bool X86::isZeroNode(SDValue Elt) {
4191   return ((isa<ConstantSDNode>(Elt) &&
4192            cast<ConstantSDNode>(Elt)->isNullValue()) ||
4193           (isa<ConstantFPSDNode>(Elt) &&
4194            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4195 }
4196
4197 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4198 /// their permute mask.
4199 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4200                                     SelectionDAG &DAG) {
4201   EVT VT = SVOp->getValueType(0);
4202   unsigned NumElems = VT.getVectorNumElements();
4203   SmallVector<int, 8> MaskVec;
4204
4205   for (unsigned i = 0; i != NumElems; ++i) {
4206     int idx = SVOp->getMaskElt(i);
4207     if (idx < 0)
4208       MaskVec.push_back(idx);
4209     else if (idx < (int)NumElems)
4210       MaskVec.push_back(idx + NumElems);
4211     else
4212       MaskVec.push_back(idx - NumElems);
4213   }
4214   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4215                               SVOp->getOperand(0), &MaskVec[0]);
4216 }
4217
4218 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
4219 /// the two vector operands have swapped position.
4220 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
4221   unsigned NumElems = VT.getVectorNumElements();
4222   for (unsigned i = 0; i != NumElems; ++i) {
4223     int idx = Mask[i];
4224     if (idx < 0)
4225       continue;
4226     else if (idx < (int)NumElems)
4227       Mask[i] = idx + NumElems;
4228     else
4229       Mask[i] = idx - NumElems;
4230   }
4231 }
4232
4233 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4234 /// match movhlps. The lower half elements should come from upper half of
4235 /// V1 (and in order), and the upper half elements should come from the upper
4236 /// half of V2 (and in order).
4237 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
4238   EVT VT = Op->getValueType(0);
4239   if (VT.getSizeInBits() != 128)
4240     return false;
4241   if (VT.getVectorNumElements() != 4)
4242     return false;
4243   for (unsigned i = 0, e = 2; i != e; ++i)
4244     if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
4245       return false;
4246   for (unsigned i = 2; i != 4; ++i)
4247     if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
4248       return false;
4249   return true;
4250 }
4251
4252 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4253 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4254 /// required.
4255 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4256   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4257     return false;
4258   N = N->getOperand(0).getNode();
4259   if (!ISD::isNON_EXTLoad(N))
4260     return false;
4261   if (LD)
4262     *LD = cast<LoadSDNode>(N);
4263   return true;
4264 }
4265
4266 // Test whether the given value is a vector value which will be legalized
4267 // into a load.
4268 static bool WillBeConstantPoolLoad(SDNode *N) {
4269   if (N->getOpcode() != ISD::BUILD_VECTOR)
4270     return false;
4271
4272   // Check for any non-constant elements.
4273   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4274     switch (N->getOperand(i).getNode()->getOpcode()) {
4275     case ISD::UNDEF:
4276     case ISD::ConstantFP:
4277     case ISD::Constant:
4278       break;
4279     default:
4280       return false;
4281     }
4282
4283   // Vectors of all-zeros and all-ones are materialized with special
4284   // instructions rather than being loaded.
4285   return !ISD::isBuildVectorAllZeros(N) &&
4286          !ISD::isBuildVectorAllOnes(N);
4287 }
4288
4289 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4290 /// match movlp{s|d}. The lower half elements should come from lower half of
4291 /// V1 (and in order), and the upper half elements should come from the upper
4292 /// half of V2 (and in order). And since V1 will become the source of the
4293 /// MOVLP, it must be either a vector load or a scalar load to vector.
4294 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4295                                ShuffleVectorSDNode *Op) {
4296   EVT VT = Op->getValueType(0);
4297   if (VT.getSizeInBits() != 128)
4298     return false;
4299
4300   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4301     return false;
4302   // Is V2 is a vector load, don't do this transformation. We will try to use
4303   // load folding shufps op.
4304   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4305     return false;
4306
4307   unsigned NumElems = VT.getVectorNumElements();
4308
4309   if (NumElems != 2 && NumElems != 4)
4310     return false;
4311   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4312     if (!isUndefOrEqual(Op->getMaskElt(i), i))
4313       return false;
4314   for (unsigned i = NumElems/2; i != NumElems; ++i)
4315     if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
4316       return false;
4317   return true;
4318 }
4319
4320 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4321 /// all the same.
4322 static bool isSplatVector(SDNode *N) {
4323   if (N->getOpcode() != ISD::BUILD_VECTOR)
4324     return false;
4325
4326   SDValue SplatValue = N->getOperand(0);
4327   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4328     if (N->getOperand(i) != SplatValue)
4329       return false;
4330   return true;
4331 }
4332
4333 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4334 /// to an zero vector.
4335 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4336 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4337   SDValue V1 = N->getOperand(0);
4338   SDValue V2 = N->getOperand(1);
4339   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4340   for (unsigned i = 0; i != NumElems; ++i) {
4341     int Idx = N->getMaskElt(i);
4342     if (Idx >= (int)NumElems) {
4343       unsigned Opc = V2.getOpcode();
4344       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4345         continue;
4346       if (Opc != ISD::BUILD_VECTOR ||
4347           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4348         return false;
4349     } else if (Idx >= 0) {
4350       unsigned Opc = V1.getOpcode();
4351       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4352         continue;
4353       if (Opc != ISD::BUILD_VECTOR ||
4354           !X86::isZeroNode(V1.getOperand(Idx)))
4355         return false;
4356     }
4357   }
4358   return true;
4359 }
4360
4361 /// getZeroVector - Returns a vector of specified type with all zero elements.
4362 ///
4363 static SDValue getZeroVector(EVT VT, bool HasXMMInt, SelectionDAG &DAG,
4364                              DebugLoc dl) {
4365   assert(VT.isVector() && "Expected a vector type");
4366
4367   // Always build SSE zero vectors as <4 x i32> bitcasted
4368   // to their dest type. This ensures they get CSE'd.
4369   SDValue Vec;
4370   if (VT.getSizeInBits() == 128) {  // SSE
4371     if (HasXMMInt) {  // SSE2
4372       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4373       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4374     } else { // SSE1
4375       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4376       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4377     }
4378   } else if (VT.getSizeInBits() == 256) { // AVX
4379     // 256-bit logic and arithmetic instructions in AVX are
4380     // all floating-point, no support for integer ops. Default
4381     // to emitting fp zeroed vectors then.
4382     SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4383     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4384     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4385   }
4386   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4387 }
4388
4389 /// getOnesVector - Returns a vector of specified type with all bits set.
4390 /// Always build ones vectors as <4 x i32>. For 256-bit types, use two
4391 /// <4 x i32> inserted in a <8 x i32> appropriately. Then bitcast to their
4392 /// original type, ensuring they get CSE'd.
4393 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
4394   assert(VT.isVector() && "Expected a vector type");
4395   assert((VT.is128BitVector() || VT.is256BitVector())
4396          && "Expected a 128-bit or 256-bit vector type");
4397
4398   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4399   SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
4400                             Cst, Cst, Cst, Cst);
4401
4402   if (VT.is256BitVector()) {
4403     SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, MVT::v8i32),
4404                               Vec, DAG.getConstant(0, MVT::i32), DAG, dl);
4405     Vec = Insert128BitVector(InsV, Vec,
4406                   DAG.getConstant(4 /* NumElems/2 */, MVT::i32), DAG, dl);
4407   }
4408
4409   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4410 }
4411
4412 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4413 /// that point to V2 points to its first element.
4414 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4415   EVT VT = SVOp->getValueType(0);
4416   unsigned NumElems = VT.getVectorNumElements();
4417
4418   bool Changed = false;
4419   SmallVector<int, 8> MaskVec;
4420   SVOp->getMask(MaskVec);
4421
4422   for (unsigned i = 0; i != NumElems; ++i) {
4423     if (MaskVec[i] > (int)NumElems) {
4424       MaskVec[i] = NumElems;
4425       Changed = true;
4426     }
4427   }
4428   if (Changed)
4429     return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
4430                                 SVOp->getOperand(1), &MaskVec[0]);
4431   return SDValue(SVOp, 0);
4432 }
4433
4434 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4435 /// operation of specified width.
4436 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4437                        SDValue V2) {
4438   unsigned NumElems = VT.getVectorNumElements();
4439   SmallVector<int, 8> Mask;
4440   Mask.push_back(NumElems);
4441   for (unsigned i = 1; i != NumElems; ++i)
4442     Mask.push_back(i);
4443   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4444 }
4445
4446 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4447 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4448                           SDValue V2) {
4449   unsigned NumElems = VT.getVectorNumElements();
4450   SmallVector<int, 8> Mask;
4451   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4452     Mask.push_back(i);
4453     Mask.push_back(i + NumElems);
4454   }
4455   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4456 }
4457
4458 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4459 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4460                           SDValue V2) {
4461   unsigned NumElems = VT.getVectorNumElements();
4462   unsigned Half = NumElems/2;
4463   SmallVector<int, 8> Mask;
4464   for (unsigned i = 0; i != Half; ++i) {
4465     Mask.push_back(i + Half);
4466     Mask.push_back(i + NumElems + Half);
4467   }
4468   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4469 }
4470
4471 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4472 // a generic shuffle instruction because the target has no such instructions.
4473 // Generate shuffles which repeat i16 and i8 several times until they can be
4474 // represented by v4f32 and then be manipulated by target suported shuffles.
4475 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4476   EVT VT = V.getValueType();
4477   int NumElems = VT.getVectorNumElements();
4478   DebugLoc dl = V.getDebugLoc();
4479
4480   while (NumElems > 4) {
4481     if (EltNo < NumElems/2) {
4482       V = getUnpackl(DAG, dl, VT, V, V);
4483     } else {
4484       V = getUnpackh(DAG, dl, VT, V, V);
4485       EltNo -= NumElems/2;
4486     }
4487     NumElems >>= 1;
4488   }
4489   return V;
4490 }
4491
4492 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4493 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4494   EVT VT = V.getValueType();
4495   DebugLoc dl = V.getDebugLoc();
4496   assert((VT.getSizeInBits() == 128 || VT.getSizeInBits() == 256)
4497          && "Vector size not supported");
4498
4499   if (VT.getSizeInBits() == 128) {
4500     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4501     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4502     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4503                              &SplatMask[0]);
4504   } else {
4505     // To use VPERMILPS to splat scalars, the second half of indicies must
4506     // refer to the higher part, which is a duplication of the lower one,
4507     // because VPERMILPS can only handle in-lane permutations.
4508     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4509                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4510
4511     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4512     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4513                              &SplatMask[0]);
4514   }
4515
4516   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4517 }
4518
4519 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4520 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4521   EVT SrcVT = SV->getValueType(0);
4522   SDValue V1 = SV->getOperand(0);
4523   DebugLoc dl = SV->getDebugLoc();
4524
4525   int EltNo = SV->getSplatIndex();
4526   int NumElems = SrcVT.getVectorNumElements();
4527   unsigned Size = SrcVT.getSizeInBits();
4528
4529   assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4530           "Unknown how to promote splat for type");
4531
4532   // Extract the 128-bit part containing the splat element and update
4533   // the splat element index when it refers to the higher register.
4534   if (Size == 256) {
4535     unsigned Idx = (EltNo > NumElems/2) ? NumElems/2 : 0;
4536     V1 = Extract128BitVector(V1, DAG.getConstant(Idx, MVT::i32), DAG, dl);
4537     if (Idx > 0)
4538       EltNo -= NumElems/2;
4539   }
4540
4541   // All i16 and i8 vector types can't be used directly by a generic shuffle
4542   // instruction because the target has no such instruction. Generate shuffles
4543   // which repeat i16 and i8 several times until they fit in i32, and then can
4544   // be manipulated by target suported shuffles.
4545   EVT EltVT = SrcVT.getVectorElementType();
4546   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4547     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4548
4549   // Recreate the 256-bit vector and place the same 128-bit vector
4550   // into the low and high part. This is necessary because we want
4551   // to use VPERM* to shuffle the vectors
4552   if (Size == 256) {
4553     SDValue InsV = Insert128BitVector(DAG.getUNDEF(SrcVT), V1,
4554                          DAG.getConstant(0, MVT::i32), DAG, dl);
4555     V1 = Insert128BitVector(InsV, V1,
4556                DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
4557   }
4558
4559   return getLegalSplat(DAG, V1, EltNo);
4560 }
4561
4562 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4563 /// vector of zero or undef vector.  This produces a shuffle where the low
4564 /// element of V2 is swizzled into the zero/undef vector, landing at element
4565 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4566 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4567                                            bool isZero, bool HasXMMInt,
4568                                            SelectionDAG &DAG) {
4569   EVT VT = V2.getValueType();
4570   SDValue V1 = isZero
4571     ? getZeroVector(VT, HasXMMInt, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4572   unsigned NumElems = VT.getVectorNumElements();
4573   SmallVector<int, 16> MaskVec;
4574   for (unsigned i = 0; i != NumElems; ++i)
4575     // If this is the insertion idx, put the low elt of V2 here.
4576     MaskVec.push_back(i == Idx ? NumElems : i);
4577   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4578 }
4579
4580 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4581 /// element of the result of the vector shuffle.
4582 static SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
4583                                    unsigned Depth) {
4584   if (Depth == 6)
4585     return SDValue();  // Limit search depth.
4586
4587   SDValue V = SDValue(N, 0);
4588   EVT VT = V.getValueType();
4589   unsigned Opcode = V.getOpcode();
4590
4591   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4592   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4593     Index = SV->getMaskElt(Index);
4594
4595     if (Index < 0)
4596       return DAG.getUNDEF(VT.getVectorElementType());
4597
4598     int NumElems = VT.getVectorNumElements();
4599     SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
4600     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
4601   }
4602
4603   // Recurse into target specific vector shuffles to find scalars.
4604   if (isTargetShuffle(Opcode)) {
4605     int NumElems = VT.getVectorNumElements();
4606     SmallVector<unsigned, 16> ShuffleMask;
4607     SDValue ImmN;
4608
4609     switch(Opcode) {
4610     case X86ISD::SHUFPS:
4611     case X86ISD::SHUFPD:
4612       ImmN = N->getOperand(N->getNumOperands()-1);
4613       DecodeSHUFPSMask(NumElems,
4614                        cast<ConstantSDNode>(ImmN)->getZExtValue(),
4615                        ShuffleMask);
4616       break;
4617     case X86ISD::PUNPCKHBW:
4618     case X86ISD::PUNPCKHWD:
4619     case X86ISD::PUNPCKHDQ:
4620     case X86ISD::PUNPCKHQDQ:
4621       DecodePUNPCKHMask(NumElems, ShuffleMask);
4622       break;
4623     case X86ISD::UNPCKHPS:
4624     case X86ISD::UNPCKHPD:
4625     case X86ISD::VUNPCKHPSY:
4626     case X86ISD::VUNPCKHPDY:
4627       DecodeUNPCKHPMask(NumElems, ShuffleMask);
4628       break;
4629     case X86ISD::PUNPCKLBW:
4630     case X86ISD::PUNPCKLWD:
4631     case X86ISD::PUNPCKLDQ:
4632     case X86ISD::PUNPCKLQDQ:
4633       DecodePUNPCKLMask(VT, ShuffleMask);
4634       break;
4635     case X86ISD::UNPCKLPS:
4636     case X86ISD::UNPCKLPD:
4637     case X86ISD::VUNPCKLPSY:
4638     case X86ISD::VUNPCKLPDY:
4639       DecodeUNPCKLPMask(VT, ShuffleMask);
4640       break;
4641     case X86ISD::MOVHLPS:
4642       DecodeMOVHLPSMask(NumElems, ShuffleMask);
4643       break;
4644     case X86ISD::MOVLHPS:
4645       DecodeMOVLHPSMask(NumElems, ShuffleMask);
4646       break;
4647     case X86ISD::PSHUFD:
4648       ImmN = N->getOperand(N->getNumOperands()-1);
4649       DecodePSHUFMask(NumElems,
4650                       cast<ConstantSDNode>(ImmN)->getZExtValue(),
4651                       ShuffleMask);
4652       break;
4653     case X86ISD::PSHUFHW:
4654       ImmN = N->getOperand(N->getNumOperands()-1);
4655       DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4656                         ShuffleMask);
4657       break;
4658     case X86ISD::PSHUFLW:
4659       ImmN = N->getOperand(N->getNumOperands()-1);
4660       DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4661                         ShuffleMask);
4662       break;
4663     case X86ISD::MOVSS:
4664     case X86ISD::MOVSD: {
4665       // The index 0 always comes from the first element of the second source,
4666       // this is why MOVSS and MOVSD are used in the first place. The other
4667       // elements come from the other positions of the first source vector.
4668       unsigned OpNum = (Index == 0) ? 1 : 0;
4669       return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
4670                                  Depth+1);
4671     }
4672     case X86ISD::VPERMILPS:
4673       ImmN = N->getOperand(N->getNumOperands()-1);
4674       DecodeVPERMILPSMask(4, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4675                         ShuffleMask);
4676       break;
4677     case X86ISD::VPERMILPSY:
4678       ImmN = N->getOperand(N->getNumOperands()-1);
4679       DecodeVPERMILPSMask(8, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4680                         ShuffleMask);
4681       break;
4682     case X86ISD::VPERMILPD:
4683       ImmN = N->getOperand(N->getNumOperands()-1);
4684       DecodeVPERMILPDMask(2, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4685                         ShuffleMask);
4686       break;
4687     case X86ISD::VPERMILPDY:
4688       ImmN = N->getOperand(N->getNumOperands()-1);
4689       DecodeVPERMILPDMask(4, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4690                         ShuffleMask);
4691       break;
4692     case X86ISD::VPERM2F128:
4693       ImmN = N->getOperand(N->getNumOperands()-1);
4694       DecodeVPERM2F128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4695                            ShuffleMask);
4696       break;
4697     case X86ISD::MOVDDUP:
4698     case X86ISD::MOVLHPD:
4699     case X86ISD::MOVLPD:
4700     case X86ISD::MOVLPS:
4701     case X86ISD::MOVSHDUP:
4702     case X86ISD::MOVSLDUP:
4703     case X86ISD::PALIGN:
4704       return SDValue(); // Not yet implemented.
4705     default:
4706       assert(0 && "unknown target shuffle node");
4707       return SDValue();
4708     }
4709
4710     Index = ShuffleMask[Index];
4711     if (Index < 0)
4712       return DAG.getUNDEF(VT.getVectorElementType());
4713
4714     SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
4715     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
4716                                Depth+1);
4717   }
4718
4719   // Actual nodes that may contain scalar elements
4720   if (Opcode == ISD::BITCAST) {
4721     V = V.getOperand(0);
4722     EVT SrcVT = V.getValueType();
4723     unsigned NumElems = VT.getVectorNumElements();
4724
4725     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4726       return SDValue();
4727   }
4728
4729   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4730     return (Index == 0) ? V.getOperand(0)
4731                           : DAG.getUNDEF(VT.getVectorElementType());
4732
4733   if (V.getOpcode() == ISD::BUILD_VECTOR)
4734     return V.getOperand(Index);
4735
4736   return SDValue();
4737 }
4738
4739 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4740 /// shuffle operation which come from a consecutively from a zero. The
4741 /// search can start in two different directions, from left or right.
4742 static
4743 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
4744                                   bool ZerosFromLeft, SelectionDAG &DAG) {
4745   int i = 0;
4746
4747   while (i < NumElems) {
4748     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4749     SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
4750     if (!(Elt.getNode() &&
4751          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4752       break;
4753     ++i;
4754   }
4755
4756   return i;
4757 }
4758
4759 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
4760 /// MaskE correspond consecutively to elements from one of the vector operands,
4761 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4762 static
4763 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
4764                               int OpIdx, int NumElems, unsigned &OpNum) {
4765   bool SeenV1 = false;
4766   bool SeenV2 = false;
4767
4768   for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
4769     int Idx = SVOp->getMaskElt(i);
4770     // Ignore undef indicies
4771     if (Idx < 0)
4772       continue;
4773
4774     if (Idx < NumElems)
4775       SeenV1 = true;
4776     else
4777       SeenV2 = true;
4778
4779     // Only accept consecutive elements from the same vector
4780     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4781       return false;
4782   }
4783
4784   OpNum = SeenV1 ? 0 : 1;
4785   return true;
4786 }
4787
4788 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4789 /// logical left shift of a vector.
4790 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4791                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4792   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4793   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4794               false /* check zeros from right */, DAG);
4795   unsigned OpSrc;
4796
4797   if (!NumZeros)
4798     return false;
4799
4800   // Considering the elements in the mask that are not consecutive zeros,
4801   // check if they consecutively come from only one of the source vectors.
4802   //
4803   //               V1 = {X, A, B, C}     0
4804   //                         \  \  \    /
4805   //   vector_shuffle V1, V2 <1, 2, 3, X>
4806   //
4807   if (!isShuffleMaskConsecutive(SVOp,
4808             0,                   // Mask Start Index
4809             NumElems-NumZeros-1, // Mask End Index
4810             NumZeros,            // Where to start looking in the src vector
4811             NumElems,            // Number of elements in vector
4812             OpSrc))              // Which source operand ?
4813     return false;
4814
4815   isLeft = false;
4816   ShAmt = NumZeros;
4817   ShVal = SVOp->getOperand(OpSrc);
4818   return true;
4819 }
4820
4821 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4822 /// logical left shift of a vector.
4823 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4824                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4825   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4826   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4827               true /* check zeros from left */, DAG);
4828   unsigned OpSrc;
4829
4830   if (!NumZeros)
4831     return false;
4832
4833   // Considering the elements in the mask that are not consecutive zeros,
4834   // check if they consecutively come from only one of the source vectors.
4835   //
4836   //                           0    { A, B, X, X } = V2
4837   //                          / \    /  /
4838   //   vector_shuffle V1, V2 <X, X, 4, 5>
4839   //
4840   if (!isShuffleMaskConsecutive(SVOp,
4841             NumZeros,     // Mask Start Index
4842             NumElems-1,   // Mask End Index
4843             0,            // Where to start looking in the src vector
4844             NumElems,     // Number of elements in vector
4845             OpSrc))       // Which source operand ?
4846     return false;
4847
4848   isLeft = true;
4849   ShAmt = NumZeros;
4850   ShVal = SVOp->getOperand(OpSrc);
4851   return true;
4852 }
4853
4854 /// isVectorShift - Returns true if the shuffle can be implemented as a
4855 /// logical left or right shift of a vector.
4856 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4857                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4858   // Although the logic below support any bitwidth size, there are no
4859   // shift instructions which handle more than 128-bit vectors.
4860   if (SVOp->getValueType(0).getSizeInBits() > 128)
4861     return false;
4862
4863   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4864       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4865     return true;
4866
4867   return false;
4868 }
4869
4870 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4871 ///
4872 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4873                                        unsigned NumNonZero, unsigned NumZero,
4874                                        SelectionDAG &DAG,
4875                                        const TargetLowering &TLI) {
4876   if (NumNonZero > 8)
4877     return SDValue();
4878
4879   DebugLoc dl = Op.getDebugLoc();
4880   SDValue V(0, 0);
4881   bool First = true;
4882   for (unsigned i = 0; i < 16; ++i) {
4883     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4884     if (ThisIsNonZero && First) {
4885       if (NumZero)
4886         V = getZeroVector(MVT::v8i16, true, DAG, dl);
4887       else
4888         V = DAG.getUNDEF(MVT::v8i16);
4889       First = false;
4890     }
4891
4892     if ((i & 1) != 0) {
4893       SDValue ThisElt(0, 0), LastElt(0, 0);
4894       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4895       if (LastIsNonZero) {
4896         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4897                               MVT::i16, Op.getOperand(i-1));
4898       }
4899       if (ThisIsNonZero) {
4900         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4901         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4902                               ThisElt, DAG.getConstant(8, MVT::i8));
4903         if (LastIsNonZero)
4904           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4905       } else
4906         ThisElt = LastElt;
4907
4908       if (ThisElt.getNode())
4909         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4910                         DAG.getIntPtrConstant(i/2));
4911     }
4912   }
4913
4914   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4915 }
4916
4917 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4918 ///
4919 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4920                                      unsigned NumNonZero, unsigned NumZero,
4921                                      SelectionDAG &DAG,
4922                                      const TargetLowering &TLI) {
4923   if (NumNonZero > 4)
4924     return SDValue();
4925
4926   DebugLoc dl = Op.getDebugLoc();
4927   SDValue V(0, 0);
4928   bool First = true;
4929   for (unsigned i = 0; i < 8; ++i) {
4930     bool isNonZero = (NonZeros & (1 << i)) != 0;
4931     if (isNonZero) {
4932       if (First) {
4933         if (NumZero)
4934           V = getZeroVector(MVT::v8i16, true, DAG, dl);
4935         else
4936           V = DAG.getUNDEF(MVT::v8i16);
4937         First = false;
4938       }
4939       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4940                       MVT::v8i16, V, Op.getOperand(i),
4941                       DAG.getIntPtrConstant(i));
4942     }
4943   }
4944
4945   return V;
4946 }
4947
4948 /// getVShift - Return a vector logical shift node.
4949 ///
4950 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4951                          unsigned NumBits, SelectionDAG &DAG,
4952                          const TargetLowering &TLI, DebugLoc dl) {
4953   assert(VT.getSizeInBits() == 128 && "Unknown type for VShift");
4954   EVT ShVT = MVT::v2i64;
4955   unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
4956   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4957   return DAG.getNode(ISD::BITCAST, dl, VT,
4958                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4959                              DAG.getConstant(NumBits,
4960                                   TLI.getShiftAmountTy(SrcOp.getValueType()))));
4961 }
4962
4963 SDValue
4964 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4965                                           SelectionDAG &DAG) const {
4966
4967   // Check if the scalar load can be widened into a vector load. And if
4968   // the address is "base + cst" see if the cst can be "absorbed" into
4969   // the shuffle mask.
4970   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4971     SDValue Ptr = LD->getBasePtr();
4972     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4973       return SDValue();
4974     EVT PVT = LD->getValueType(0);
4975     if (PVT != MVT::i32 && PVT != MVT::f32)
4976       return SDValue();
4977
4978     int FI = -1;
4979     int64_t Offset = 0;
4980     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4981       FI = FINode->getIndex();
4982       Offset = 0;
4983     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4984                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4985       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4986       Offset = Ptr.getConstantOperandVal(1);
4987       Ptr = Ptr.getOperand(0);
4988     } else {
4989       return SDValue();
4990     }
4991
4992     // FIXME: 256-bit vector instructions don't require a strict alignment,
4993     // improve this code to support it better.
4994     unsigned RequiredAlign = VT.getSizeInBits()/8;
4995     SDValue Chain = LD->getChain();
4996     // Make sure the stack object alignment is at least 16 or 32.
4997     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4998     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4999       if (MFI->isFixedObjectIndex(FI)) {
5000         // Can't change the alignment. FIXME: It's possible to compute
5001         // the exact stack offset and reference FI + adjust offset instead.
5002         // If someone *really* cares about this. That's the way to implement it.
5003         return SDValue();
5004       } else {
5005         MFI->setObjectAlignment(FI, RequiredAlign);
5006       }
5007     }
5008
5009     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5010     // Ptr + (Offset & ~15).
5011     if (Offset < 0)
5012       return SDValue();
5013     if ((Offset % RequiredAlign) & 3)
5014       return SDValue();
5015     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5016     if (StartOffset)
5017       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
5018                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5019
5020     int EltNo = (Offset - StartOffset) >> 2;
5021     int NumElems = VT.getVectorNumElements();
5022
5023     EVT CanonVT = VT.getSizeInBits() == 128 ? MVT::v4i32 : MVT::v8i32;
5024     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5025     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5026                              LD->getPointerInfo().getWithOffset(StartOffset),
5027                              false, false, false, 0);
5028
5029     // Canonicalize it to a v4i32 or v8i32 shuffle.
5030     SmallVector<int, 8> Mask;
5031     for (int i = 0; i < NumElems; ++i)
5032       Mask.push_back(EltNo);
5033
5034     V1 = DAG.getNode(ISD::BITCAST, dl, CanonVT, V1);
5035     return DAG.getNode(ISD::BITCAST, dl, NVT,
5036                        DAG.getVectorShuffle(CanonVT, dl, V1,
5037                                             DAG.getUNDEF(CanonVT),&Mask[0]));
5038   }
5039
5040   return SDValue();
5041 }
5042
5043 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5044 /// vector of type 'VT', see if the elements can be replaced by a single large
5045 /// load which has the same value as a build_vector whose operands are 'elts'.
5046 ///
5047 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5048 ///
5049 /// FIXME: we'd also like to handle the case where the last elements are zero
5050 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5051 /// There's even a handy isZeroNode for that purpose.
5052 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5053                                         DebugLoc &DL, SelectionDAG &DAG) {
5054   EVT EltVT = VT.getVectorElementType();
5055   unsigned NumElems = Elts.size();
5056
5057   LoadSDNode *LDBase = NULL;
5058   unsigned LastLoadedElt = -1U;
5059
5060   // For each element in the initializer, see if we've found a load or an undef.
5061   // If we don't find an initial load element, or later load elements are
5062   // non-consecutive, bail out.
5063   for (unsigned i = 0; i < NumElems; ++i) {
5064     SDValue Elt = Elts[i];
5065
5066     if (!Elt.getNode() ||
5067         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5068       return SDValue();
5069     if (!LDBase) {
5070       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5071         return SDValue();
5072       LDBase = cast<LoadSDNode>(Elt.getNode());
5073       LastLoadedElt = i;
5074       continue;
5075     }
5076     if (Elt.getOpcode() == ISD::UNDEF)
5077       continue;
5078
5079     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5080     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5081       return SDValue();
5082     LastLoadedElt = i;
5083   }
5084
5085   // If we have found an entire vector of loads and undefs, then return a large
5086   // load of the entire vector width starting at the base pointer.  If we found
5087   // consecutive loads for the low half, generate a vzext_load node.
5088   if (LastLoadedElt == NumElems - 1) {
5089     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5090       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5091                          LDBase->getPointerInfo(),
5092                          LDBase->isVolatile(), LDBase->isNonTemporal(),
5093                          LDBase->isInvariant(), 0);
5094     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5095                        LDBase->getPointerInfo(),
5096                        LDBase->isVolatile(), LDBase->isNonTemporal(),
5097                        LDBase->isInvariant(), LDBase->getAlignment());
5098   } else if (NumElems == 4 && LastLoadedElt == 1 &&
5099              DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5100     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5101     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5102     SDValue ResNode =
5103         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
5104                                 LDBase->getPointerInfo(),
5105                                 LDBase->getAlignment(),
5106                                 false/*isVolatile*/, true/*ReadMem*/,
5107                                 false/*WriteMem*/);
5108     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5109   }
5110   return SDValue();
5111 }
5112
5113 /// isVectorBroadcast - Check if the node chain is suitable to be xformed to
5114 /// a vbroadcast node. We support two patterns:
5115 /// 1. A splat BUILD_VECTOR which uses a single scalar load.
5116 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5117 /// a scalar load.
5118 /// The scalar load node is returned when a pattern is found,
5119 /// or SDValue() otherwise.
5120 static SDValue isVectorBroadcast(SDValue &Op, bool hasAVX2) {
5121   EVT VT = Op.getValueType();
5122   SDValue V = Op;
5123
5124   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5125     V = V.getOperand(0);
5126
5127   //A suspected load to be broadcasted.
5128   SDValue Ld;
5129
5130   switch (V.getOpcode()) {
5131     default:
5132       // Unknown pattern found.
5133       return SDValue();
5134
5135     case ISD::BUILD_VECTOR: {
5136       // The BUILD_VECTOR node must be a splat.
5137       if (!isSplatVector(V.getNode()))
5138         return SDValue();
5139
5140       Ld = V.getOperand(0);
5141
5142       // The suspected load node has several users. Make sure that all
5143       // of its users are from the BUILD_VECTOR node.
5144       if (!Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5145         return SDValue();
5146       break;
5147     }
5148
5149     case ISD::VECTOR_SHUFFLE: {
5150       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5151
5152       // Shuffles must have a splat mask where the first element is
5153       // broadcasted.
5154       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5155         return SDValue();
5156
5157       SDValue Sc = Op.getOperand(0);
5158       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR)
5159         return SDValue();
5160
5161       Ld = Sc.getOperand(0);
5162
5163       // The scalar_to_vector node and the suspected
5164       // load node must have exactly one user.
5165       if (!Sc.hasOneUse() || !Ld.hasOneUse())
5166         return SDValue();
5167       break;
5168     }
5169   }
5170
5171   // The scalar source must be a normal load.
5172   if (!ISD::isNormalLoad(Ld.getNode()))
5173     return SDValue();
5174
5175   bool Is256 = VT.getSizeInBits() == 256;
5176   bool Is128 = VT.getSizeInBits() == 128;
5177   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5178
5179   if (hasAVX2) {
5180     // VBroadcast to YMM
5181     if (Is256 && (ScalarSize == 8  || ScalarSize == 16 ||
5182                   ScalarSize == 32 || ScalarSize == 64 ))
5183       return Ld;
5184
5185     // VBroadcast to XMM
5186     if (Is128 && (ScalarSize ==  8 || ScalarSize == 32 ||
5187                   ScalarSize == 16 || ScalarSize == 64 ))
5188       return Ld;
5189   }
5190
5191   // VBroadcast to YMM
5192   if (Is256 && (ScalarSize == 32 || ScalarSize == 64))
5193     return Ld;
5194
5195   // VBroadcast to XMM
5196   if (Is128 && (ScalarSize == 32))
5197     return Ld;
5198
5199
5200   // Unsupported broadcast.
5201   return SDValue();
5202 }
5203
5204 SDValue
5205 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5206   DebugLoc dl = Op.getDebugLoc();
5207
5208   EVT VT = Op.getValueType();
5209   EVT ExtVT = VT.getVectorElementType();
5210   unsigned NumElems = Op.getNumOperands();
5211
5212   // Vectors containing all zeros can be matched by pxor and xorps later
5213   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5214     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5215     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5216     if (Op.getValueType() == MVT::v4i32 ||
5217         Op.getValueType() == MVT::v8i32)
5218       return Op;
5219
5220     return getZeroVector(Op.getValueType(), Subtarget->hasXMMInt(), DAG, dl);
5221   }
5222
5223   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5224   // vectors or broken into v4i32 operations on 256-bit vectors.
5225   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5226     if (Op.getValueType() == MVT::v4i32)
5227       return Op;
5228
5229     return getOnesVector(Op.getValueType(), DAG, dl);
5230   }
5231
5232   SDValue LD = isVectorBroadcast(Op, Subtarget->hasAVX2());
5233   if (Subtarget->hasAVX() && LD.getNode())
5234       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, LD);
5235
5236   unsigned EVTBits = ExtVT.getSizeInBits();
5237
5238   unsigned NumZero  = 0;
5239   unsigned NumNonZero = 0;
5240   unsigned NonZeros = 0;
5241   bool IsAllConstants = true;
5242   SmallSet<SDValue, 8> Values;
5243   for (unsigned i = 0; i < NumElems; ++i) {
5244     SDValue Elt = Op.getOperand(i);
5245     if (Elt.getOpcode() == ISD::UNDEF)
5246       continue;
5247     Values.insert(Elt);
5248     if (Elt.getOpcode() != ISD::Constant &&
5249         Elt.getOpcode() != ISD::ConstantFP)
5250       IsAllConstants = false;
5251     if (X86::isZeroNode(Elt))
5252       NumZero++;
5253     else {
5254       NonZeros |= (1 << i);
5255       NumNonZero++;
5256     }
5257   }
5258
5259   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5260   if (NumNonZero == 0)
5261     return DAG.getUNDEF(VT);
5262
5263   // Special case for single non-zero, non-undef, element.
5264   if (NumNonZero == 1) {
5265     unsigned Idx = CountTrailingZeros_32(NonZeros);
5266     SDValue Item = Op.getOperand(Idx);
5267
5268     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5269     // the value are obviously zero, truncate the value to i32 and do the
5270     // insertion that way.  Only do this if the value is non-constant or if the
5271     // value is a constant being inserted into element 0.  It is cheaper to do
5272     // a constant pool load than it is to do a movd + shuffle.
5273     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5274         (!IsAllConstants || Idx == 0)) {
5275       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5276         // Handle SSE only.
5277         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5278         EVT VecVT = MVT::v4i32;
5279         unsigned VecElts = 4;
5280
5281         // Truncate the value (which may itself be a constant) to i32, and
5282         // convert it to a vector with movd (S2V+shuffle to zero extend).
5283         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5284         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5285         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
5286                                            Subtarget->hasXMMInt(), DAG);
5287
5288         // Now we have our 32-bit value zero extended in the low element of
5289         // a vector.  If Idx != 0, swizzle it into place.
5290         if (Idx != 0) {
5291           SmallVector<int, 4> Mask;
5292           Mask.push_back(Idx);
5293           for (unsigned i = 1; i != VecElts; ++i)
5294             Mask.push_back(i);
5295           Item = DAG.getVectorShuffle(VecVT, dl, Item,
5296                                       DAG.getUNDEF(Item.getValueType()),
5297                                       &Mask[0]);
5298         }
5299         return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
5300       }
5301     }
5302
5303     // If we have a constant or non-constant insertion into the low element of
5304     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5305     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5306     // depending on what the source datatype is.
5307     if (Idx == 0) {
5308       if (NumZero == 0) {
5309         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5310       } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5311           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5312         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5313         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5314         return getShuffleVectorZeroOrUndef(Item, 0, true,Subtarget->hasXMMInt(),
5315                                            DAG);
5316       } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5317         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5318         assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
5319         EVT MiddleVT = MVT::v4i32;
5320         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
5321         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
5322                                            Subtarget->hasXMMInt(), DAG);
5323         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5324       }
5325     }
5326
5327     // Is it a vector logical left shift?
5328     if (NumElems == 2 && Idx == 1 &&
5329         X86::isZeroNode(Op.getOperand(0)) &&
5330         !X86::isZeroNode(Op.getOperand(1))) {
5331       unsigned NumBits = VT.getSizeInBits();
5332       return getVShift(true, VT,
5333                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5334                                    VT, Op.getOperand(1)),
5335                        NumBits/2, DAG, *this, dl);
5336     }
5337
5338     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5339       return SDValue();
5340
5341     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5342     // is a non-constant being inserted into an element other than the low one,
5343     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5344     // movd/movss) to move this into the low element, then shuffle it into
5345     // place.
5346     if (EVTBits == 32) {
5347       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5348
5349       // Turn it into a shuffle of zero and zero-extended scalar to vector.
5350       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
5351                                          Subtarget->hasXMMInt(), DAG);
5352       SmallVector<int, 8> MaskVec;
5353       for (unsigned i = 0; i < NumElems; i++)
5354         MaskVec.push_back(i == Idx ? 0 : 1);
5355       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5356     }
5357   }
5358
5359   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5360   if (Values.size() == 1) {
5361     if (EVTBits == 32) {
5362       // Instead of a shuffle like this:
5363       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5364       // Check if it's possible to issue this instead.
5365       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5366       unsigned Idx = CountTrailingZeros_32(NonZeros);
5367       SDValue Item = Op.getOperand(Idx);
5368       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5369         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5370     }
5371     return SDValue();
5372   }
5373
5374   // A vector full of immediates; various special cases are already
5375   // handled, so this is best done with a single constant-pool load.
5376   if (IsAllConstants)
5377     return SDValue();
5378
5379   // For AVX-length vectors, build the individual 128-bit pieces and use
5380   // shuffles to put them in place.
5381   if (VT.getSizeInBits() == 256 && !ISD::isBuildVectorAllZeros(Op.getNode())) {
5382     SmallVector<SDValue, 32> V;
5383     for (unsigned i = 0; i < NumElems; ++i)
5384       V.push_back(Op.getOperand(i));
5385
5386     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5387
5388     // Build both the lower and upper subvector.
5389     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5390     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5391                                 NumElems/2);
5392
5393     // Recreate the wider vector with the lower and upper part.
5394     SDValue Vec = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), Lower,
5395                                 DAG.getConstant(0, MVT::i32), DAG, dl);
5396     return Insert128BitVector(Vec, Upper, DAG.getConstant(NumElems/2, MVT::i32),
5397                               DAG, dl);
5398   }
5399
5400   // Let legalizer expand 2-wide build_vectors.
5401   if (EVTBits == 64) {
5402     if (NumNonZero == 1) {
5403       // One half is zero or undef.
5404       unsigned Idx = CountTrailingZeros_32(NonZeros);
5405       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5406                                  Op.getOperand(Idx));
5407       return getShuffleVectorZeroOrUndef(V2, Idx, true,
5408                                          Subtarget->hasXMMInt(), DAG);
5409     }
5410     return SDValue();
5411   }
5412
5413   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5414   if (EVTBits == 8 && NumElems == 16) {
5415     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5416                                         *this);
5417     if (V.getNode()) return V;
5418   }
5419
5420   if (EVTBits == 16 && NumElems == 8) {
5421     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5422                                       *this);
5423     if (V.getNode()) return V;
5424   }
5425
5426   // If element VT is == 32 bits, turn it into a number of shuffles.
5427   SmallVector<SDValue, 8> V;
5428   V.resize(NumElems);
5429   if (NumElems == 4 && NumZero > 0) {
5430     for (unsigned i = 0; i < 4; ++i) {
5431       bool isZero = !(NonZeros & (1 << i));
5432       if (isZero)
5433         V[i] = getZeroVector(VT, Subtarget->hasXMMInt(), DAG, dl);
5434       else
5435         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5436     }
5437
5438     for (unsigned i = 0; i < 2; ++i) {
5439       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5440         default: break;
5441         case 0:
5442           V[i] = V[i*2];  // Must be a zero vector.
5443           break;
5444         case 1:
5445           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5446           break;
5447         case 2:
5448           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5449           break;
5450         case 3:
5451           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5452           break;
5453       }
5454     }
5455
5456     SmallVector<int, 8> MaskVec;
5457     bool Reverse = (NonZeros & 0x3) == 2;
5458     for (unsigned i = 0; i < 2; ++i)
5459       MaskVec.push_back(Reverse ? 1-i : i);
5460     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5461     for (unsigned i = 0; i < 2; ++i)
5462       MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
5463     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5464   }
5465
5466   if (Values.size() > 1 && VT.getSizeInBits() == 128) {
5467     // Check for a build vector of consecutive loads.
5468     for (unsigned i = 0; i < NumElems; ++i)
5469       V[i] = Op.getOperand(i);
5470
5471     // Check for elements which are consecutive loads.
5472     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5473     if (LD.getNode())
5474       return LD;
5475
5476     // For SSE 4.1, use insertps to put the high elements into the low element.
5477     if (getSubtarget()->hasSSE41() || getSubtarget()->hasAVX()) {
5478       SDValue Result;
5479       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5480         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5481       else
5482         Result = DAG.getUNDEF(VT);
5483
5484       for (unsigned i = 1; i < NumElems; ++i) {
5485         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5486         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5487                              Op.getOperand(i), DAG.getIntPtrConstant(i));
5488       }
5489       return Result;
5490     }
5491
5492     // Otherwise, expand into a number of unpckl*, start by extending each of
5493     // our (non-undef) elements to the full vector width with the element in the
5494     // bottom slot of the vector (which generates no code for SSE).
5495     for (unsigned i = 0; i < NumElems; ++i) {
5496       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5497         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5498       else
5499         V[i] = DAG.getUNDEF(VT);
5500     }
5501
5502     // Next, we iteratively mix elements, e.g. for v4f32:
5503     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5504     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5505     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5506     unsigned EltStride = NumElems >> 1;
5507     while (EltStride != 0) {
5508       for (unsigned i = 0; i < EltStride; ++i) {
5509         // If V[i+EltStride] is undef and this is the first round of mixing,
5510         // then it is safe to just drop this shuffle: V[i] is already in the
5511         // right place, the one element (since it's the first round) being
5512         // inserted as undef can be dropped.  This isn't safe for successive
5513         // rounds because they will permute elements within both vectors.
5514         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5515             EltStride == NumElems/2)
5516           continue;
5517
5518         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5519       }
5520       EltStride >>= 1;
5521     }
5522     return V[0];
5523   }
5524   return SDValue();
5525 }
5526
5527 // LowerMMXCONCAT_VECTORS - We support concatenate two MMX registers and place
5528 // them in a MMX register.  This is better than doing a stack convert.
5529 static SDValue LowerMMXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5530   DebugLoc dl = Op.getDebugLoc();
5531   EVT ResVT = Op.getValueType();
5532
5533   assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
5534          ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
5535   int Mask[2];
5536   SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
5537   SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5538   InVec = Op.getOperand(1);
5539   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5540     unsigned NumElts = ResVT.getVectorNumElements();
5541     VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5542     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
5543                        InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
5544   } else {
5545     InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
5546     SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5547     Mask[0] = 0; Mask[1] = 2;
5548     VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
5549   }
5550   return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5551 }
5552
5553 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5554 // to create 256-bit vectors from two other 128-bit ones.
5555 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5556   DebugLoc dl = Op.getDebugLoc();
5557   EVT ResVT = Op.getValueType();
5558
5559   assert(ResVT.getSizeInBits() == 256 && "Value type must be 256-bit wide");
5560
5561   SDValue V1 = Op.getOperand(0);
5562   SDValue V2 = Op.getOperand(1);
5563   unsigned NumElems = ResVT.getVectorNumElements();
5564
5565   SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, ResVT), V1,
5566                                  DAG.getConstant(0, MVT::i32), DAG, dl);
5567   return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32),
5568                             DAG, dl);
5569 }
5570
5571 SDValue
5572 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
5573   EVT ResVT = Op.getValueType();
5574
5575   assert(Op.getNumOperands() == 2);
5576   assert((ResVT.getSizeInBits() == 128 || ResVT.getSizeInBits() == 256) &&
5577          "Unsupported CONCAT_VECTORS for value type");
5578
5579   // We support concatenate two MMX registers and place them in a MMX register.
5580   // This is better than doing a stack convert.
5581   if (ResVT.is128BitVector())
5582     return LowerMMXCONCAT_VECTORS(Op, DAG);
5583
5584   // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5585   // from two other 128-bit ones.
5586   return LowerAVXCONCAT_VECTORS(Op, DAG);
5587 }
5588
5589 // v8i16 shuffles - Prefer shuffles in the following order:
5590 // 1. [all]   pshuflw, pshufhw, optional move
5591 // 2. [ssse3] 1 x pshufb
5592 // 3. [ssse3] 2 x pshufb + 1 x por
5593 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5594 SDValue
5595 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
5596                                             SelectionDAG &DAG) const {
5597   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5598   SDValue V1 = SVOp->getOperand(0);
5599   SDValue V2 = SVOp->getOperand(1);
5600   DebugLoc dl = SVOp->getDebugLoc();
5601   SmallVector<int, 8> MaskVals;
5602
5603   // Determine if more than 1 of the words in each of the low and high quadwords
5604   // of the result come from the same quadword of one of the two inputs.  Undef
5605   // mask values count as coming from any quadword, for better codegen.
5606   unsigned LoQuad[] = { 0, 0, 0, 0 };
5607   unsigned HiQuad[] = { 0, 0, 0, 0 };
5608   BitVector InputQuads(4);
5609   for (unsigned i = 0; i < 8; ++i) {
5610     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5611     int EltIdx = SVOp->getMaskElt(i);
5612     MaskVals.push_back(EltIdx);
5613     if (EltIdx < 0) {
5614       ++Quad[0];
5615       ++Quad[1];
5616       ++Quad[2];
5617       ++Quad[3];
5618       continue;
5619     }
5620     ++Quad[EltIdx / 4];
5621     InputQuads.set(EltIdx / 4);
5622   }
5623
5624   int BestLoQuad = -1;
5625   unsigned MaxQuad = 1;
5626   for (unsigned i = 0; i < 4; ++i) {
5627     if (LoQuad[i] > MaxQuad) {
5628       BestLoQuad = i;
5629       MaxQuad = LoQuad[i];
5630     }
5631   }
5632
5633   int BestHiQuad = -1;
5634   MaxQuad = 1;
5635   for (unsigned i = 0; i < 4; ++i) {
5636     if (HiQuad[i] > MaxQuad) {
5637       BestHiQuad = i;
5638       MaxQuad = HiQuad[i];
5639     }
5640   }
5641
5642   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5643   // of the two input vectors, shuffle them into one input vector so only a
5644   // single pshufb instruction is necessary. If There are more than 2 input
5645   // quads, disable the next transformation since it does not help SSSE3.
5646   bool V1Used = InputQuads[0] || InputQuads[1];
5647   bool V2Used = InputQuads[2] || InputQuads[3];
5648   if (Subtarget->hasSSSE3() || Subtarget->hasAVX()) {
5649     if (InputQuads.count() == 2 && V1Used && V2Used) {
5650       BestLoQuad = InputQuads.find_first();
5651       BestHiQuad = InputQuads.find_next(BestLoQuad);
5652     }
5653     if (InputQuads.count() > 2) {
5654       BestLoQuad = -1;
5655       BestHiQuad = -1;
5656     }
5657   }
5658
5659   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5660   // the shuffle mask.  If a quad is scored as -1, that means that it contains
5661   // words from all 4 input quadwords.
5662   SDValue NewV;
5663   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5664     SmallVector<int, 8> MaskV;
5665     MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
5666     MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
5667     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5668                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5669                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5670     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5671
5672     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5673     // source words for the shuffle, to aid later transformations.
5674     bool AllWordsInNewV = true;
5675     bool InOrder[2] = { true, true };
5676     for (unsigned i = 0; i != 8; ++i) {
5677       int idx = MaskVals[i];
5678       if (idx != (int)i)
5679         InOrder[i/4] = false;
5680       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5681         continue;
5682       AllWordsInNewV = false;
5683       break;
5684     }
5685
5686     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5687     if (AllWordsInNewV) {
5688       for (int i = 0; i != 8; ++i) {
5689         int idx = MaskVals[i];
5690         if (idx < 0)
5691           continue;
5692         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5693         if ((idx != i) && idx < 4)
5694           pshufhw = false;
5695         if ((idx != i) && idx > 3)
5696           pshuflw = false;
5697       }
5698       V1 = NewV;
5699       V2Used = false;
5700       BestLoQuad = 0;
5701       BestHiQuad = 1;
5702     }
5703
5704     // If we've eliminated the use of V2, and the new mask is a pshuflw or
5705     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
5706     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5707       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5708       unsigned TargetMask = 0;
5709       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5710                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5711       TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
5712                              X86::getShufflePSHUFLWImmediate(NewV.getNode());
5713       V1 = NewV.getOperand(0);
5714       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5715     }
5716   }
5717
5718   // If we have SSSE3, and all words of the result are from 1 input vector,
5719   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5720   // is present, fall back to case 4.
5721   if (Subtarget->hasSSSE3() || Subtarget->hasAVX()) {
5722     SmallVector<SDValue,16> pshufbMask;
5723
5724     // If we have elements from both input vectors, set the high bit of the
5725     // shuffle mask element to zero out elements that come from V2 in the V1
5726     // mask, and elements that come from V1 in the V2 mask, so that the two
5727     // results can be OR'd together.
5728     bool TwoInputs = V1Used && V2Used;
5729     for (unsigned i = 0; i != 8; ++i) {
5730       int EltIdx = MaskVals[i] * 2;
5731       if (TwoInputs && (EltIdx >= 16)) {
5732         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5733         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5734         continue;
5735       }
5736       pshufbMask.push_back(DAG.getConstant(EltIdx,   MVT::i8));
5737       pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
5738     }
5739     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5740     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5741                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5742                                  MVT::v16i8, &pshufbMask[0], 16));
5743     if (!TwoInputs)
5744       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5745
5746     // Calculate the shuffle mask for the second input, shuffle it, and
5747     // OR it with the first shuffled input.
5748     pshufbMask.clear();
5749     for (unsigned i = 0; i != 8; ++i) {
5750       int EltIdx = MaskVals[i] * 2;
5751       if (EltIdx < 16) {
5752         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5753         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5754         continue;
5755       }
5756       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5757       pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
5758     }
5759     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5760     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5761                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5762                                  MVT::v16i8, &pshufbMask[0], 16));
5763     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5764     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5765   }
5766
5767   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5768   // and update MaskVals with new element order.
5769   BitVector InOrder(8);
5770   if (BestLoQuad >= 0) {
5771     SmallVector<int, 8> MaskV;
5772     for (int i = 0; i != 4; ++i) {
5773       int idx = MaskVals[i];
5774       if (idx < 0) {
5775         MaskV.push_back(-1);
5776         InOrder.set(i);
5777       } else if ((idx / 4) == BestLoQuad) {
5778         MaskV.push_back(idx & 3);
5779         InOrder.set(i);
5780       } else {
5781         MaskV.push_back(-1);
5782       }
5783     }
5784     for (unsigned i = 4; i != 8; ++i)
5785       MaskV.push_back(i);
5786     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5787                                 &MaskV[0]);
5788
5789     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE &&
5790         (Subtarget->hasSSSE3() || Subtarget->hasAVX()))
5791       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5792                                NewV.getOperand(0),
5793                                X86::getShufflePSHUFLWImmediate(NewV.getNode()),
5794                                DAG);
5795   }
5796
5797   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5798   // and update MaskVals with the new element order.
5799   if (BestHiQuad >= 0) {
5800     SmallVector<int, 8> MaskV;
5801     for (unsigned i = 0; i != 4; ++i)
5802       MaskV.push_back(i);
5803     for (unsigned i = 4; i != 8; ++i) {
5804       int idx = MaskVals[i];
5805       if (idx < 0) {
5806         MaskV.push_back(-1);
5807         InOrder.set(i);
5808       } else if ((idx / 4) == BestHiQuad) {
5809         MaskV.push_back((idx & 3) + 4);
5810         InOrder.set(i);
5811       } else {
5812         MaskV.push_back(-1);
5813       }
5814     }
5815     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5816                                 &MaskV[0]);
5817
5818     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE &&
5819         (Subtarget->hasSSSE3() || Subtarget->hasAVX()))
5820       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5821                               NewV.getOperand(0),
5822                               X86::getShufflePSHUFHWImmediate(NewV.getNode()),
5823                               DAG);
5824   }
5825
5826   // In case BestHi & BestLo were both -1, which means each quadword has a word
5827   // from each of the four input quadwords, calculate the InOrder bitvector now
5828   // before falling through to the insert/extract cleanup.
5829   if (BestLoQuad == -1 && BestHiQuad == -1) {
5830     NewV = V1;
5831     for (int i = 0; i != 8; ++i)
5832       if (MaskVals[i] < 0 || MaskVals[i] == i)
5833         InOrder.set(i);
5834   }
5835
5836   // The other elements are put in the right place using pextrw and pinsrw.
5837   for (unsigned i = 0; i != 8; ++i) {
5838     if (InOrder[i])
5839       continue;
5840     int EltIdx = MaskVals[i];
5841     if (EltIdx < 0)
5842       continue;
5843     SDValue ExtOp = (EltIdx < 8)
5844     ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5845                   DAG.getIntPtrConstant(EltIdx))
5846     : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5847                   DAG.getIntPtrConstant(EltIdx - 8));
5848     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5849                        DAG.getIntPtrConstant(i));
5850   }
5851   return NewV;
5852 }
5853
5854 // v16i8 shuffles - Prefer shuffles in the following order:
5855 // 1. [ssse3] 1 x pshufb
5856 // 2. [ssse3] 2 x pshufb + 1 x por
5857 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
5858 static
5859 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5860                                  SelectionDAG &DAG,
5861                                  const X86TargetLowering &TLI) {
5862   SDValue V1 = SVOp->getOperand(0);
5863   SDValue V2 = SVOp->getOperand(1);
5864   DebugLoc dl = SVOp->getDebugLoc();
5865   SmallVector<int, 16> MaskVals;
5866   SVOp->getMask(MaskVals);
5867
5868   // If we have SSSE3, case 1 is generated when all result bytes come from
5869   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
5870   // present, fall back to case 3.
5871   // FIXME: kill V2Only once shuffles are canonizalized by getNode.
5872   bool V1Only = true;
5873   bool V2Only = true;
5874   for (unsigned i = 0; i < 16; ++i) {
5875     int EltIdx = MaskVals[i];
5876     if (EltIdx < 0)
5877       continue;
5878     if (EltIdx < 16)
5879       V2Only = false;
5880     else
5881       V1Only = false;
5882   }
5883
5884   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5885   if (TLI.getSubtarget()->hasSSSE3() || TLI.getSubtarget()->hasAVX()) {
5886     SmallVector<SDValue,16> pshufbMask;
5887
5888     // If all result elements are from one input vector, then only translate
5889     // undef mask values to 0x80 (zero out result) in the pshufb mask.
5890     //
5891     // Otherwise, we have elements from both input vectors, and must zero out
5892     // elements that come from V2 in the first mask, and V1 in the second mask
5893     // so that we can OR them together.
5894     bool TwoInputs = !(V1Only || V2Only);
5895     for (unsigned i = 0; i != 16; ++i) {
5896       int EltIdx = MaskVals[i];
5897       if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
5898         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5899         continue;
5900       }
5901       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5902     }
5903     // If all the elements are from V2, assign it to V1 and return after
5904     // building the first pshufb.
5905     if (V2Only)
5906       V1 = V2;
5907     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5908                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5909                                  MVT::v16i8, &pshufbMask[0], 16));
5910     if (!TwoInputs)
5911       return V1;
5912
5913     // Calculate the shuffle mask for the second input, shuffle it, and
5914     // OR it with the first shuffled input.
5915     pshufbMask.clear();
5916     for (unsigned i = 0; i != 16; ++i) {
5917       int EltIdx = MaskVals[i];
5918       if (EltIdx < 16) {
5919         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5920         continue;
5921       }
5922       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5923     }
5924     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5925                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5926                                  MVT::v16i8, &pshufbMask[0], 16));
5927     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5928   }
5929
5930   // No SSSE3 - Calculate in place words and then fix all out of place words
5931   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
5932   // the 16 different words that comprise the two doublequadword input vectors.
5933   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5934   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5935   SDValue NewV = V2Only ? V2 : V1;
5936   for (int i = 0; i != 8; ++i) {
5937     int Elt0 = MaskVals[i*2];
5938     int Elt1 = MaskVals[i*2+1];
5939
5940     // This word of the result is all undef, skip it.
5941     if (Elt0 < 0 && Elt1 < 0)
5942       continue;
5943
5944     // This word of the result is already in the correct place, skip it.
5945     if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
5946       continue;
5947     if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
5948       continue;
5949
5950     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5951     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5952     SDValue InsElt;
5953
5954     // If Elt0 and Elt1 are defined, are consecutive, and can be load
5955     // using a single extract together, load it and store it.
5956     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5957       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5958                            DAG.getIntPtrConstant(Elt1 / 2));
5959       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5960                         DAG.getIntPtrConstant(i));
5961       continue;
5962     }
5963
5964     // If Elt1 is defined, extract it from the appropriate source.  If the
5965     // source byte is not also odd, shift the extracted word left 8 bits
5966     // otherwise clear the bottom 8 bits if we need to do an or.
5967     if (Elt1 >= 0) {
5968       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5969                            DAG.getIntPtrConstant(Elt1 / 2));
5970       if ((Elt1 & 1) == 0)
5971         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5972                              DAG.getConstant(8,
5973                                   TLI.getShiftAmountTy(InsElt.getValueType())));
5974       else if (Elt0 >= 0)
5975         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5976                              DAG.getConstant(0xFF00, MVT::i16));
5977     }
5978     // If Elt0 is defined, extract it from the appropriate source.  If the
5979     // source byte is not also even, shift the extracted word right 8 bits. If
5980     // Elt1 was also defined, OR the extracted values together before
5981     // inserting them in the result.
5982     if (Elt0 >= 0) {
5983       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5984                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5985       if ((Elt0 & 1) != 0)
5986         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5987                               DAG.getConstant(8,
5988                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
5989       else if (Elt1 >= 0)
5990         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5991                              DAG.getConstant(0x00FF, MVT::i16));
5992       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5993                          : InsElt0;
5994     }
5995     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5996                        DAG.getIntPtrConstant(i));
5997   }
5998   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5999 }
6000
6001 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6002 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6003 /// done when every pair / quad of shuffle mask elements point to elements in
6004 /// the right sequence. e.g.
6005 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6006 static
6007 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6008                                  SelectionDAG &DAG, DebugLoc dl) {
6009   EVT VT = SVOp->getValueType(0);
6010   SDValue V1 = SVOp->getOperand(0);
6011   SDValue V2 = SVOp->getOperand(1);
6012   unsigned NumElems = VT.getVectorNumElements();
6013   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
6014   EVT NewVT;
6015   switch (VT.getSimpleVT().SimpleTy) {
6016   default: assert(false && "Unexpected!");
6017   case MVT::v4f32: NewVT = MVT::v2f64; break;
6018   case MVT::v4i32: NewVT = MVT::v2i64; break;
6019   case MVT::v8i16: NewVT = MVT::v4i32; break;
6020   case MVT::v16i8: NewVT = MVT::v4i32; break;
6021   }
6022
6023   int Scale = NumElems / NewWidth;
6024   SmallVector<int, 8> MaskVec;
6025   for (unsigned i = 0; i < NumElems; i += Scale) {
6026     int StartIdx = -1;
6027     for (int j = 0; j < Scale; ++j) {
6028       int EltIdx = SVOp->getMaskElt(i+j);
6029       if (EltIdx < 0)
6030         continue;
6031       if (StartIdx == -1)
6032         StartIdx = EltIdx - (EltIdx % Scale);
6033       if (EltIdx != StartIdx + j)
6034         return SDValue();
6035     }
6036     if (StartIdx == -1)
6037       MaskVec.push_back(-1);
6038     else
6039       MaskVec.push_back(StartIdx / Scale);
6040   }
6041
6042   V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
6043   V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
6044   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6045 }
6046
6047 /// getVZextMovL - Return a zero-extending vector move low node.
6048 ///
6049 static SDValue getVZextMovL(EVT VT, EVT OpVT,
6050                             SDValue SrcOp, SelectionDAG &DAG,
6051                             const X86Subtarget *Subtarget, DebugLoc dl) {
6052   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6053     LoadSDNode *LD = NULL;
6054     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6055       LD = dyn_cast<LoadSDNode>(SrcOp);
6056     if (!LD) {
6057       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6058       // instead.
6059       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6060       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6061           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6062           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6063           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6064         // PR2108
6065         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6066         return DAG.getNode(ISD::BITCAST, dl, VT,
6067                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6068                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6069                                                    OpVT,
6070                                                    SrcOp.getOperand(0)
6071                                                           .getOperand(0))));
6072       }
6073     }
6074   }
6075
6076   return DAG.getNode(ISD::BITCAST, dl, VT,
6077                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6078                                  DAG.getNode(ISD::BITCAST, dl,
6079                                              OpVT, SrcOp)));
6080 }
6081
6082 /// areShuffleHalvesWithinDisjointLanes - Check whether each half of a vector
6083 /// shuffle node referes to only one lane in the sources.
6084 static bool areShuffleHalvesWithinDisjointLanes(ShuffleVectorSDNode *SVOp) {
6085   EVT VT = SVOp->getValueType(0);
6086   int NumElems = VT.getVectorNumElements();
6087   int HalfSize = NumElems/2;
6088   SmallVector<int, 16> M;
6089   SVOp->getMask(M);
6090   bool MatchA = false, MatchB = false;
6091
6092   for (int l = 0; l < NumElems*2; l += HalfSize) {
6093     if (isUndefOrInRange(M, 0, HalfSize, l, l+HalfSize)) {
6094       MatchA = true;
6095       break;
6096     }
6097   }
6098
6099   for (int l = 0; l < NumElems*2; l += HalfSize) {
6100     if (isUndefOrInRange(M, HalfSize, HalfSize, l, l+HalfSize)) {
6101       MatchB = true;
6102       break;
6103     }
6104   }
6105
6106   return MatchA && MatchB;
6107 }
6108
6109 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6110 /// which could not be matched by any known target speficic shuffle
6111 static SDValue
6112 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6113   if (areShuffleHalvesWithinDisjointLanes(SVOp)) {
6114     // If each half of a vector shuffle node referes to only one lane in the
6115     // source vectors, extract each used 128-bit lane and shuffle them using
6116     // 128-bit shuffles. Then, concatenate the results. Otherwise leave
6117     // the work to the legalizer.
6118     DebugLoc dl = SVOp->getDebugLoc();
6119     EVT VT = SVOp->getValueType(0);
6120     int NumElems = VT.getVectorNumElements();
6121     int HalfSize = NumElems/2;
6122
6123     // Extract the reference for each half
6124     int FstVecExtractIdx = 0, SndVecExtractIdx = 0;
6125     int FstVecOpNum = 0, SndVecOpNum = 0;
6126     for (int i = 0; i < HalfSize; ++i) {
6127       int Elt = SVOp->getMaskElt(i);
6128       if (SVOp->getMaskElt(i) < 0)
6129         continue;
6130       FstVecOpNum = Elt/NumElems;
6131       FstVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize;
6132       break;
6133     }
6134     for (int i = HalfSize; i < NumElems; ++i) {
6135       int Elt = SVOp->getMaskElt(i);
6136       if (SVOp->getMaskElt(i) < 0)
6137         continue;
6138       SndVecOpNum = Elt/NumElems;
6139       SndVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize;
6140       break;
6141     }
6142
6143     // Extract the subvectors
6144     SDValue V1 = Extract128BitVector(SVOp->getOperand(FstVecOpNum),
6145                       DAG.getConstant(FstVecExtractIdx, MVT::i32), DAG, dl);
6146     SDValue V2 = Extract128BitVector(SVOp->getOperand(SndVecOpNum),
6147                       DAG.getConstant(SndVecExtractIdx, MVT::i32), DAG, dl);
6148
6149     // Generate 128-bit shuffles
6150     SmallVector<int, 16> MaskV1, MaskV2;
6151     for (int i = 0; i < HalfSize; ++i) {
6152       int Elt = SVOp->getMaskElt(i);
6153       MaskV1.push_back(Elt < 0 ? Elt : Elt % HalfSize);
6154     }
6155     for (int i = HalfSize; i < NumElems; ++i) {
6156       int Elt = SVOp->getMaskElt(i);
6157       MaskV2.push_back(Elt < 0 ? Elt : Elt % HalfSize);
6158     }
6159
6160     EVT NVT = V1.getValueType();
6161     V1 = DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &MaskV1[0]);
6162     V2 = DAG.getVectorShuffle(NVT, dl, V2, DAG.getUNDEF(NVT), &MaskV2[0]);
6163
6164     // Concatenate the result back
6165     SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), V1,
6166                                    DAG.getConstant(0, MVT::i32), DAG, dl);
6167     return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32),
6168                               DAG, dl);
6169   }
6170
6171   return SDValue();
6172 }
6173
6174 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6175 /// 4 elements, and match them with several different shuffle types.
6176 static SDValue
6177 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6178   SDValue V1 = SVOp->getOperand(0);
6179   SDValue V2 = SVOp->getOperand(1);
6180   DebugLoc dl = SVOp->getDebugLoc();
6181   EVT VT = SVOp->getValueType(0);
6182
6183   assert(VT.getSizeInBits() == 128 && "Unsupported vector size");
6184
6185   SmallVector<std::pair<int, int>, 8> Locs;
6186   Locs.resize(4);
6187   SmallVector<int, 8> Mask1(4U, -1);
6188   SmallVector<int, 8> PermMask;
6189   SVOp->getMask(PermMask);
6190
6191   unsigned NumHi = 0;
6192   unsigned NumLo = 0;
6193   for (unsigned i = 0; i != 4; ++i) {
6194     int Idx = PermMask[i];
6195     if (Idx < 0) {
6196       Locs[i] = std::make_pair(-1, -1);
6197     } else {
6198       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6199       if (Idx < 4) {
6200         Locs[i] = std::make_pair(0, NumLo);
6201         Mask1[NumLo] = Idx;
6202         NumLo++;
6203       } else {
6204         Locs[i] = std::make_pair(1, NumHi);
6205         if (2+NumHi < 4)
6206           Mask1[2+NumHi] = Idx;
6207         NumHi++;
6208       }
6209     }
6210   }
6211
6212   if (NumLo <= 2 && NumHi <= 2) {
6213     // If no more than two elements come from either vector. This can be
6214     // implemented with two shuffles. First shuffle gather the elements.
6215     // The second shuffle, which takes the first shuffle as both of its
6216     // vector operands, put the elements into the right order.
6217     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6218
6219     SmallVector<int, 8> Mask2(4U, -1);
6220
6221     for (unsigned i = 0; i != 4; ++i) {
6222       if (Locs[i].first == -1)
6223         continue;
6224       else {
6225         unsigned Idx = (i < 2) ? 0 : 4;
6226         Idx += Locs[i].first * 2 + Locs[i].second;
6227         Mask2[i] = Idx;
6228       }
6229     }
6230
6231     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6232   } else if (NumLo == 3 || NumHi == 3) {
6233     // Otherwise, we must have three elements from one vector, call it X, and
6234     // one element from the other, call it Y.  First, use a shufps to build an
6235     // intermediate vector with the one element from Y and the element from X
6236     // that will be in the same half in the final destination (the indexes don't
6237     // matter). Then, use a shufps to build the final vector, taking the half
6238     // containing the element from Y from the intermediate, and the other half
6239     // from X.
6240     if (NumHi == 3) {
6241       // Normalize it so the 3 elements come from V1.
6242       CommuteVectorShuffleMask(PermMask, VT);
6243       std::swap(V1, V2);
6244     }
6245
6246     // Find the element from V2.
6247     unsigned HiIndex;
6248     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6249       int Val = PermMask[HiIndex];
6250       if (Val < 0)
6251         continue;
6252       if (Val >= 4)
6253         break;
6254     }
6255
6256     Mask1[0] = PermMask[HiIndex];
6257     Mask1[1] = -1;
6258     Mask1[2] = PermMask[HiIndex^1];
6259     Mask1[3] = -1;
6260     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6261
6262     if (HiIndex >= 2) {
6263       Mask1[0] = PermMask[0];
6264       Mask1[1] = PermMask[1];
6265       Mask1[2] = HiIndex & 1 ? 6 : 4;
6266       Mask1[3] = HiIndex & 1 ? 4 : 6;
6267       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6268     } else {
6269       Mask1[0] = HiIndex & 1 ? 2 : 0;
6270       Mask1[1] = HiIndex & 1 ? 0 : 2;
6271       Mask1[2] = PermMask[2];
6272       Mask1[3] = PermMask[3];
6273       if (Mask1[2] >= 0)
6274         Mask1[2] += 4;
6275       if (Mask1[3] >= 0)
6276         Mask1[3] += 4;
6277       return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6278     }
6279   }
6280
6281   // Break it into (shuffle shuffle_hi, shuffle_lo).
6282   Locs.clear();
6283   Locs.resize(4);
6284   SmallVector<int,8> LoMask(4U, -1);
6285   SmallVector<int,8> HiMask(4U, -1);
6286
6287   SmallVector<int,8> *MaskPtr = &LoMask;
6288   unsigned MaskIdx = 0;
6289   unsigned LoIdx = 0;
6290   unsigned HiIdx = 2;
6291   for (unsigned i = 0; i != 4; ++i) {
6292     if (i == 2) {
6293       MaskPtr = &HiMask;
6294       MaskIdx = 1;
6295       LoIdx = 0;
6296       HiIdx = 2;
6297     }
6298     int Idx = PermMask[i];
6299     if (Idx < 0) {
6300       Locs[i] = std::make_pair(-1, -1);
6301     } else if (Idx < 4) {
6302       Locs[i] = std::make_pair(MaskIdx, LoIdx);
6303       (*MaskPtr)[LoIdx] = Idx;
6304       LoIdx++;
6305     } else {
6306       Locs[i] = std::make_pair(MaskIdx, HiIdx);
6307       (*MaskPtr)[HiIdx] = Idx;
6308       HiIdx++;
6309     }
6310   }
6311
6312   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6313   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6314   SmallVector<int, 8> MaskOps;
6315   for (unsigned i = 0; i != 4; ++i) {
6316     if (Locs[i].first == -1) {
6317       MaskOps.push_back(-1);
6318     } else {
6319       unsigned Idx = Locs[i].first * 4 + Locs[i].second;
6320       MaskOps.push_back(Idx);
6321     }
6322   }
6323   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6324 }
6325
6326 static bool MayFoldVectorLoad(SDValue V) {
6327   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6328     V = V.getOperand(0);
6329   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6330     V = V.getOperand(0);
6331   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6332       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6333     // BUILD_VECTOR (load), undef
6334     V = V.getOperand(0);
6335   if (MayFoldLoad(V))
6336     return true;
6337   return false;
6338 }
6339
6340 // FIXME: the version above should always be used. Since there's
6341 // a bug where several vector shuffles can't be folded because the
6342 // DAG is not updated during lowering and a node claims to have two
6343 // uses while it only has one, use this version, and let isel match
6344 // another instruction if the load really happens to have more than
6345 // one use. Remove this version after this bug get fixed.
6346 // rdar://8434668, PR8156
6347 static bool RelaxedMayFoldVectorLoad(SDValue V) {
6348   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6349     V = V.getOperand(0);
6350   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6351     V = V.getOperand(0);
6352   if (ISD::isNormalLoad(V.getNode()))
6353     return true;
6354   return false;
6355 }
6356
6357 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
6358 /// a vector extract, and if both can be later optimized into a single load.
6359 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
6360 /// here because otherwise a target specific shuffle node is going to be
6361 /// emitted for this shuffle, and the optimization not done.
6362 /// FIXME: This is probably not the best approach, but fix the problem
6363 /// until the right path is decided.
6364 static
6365 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
6366                                          const TargetLowering &TLI) {
6367   EVT VT = V.getValueType();
6368   ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
6369
6370   // Be sure that the vector shuffle is present in a pattern like this:
6371   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
6372   if (!V.hasOneUse())
6373     return false;
6374
6375   SDNode *N = *V.getNode()->use_begin();
6376   if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
6377     return false;
6378
6379   SDValue EltNo = N->getOperand(1);
6380   if (!isa<ConstantSDNode>(EltNo))
6381     return false;
6382
6383   // If the bit convert changed the number of elements, it is unsafe
6384   // to examine the mask.
6385   bool HasShuffleIntoBitcast = false;
6386   if (V.getOpcode() == ISD::BITCAST) {
6387     EVT SrcVT = V.getOperand(0).getValueType();
6388     if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
6389       return false;
6390     V = V.getOperand(0);
6391     HasShuffleIntoBitcast = true;
6392   }
6393
6394   // Select the input vector, guarding against out of range extract vector.
6395   unsigned NumElems = VT.getVectorNumElements();
6396   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6397   int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
6398   V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
6399
6400   // Skip one more bit_convert if necessary
6401   if (V.getOpcode() == ISD::BITCAST)
6402     V = V.getOperand(0);
6403
6404   if (ISD::isNormalLoad(V.getNode())) {
6405     // Is the original load suitable?
6406     LoadSDNode *LN0 = cast<LoadSDNode>(V);
6407
6408     // FIXME: avoid the multi-use bug that is preventing lots of
6409     // of foldings to be detected, this is still wrong of course, but
6410     // give the temporary desired behavior, and if it happens that
6411     // the load has real more uses, during isel it will not fold, and
6412     // will generate poor code.
6413     if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
6414       return false;
6415
6416     if (!HasShuffleIntoBitcast)
6417       return true;
6418
6419     // If there's a bitcast before the shuffle, check if the load type and
6420     // alignment is valid.
6421     unsigned Align = LN0->getAlignment();
6422     unsigned NewAlign =
6423       TLI.getTargetData()->getABITypeAlignment(
6424                                     VT.getTypeForEVT(*DAG.getContext()));
6425
6426     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
6427       return false;
6428   }
6429
6430   return true;
6431 }
6432
6433 static
6434 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6435   EVT VT = Op.getValueType();
6436
6437   // Canonizalize to v2f64.
6438   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6439   return DAG.getNode(ISD::BITCAST, dl, VT,
6440                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6441                                           V1, DAG));
6442 }
6443
6444 static
6445 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6446                         bool HasXMMInt) {
6447   SDValue V1 = Op.getOperand(0);
6448   SDValue V2 = Op.getOperand(1);
6449   EVT VT = Op.getValueType();
6450
6451   assert(VT != MVT::v2i64 && "unsupported shuffle type");
6452
6453   if (HasXMMInt && VT == MVT::v2f64)
6454     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6455
6456   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6457   return DAG.getNode(ISD::BITCAST, dl, VT,
6458                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6459                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6460                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6461 }
6462
6463 static
6464 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6465   SDValue V1 = Op.getOperand(0);
6466   SDValue V2 = Op.getOperand(1);
6467   EVT VT = Op.getValueType();
6468
6469   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6470          "unsupported shuffle type");
6471
6472   if (V2.getOpcode() == ISD::UNDEF)
6473     V2 = V1;
6474
6475   // v4i32 or v4f32
6476   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6477 }
6478
6479 static inline unsigned getSHUFPOpcode(EVT VT) {
6480   switch(VT.getSimpleVT().SimpleTy) {
6481   case MVT::v8i32: // Use fp unit for int unpack.
6482   case MVT::v8f32:
6483   case MVT::v4i32: // Use fp unit for int unpack.
6484   case MVT::v4f32: return X86ISD::SHUFPS;
6485   case MVT::v4i64: // Use fp unit for int unpack.
6486   case MVT::v4f64:
6487   case MVT::v2i64: // Use fp unit for int unpack.
6488   case MVT::v2f64: return X86ISD::SHUFPD;
6489   default:
6490     llvm_unreachable("Unknown type for shufp*");
6491   }
6492   return 0;
6493 }
6494
6495 static
6496 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasXMMInt) {
6497   SDValue V1 = Op.getOperand(0);
6498   SDValue V2 = Op.getOperand(1);
6499   EVT VT = Op.getValueType();
6500   unsigned NumElems = VT.getVectorNumElements();
6501
6502   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6503   // operand of these instructions is only memory, so check if there's a
6504   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6505   // same masks.
6506   bool CanFoldLoad = false;
6507
6508   // Trivial case, when V2 comes from a load.
6509   if (MayFoldVectorLoad(V2))
6510     CanFoldLoad = true;
6511
6512   // When V1 is a load, it can be folded later into a store in isel, example:
6513   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6514   //    turns into:
6515   //  (MOVLPSmr addr:$src1, VR128:$src2)
6516   // So, recognize this potential and also use MOVLPS or MOVLPD
6517   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6518     CanFoldLoad = true;
6519
6520   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6521   if (CanFoldLoad) {
6522     if (HasXMMInt && NumElems == 2)
6523       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6524
6525     if (NumElems == 4)
6526       // If we don't care about the second element, procede to use movss.
6527       if (SVOp->getMaskElt(1) != -1)
6528         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6529   }
6530
6531   // movl and movlp will both match v2i64, but v2i64 is never matched by
6532   // movl earlier because we make it strict to avoid messing with the movlp load
6533   // folding logic (see the code above getMOVLP call). Match it here then,
6534   // this is horrible, but will stay like this until we move all shuffle
6535   // matching to x86 specific nodes. Note that for the 1st condition all
6536   // types are matched with movsd.
6537   if (HasXMMInt) {
6538     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6539     // as to remove this logic from here, as much as possible
6540     if (NumElems == 2 || !X86::isMOVLMask(SVOp))
6541       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6542     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6543   }
6544
6545   assert(VT != MVT::v4i32 && "unsupported shuffle type");
6546
6547   // Invert the operand order and use SHUFPS to match it.
6548   return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V2, V1,
6549                               X86::getShuffleSHUFImmediate(SVOp), DAG);
6550 }
6551
6552 static inline unsigned getUNPCKLOpcode(EVT VT) {
6553   switch(VT.getSimpleVT().SimpleTy) {
6554   case MVT::v4i32: return X86ISD::PUNPCKLDQ;
6555   case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
6556   case MVT::v4f32: return X86ISD::UNPCKLPS;
6557   case MVT::v2f64: return X86ISD::UNPCKLPD;
6558   case MVT::v8i32: // Use fp unit for int unpack.
6559   case MVT::v8f32: return X86ISD::VUNPCKLPSY;
6560   case MVT::v4i64: // Use fp unit for int unpack.
6561   case MVT::v4f64: return X86ISD::VUNPCKLPDY;
6562   case MVT::v16i8: return X86ISD::PUNPCKLBW;
6563   case MVT::v8i16: return X86ISD::PUNPCKLWD;
6564   default:
6565     llvm_unreachable("Unknown type for unpckl");
6566   }
6567   return 0;
6568 }
6569
6570 static inline unsigned getUNPCKHOpcode(EVT VT) {
6571   switch(VT.getSimpleVT().SimpleTy) {
6572   case MVT::v4i32: return X86ISD::PUNPCKHDQ;
6573   case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
6574   case MVT::v4f32: return X86ISD::UNPCKHPS;
6575   case MVT::v2f64: return X86ISD::UNPCKHPD;
6576   case MVT::v8i32: // Use fp unit for int unpack.
6577   case MVT::v8f32: return X86ISD::VUNPCKHPSY;
6578   case MVT::v4i64: // Use fp unit for int unpack.
6579   case MVT::v4f64: return X86ISD::VUNPCKHPDY;
6580   case MVT::v16i8: return X86ISD::PUNPCKHBW;
6581   case MVT::v8i16: return X86ISD::PUNPCKHWD;
6582   default:
6583     llvm_unreachable("Unknown type for unpckh");
6584   }
6585   return 0;
6586 }
6587
6588 static inline unsigned getVPERMILOpcode(EVT VT) {
6589   switch(VT.getSimpleVT().SimpleTy) {
6590   case MVT::v4i32:
6591   case MVT::v4f32: return X86ISD::VPERMILPS;
6592   case MVT::v2i64:
6593   case MVT::v2f64: return X86ISD::VPERMILPD;
6594   case MVT::v8i32:
6595   case MVT::v8f32: return X86ISD::VPERMILPSY;
6596   case MVT::v4i64:
6597   case MVT::v4f64: return X86ISD::VPERMILPDY;
6598   default:
6599     llvm_unreachable("Unknown type for vpermil");
6600   }
6601   return 0;
6602 }
6603
6604 static
6605 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
6606                                const TargetLowering &TLI,
6607                                const X86Subtarget *Subtarget) {
6608   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6609   EVT VT = Op.getValueType();
6610   DebugLoc dl = Op.getDebugLoc();
6611   SDValue V1 = Op.getOperand(0);
6612   SDValue V2 = Op.getOperand(1);
6613
6614   if (isZeroShuffle(SVOp))
6615     return getZeroVector(VT, Subtarget->hasXMMInt(), DAG, dl);
6616
6617   // Handle splat operations
6618   if (SVOp->isSplat()) {
6619     unsigned NumElem = VT.getVectorNumElements();
6620     int Size = VT.getSizeInBits();
6621     // Special case, this is the only place now where it's allowed to return
6622     // a vector_shuffle operation without using a target specific node, because
6623     // *hopefully* it will be optimized away by the dag combiner. FIXME: should
6624     // this be moved to DAGCombine instead?
6625     if (NumElem <= 4 && CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
6626       return Op;
6627
6628     // Use vbroadcast whenever the splat comes from a foldable load
6629     SDValue LD = isVectorBroadcast(Op, Subtarget->hasAVX2());
6630     if (Subtarget->hasAVX() && LD.getNode())
6631       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, LD);
6632
6633     // Handle splats by matching through known shuffle masks
6634     if ((Size == 128 && NumElem <= 4) ||
6635         (Size == 256 && NumElem < 8))
6636       return SDValue();
6637
6638     // All remaning splats are promoted to target supported vector shuffles.
6639     return PromoteSplat(SVOp, DAG);
6640   }
6641
6642   // If the shuffle can be profitably rewritten as a narrower shuffle, then
6643   // do it!
6644   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
6645     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6646     if (NewOp.getNode())
6647       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6648   } else if ((VT == MVT::v4i32 ||
6649              (VT == MVT::v4f32 && Subtarget->hasXMMInt()))) {
6650     // FIXME: Figure out a cleaner way to do this.
6651     // Try to make use of movq to zero out the top part.
6652     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6653       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6654       if (NewOp.getNode()) {
6655         if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
6656           return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
6657                               DAG, Subtarget, dl);
6658       }
6659     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6660       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6661       if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
6662         return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
6663                             DAG, Subtarget, dl);
6664     }
6665   }
6666   return SDValue();
6667 }
6668
6669 SDValue
6670 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6671   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6672   SDValue V1 = Op.getOperand(0);
6673   SDValue V2 = Op.getOperand(1);
6674   EVT VT = Op.getValueType();
6675   DebugLoc dl = Op.getDebugLoc();
6676   unsigned NumElems = VT.getVectorNumElements();
6677   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6678   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6679   bool V1IsSplat = false;
6680   bool V2IsSplat = false;
6681   bool HasXMMInt = Subtarget->hasXMMInt();
6682   MachineFunction &MF = DAG.getMachineFunction();
6683   bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
6684
6685   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6686
6687   // Vector shuffle lowering takes 3 steps:
6688   //
6689   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6690   //    narrowing and commutation of operands should be handled.
6691   // 2) Matching of shuffles with known shuffle masks to x86 target specific
6692   //    shuffle nodes.
6693   // 3) Rewriting of unmatched masks into new generic shuffle operations,
6694   //    so the shuffle can be broken into other shuffles and the legalizer can
6695   //    try the lowering again.
6696   //
6697   // The general idea is that no vector_shuffle operation should be left to
6698   // be matched during isel, all of them must be converted to a target specific
6699   // node here.
6700
6701   // Normalize the input vectors. Here splats, zeroed vectors, profitable
6702   // narrowing and commutation of operands should be handled. The actual code
6703   // doesn't include all of those, work in progress...
6704   SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
6705   if (NewOp.getNode())
6706     return NewOp;
6707
6708   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6709   // unpckh_undef). Only use pshufd if speed is more important than size.
6710   if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
6711     return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
6712   if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
6713     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
6714
6715   if (X86::isMOVDDUPMask(SVOp) &&
6716       (Subtarget->hasSSE3() || Subtarget->hasAVX()) &&
6717       V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6718     return getMOVDDup(Op, dl, V1, DAG);
6719
6720   if (X86::isMOVHLPS_v_undef_Mask(SVOp))
6721     return getMOVHighToLow(Op, dl, DAG);
6722
6723   // Use to match splats
6724   if (HasXMMInt && X86::isUNPCKHMask(SVOp) && V2IsUndef &&
6725       (VT == MVT::v2f64 || VT == MVT::v2i64))
6726     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
6727
6728   if (X86::isPSHUFDMask(SVOp)) {
6729     // The actual implementation will match the mask in the if above and then
6730     // during isel it can match several different instructions, not only pshufd
6731     // as its name says, sad but true, emulate the behavior for now...
6732     if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6733         return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6734
6735     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
6736
6737     if (HasXMMInt && (VT == MVT::v4f32 || VT == MVT::v4i32))
6738       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6739
6740     return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V1,
6741                                 TargetMask, DAG);
6742   }
6743
6744   // Check if this can be converted into a logical shift.
6745   bool isLeft = false;
6746   unsigned ShAmt = 0;
6747   SDValue ShVal;
6748   bool isShift = getSubtarget()->hasXMMInt() &&
6749                  isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6750   if (isShift && ShVal.hasOneUse()) {
6751     // If the shifted value has multiple uses, it may be cheaper to use
6752     // v_set0 + movlhps or movhlps, etc.
6753     EVT EltVT = VT.getVectorElementType();
6754     ShAmt *= EltVT.getSizeInBits();
6755     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6756   }
6757
6758   if (X86::isMOVLMask(SVOp)) {
6759     if (V1IsUndef)
6760       return V2;
6761     if (ISD::isBuildVectorAllZeros(V1.getNode()))
6762       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6763     if (!X86::isMOVLPMask(SVOp)) {
6764       if (HasXMMInt && (VT == MVT::v2i64 || VT == MVT::v2f64))
6765         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6766
6767       if (VT == MVT::v4i32 || VT == MVT::v4f32)
6768         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6769     }
6770   }
6771
6772   // FIXME: fold these into legal mask.
6773   if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp))
6774     return getMOVLowToHigh(Op, dl, DAG, HasXMMInt);
6775
6776   if (X86::isMOVHLPSMask(SVOp))
6777     return getMOVHighToLow(Op, dl, DAG);
6778
6779   if (X86::isMOVSHDUPMask(SVOp, Subtarget))
6780     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6781
6782   if (X86::isMOVSLDUPMask(SVOp, Subtarget))
6783     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6784
6785   if (X86::isMOVLPMask(SVOp))
6786     return getMOVLP(Op, dl, DAG, HasXMMInt);
6787
6788   if (ShouldXformToMOVHLPS(SVOp) ||
6789       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
6790     return CommuteVectorShuffle(SVOp, DAG);
6791
6792   if (isShift) {
6793     // No better options. Use a vshl / vsrl.
6794     EVT EltVT = VT.getVectorElementType();
6795     ShAmt *= EltVT.getSizeInBits();
6796     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6797   }
6798
6799   bool Commuted = false;
6800   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
6801   // 1,1,1,1 -> v8i16 though.
6802   V1IsSplat = isSplatVector(V1.getNode());
6803   V2IsSplat = isSplatVector(V2.getNode());
6804
6805   // Canonicalize the splat or undef, if present, to be on the RHS.
6806   if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
6807     Op = CommuteVectorShuffle(SVOp, DAG);
6808     SVOp = cast<ShuffleVectorSDNode>(Op);
6809     V1 = SVOp->getOperand(0);
6810     V2 = SVOp->getOperand(1);
6811     std::swap(V1IsSplat, V2IsSplat);
6812     std::swap(V1IsUndef, V2IsUndef);
6813     Commuted = true;
6814   }
6815
6816   if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
6817     // Shuffling low element of v1 into undef, just return v1.
6818     if (V2IsUndef)
6819       return V1;
6820     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6821     // the instruction selector will not match, so get a canonical MOVL with
6822     // swapped operands to undo the commute.
6823     return getMOVL(DAG, dl, VT, V2, V1);
6824   }
6825
6826   if (X86::isUNPCKLMask(SVOp))
6827     return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V2, DAG);
6828
6829   if (X86::isUNPCKHMask(SVOp))
6830     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG);
6831
6832   if (V2IsSplat) {
6833     // Normalize mask so all entries that point to V2 points to its first
6834     // element then try to match unpck{h|l} again. If match, return a
6835     // new vector_shuffle with the corrected mask.
6836     SDValue NewMask = NormalizeMask(SVOp, DAG);
6837     ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
6838     if (NSVOp != SVOp) {
6839       if (X86::isUNPCKLMask(NSVOp, true)) {
6840         return NewMask;
6841       } else if (X86::isUNPCKHMask(NSVOp, true)) {
6842         return NewMask;
6843       }
6844     }
6845   }
6846
6847   if (Commuted) {
6848     // Commute is back and try unpck* again.
6849     // FIXME: this seems wrong.
6850     SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
6851     ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
6852
6853     if (X86::isUNPCKLMask(NewSVOp))
6854       return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V2, V1, DAG);
6855
6856     if (X86::isUNPCKHMask(NewSVOp))
6857       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG);
6858   }
6859
6860   // Normalize the node to match x86 shuffle ops if needed
6861   if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
6862     return CommuteVectorShuffle(SVOp, DAG);
6863
6864   // The checks below are all present in isShuffleMaskLegal, but they are
6865   // inlined here right now to enable us to directly emit target specific
6866   // nodes, and remove one by one until they don't return Op anymore.
6867   SmallVector<int, 16> M;
6868   SVOp->getMask(M);
6869
6870   if (isPALIGNRMask(M, VT, Subtarget->hasSSSE3() || Subtarget->hasAVX()))
6871     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6872                                 X86::getShufflePALIGNRImmediate(SVOp),
6873                                 DAG);
6874
6875   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6876       SVOp->getSplatIndex() == 0 && V2IsUndef) {
6877     if (VT == MVT::v2f64)
6878       return getTargetShuffleNode(X86ISD::UNPCKLPD, dl, VT, V1, V1, DAG);
6879     if (VT == MVT::v2i64)
6880       return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
6881   }
6882
6883   if (isPSHUFHWMask(M, VT))
6884     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6885                                 X86::getShufflePSHUFHWImmediate(SVOp),
6886                                 DAG);
6887
6888   if (isPSHUFLWMask(M, VT))
6889     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6890                                 X86::getShufflePSHUFLWImmediate(SVOp),
6891                                 DAG);
6892
6893   if (isSHUFPMask(M, VT))
6894     return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6895                                 X86::getShuffleSHUFImmediate(SVOp), DAG);
6896
6897   if (X86::isUNPCKL_v_undef_Mask(SVOp))
6898     return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
6899   if (X86::isUNPCKH_v_undef_Mask(SVOp))
6900     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
6901
6902   //===--------------------------------------------------------------------===//
6903   // Generate target specific nodes for 128 or 256-bit shuffles only
6904   // supported in the AVX instruction set.
6905   //
6906
6907   // Handle VMOVDDUPY permutations
6908   if (isMOVDDUPYMask(SVOp, Subtarget))
6909     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6910
6911   // Handle VPERMILPS* permutations
6912   if (isVPERMILPSMask(M, VT, Subtarget))
6913     return getTargetShuffleNode(getVPERMILOpcode(VT), dl, VT, V1,
6914                                 getShuffleVPERMILPSImmediate(SVOp), DAG);
6915
6916   // Handle VPERMILPD* permutations
6917   if (isVPERMILPDMask(M, VT, Subtarget))
6918     return getTargetShuffleNode(getVPERMILOpcode(VT), dl, VT, V1,
6919                                 getShuffleVPERMILPDImmediate(SVOp), DAG);
6920
6921   // Handle VPERM2F128 permutations
6922   if (isVPERM2F128Mask(M, VT, Subtarget))
6923     return getTargetShuffleNode(X86ISD::VPERM2F128, dl, VT, V1, V2,
6924                                 getShuffleVPERM2F128Immediate(SVOp), DAG);
6925
6926   // Handle VSHUFPSY permutations
6927   if (isVSHUFPSYMask(M, VT, Subtarget))
6928     return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6929                                 getShuffleVSHUFPSYImmediate(SVOp), DAG);
6930
6931   // Handle VSHUFPDY permutations
6932   if (isVSHUFPDYMask(M, VT, Subtarget))
6933     return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6934                                 getShuffleVSHUFPDYImmediate(SVOp), DAG);
6935
6936   //===--------------------------------------------------------------------===//
6937   // Since no target specific shuffle was selected for this generic one,
6938   // lower it into other known shuffles. FIXME: this isn't true yet, but
6939   // this is the plan.
6940   //
6941
6942   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6943   if (VT == MVT::v8i16) {
6944     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
6945     if (NewOp.getNode())
6946       return NewOp;
6947   }
6948
6949   if (VT == MVT::v16i8) {
6950     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6951     if (NewOp.getNode())
6952       return NewOp;
6953   }
6954
6955   // Handle all 128-bit wide vectors with 4 elements, and match them with
6956   // several different shuffle types.
6957   if (NumElems == 4 && VT.getSizeInBits() == 128)
6958     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6959
6960   // Handle general 256-bit shuffles
6961   if (VT.is256BitVector())
6962     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6963
6964   return SDValue();
6965 }
6966
6967 SDValue
6968 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6969                                                 SelectionDAG &DAG) const {
6970   EVT VT = Op.getValueType();
6971   DebugLoc dl = Op.getDebugLoc();
6972
6973   if (Op.getOperand(0).getValueType().getSizeInBits() != 128)
6974     return SDValue();
6975
6976   if (VT.getSizeInBits() == 8) {
6977     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6978                                     Op.getOperand(0), Op.getOperand(1));
6979     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6980                                     DAG.getValueType(VT));
6981     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6982   } else if (VT.getSizeInBits() == 16) {
6983     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6984     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6985     if (Idx == 0)
6986       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6987                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6988                                      DAG.getNode(ISD::BITCAST, dl,
6989                                                  MVT::v4i32,
6990                                                  Op.getOperand(0)),
6991                                      Op.getOperand(1)));
6992     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6993                                     Op.getOperand(0), Op.getOperand(1));
6994     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6995                                     DAG.getValueType(VT));
6996     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6997   } else if (VT == MVT::f32) {
6998     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6999     // the result back to FR32 register. It's only worth matching if the
7000     // result has a single use which is a store or a bitcast to i32.  And in
7001     // the case of a store, it's not worth it if the index is a constant 0,
7002     // because a MOVSSmr can be used instead, which is smaller and faster.
7003     if (!Op.hasOneUse())
7004       return SDValue();
7005     SDNode *User = *Op.getNode()->use_begin();
7006     if ((User->getOpcode() != ISD::STORE ||
7007          (isa<ConstantSDNode>(Op.getOperand(1)) &&
7008           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7009         (User->getOpcode() != ISD::BITCAST ||
7010          User->getValueType(0) != MVT::i32))
7011       return SDValue();
7012     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7013                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7014                                               Op.getOperand(0)),
7015                                               Op.getOperand(1));
7016     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7017   } else if (VT == MVT::i32 || VT == MVT::i64) {
7018     // ExtractPS/pextrq works with constant index.
7019     if (isa<ConstantSDNode>(Op.getOperand(1)))
7020       return Op;
7021   }
7022   return SDValue();
7023 }
7024
7025
7026 SDValue
7027 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7028                                            SelectionDAG &DAG) const {
7029   if (!isa<ConstantSDNode>(Op.getOperand(1)))
7030     return SDValue();
7031
7032   SDValue Vec = Op.getOperand(0);
7033   EVT VecVT = Vec.getValueType();
7034
7035   // If this is a 256-bit vector result, first extract the 128-bit vector and
7036   // then extract the element from the 128-bit vector.
7037   if (VecVT.getSizeInBits() == 256) {
7038     DebugLoc dl = Op.getNode()->getDebugLoc();
7039     unsigned NumElems = VecVT.getVectorNumElements();
7040     SDValue Idx = Op.getOperand(1);
7041     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7042
7043     // Get the 128-bit vector.
7044     bool Upper = IdxVal >= NumElems/2;
7045     Vec = Extract128BitVector(Vec,
7046                     DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32), DAG, dl);
7047
7048     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7049                     Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : Idx);
7050   }
7051
7052   assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
7053
7054   if (Subtarget->hasSSE41() || Subtarget->hasAVX()) {
7055     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7056     if (Res.getNode())
7057       return Res;
7058   }
7059
7060   EVT VT = Op.getValueType();
7061   DebugLoc dl = Op.getDebugLoc();
7062   // TODO: handle v16i8.
7063   if (VT.getSizeInBits() == 16) {
7064     SDValue Vec = Op.getOperand(0);
7065     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7066     if (Idx == 0)
7067       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7068                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7069                                      DAG.getNode(ISD::BITCAST, dl,
7070                                                  MVT::v4i32, Vec),
7071                                      Op.getOperand(1)));
7072     // Transform it so it match pextrw which produces a 32-bit result.
7073     EVT EltVT = MVT::i32;
7074     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7075                                     Op.getOperand(0), Op.getOperand(1));
7076     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7077                                     DAG.getValueType(VT));
7078     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7079   } else if (VT.getSizeInBits() == 32) {
7080     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7081     if (Idx == 0)
7082       return Op;
7083
7084     // SHUFPS the element to the lowest double word, then movss.
7085     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7086     EVT VVT = Op.getOperand(0).getValueType();
7087     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7088                                        DAG.getUNDEF(VVT), Mask);
7089     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7090                        DAG.getIntPtrConstant(0));
7091   } else if (VT.getSizeInBits() == 64) {
7092     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7093     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7094     //        to match extract_elt for f64.
7095     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7096     if (Idx == 0)
7097       return Op;
7098
7099     // UNPCKHPD the element to the lowest double word, then movsd.
7100     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7101     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7102     int Mask[2] = { 1, -1 };
7103     EVT VVT = Op.getOperand(0).getValueType();
7104     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7105                                        DAG.getUNDEF(VVT), Mask);
7106     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7107                        DAG.getIntPtrConstant(0));
7108   }
7109
7110   return SDValue();
7111 }
7112
7113 SDValue
7114 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
7115                                                SelectionDAG &DAG) const {
7116   EVT VT = Op.getValueType();
7117   EVT EltVT = VT.getVectorElementType();
7118   DebugLoc dl = Op.getDebugLoc();
7119
7120   SDValue N0 = Op.getOperand(0);
7121   SDValue N1 = Op.getOperand(1);
7122   SDValue N2 = Op.getOperand(2);
7123
7124   if (VT.getSizeInBits() == 256)
7125     return SDValue();
7126
7127   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7128       isa<ConstantSDNode>(N2)) {
7129     unsigned Opc;
7130     if (VT == MVT::v8i16)
7131       Opc = X86ISD::PINSRW;
7132     else if (VT == MVT::v16i8)
7133       Opc = X86ISD::PINSRB;
7134     else
7135       Opc = X86ISD::PINSRB;
7136
7137     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7138     // argument.
7139     if (N1.getValueType() != MVT::i32)
7140       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7141     if (N2.getValueType() != MVT::i32)
7142       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7143     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7144   } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7145     // Bits [7:6] of the constant are the source select.  This will always be
7146     //  zero here.  The DAG Combiner may combine an extract_elt index into these
7147     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
7148     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
7149     // Bits [5:4] of the constant are the destination select.  This is the
7150     //  value of the incoming immediate.
7151     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
7152     //   combine either bitwise AND or insert of float 0.0 to set these bits.
7153     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7154     // Create this as a scalar to vector..
7155     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7156     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7157   } else if ((EltVT == MVT::i32 || EltVT == MVT::i64) && 
7158              isa<ConstantSDNode>(N2)) {
7159     // PINSR* works with constant index.
7160     return Op;
7161   }
7162   return SDValue();
7163 }
7164
7165 SDValue
7166 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7167   EVT VT = Op.getValueType();
7168   EVT EltVT = VT.getVectorElementType();
7169
7170   DebugLoc dl = Op.getDebugLoc();
7171   SDValue N0 = Op.getOperand(0);
7172   SDValue N1 = Op.getOperand(1);
7173   SDValue N2 = Op.getOperand(2);
7174
7175   // If this is a 256-bit vector result, first extract the 128-bit vector,
7176   // insert the element into the extracted half and then place it back.
7177   if (VT.getSizeInBits() == 256) {
7178     if (!isa<ConstantSDNode>(N2))
7179       return SDValue();
7180
7181     // Get the desired 128-bit vector half.
7182     unsigned NumElems = VT.getVectorNumElements();
7183     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7184     bool Upper = IdxVal >= NumElems/2;
7185     SDValue Ins128Idx = DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32);
7186     SDValue V = Extract128BitVector(N0, Ins128Idx, DAG, dl);
7187
7188     // Insert the element into the desired half.
7189     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V,
7190                  N1, Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : N2);
7191
7192     // Insert the changed part back to the 256-bit vector
7193     return Insert128BitVector(N0, V, Ins128Idx, DAG, dl);
7194   }
7195
7196   if (Subtarget->hasSSE41() || Subtarget->hasAVX())
7197     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7198
7199   if (EltVT == MVT::i8)
7200     return SDValue();
7201
7202   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7203     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7204     // as its second argument.
7205     if (N1.getValueType() != MVT::i32)
7206       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7207     if (N2.getValueType() != MVT::i32)
7208       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7209     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7210   }
7211   return SDValue();
7212 }
7213
7214 SDValue
7215 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
7216   LLVMContext *Context = DAG.getContext();
7217   DebugLoc dl = Op.getDebugLoc();
7218   EVT OpVT = Op.getValueType();
7219
7220   // If this is a 256-bit vector result, first insert into a 128-bit
7221   // vector and then insert into the 256-bit vector.
7222   if (OpVT.getSizeInBits() > 128) {
7223     // Insert into a 128-bit vector.
7224     EVT VT128 = EVT::getVectorVT(*Context,
7225                                  OpVT.getVectorElementType(),
7226                                  OpVT.getVectorNumElements() / 2);
7227
7228     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7229
7230     // Insert the 128-bit vector.
7231     return Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, OpVT), Op,
7232                               DAG.getConstant(0, MVT::i32),
7233                               DAG, dl);
7234   }
7235
7236   if (Op.getValueType() == MVT::v1i64 &&
7237       Op.getOperand(0).getValueType() == MVT::i64)
7238     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7239
7240   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7241   assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
7242          "Expected an SSE type!");
7243   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
7244                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7245 }
7246
7247 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7248 // a simple subregister reference or explicit instructions to grab
7249 // upper bits of a vector.
7250 SDValue
7251 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7252   if (Subtarget->hasAVX()) {
7253     DebugLoc dl = Op.getNode()->getDebugLoc();
7254     SDValue Vec = Op.getNode()->getOperand(0);
7255     SDValue Idx = Op.getNode()->getOperand(1);
7256
7257     if (Op.getNode()->getValueType(0).getSizeInBits() == 128
7258         && Vec.getNode()->getValueType(0).getSizeInBits() == 256) {
7259         return Extract128BitVector(Vec, Idx, DAG, dl);
7260     }
7261   }
7262   return SDValue();
7263 }
7264
7265 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7266 // simple superregister reference or explicit instructions to insert
7267 // the upper bits of a vector.
7268 SDValue
7269 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7270   if (Subtarget->hasAVX()) {
7271     DebugLoc dl = Op.getNode()->getDebugLoc();
7272     SDValue Vec = Op.getNode()->getOperand(0);
7273     SDValue SubVec = Op.getNode()->getOperand(1);
7274     SDValue Idx = Op.getNode()->getOperand(2);
7275
7276     if (Op.getNode()->getValueType(0).getSizeInBits() == 256
7277         && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) {
7278       return Insert128BitVector(Vec, SubVec, Idx, DAG, dl);
7279     }
7280   }
7281   return SDValue();
7282 }
7283
7284 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7285 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7286 // one of the above mentioned nodes. It has to be wrapped because otherwise
7287 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7288 // be used to form addressing mode. These wrapped nodes will be selected
7289 // into MOV32ri.
7290 SDValue
7291 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7292   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7293
7294   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7295   // global base reg.
7296   unsigned char OpFlag = 0;
7297   unsigned WrapperKind = X86ISD::Wrapper;
7298   CodeModel::Model M = getTargetMachine().getCodeModel();
7299
7300   if (Subtarget->isPICStyleRIPRel() &&
7301       (M == CodeModel::Small || M == CodeModel::Kernel))
7302     WrapperKind = X86ISD::WrapperRIP;
7303   else if (Subtarget->isPICStyleGOT())
7304     OpFlag = X86II::MO_GOTOFF;
7305   else if (Subtarget->isPICStyleStubPIC())
7306     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7307
7308   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7309                                              CP->getAlignment(),
7310                                              CP->getOffset(), OpFlag);
7311   DebugLoc DL = CP->getDebugLoc();
7312   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7313   // With PIC, the address is actually $g + Offset.
7314   if (OpFlag) {
7315     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7316                          DAG.getNode(X86ISD::GlobalBaseReg,
7317                                      DebugLoc(), getPointerTy()),
7318                          Result);
7319   }
7320
7321   return Result;
7322 }
7323
7324 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7325   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7326
7327   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7328   // global base reg.
7329   unsigned char OpFlag = 0;
7330   unsigned WrapperKind = X86ISD::Wrapper;
7331   CodeModel::Model M = getTargetMachine().getCodeModel();
7332
7333   if (Subtarget->isPICStyleRIPRel() &&
7334       (M == CodeModel::Small || M == CodeModel::Kernel))
7335     WrapperKind = X86ISD::WrapperRIP;
7336   else if (Subtarget->isPICStyleGOT())
7337     OpFlag = X86II::MO_GOTOFF;
7338   else if (Subtarget->isPICStyleStubPIC())
7339     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7340
7341   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7342                                           OpFlag);
7343   DebugLoc DL = JT->getDebugLoc();
7344   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7345
7346   // With PIC, the address is actually $g + Offset.
7347   if (OpFlag)
7348     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7349                          DAG.getNode(X86ISD::GlobalBaseReg,
7350                                      DebugLoc(), getPointerTy()),
7351                          Result);
7352
7353   return Result;
7354 }
7355
7356 SDValue
7357 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7358   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7359
7360   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7361   // global base reg.
7362   unsigned char OpFlag = 0;
7363   unsigned WrapperKind = X86ISD::Wrapper;
7364   CodeModel::Model M = getTargetMachine().getCodeModel();
7365
7366   if (Subtarget->isPICStyleRIPRel() &&
7367       (M == CodeModel::Small || M == CodeModel::Kernel)) {
7368     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7369       OpFlag = X86II::MO_GOTPCREL;
7370     WrapperKind = X86ISD::WrapperRIP;
7371   } else if (Subtarget->isPICStyleGOT()) {
7372     OpFlag = X86II::MO_GOT;
7373   } else if (Subtarget->isPICStyleStubPIC()) {
7374     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7375   } else if (Subtarget->isPICStyleStubNoDynamic()) {
7376     OpFlag = X86II::MO_DARWIN_NONLAZY;
7377   }
7378
7379   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7380
7381   DebugLoc DL = Op.getDebugLoc();
7382   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7383
7384
7385   // With PIC, the address is actually $g + Offset.
7386   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7387       !Subtarget->is64Bit()) {
7388     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7389                          DAG.getNode(X86ISD::GlobalBaseReg,
7390                                      DebugLoc(), getPointerTy()),
7391                          Result);
7392   }
7393
7394   // For symbols that require a load from a stub to get the address, emit the
7395   // load.
7396   if (isGlobalStubReference(OpFlag))
7397     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7398                          MachinePointerInfo::getGOT(), false, false, false, 0);
7399
7400   return Result;
7401 }
7402
7403 SDValue
7404 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7405   // Create the TargetBlockAddressAddress node.
7406   unsigned char OpFlags =
7407     Subtarget->ClassifyBlockAddressReference();
7408   CodeModel::Model M = getTargetMachine().getCodeModel();
7409   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7410   DebugLoc dl = Op.getDebugLoc();
7411   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
7412                                        /*isTarget=*/true, OpFlags);
7413
7414   if (Subtarget->isPICStyleRIPRel() &&
7415       (M == CodeModel::Small || M == CodeModel::Kernel))
7416     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7417   else
7418     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7419
7420   // With PIC, the address is actually $g + Offset.
7421   if (isGlobalRelativeToPICBase(OpFlags)) {
7422     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7423                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7424                          Result);
7425   }
7426
7427   return Result;
7428 }
7429
7430 SDValue
7431 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7432                                       int64_t Offset,
7433                                       SelectionDAG &DAG) const {
7434   // Create the TargetGlobalAddress node, folding in the constant
7435   // offset if it is legal.
7436   unsigned char OpFlags =
7437     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7438   CodeModel::Model M = getTargetMachine().getCodeModel();
7439   SDValue Result;
7440   if (OpFlags == X86II::MO_NO_FLAG &&
7441       X86::isOffsetSuitableForCodeModel(Offset, M)) {
7442     // A direct static reference to a global.
7443     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7444     Offset = 0;
7445   } else {
7446     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7447   }
7448
7449   if (Subtarget->isPICStyleRIPRel() &&
7450       (M == CodeModel::Small || M == CodeModel::Kernel))
7451     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7452   else
7453     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7454
7455   // With PIC, the address is actually $g + Offset.
7456   if (isGlobalRelativeToPICBase(OpFlags)) {
7457     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7458                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7459                          Result);
7460   }
7461
7462   // For globals that require a load from a stub to get the address, emit the
7463   // load.
7464   if (isGlobalStubReference(OpFlags))
7465     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7466                          MachinePointerInfo::getGOT(), false, false, false, 0);
7467
7468   // If there was a non-zero offset that we didn't fold, create an explicit
7469   // addition for it.
7470   if (Offset != 0)
7471     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7472                          DAG.getConstant(Offset, getPointerTy()));
7473
7474   return Result;
7475 }
7476
7477 SDValue
7478 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7479   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7480   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7481   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7482 }
7483
7484 static SDValue
7485 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7486            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7487            unsigned char OperandFlags) {
7488   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7489   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7490   DebugLoc dl = GA->getDebugLoc();
7491   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7492                                            GA->getValueType(0),
7493                                            GA->getOffset(),
7494                                            OperandFlags);
7495   if (InFlag) {
7496     SDValue Ops[] = { Chain,  TGA, *InFlag };
7497     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
7498   } else {
7499     SDValue Ops[]  = { Chain, TGA };
7500     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
7501   }
7502
7503   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7504   MFI->setAdjustsStack(true);
7505
7506   SDValue Flag = Chain.getValue(1);
7507   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7508 }
7509
7510 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7511 static SDValue
7512 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7513                                 const EVT PtrVT) {
7514   SDValue InFlag;
7515   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
7516   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7517                                      DAG.getNode(X86ISD::GlobalBaseReg,
7518                                                  DebugLoc(), PtrVT), InFlag);
7519   InFlag = Chain.getValue(1);
7520
7521   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7522 }
7523
7524 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7525 static SDValue
7526 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7527                                 const EVT PtrVT) {
7528   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7529                     X86::RAX, X86II::MO_TLSGD);
7530 }
7531
7532 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
7533 // "local exec" model.
7534 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7535                                    const EVT PtrVT, TLSModel::Model model,
7536                                    bool is64Bit) {
7537   DebugLoc dl = GA->getDebugLoc();
7538
7539   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7540   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7541                                                          is64Bit ? 257 : 256));
7542
7543   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7544                                       DAG.getIntPtrConstant(0),
7545                                       MachinePointerInfo(Ptr),
7546                                       false, false, false, 0);
7547
7548   unsigned char OperandFlags = 0;
7549   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
7550   // initialexec.
7551   unsigned WrapperKind = X86ISD::Wrapper;
7552   if (model == TLSModel::LocalExec) {
7553     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7554   } else if (is64Bit) {
7555     assert(model == TLSModel::InitialExec);
7556     OperandFlags = X86II::MO_GOTTPOFF;
7557     WrapperKind = X86ISD::WrapperRIP;
7558   } else {
7559     assert(model == TLSModel::InitialExec);
7560     OperandFlags = X86II::MO_INDNTPOFF;
7561   }
7562
7563   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
7564   // exec)
7565   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7566                                            GA->getValueType(0),
7567                                            GA->getOffset(), OperandFlags);
7568   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7569
7570   if (model == TLSModel::InitialExec)
7571     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7572                          MachinePointerInfo::getGOT(), false, false, false, 0);
7573
7574   // The address of the thread local variable is the add of the thread
7575   // pointer with the offset of the variable.
7576   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7577 }
7578
7579 SDValue
7580 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7581
7582   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7583   const GlobalValue *GV = GA->getGlobal();
7584
7585   if (Subtarget->isTargetELF()) {
7586     // TODO: implement the "local dynamic" model
7587     // TODO: implement the "initial exec"model for pic executables
7588
7589     // If GV is an alias then use the aliasee for determining
7590     // thread-localness.
7591     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7592       GV = GA->resolveAliasedGlobal(false);
7593
7594     TLSModel::Model model
7595       = getTLSModel(GV, getTargetMachine().getRelocationModel());
7596
7597     switch (model) {
7598       case TLSModel::GeneralDynamic:
7599       case TLSModel::LocalDynamic: // not implemented
7600         if (Subtarget->is64Bit())
7601           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7602         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7603
7604       case TLSModel::InitialExec:
7605       case TLSModel::LocalExec:
7606         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7607                                    Subtarget->is64Bit());
7608     }
7609   } else if (Subtarget->isTargetDarwin()) {
7610     // Darwin only has one model of TLS.  Lower to that.
7611     unsigned char OpFlag = 0;
7612     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7613                            X86ISD::WrapperRIP : X86ISD::Wrapper;
7614
7615     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7616     // global base reg.
7617     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7618                   !Subtarget->is64Bit();
7619     if (PIC32)
7620       OpFlag = X86II::MO_TLVP_PIC_BASE;
7621     else
7622       OpFlag = X86II::MO_TLVP;
7623     DebugLoc DL = Op.getDebugLoc();
7624     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7625                                                 GA->getValueType(0),
7626                                                 GA->getOffset(), OpFlag);
7627     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7628
7629     // With PIC32, the address is actually $g + Offset.
7630     if (PIC32)
7631       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7632                            DAG.getNode(X86ISD::GlobalBaseReg,
7633                                        DebugLoc(), getPointerTy()),
7634                            Offset);
7635
7636     // Lowering the machine isd will make sure everything is in the right
7637     // location.
7638     SDValue Chain = DAG.getEntryNode();
7639     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7640     SDValue Args[] = { Chain, Offset };
7641     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7642
7643     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7644     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7645     MFI->setAdjustsStack(true);
7646
7647     // And our return value (tls address) is in the standard call return value
7648     // location.
7649     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7650     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7651                               Chain.getValue(1));
7652   }
7653
7654   assert(false &&
7655          "TLS not implemented for this target.");
7656
7657   llvm_unreachable("Unreachable");
7658   return SDValue();
7659 }
7660
7661
7662 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values and
7663 /// take a 2 x i32 value to shift plus a shift amount.
7664 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const {
7665   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7666   EVT VT = Op.getValueType();
7667   unsigned VTBits = VT.getSizeInBits();
7668   DebugLoc dl = Op.getDebugLoc();
7669   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7670   SDValue ShOpLo = Op.getOperand(0);
7671   SDValue ShOpHi = Op.getOperand(1);
7672   SDValue ShAmt  = Op.getOperand(2);
7673   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7674                                      DAG.getConstant(VTBits - 1, MVT::i8))
7675                        : DAG.getConstant(0, VT);
7676
7677   SDValue Tmp2, Tmp3;
7678   if (Op.getOpcode() == ISD::SHL_PARTS) {
7679     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7680     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7681   } else {
7682     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7683     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7684   }
7685
7686   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7687                                 DAG.getConstant(VTBits, MVT::i8));
7688   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7689                              AndNode, DAG.getConstant(0, MVT::i8));
7690
7691   SDValue Hi, Lo;
7692   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7693   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7694   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7695
7696   if (Op.getOpcode() == ISD::SHL_PARTS) {
7697     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7698     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7699   } else {
7700     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7701     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7702   }
7703
7704   SDValue Ops[2] = { Lo, Hi };
7705   return DAG.getMergeValues(Ops, 2, dl);
7706 }
7707
7708 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7709                                            SelectionDAG &DAG) const {
7710   EVT SrcVT = Op.getOperand(0).getValueType();
7711
7712   if (SrcVT.isVector())
7713     return SDValue();
7714
7715   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7716          "Unknown SINT_TO_FP to lower!");
7717
7718   // These are really Legal; return the operand so the caller accepts it as
7719   // Legal.
7720   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7721     return Op;
7722   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7723       Subtarget->is64Bit()) {
7724     return Op;
7725   }
7726
7727   DebugLoc dl = Op.getDebugLoc();
7728   unsigned Size = SrcVT.getSizeInBits()/8;
7729   MachineFunction &MF = DAG.getMachineFunction();
7730   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7731   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7732   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7733                                StackSlot,
7734                                MachinePointerInfo::getFixedStack(SSFI),
7735                                false, false, 0);
7736   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7737 }
7738
7739 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7740                                      SDValue StackSlot,
7741                                      SelectionDAG &DAG) const {
7742   // Build the FILD
7743   DebugLoc DL = Op.getDebugLoc();
7744   SDVTList Tys;
7745   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7746   if (useSSE)
7747     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7748   else
7749     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7750
7751   unsigned ByteSize = SrcVT.getSizeInBits()/8;
7752
7753   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7754   MachineMemOperand *MMO;
7755   if (FI) {
7756     int SSFI = FI->getIndex();
7757     MMO =
7758       DAG.getMachineFunction()
7759       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7760                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
7761   } else {
7762     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7763     StackSlot = StackSlot.getOperand(1);
7764   }
7765   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7766   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7767                                            X86ISD::FILD, DL,
7768                                            Tys, Ops, array_lengthof(Ops),
7769                                            SrcVT, MMO);
7770
7771   if (useSSE) {
7772     Chain = Result.getValue(1);
7773     SDValue InFlag = Result.getValue(2);
7774
7775     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7776     // shouldn't be necessary except that RFP cannot be live across
7777     // multiple blocks. When stackifier is fixed, they can be uncoupled.
7778     MachineFunction &MF = DAG.getMachineFunction();
7779     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7780     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7781     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7782     Tys = DAG.getVTList(MVT::Other);
7783     SDValue Ops[] = {
7784       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7785     };
7786     MachineMemOperand *MMO =
7787       DAG.getMachineFunction()
7788       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7789                             MachineMemOperand::MOStore, SSFISize, SSFISize);
7790
7791     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7792                                     Ops, array_lengthof(Ops),
7793                                     Op.getValueType(), MMO);
7794     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7795                          MachinePointerInfo::getFixedStack(SSFI),
7796                          false, false, false, 0);
7797   }
7798
7799   return Result;
7800 }
7801
7802 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7803 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7804                                                SelectionDAG &DAG) const {
7805   // This algorithm is not obvious. Here it is in C code, more or less:
7806   /*
7807     double uint64_to_double( uint32_t hi, uint32_t lo ) {
7808       static const __m128i exp = { 0x4330000045300000ULL, 0 };
7809       static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
7810
7811       // Copy ints to xmm registers.
7812       __m128i xh = _mm_cvtsi32_si128( hi );
7813       __m128i xl = _mm_cvtsi32_si128( lo );
7814
7815       // Combine into low half of a single xmm register.
7816       __m128i x = _mm_unpacklo_epi32( xh, xl );
7817       __m128d d;
7818       double sd;
7819
7820       // Merge in appropriate exponents to give the integer bits the right
7821       // magnitude.
7822       x = _mm_unpacklo_epi32( x, exp );
7823
7824       // Subtract away the biases to deal with the IEEE-754 double precision
7825       // implicit 1.
7826       d = _mm_sub_pd( (__m128d) x, bias );
7827
7828       // All conversions up to here are exact. The correctly rounded result is
7829       // calculated using the current rounding mode using the following
7830       // horizontal add.
7831       d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
7832       _mm_store_sd( &sd, d );   // Because we are returning doubles in XMM, this
7833                                 // store doesn't really need to be here (except
7834                                 // maybe to zero the other double)
7835       return sd;
7836     }
7837   */
7838
7839   DebugLoc dl = Op.getDebugLoc();
7840   LLVMContext *Context = DAG.getContext();
7841
7842   // Build some magic constants.
7843   std::vector<Constant*> CV0;
7844   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
7845   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
7846   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7847   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7848   Constant *C0 = ConstantVector::get(CV0);
7849   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7850
7851   std::vector<Constant*> CV1;
7852   CV1.push_back(
7853     ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7854   CV1.push_back(
7855     ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7856   Constant *C1 = ConstantVector::get(CV1);
7857   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7858
7859   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7860                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7861                                         Op.getOperand(0),
7862                                         DAG.getIntPtrConstant(1)));
7863   SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7864                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7865                                         Op.getOperand(0),
7866                                         DAG.getIntPtrConstant(0)));
7867   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
7868   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7869                               MachinePointerInfo::getConstantPool(),
7870                               false, false, false, 16);
7871   SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
7872   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
7873   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7874                               MachinePointerInfo::getConstantPool(),
7875                               false, false, false, 16);
7876   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7877
7878   // Add the halves; easiest way is to swap them into another reg first.
7879   int ShufMask[2] = { 1, -1 };
7880   SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
7881                                       DAG.getUNDEF(MVT::v2f64), ShufMask);
7882   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
7883   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
7884                      DAG.getIntPtrConstant(0));
7885 }
7886
7887 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7888 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7889                                                SelectionDAG &DAG) const {
7890   DebugLoc dl = Op.getDebugLoc();
7891   // FP constant to bias correct the final result.
7892   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7893                                    MVT::f64);
7894
7895   // Load the 32-bit value into an XMM register.
7896   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7897                              Op.getOperand(0));
7898
7899   // Zero out the upper parts of the register.
7900   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget->hasXMMInt(),
7901                                      DAG);
7902
7903   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7904                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7905                      DAG.getIntPtrConstant(0));
7906
7907   // Or the load with the bias.
7908   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7909                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7910                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7911                                                    MVT::v2f64, Load)),
7912                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7913                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7914                                                    MVT::v2f64, Bias)));
7915   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7916                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7917                    DAG.getIntPtrConstant(0));
7918
7919   // Subtract the bias.
7920   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7921
7922   // Handle final rounding.
7923   EVT DestVT = Op.getValueType();
7924
7925   if (DestVT.bitsLT(MVT::f64)) {
7926     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7927                        DAG.getIntPtrConstant(0));
7928   } else if (DestVT.bitsGT(MVT::f64)) {
7929     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7930   }
7931
7932   // Handle final rounding.
7933   return Sub;
7934 }
7935
7936 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7937                                            SelectionDAG &DAG) const {
7938   SDValue N0 = Op.getOperand(0);
7939   DebugLoc dl = Op.getDebugLoc();
7940
7941   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
7942   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
7943   // the optimization here.
7944   if (DAG.SignBitIsZero(N0))
7945     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
7946
7947   EVT SrcVT = N0.getValueType();
7948   EVT DstVT = Op.getValueType();
7949   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
7950     return LowerUINT_TO_FP_i64(Op, DAG);
7951   else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
7952     return LowerUINT_TO_FP_i32(Op, DAG);
7953
7954   // Make a 64-bit buffer, and use it to build an FILD.
7955   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
7956   if (SrcVT == MVT::i32) {
7957     SDValue WordOff = DAG.getConstant(4, getPointerTy());
7958     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
7959                                      getPointerTy(), StackSlot, WordOff);
7960     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7961                                   StackSlot, MachinePointerInfo(),
7962                                   false, false, 0);
7963     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
7964                                   OffsetSlot, MachinePointerInfo(),
7965                                   false, false, 0);
7966     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
7967     return Fild;
7968   }
7969
7970   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
7971   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7972                                 StackSlot, MachinePointerInfo(),
7973                                false, false, 0);
7974   // For i64 source, we need to add the appropriate power of 2 if the input
7975   // was negative.  This is the same as the optimization in
7976   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
7977   // we must be careful to do the computation in x87 extended precision, not
7978   // in SSE. (The generic code can't know it's OK to do this, or how to.)
7979   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
7980   MachineMemOperand *MMO =
7981     DAG.getMachineFunction()
7982     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7983                           MachineMemOperand::MOLoad, 8, 8);
7984
7985   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
7986   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
7987   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
7988                                          MVT::i64, MMO);
7989
7990   APInt FF(32, 0x5F800000ULL);
7991
7992   // Check whether the sign bit is set.
7993   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
7994                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
7995                                  ISD::SETLT);
7996
7997   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
7998   SDValue FudgePtr = DAG.getConstantPool(
7999                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8000                                          getPointerTy());
8001
8002   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8003   SDValue Zero = DAG.getIntPtrConstant(0);
8004   SDValue Four = DAG.getIntPtrConstant(4);
8005   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8006                                Zero, Four);
8007   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8008
8009   // Load the value out, extending it from f32 to f80.
8010   // FIXME: Avoid the extend by constructing the right constant pool?
8011   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8012                                  FudgePtr, MachinePointerInfo::getConstantPool(),
8013                                  MVT::f32, false, false, 4);
8014   // Extend everything to 80 bits to force it to be done on x87.
8015   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8016   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8017 }
8018
8019 std::pair<SDValue,SDValue> X86TargetLowering::
8020 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
8021   DebugLoc DL = Op.getDebugLoc();
8022
8023   EVT DstTy = Op.getValueType();
8024
8025   if (!IsSigned) {
8026     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8027     DstTy = MVT::i64;
8028   }
8029
8030   assert(DstTy.getSimpleVT() <= MVT::i64 &&
8031          DstTy.getSimpleVT() >= MVT::i16 &&
8032          "Unknown FP_TO_SINT to lower!");
8033
8034   // These are really Legal.
8035   if (DstTy == MVT::i32 &&
8036       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8037     return std::make_pair(SDValue(), SDValue());
8038   if (Subtarget->is64Bit() &&
8039       DstTy == MVT::i64 &&
8040       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8041     return std::make_pair(SDValue(), SDValue());
8042
8043   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
8044   // stack slot.
8045   MachineFunction &MF = DAG.getMachineFunction();
8046   unsigned MemSize = DstTy.getSizeInBits()/8;
8047   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8048   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8049
8050
8051
8052   unsigned Opc;
8053   switch (DstTy.getSimpleVT().SimpleTy) {
8054   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8055   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8056   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8057   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8058   }
8059
8060   SDValue Chain = DAG.getEntryNode();
8061   SDValue Value = Op.getOperand(0);
8062   EVT TheVT = Op.getOperand(0).getValueType();
8063   if (isScalarFPTypeInSSEReg(TheVT)) {
8064     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8065     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8066                          MachinePointerInfo::getFixedStack(SSFI),
8067                          false, false, 0);
8068     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8069     SDValue Ops[] = {
8070       Chain, StackSlot, DAG.getValueType(TheVT)
8071     };
8072
8073     MachineMemOperand *MMO =
8074       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8075                               MachineMemOperand::MOLoad, MemSize, MemSize);
8076     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
8077                                     DstTy, MMO);
8078     Chain = Value.getValue(1);
8079     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8080     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8081   }
8082
8083   MachineMemOperand *MMO =
8084     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8085                             MachineMemOperand::MOStore, MemSize, MemSize);
8086
8087   // Build the FP_TO_INT*_IN_MEM
8088   SDValue Ops[] = { Chain, Value, StackSlot };
8089   SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8090                                          Ops, 3, DstTy, MMO);
8091
8092   return std::make_pair(FIST, StackSlot);
8093 }
8094
8095 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8096                                            SelectionDAG &DAG) const {
8097   if (Op.getValueType().isVector())
8098     return SDValue();
8099
8100   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
8101   SDValue FIST = Vals.first, StackSlot = Vals.second;
8102   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8103   if (FIST.getNode() == 0) return Op;
8104
8105   // Load the result.
8106   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8107                      FIST, StackSlot, MachinePointerInfo(),
8108                      false, false, false, 0);
8109 }
8110
8111 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8112                                            SelectionDAG &DAG) const {
8113   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
8114   SDValue FIST = Vals.first, StackSlot = Vals.second;
8115   assert(FIST.getNode() && "Unexpected failure");
8116
8117   // Load the result.
8118   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8119                      FIST, StackSlot, MachinePointerInfo(),
8120                      false, false, false, 0);
8121 }
8122
8123 SDValue X86TargetLowering::LowerFABS(SDValue Op,
8124                                      SelectionDAG &DAG) const {
8125   LLVMContext *Context = DAG.getContext();
8126   DebugLoc dl = Op.getDebugLoc();
8127   EVT VT = Op.getValueType();
8128   EVT EltVT = VT;
8129   if (VT.isVector())
8130     EltVT = VT.getVectorElementType();
8131   std::vector<Constant*> CV;
8132   if (EltVT == MVT::f64) {
8133     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
8134     CV.push_back(C);
8135     CV.push_back(C);
8136   } else {
8137     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
8138     CV.push_back(C);
8139     CV.push_back(C);
8140     CV.push_back(C);
8141     CV.push_back(C);
8142   }
8143   Constant *C = ConstantVector::get(CV);
8144   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8145   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8146                              MachinePointerInfo::getConstantPool(),
8147                              false, false, false, 16);
8148   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8149 }
8150
8151 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8152   LLVMContext *Context = DAG.getContext();
8153   DebugLoc dl = Op.getDebugLoc();
8154   EVT VT = Op.getValueType();
8155   EVT EltVT = VT;
8156   if (VT.isVector())
8157     EltVT = VT.getVectorElementType();
8158   std::vector<Constant*> CV;
8159   if (EltVT == MVT::f64) {
8160     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8161     CV.push_back(C);
8162     CV.push_back(C);
8163   } else {
8164     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8165     CV.push_back(C);
8166     CV.push_back(C);
8167     CV.push_back(C);
8168     CV.push_back(C);
8169   }
8170   Constant *C = ConstantVector::get(CV);
8171   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8172   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8173                              MachinePointerInfo::getConstantPool(),
8174                              false, false, false, 16);
8175   if (VT.isVector()) {
8176     return DAG.getNode(ISD::BITCAST, dl, VT,
8177                        DAG.getNode(ISD::XOR, dl, MVT::v2i64,
8178                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8179                                 Op.getOperand(0)),
8180                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask)));
8181   } else {
8182     return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8183   }
8184 }
8185
8186 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8187   LLVMContext *Context = DAG.getContext();
8188   SDValue Op0 = Op.getOperand(0);
8189   SDValue Op1 = Op.getOperand(1);
8190   DebugLoc dl = Op.getDebugLoc();
8191   EVT VT = Op.getValueType();
8192   EVT SrcVT = Op1.getValueType();
8193
8194   // If second operand is smaller, extend it first.
8195   if (SrcVT.bitsLT(VT)) {
8196     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8197     SrcVT = VT;
8198   }
8199   // And if it is bigger, shrink it first.
8200   if (SrcVT.bitsGT(VT)) {
8201     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8202     SrcVT = VT;
8203   }
8204
8205   // At this point the operands and the result should have the same
8206   // type, and that won't be f80 since that is not custom lowered.
8207
8208   // First get the sign bit of second operand.
8209   std::vector<Constant*> CV;
8210   if (SrcVT == MVT::f64) {
8211     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8212     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8213   } else {
8214     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8215     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8216     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8217     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8218   }
8219   Constant *C = ConstantVector::get(CV);
8220   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8221   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8222                               MachinePointerInfo::getConstantPool(),
8223                               false, false, false, 16);
8224   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8225
8226   // Shift sign bit right or left if the two operands have different types.
8227   if (SrcVT.bitsGT(VT)) {
8228     // Op0 is MVT::f32, Op1 is MVT::f64.
8229     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8230     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8231                           DAG.getConstant(32, MVT::i32));
8232     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8233     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8234                           DAG.getIntPtrConstant(0));
8235   }
8236
8237   // Clear first operand sign bit.
8238   CV.clear();
8239   if (VT == MVT::f64) {
8240     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8241     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8242   } else {
8243     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8244     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8245     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8246     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8247   }
8248   C = ConstantVector::get(CV);
8249   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8250   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8251                               MachinePointerInfo::getConstantPool(),
8252                               false, false, false, 16);
8253   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8254
8255   // Or the value with the sign bit.
8256   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8257 }
8258
8259 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
8260   SDValue N0 = Op.getOperand(0);
8261   DebugLoc dl = Op.getDebugLoc();
8262   EVT VT = Op.getValueType();
8263
8264   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8265   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8266                                   DAG.getConstant(1, VT));
8267   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8268 }
8269
8270 /// Emit nodes that will be selected as "test Op0,Op0", or something
8271 /// equivalent.
8272 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8273                                     SelectionDAG &DAG) const {
8274   DebugLoc dl = Op.getDebugLoc();
8275
8276   // CF and OF aren't always set the way we want. Determine which
8277   // of these we need.
8278   bool NeedCF = false;
8279   bool NeedOF = false;
8280   switch (X86CC) {
8281   default: break;
8282   case X86::COND_A: case X86::COND_AE:
8283   case X86::COND_B: case X86::COND_BE:
8284     NeedCF = true;
8285     break;
8286   case X86::COND_G: case X86::COND_GE:
8287   case X86::COND_L: case X86::COND_LE:
8288   case X86::COND_O: case X86::COND_NO:
8289     NeedOF = true;
8290     break;
8291   }
8292
8293   // See if we can use the EFLAGS value from the operand instead of
8294   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8295   // we prove that the arithmetic won't overflow, we can't use OF or CF.
8296   if (Op.getResNo() != 0 || NeedOF || NeedCF)
8297     // Emit a CMP with 0, which is the TEST pattern.
8298     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8299                        DAG.getConstant(0, Op.getValueType()));
8300
8301   unsigned Opcode = 0;
8302   unsigned NumOperands = 0;
8303   switch (Op.getNode()->getOpcode()) {
8304   case ISD::ADD:
8305     // Due to an isel shortcoming, be conservative if this add is likely to be
8306     // selected as part of a load-modify-store instruction. When the root node
8307     // in a match is a store, isel doesn't know how to remap non-chain non-flag
8308     // uses of other nodes in the match, such as the ADD in this case. This
8309     // leads to the ADD being left around and reselected, with the result being
8310     // two adds in the output.  Alas, even if none our users are stores, that
8311     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
8312     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
8313     // climbing the DAG back to the root, and it doesn't seem to be worth the
8314     // effort.
8315     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8316          UE = Op.getNode()->use_end(); UI != UE; ++UI)
8317       if (UI->getOpcode() != ISD::CopyToReg &&
8318           UI->getOpcode() != ISD::SETCC &&
8319           UI->getOpcode() != ISD::STORE)
8320         goto default_case;
8321
8322     if (ConstantSDNode *C =
8323         dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
8324       // An add of one will be selected as an INC.
8325       if (C->getAPIntValue() == 1) {
8326         Opcode = X86ISD::INC;
8327         NumOperands = 1;
8328         break;
8329       }
8330
8331       // An add of negative one (subtract of one) will be selected as a DEC.
8332       if (C->getAPIntValue().isAllOnesValue()) {
8333         Opcode = X86ISD::DEC;
8334         NumOperands = 1;
8335         break;
8336       }
8337     }
8338
8339     // Otherwise use a regular EFLAGS-setting add.
8340     Opcode = X86ISD::ADD;
8341     NumOperands = 2;
8342     break;
8343   case ISD::AND: {
8344     // If the primary and result isn't used, don't bother using X86ISD::AND,
8345     // because a TEST instruction will be better.
8346     bool NonFlagUse = false;
8347     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8348            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8349       SDNode *User = *UI;
8350       unsigned UOpNo = UI.getOperandNo();
8351       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8352         // Look pass truncate.
8353         UOpNo = User->use_begin().getOperandNo();
8354         User = *User->use_begin();
8355       }
8356
8357       if (User->getOpcode() != ISD::BRCOND &&
8358           User->getOpcode() != ISD::SETCC &&
8359           (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
8360         NonFlagUse = true;
8361         break;
8362       }
8363     }
8364
8365     if (!NonFlagUse)
8366       break;
8367   }
8368     // FALL THROUGH
8369   case ISD::SUB:
8370   case ISD::OR:
8371   case ISD::XOR:
8372     // Due to the ISEL shortcoming noted above, be conservative if this op is
8373     // likely to be selected as part of a load-modify-store instruction.
8374     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8375            UE = Op.getNode()->use_end(); UI != UE; ++UI)
8376       if (UI->getOpcode() == ISD::STORE)
8377         goto default_case;
8378
8379     // Otherwise use a regular EFLAGS-setting instruction.
8380     switch (Op.getNode()->getOpcode()) {
8381     default: llvm_unreachable("unexpected operator!");
8382     case ISD::SUB: Opcode = X86ISD::SUB; break;
8383     case ISD::OR:  Opcode = X86ISD::OR;  break;
8384     case ISD::XOR: Opcode = X86ISD::XOR; break;
8385     case ISD::AND: Opcode = X86ISD::AND; break;
8386     }
8387
8388     NumOperands = 2;
8389     break;
8390   case X86ISD::ADD:
8391   case X86ISD::SUB:
8392   case X86ISD::INC:
8393   case X86ISD::DEC:
8394   case X86ISD::OR:
8395   case X86ISD::XOR:
8396   case X86ISD::AND:
8397     return SDValue(Op.getNode(), 1);
8398   default:
8399   default_case:
8400     break;
8401   }
8402
8403   if (Opcode == 0)
8404     // Emit a CMP with 0, which is the TEST pattern.
8405     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8406                        DAG.getConstant(0, Op.getValueType()));
8407
8408   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8409   SmallVector<SDValue, 4> Ops;
8410   for (unsigned i = 0; i != NumOperands; ++i)
8411     Ops.push_back(Op.getOperand(i));
8412
8413   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8414   DAG.ReplaceAllUsesWith(Op, New);
8415   return SDValue(New.getNode(), 1);
8416 }
8417
8418 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8419 /// equivalent.
8420 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8421                                    SelectionDAG &DAG) const {
8422   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8423     if (C->getAPIntValue() == 0)
8424       return EmitTest(Op0, X86CC, DAG);
8425
8426   DebugLoc dl = Op0.getDebugLoc();
8427   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8428 }
8429
8430 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8431 /// if it's possible.
8432 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8433                                      DebugLoc dl, SelectionDAG &DAG) const {
8434   SDValue Op0 = And.getOperand(0);
8435   SDValue Op1 = And.getOperand(1);
8436   if (Op0.getOpcode() == ISD::TRUNCATE)
8437     Op0 = Op0.getOperand(0);
8438   if (Op1.getOpcode() == ISD::TRUNCATE)
8439     Op1 = Op1.getOperand(0);
8440
8441   SDValue LHS, RHS;
8442   if (Op1.getOpcode() == ISD::SHL)
8443     std::swap(Op0, Op1);
8444   if (Op0.getOpcode() == ISD::SHL) {
8445     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8446       if (And00C->getZExtValue() == 1) {
8447         // If we looked past a truncate, check that it's only truncating away
8448         // known zeros.
8449         unsigned BitWidth = Op0.getValueSizeInBits();
8450         unsigned AndBitWidth = And.getValueSizeInBits();
8451         if (BitWidth > AndBitWidth) {
8452           APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
8453           DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
8454           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8455             return SDValue();
8456         }
8457         LHS = Op1;
8458         RHS = Op0.getOperand(1);
8459       }
8460   } else if (Op1.getOpcode() == ISD::Constant) {
8461     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8462     SDValue AndLHS = Op0;
8463     if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
8464       LHS = AndLHS.getOperand(0);
8465       RHS = AndLHS.getOperand(1);
8466     }
8467   }
8468
8469   if (LHS.getNode()) {
8470     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
8471     // instruction.  Since the shift amount is in-range-or-undefined, we know
8472     // that doing a bittest on the i32 value is ok.  We extend to i32 because
8473     // the encoding for the i16 version is larger than the i32 version.
8474     // Also promote i16 to i32 for performance / code size reason.
8475     if (LHS.getValueType() == MVT::i8 ||
8476         LHS.getValueType() == MVT::i16)
8477       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8478
8479     // If the operand types disagree, extend the shift amount to match.  Since
8480     // BT ignores high bits (like shifts) we can use anyextend.
8481     if (LHS.getValueType() != RHS.getValueType())
8482       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8483
8484     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8485     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8486     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8487                        DAG.getConstant(Cond, MVT::i8), BT);
8488   }
8489
8490   return SDValue();
8491 }
8492
8493 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8494
8495   if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8496
8497   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8498   SDValue Op0 = Op.getOperand(0);
8499   SDValue Op1 = Op.getOperand(1);
8500   DebugLoc dl = Op.getDebugLoc();
8501   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8502
8503   // Optimize to BT if possible.
8504   // Lower (X & (1 << N)) == 0 to BT(X, N).
8505   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8506   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8507   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8508       Op1.getOpcode() == ISD::Constant &&
8509       cast<ConstantSDNode>(Op1)->isNullValue() &&
8510       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8511     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8512     if (NewSetCC.getNode())
8513       return NewSetCC;
8514   }
8515
8516   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
8517   // these.
8518   if (Op1.getOpcode() == ISD::Constant &&
8519       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8520        cast<ConstantSDNode>(Op1)->isNullValue()) &&
8521       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8522
8523     // If the input is a setcc, then reuse the input setcc or use a new one with
8524     // the inverted condition.
8525     if (Op0.getOpcode() == X86ISD::SETCC) {
8526       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8527       bool Invert = (CC == ISD::SETNE) ^
8528         cast<ConstantSDNode>(Op1)->isNullValue();
8529       if (!Invert) return Op0;
8530
8531       CCode = X86::GetOppositeBranchCondition(CCode);
8532       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8533                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8534     }
8535   }
8536
8537   bool isFP = Op1.getValueType().isFloatingPoint();
8538   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8539   if (X86CC == X86::COND_INVALID)
8540     return SDValue();
8541
8542   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8543   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8544                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8545 }
8546
8547 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8548 // ones, and then concatenate the result back.
8549 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
8550   EVT VT = Op.getValueType();
8551
8552   assert(VT.getSizeInBits() == 256 && Op.getOpcode() == ISD::SETCC &&
8553          "Unsupported value type for operation");
8554
8555   int NumElems = VT.getVectorNumElements();
8556   DebugLoc dl = Op.getDebugLoc();
8557   SDValue CC = Op.getOperand(2);
8558   SDValue Idx0 = DAG.getConstant(0, MVT::i32);
8559   SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
8560
8561   // Extract the LHS vectors
8562   SDValue LHS = Op.getOperand(0);
8563   SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
8564   SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
8565
8566   // Extract the RHS vectors
8567   SDValue RHS = Op.getOperand(1);
8568   SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl);
8569   SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl);
8570
8571   // Issue the operation on the smaller types and concatenate the result back
8572   MVT EltVT = VT.getVectorElementType().getSimpleVT();
8573   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8574   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8575                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8576                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8577 }
8578
8579
8580 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8581   SDValue Cond;
8582   SDValue Op0 = Op.getOperand(0);
8583   SDValue Op1 = Op.getOperand(1);
8584   SDValue CC = Op.getOperand(2);
8585   EVT VT = Op.getValueType();
8586   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8587   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8588   DebugLoc dl = Op.getDebugLoc();
8589
8590   if (isFP) {
8591     unsigned SSECC = 8;
8592     EVT EltVT = Op0.getValueType().getVectorElementType();
8593     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
8594
8595     unsigned Opc = EltVT == MVT::f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
8596     bool Swap = false;
8597
8598     // SSE Condition code mapping:
8599     //  0 - EQ
8600     //  1 - LT
8601     //  2 - LE
8602     //  3 - UNORD
8603     //  4 - NEQ
8604     //  5 - NLT
8605     //  6 - NLE
8606     //  7 - ORD
8607     switch (SetCCOpcode) {
8608     default: break;
8609     case ISD::SETOEQ:
8610     case ISD::SETEQ:  SSECC = 0; break;
8611     case ISD::SETOGT:
8612     case ISD::SETGT: Swap = true; // Fallthrough
8613     case ISD::SETLT:
8614     case ISD::SETOLT: SSECC = 1; break;
8615     case ISD::SETOGE:
8616     case ISD::SETGE: Swap = true; // Fallthrough
8617     case ISD::SETLE:
8618     case ISD::SETOLE: SSECC = 2; break;
8619     case ISD::SETUO:  SSECC = 3; break;
8620     case ISD::SETUNE:
8621     case ISD::SETNE:  SSECC = 4; break;
8622     case ISD::SETULE: Swap = true;
8623     case ISD::SETUGE: SSECC = 5; break;
8624     case ISD::SETULT: Swap = true;
8625     case ISD::SETUGT: SSECC = 6; break;
8626     case ISD::SETO:   SSECC = 7; break;
8627     }
8628     if (Swap)
8629       std::swap(Op0, Op1);
8630
8631     // In the two special cases we can't handle, emit two comparisons.
8632     if (SSECC == 8) {
8633       if (SetCCOpcode == ISD::SETUEQ) {
8634         SDValue UNORD, EQ;
8635         UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
8636         EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
8637         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
8638       } else if (SetCCOpcode == ISD::SETONE) {
8639         SDValue ORD, NEQ;
8640         ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
8641         NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
8642         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
8643       }
8644       llvm_unreachable("Illegal FP comparison");
8645     }
8646     // Handle all other FP comparisons here.
8647     return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
8648   }
8649
8650   // Break 256-bit integer vector compare into smaller ones.
8651   if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2())
8652     return Lower256IntVSETCC(Op, DAG);
8653
8654   // We are handling one of the integer comparisons here.  Since SSE only has
8655   // GT and EQ comparisons for integer, swapping operands and multiple
8656   // operations may be required for some comparisons.
8657   unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
8658   bool Swap = false, Invert = false, FlipSigns = false;
8659
8660   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
8661   default: break;
8662   case MVT::i8:   EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
8663   case MVT::i16:  EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
8664   case MVT::i32:  EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
8665   case MVT::i64:  EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
8666   }
8667
8668   switch (SetCCOpcode) {
8669   default: break;
8670   case ISD::SETNE:  Invert = true;
8671   case ISD::SETEQ:  Opc = EQOpc; break;
8672   case ISD::SETLT:  Swap = true;
8673   case ISD::SETGT:  Opc = GTOpc; break;
8674   case ISD::SETGE:  Swap = true;
8675   case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
8676   case ISD::SETULT: Swap = true;
8677   case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
8678   case ISD::SETUGE: Swap = true;
8679   case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
8680   }
8681   if (Swap)
8682     std::swap(Op0, Op1);
8683
8684   // Check that the operation in question is available (most are plain SSE2,
8685   // but PCMPGTQ and PCMPEQQ have different requirements).
8686   if (Opc == X86ISD::PCMPGTQ && !Subtarget->hasSSE42() && !Subtarget->hasAVX())
8687     return SDValue();
8688   if (Opc == X86ISD::PCMPEQQ && !Subtarget->hasSSE41() && !Subtarget->hasAVX())
8689     return SDValue();
8690
8691   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
8692   // bits of the inputs before performing those operations.
8693   if (FlipSigns) {
8694     EVT EltVT = VT.getVectorElementType();
8695     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
8696                                       EltVT);
8697     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
8698     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
8699                                     SignBits.size());
8700     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
8701     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
8702   }
8703
8704   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
8705
8706   // If the logical-not of the result is required, perform that now.
8707   if (Invert)
8708     Result = DAG.getNOT(dl, Result, VT);
8709
8710   return Result;
8711 }
8712
8713 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
8714 static bool isX86LogicalCmp(SDValue Op) {
8715   unsigned Opc = Op.getNode()->getOpcode();
8716   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
8717     return true;
8718   if (Op.getResNo() == 1 &&
8719       (Opc == X86ISD::ADD ||
8720        Opc == X86ISD::SUB ||
8721        Opc == X86ISD::ADC ||
8722        Opc == X86ISD::SBB ||
8723        Opc == X86ISD::SMUL ||
8724        Opc == X86ISD::UMUL ||
8725        Opc == X86ISD::INC ||
8726        Opc == X86ISD::DEC ||
8727        Opc == X86ISD::OR ||
8728        Opc == X86ISD::XOR ||
8729        Opc == X86ISD::AND))
8730     return true;
8731
8732   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
8733     return true;
8734
8735   return false;
8736 }
8737
8738 static bool isZero(SDValue V) {
8739   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8740   return C && C->isNullValue();
8741 }
8742
8743 static bool isAllOnes(SDValue V) {
8744   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8745   return C && C->isAllOnesValue();
8746 }
8747
8748 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8749   bool addTest = true;
8750   SDValue Cond  = Op.getOperand(0);
8751   SDValue Op1 = Op.getOperand(1);
8752   SDValue Op2 = Op.getOperand(2);
8753   DebugLoc DL = Op.getDebugLoc();
8754   SDValue CC;
8755
8756   if (Cond.getOpcode() == ISD::SETCC) {
8757     SDValue NewCond = LowerSETCC(Cond, DAG);
8758     if (NewCond.getNode())
8759       Cond = NewCond;
8760   }
8761
8762   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
8763   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
8764   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
8765   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
8766   if (Cond.getOpcode() == X86ISD::SETCC &&
8767       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
8768       isZero(Cond.getOperand(1).getOperand(1))) {
8769     SDValue Cmp = Cond.getOperand(1);
8770
8771     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
8772
8773     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
8774         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
8775       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
8776
8777       SDValue CmpOp0 = Cmp.getOperand(0);
8778       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
8779                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
8780
8781       SDValue Res =   // Res = 0 or -1.
8782         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8783                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
8784
8785       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
8786         Res = DAG.getNOT(DL, Res, Res.getValueType());
8787
8788       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
8789       if (N2C == 0 || !N2C->isNullValue())
8790         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
8791       return Res;
8792     }
8793   }
8794
8795   // Look past (and (setcc_carry (cmp ...)), 1).
8796   if (Cond.getOpcode() == ISD::AND &&
8797       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8798     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8799     if (C && C->getAPIntValue() == 1)
8800       Cond = Cond.getOperand(0);
8801   }
8802
8803   // If condition flag is set by a X86ISD::CMP, then use it as the condition
8804   // setting operand in place of the X86ISD::SETCC.
8805   unsigned CondOpcode = Cond.getOpcode();
8806   if (CondOpcode == X86ISD::SETCC ||
8807       CondOpcode == X86ISD::SETCC_CARRY) {
8808     CC = Cond.getOperand(0);
8809
8810     SDValue Cmp = Cond.getOperand(1);
8811     unsigned Opc = Cmp.getOpcode();
8812     EVT VT = Op.getValueType();
8813
8814     bool IllegalFPCMov = false;
8815     if (VT.isFloatingPoint() && !VT.isVector() &&
8816         !isScalarFPTypeInSSEReg(VT))  // FPStack?
8817       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
8818
8819     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
8820         Opc == X86ISD::BT) { // FIXME
8821       Cond = Cmp;
8822       addTest = false;
8823     }
8824   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
8825              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
8826              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
8827               Cond.getOperand(0).getValueType() != MVT::i8)) {
8828     SDValue LHS = Cond.getOperand(0);
8829     SDValue RHS = Cond.getOperand(1);
8830     unsigned X86Opcode;
8831     unsigned X86Cond;
8832     SDVTList VTs;
8833     switch (CondOpcode) {
8834     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
8835     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
8836     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
8837     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
8838     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
8839     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
8840     default: llvm_unreachable("unexpected overflowing operator");
8841     }
8842     if (CondOpcode == ISD::UMULO)
8843       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
8844                           MVT::i32);
8845     else
8846       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
8847
8848     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
8849
8850     if (CondOpcode == ISD::UMULO)
8851       Cond = X86Op.getValue(2);
8852     else
8853       Cond = X86Op.getValue(1);
8854
8855     CC = DAG.getConstant(X86Cond, MVT::i8);
8856     addTest = false;
8857   }
8858
8859   if (addTest) {
8860     // Look pass the truncate.
8861     if (Cond.getOpcode() == ISD::TRUNCATE)
8862       Cond = Cond.getOperand(0);
8863
8864     // We know the result of AND is compared against zero. Try to match
8865     // it to BT.
8866     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8867       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
8868       if (NewSetCC.getNode()) {
8869         CC = NewSetCC.getOperand(0);
8870         Cond = NewSetCC.getOperand(1);
8871         addTest = false;
8872       }
8873     }
8874   }
8875
8876   if (addTest) {
8877     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8878     Cond = EmitTest(Cond, X86::COND_NE, DAG);
8879   }
8880
8881   // a <  b ? -1 :  0 -> RES = ~setcc_carry
8882   // a <  b ?  0 : -1 -> RES = setcc_carry
8883   // a >= b ? -1 :  0 -> RES = setcc_carry
8884   // a >= b ?  0 : -1 -> RES = ~setcc_carry
8885   if (Cond.getOpcode() == X86ISD::CMP) {
8886     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
8887
8888     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
8889         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
8890       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8891                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
8892       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
8893         return DAG.getNOT(DL, Res, Res.getValueType());
8894       return Res;
8895     }
8896   }
8897
8898   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
8899   // condition is true.
8900   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
8901   SDValue Ops[] = { Op2, Op1, CC, Cond };
8902   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
8903 }
8904
8905 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
8906 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
8907 // from the AND / OR.
8908 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
8909   Opc = Op.getOpcode();
8910   if (Opc != ISD::OR && Opc != ISD::AND)
8911     return false;
8912   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8913           Op.getOperand(0).hasOneUse() &&
8914           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
8915           Op.getOperand(1).hasOneUse());
8916 }
8917
8918 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
8919 // 1 and that the SETCC node has a single use.
8920 static bool isXor1OfSetCC(SDValue Op) {
8921   if (Op.getOpcode() != ISD::XOR)
8922     return false;
8923   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8924   if (N1C && N1C->getAPIntValue() == 1) {
8925     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8926       Op.getOperand(0).hasOneUse();
8927   }
8928   return false;
8929 }
8930
8931 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
8932   bool addTest = true;
8933   SDValue Chain = Op.getOperand(0);
8934   SDValue Cond  = Op.getOperand(1);
8935   SDValue Dest  = Op.getOperand(2);
8936   DebugLoc dl = Op.getDebugLoc();
8937   SDValue CC;
8938   bool Inverted = false;
8939
8940   if (Cond.getOpcode() == ISD::SETCC) {
8941     // Check for setcc([su]{add,sub,mul}o == 0).
8942     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
8943         isa<ConstantSDNode>(Cond.getOperand(1)) &&
8944         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
8945         Cond.getOperand(0).getResNo() == 1 &&
8946         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
8947          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
8948          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
8949          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
8950          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
8951          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
8952       Inverted = true;
8953       Cond = Cond.getOperand(0);
8954     } else {
8955       SDValue NewCond = LowerSETCC(Cond, DAG);
8956       if (NewCond.getNode())
8957         Cond = NewCond;
8958     }
8959   }
8960 #if 0
8961   // FIXME: LowerXALUO doesn't handle these!!
8962   else if (Cond.getOpcode() == X86ISD::ADD  ||
8963            Cond.getOpcode() == X86ISD::SUB  ||
8964            Cond.getOpcode() == X86ISD::SMUL ||
8965            Cond.getOpcode() == X86ISD::UMUL)
8966     Cond = LowerXALUO(Cond, DAG);
8967 #endif
8968
8969   // Look pass (and (setcc_carry (cmp ...)), 1).
8970   if (Cond.getOpcode() == ISD::AND &&
8971       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8972     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8973     if (C && C->getAPIntValue() == 1)
8974       Cond = Cond.getOperand(0);
8975   }
8976
8977   // If condition flag is set by a X86ISD::CMP, then use it as the condition
8978   // setting operand in place of the X86ISD::SETCC.
8979   unsigned CondOpcode = Cond.getOpcode();
8980   if (CondOpcode == X86ISD::SETCC ||
8981       CondOpcode == X86ISD::SETCC_CARRY) {
8982     CC = Cond.getOperand(0);
8983
8984     SDValue Cmp = Cond.getOperand(1);
8985     unsigned Opc = Cmp.getOpcode();
8986     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
8987     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
8988       Cond = Cmp;
8989       addTest = false;
8990     } else {
8991       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
8992       default: break;
8993       case X86::COND_O:
8994       case X86::COND_B:
8995         // These can only come from an arithmetic instruction with overflow,
8996         // e.g. SADDO, UADDO.
8997         Cond = Cond.getNode()->getOperand(1);
8998         addTest = false;
8999         break;
9000       }
9001     }
9002   }
9003   CondOpcode = Cond.getOpcode();
9004   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9005       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9006       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9007        Cond.getOperand(0).getValueType() != MVT::i8)) {
9008     SDValue LHS = Cond.getOperand(0);
9009     SDValue RHS = Cond.getOperand(1);
9010     unsigned X86Opcode;
9011     unsigned X86Cond;
9012     SDVTList VTs;
9013     switch (CondOpcode) {
9014     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9015     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9016     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9017     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9018     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9019     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9020     default: llvm_unreachable("unexpected overflowing operator");
9021     }
9022     if (Inverted)
9023       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9024     if (CondOpcode == ISD::UMULO)
9025       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9026                           MVT::i32);
9027     else
9028       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9029
9030     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9031
9032     if (CondOpcode == ISD::UMULO)
9033       Cond = X86Op.getValue(2);
9034     else
9035       Cond = X86Op.getValue(1);
9036
9037     CC = DAG.getConstant(X86Cond, MVT::i8);
9038     addTest = false;
9039   } else {
9040     unsigned CondOpc;
9041     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9042       SDValue Cmp = Cond.getOperand(0).getOperand(1);
9043       if (CondOpc == ISD::OR) {
9044         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9045         // two branches instead of an explicit OR instruction with a
9046         // separate test.
9047         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9048             isX86LogicalCmp(Cmp)) {
9049           CC = Cond.getOperand(0).getOperand(0);
9050           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9051                               Chain, Dest, CC, Cmp);
9052           CC = Cond.getOperand(1).getOperand(0);
9053           Cond = Cmp;
9054           addTest = false;
9055         }
9056       } else { // ISD::AND
9057         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9058         // two branches instead of an explicit AND instruction with a
9059         // separate test. However, we only do this if this block doesn't
9060         // have a fall-through edge, because this requires an explicit
9061         // jmp when the condition is false.
9062         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9063             isX86LogicalCmp(Cmp) &&
9064             Op.getNode()->hasOneUse()) {
9065           X86::CondCode CCode =
9066             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9067           CCode = X86::GetOppositeBranchCondition(CCode);
9068           CC = DAG.getConstant(CCode, MVT::i8);
9069           SDNode *User = *Op.getNode()->use_begin();
9070           // Look for an unconditional branch following this conditional branch.
9071           // We need this because we need to reverse the successors in order
9072           // to implement FCMP_OEQ.
9073           if (User->getOpcode() == ISD::BR) {
9074             SDValue FalseBB = User->getOperand(1);
9075             SDNode *NewBR =
9076               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9077             assert(NewBR == User);
9078             (void)NewBR;
9079             Dest = FalseBB;
9080
9081             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9082                                 Chain, Dest, CC, Cmp);
9083             X86::CondCode CCode =
9084               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9085             CCode = X86::GetOppositeBranchCondition(CCode);
9086             CC = DAG.getConstant(CCode, MVT::i8);
9087             Cond = Cmp;
9088             addTest = false;
9089           }
9090         }
9091       }
9092     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9093       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9094       // It should be transformed during dag combiner except when the condition
9095       // is set by a arithmetics with overflow node.
9096       X86::CondCode CCode =
9097         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9098       CCode = X86::GetOppositeBranchCondition(CCode);
9099       CC = DAG.getConstant(CCode, MVT::i8);
9100       Cond = Cond.getOperand(0).getOperand(1);
9101       addTest = false;
9102     } else if (Cond.getOpcode() == ISD::SETCC &&
9103                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9104       // For FCMP_OEQ, we can emit
9105       // two branches instead of an explicit AND instruction with a
9106       // separate test. However, we only do this if this block doesn't
9107       // have a fall-through edge, because this requires an explicit
9108       // jmp when the condition is false.
9109       if (Op.getNode()->hasOneUse()) {
9110         SDNode *User = *Op.getNode()->use_begin();
9111         // Look for an unconditional branch following this conditional branch.
9112         // We need this because we need to reverse the successors in order
9113         // to implement FCMP_OEQ.
9114         if (User->getOpcode() == ISD::BR) {
9115           SDValue FalseBB = User->getOperand(1);
9116           SDNode *NewBR =
9117             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9118           assert(NewBR == User);
9119           (void)NewBR;
9120           Dest = FalseBB;
9121
9122           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9123                                     Cond.getOperand(0), Cond.getOperand(1));
9124           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9125           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9126                               Chain, Dest, CC, Cmp);
9127           CC = DAG.getConstant(X86::COND_P, MVT::i8);
9128           Cond = Cmp;
9129           addTest = false;
9130         }
9131       }
9132     } else if (Cond.getOpcode() == ISD::SETCC &&
9133                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9134       // For FCMP_UNE, we can emit
9135       // two branches instead of an explicit AND instruction with a
9136       // separate test. However, we only do this if this block doesn't
9137       // have a fall-through edge, because this requires an explicit
9138       // jmp when the condition is false.
9139       if (Op.getNode()->hasOneUse()) {
9140         SDNode *User = *Op.getNode()->use_begin();
9141         // Look for an unconditional branch following this conditional branch.
9142         // We need this because we need to reverse the successors in order
9143         // to implement FCMP_UNE.
9144         if (User->getOpcode() == ISD::BR) {
9145           SDValue FalseBB = User->getOperand(1);
9146           SDNode *NewBR =
9147             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9148           assert(NewBR == User);
9149           (void)NewBR;
9150
9151           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9152                                     Cond.getOperand(0), Cond.getOperand(1));
9153           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9154           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9155                               Chain, Dest, CC, Cmp);
9156           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9157           Cond = Cmp;
9158           addTest = false;
9159           Dest = FalseBB;
9160         }
9161       }
9162     }
9163   }
9164
9165   if (addTest) {
9166     // Look pass the truncate.
9167     if (Cond.getOpcode() == ISD::TRUNCATE)
9168       Cond = Cond.getOperand(0);
9169
9170     // We know the result of AND is compared against zero. Try to match
9171     // it to BT.
9172     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9173       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9174       if (NewSetCC.getNode()) {
9175         CC = NewSetCC.getOperand(0);
9176         Cond = NewSetCC.getOperand(1);
9177         addTest = false;
9178       }
9179     }
9180   }
9181
9182   if (addTest) {
9183     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9184     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9185   }
9186   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9187                      Chain, Dest, CC, Cond);
9188 }
9189
9190
9191 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
9192 // Calls to _alloca is needed to probe the stack when allocating more than 4k
9193 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
9194 // that the guard pages used by the OS virtual memory manager are allocated in
9195 // correct sequence.
9196 SDValue
9197 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9198                                            SelectionDAG &DAG) const {
9199   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
9200           EnableSegmentedStacks) &&
9201          "This should be used only on Windows targets or when segmented stacks "
9202          "are being used");
9203   assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
9204   DebugLoc dl = Op.getDebugLoc();
9205
9206   // Get the inputs.
9207   SDValue Chain = Op.getOperand(0);
9208   SDValue Size  = Op.getOperand(1);
9209   // FIXME: Ensure alignment here
9210
9211   bool Is64Bit = Subtarget->is64Bit();
9212   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
9213
9214   if (EnableSegmentedStacks) {
9215     MachineFunction &MF = DAG.getMachineFunction();
9216     MachineRegisterInfo &MRI = MF.getRegInfo();
9217
9218     if (Is64Bit) {
9219       // The 64 bit implementation of segmented stacks needs to clobber both r10
9220       // r11. This makes it impossible to use it along with nested parameters.
9221       const Function *F = MF.getFunction();
9222
9223       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9224            I != E; I++)
9225         if (I->hasNestAttr())
9226           report_fatal_error("Cannot use segmented stacks with functions that "
9227                              "have nested arguments.");
9228     }
9229
9230     const TargetRegisterClass *AddrRegClass =
9231       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9232     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9233     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9234     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9235                                 DAG.getRegister(Vreg, SPTy));
9236     SDValue Ops1[2] = { Value, Chain };
9237     return DAG.getMergeValues(Ops1, 2, dl);
9238   } else {
9239     SDValue Flag;
9240     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9241
9242     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9243     Flag = Chain.getValue(1);
9244     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9245
9246     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
9247     Flag = Chain.getValue(1);
9248
9249     Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
9250
9251     SDValue Ops1[2] = { Chain.getValue(0), Chain };
9252     return DAG.getMergeValues(Ops1, 2, dl);
9253   }
9254 }
9255
9256 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9257   MachineFunction &MF = DAG.getMachineFunction();
9258   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9259
9260   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9261   DebugLoc DL = Op.getDebugLoc();
9262
9263   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9264     // vastart just stores the address of the VarArgsFrameIndex slot into the
9265     // memory location argument.
9266     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9267                                    getPointerTy());
9268     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9269                         MachinePointerInfo(SV), false, false, 0);
9270   }
9271
9272   // __va_list_tag:
9273   //   gp_offset         (0 - 6 * 8)
9274   //   fp_offset         (48 - 48 + 8 * 16)
9275   //   overflow_arg_area (point to parameters coming in memory).
9276   //   reg_save_area
9277   SmallVector<SDValue, 8> MemOps;
9278   SDValue FIN = Op.getOperand(1);
9279   // Store gp_offset
9280   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9281                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9282                                                MVT::i32),
9283                                FIN, MachinePointerInfo(SV), false, false, 0);
9284   MemOps.push_back(Store);
9285
9286   // Store fp_offset
9287   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9288                     FIN, DAG.getIntPtrConstant(4));
9289   Store = DAG.getStore(Op.getOperand(0), DL,
9290                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9291                                        MVT::i32),
9292                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
9293   MemOps.push_back(Store);
9294
9295   // Store ptr to overflow_arg_area
9296   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9297                     FIN, DAG.getIntPtrConstant(4));
9298   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9299                                     getPointerTy());
9300   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9301                        MachinePointerInfo(SV, 8),
9302                        false, false, 0);
9303   MemOps.push_back(Store);
9304
9305   // Store ptr to reg_save_area.
9306   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9307                     FIN, DAG.getIntPtrConstant(8));
9308   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9309                                     getPointerTy());
9310   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9311                        MachinePointerInfo(SV, 16), false, false, 0);
9312   MemOps.push_back(Store);
9313   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9314                      &MemOps[0], MemOps.size());
9315 }
9316
9317 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9318   assert(Subtarget->is64Bit() &&
9319          "LowerVAARG only handles 64-bit va_arg!");
9320   assert((Subtarget->isTargetLinux() ||
9321           Subtarget->isTargetDarwin()) &&
9322           "Unhandled target in LowerVAARG");
9323   assert(Op.getNode()->getNumOperands() == 4);
9324   SDValue Chain = Op.getOperand(0);
9325   SDValue SrcPtr = Op.getOperand(1);
9326   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9327   unsigned Align = Op.getConstantOperandVal(3);
9328   DebugLoc dl = Op.getDebugLoc();
9329
9330   EVT ArgVT = Op.getNode()->getValueType(0);
9331   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9332   uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
9333   uint8_t ArgMode;
9334
9335   // Decide which area this value should be read from.
9336   // TODO: Implement the AMD64 ABI in its entirety. This simple
9337   // selection mechanism works only for the basic types.
9338   if (ArgVT == MVT::f80) {
9339     llvm_unreachable("va_arg for f80 not yet implemented");
9340   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9341     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
9342   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9343     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
9344   } else {
9345     llvm_unreachable("Unhandled argument type in LowerVAARG");
9346   }
9347
9348   if (ArgMode == 2) {
9349     // Sanity Check: Make sure using fp_offset makes sense.
9350     assert(!UseSoftFloat &&
9351            !(DAG.getMachineFunction()
9352                 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
9353            Subtarget->hasXMM());
9354   }
9355
9356   // Insert VAARG_64 node into the DAG
9357   // VAARG_64 returns two values: Variable Argument Address, Chain
9358   SmallVector<SDValue, 11> InstOps;
9359   InstOps.push_back(Chain);
9360   InstOps.push_back(SrcPtr);
9361   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9362   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9363   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9364   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9365   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9366                                           VTs, &InstOps[0], InstOps.size(),
9367                                           MVT::i64,
9368                                           MachinePointerInfo(SV),
9369                                           /*Align=*/0,
9370                                           /*Volatile=*/false,
9371                                           /*ReadMem=*/true,
9372                                           /*WriteMem=*/true);
9373   Chain = VAARG.getValue(1);
9374
9375   // Load the next argument and return it
9376   return DAG.getLoad(ArgVT, dl,
9377                      Chain,
9378                      VAARG,
9379                      MachinePointerInfo(),
9380                      false, false, false, 0);
9381 }
9382
9383 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
9384   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9385   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9386   SDValue Chain = Op.getOperand(0);
9387   SDValue DstPtr = Op.getOperand(1);
9388   SDValue SrcPtr = Op.getOperand(2);
9389   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9390   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9391   DebugLoc DL = Op.getDebugLoc();
9392
9393   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9394                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9395                        false,
9396                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9397 }
9398
9399 SDValue
9400 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
9401   DebugLoc dl = Op.getDebugLoc();
9402   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9403   switch (IntNo) {
9404   default: return SDValue();    // Don't custom lower most intrinsics.
9405   // Comparison intrinsics.
9406   case Intrinsic::x86_sse_comieq_ss:
9407   case Intrinsic::x86_sse_comilt_ss:
9408   case Intrinsic::x86_sse_comile_ss:
9409   case Intrinsic::x86_sse_comigt_ss:
9410   case Intrinsic::x86_sse_comige_ss:
9411   case Intrinsic::x86_sse_comineq_ss:
9412   case Intrinsic::x86_sse_ucomieq_ss:
9413   case Intrinsic::x86_sse_ucomilt_ss:
9414   case Intrinsic::x86_sse_ucomile_ss:
9415   case Intrinsic::x86_sse_ucomigt_ss:
9416   case Intrinsic::x86_sse_ucomige_ss:
9417   case Intrinsic::x86_sse_ucomineq_ss:
9418   case Intrinsic::x86_sse2_comieq_sd:
9419   case Intrinsic::x86_sse2_comilt_sd:
9420   case Intrinsic::x86_sse2_comile_sd:
9421   case Intrinsic::x86_sse2_comigt_sd:
9422   case Intrinsic::x86_sse2_comige_sd:
9423   case Intrinsic::x86_sse2_comineq_sd:
9424   case Intrinsic::x86_sse2_ucomieq_sd:
9425   case Intrinsic::x86_sse2_ucomilt_sd:
9426   case Intrinsic::x86_sse2_ucomile_sd:
9427   case Intrinsic::x86_sse2_ucomigt_sd:
9428   case Intrinsic::x86_sse2_ucomige_sd:
9429   case Intrinsic::x86_sse2_ucomineq_sd: {
9430     unsigned Opc = 0;
9431     ISD::CondCode CC = ISD::SETCC_INVALID;
9432     switch (IntNo) {
9433     default: break;
9434     case Intrinsic::x86_sse_comieq_ss:
9435     case Intrinsic::x86_sse2_comieq_sd:
9436       Opc = X86ISD::COMI;
9437       CC = ISD::SETEQ;
9438       break;
9439     case Intrinsic::x86_sse_comilt_ss:
9440     case Intrinsic::x86_sse2_comilt_sd:
9441       Opc = X86ISD::COMI;
9442       CC = ISD::SETLT;
9443       break;
9444     case Intrinsic::x86_sse_comile_ss:
9445     case Intrinsic::x86_sse2_comile_sd:
9446       Opc = X86ISD::COMI;
9447       CC = ISD::SETLE;
9448       break;
9449     case Intrinsic::x86_sse_comigt_ss:
9450     case Intrinsic::x86_sse2_comigt_sd:
9451       Opc = X86ISD::COMI;
9452       CC = ISD::SETGT;
9453       break;
9454     case Intrinsic::x86_sse_comige_ss:
9455     case Intrinsic::x86_sse2_comige_sd:
9456       Opc = X86ISD::COMI;
9457       CC = ISD::SETGE;
9458       break;
9459     case Intrinsic::x86_sse_comineq_ss:
9460     case Intrinsic::x86_sse2_comineq_sd:
9461       Opc = X86ISD::COMI;
9462       CC = ISD::SETNE;
9463       break;
9464     case Intrinsic::x86_sse_ucomieq_ss:
9465     case Intrinsic::x86_sse2_ucomieq_sd:
9466       Opc = X86ISD::UCOMI;
9467       CC = ISD::SETEQ;
9468       break;
9469     case Intrinsic::x86_sse_ucomilt_ss:
9470     case Intrinsic::x86_sse2_ucomilt_sd:
9471       Opc = X86ISD::UCOMI;
9472       CC = ISD::SETLT;
9473       break;
9474     case Intrinsic::x86_sse_ucomile_ss:
9475     case Intrinsic::x86_sse2_ucomile_sd:
9476       Opc = X86ISD::UCOMI;
9477       CC = ISD::SETLE;
9478       break;
9479     case Intrinsic::x86_sse_ucomigt_ss:
9480     case Intrinsic::x86_sse2_ucomigt_sd:
9481       Opc = X86ISD::UCOMI;
9482       CC = ISD::SETGT;
9483       break;
9484     case Intrinsic::x86_sse_ucomige_ss:
9485     case Intrinsic::x86_sse2_ucomige_sd:
9486       Opc = X86ISD::UCOMI;
9487       CC = ISD::SETGE;
9488       break;
9489     case Intrinsic::x86_sse_ucomineq_ss:
9490     case Intrinsic::x86_sse2_ucomineq_sd:
9491       Opc = X86ISD::UCOMI;
9492       CC = ISD::SETNE;
9493       break;
9494     }
9495
9496     SDValue LHS = Op.getOperand(1);
9497     SDValue RHS = Op.getOperand(2);
9498     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
9499     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
9500     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
9501     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9502                                 DAG.getConstant(X86CC, MVT::i8), Cond);
9503     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9504   }
9505   // Arithmetic intrinsics.
9506   case Intrinsic::x86_sse3_hadd_ps:
9507   case Intrinsic::x86_sse3_hadd_pd:
9508   case Intrinsic::x86_avx_hadd_ps_256:
9509   case Intrinsic::x86_avx_hadd_pd_256:
9510     return DAG.getNode(X86ISD::FHADD, dl, Op.getValueType(),
9511                        Op.getOperand(1), Op.getOperand(2));
9512   case Intrinsic::x86_sse3_hsub_ps:
9513   case Intrinsic::x86_sse3_hsub_pd:
9514   case Intrinsic::x86_avx_hsub_ps_256:
9515   case Intrinsic::x86_avx_hsub_pd_256:
9516     return DAG.getNode(X86ISD::FHSUB, dl, Op.getValueType(),
9517                        Op.getOperand(1), Op.getOperand(2));
9518   // ptest and testp intrinsics. The intrinsic these come from are designed to
9519   // return an integer value, not just an instruction so lower it to the ptest
9520   // or testp pattern and a setcc for the result.
9521   case Intrinsic::x86_sse41_ptestz:
9522   case Intrinsic::x86_sse41_ptestc:
9523   case Intrinsic::x86_sse41_ptestnzc:
9524   case Intrinsic::x86_avx_ptestz_256:
9525   case Intrinsic::x86_avx_ptestc_256:
9526   case Intrinsic::x86_avx_ptestnzc_256:
9527   case Intrinsic::x86_avx_vtestz_ps:
9528   case Intrinsic::x86_avx_vtestc_ps:
9529   case Intrinsic::x86_avx_vtestnzc_ps:
9530   case Intrinsic::x86_avx_vtestz_pd:
9531   case Intrinsic::x86_avx_vtestc_pd:
9532   case Intrinsic::x86_avx_vtestnzc_pd:
9533   case Intrinsic::x86_avx_vtestz_ps_256:
9534   case Intrinsic::x86_avx_vtestc_ps_256:
9535   case Intrinsic::x86_avx_vtestnzc_ps_256:
9536   case Intrinsic::x86_avx_vtestz_pd_256:
9537   case Intrinsic::x86_avx_vtestc_pd_256:
9538   case Intrinsic::x86_avx_vtestnzc_pd_256: {
9539     bool IsTestPacked = false;
9540     unsigned X86CC = 0;
9541     switch (IntNo) {
9542     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
9543     case Intrinsic::x86_avx_vtestz_ps:
9544     case Intrinsic::x86_avx_vtestz_pd:
9545     case Intrinsic::x86_avx_vtestz_ps_256:
9546     case Intrinsic::x86_avx_vtestz_pd_256:
9547       IsTestPacked = true; // Fallthrough
9548     case Intrinsic::x86_sse41_ptestz:
9549     case Intrinsic::x86_avx_ptestz_256:
9550       // ZF = 1
9551       X86CC = X86::COND_E;
9552       break;
9553     case Intrinsic::x86_avx_vtestc_ps:
9554     case Intrinsic::x86_avx_vtestc_pd:
9555     case Intrinsic::x86_avx_vtestc_ps_256:
9556     case Intrinsic::x86_avx_vtestc_pd_256:
9557       IsTestPacked = true; // Fallthrough
9558     case Intrinsic::x86_sse41_ptestc:
9559     case Intrinsic::x86_avx_ptestc_256:
9560       // CF = 1
9561       X86CC = X86::COND_B;
9562       break;
9563     case Intrinsic::x86_avx_vtestnzc_ps:
9564     case Intrinsic::x86_avx_vtestnzc_pd:
9565     case Intrinsic::x86_avx_vtestnzc_ps_256:
9566     case Intrinsic::x86_avx_vtestnzc_pd_256:
9567       IsTestPacked = true; // Fallthrough
9568     case Intrinsic::x86_sse41_ptestnzc:
9569     case Intrinsic::x86_avx_ptestnzc_256:
9570       // ZF and CF = 0
9571       X86CC = X86::COND_A;
9572       break;
9573     }
9574
9575     SDValue LHS = Op.getOperand(1);
9576     SDValue RHS = Op.getOperand(2);
9577     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
9578     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
9579     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
9580     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
9581     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9582   }
9583
9584   // Fix vector shift instructions where the last operand is a non-immediate
9585   // i32 value.
9586   case Intrinsic::x86_avx2_pslli_w:
9587   case Intrinsic::x86_avx2_pslli_d:
9588   case Intrinsic::x86_avx2_pslli_q:
9589   case Intrinsic::x86_avx2_psrli_w:
9590   case Intrinsic::x86_avx2_psrli_d:
9591   case Intrinsic::x86_avx2_psrli_q:
9592   case Intrinsic::x86_avx2_psrai_w:
9593   case Intrinsic::x86_avx2_psrai_d:
9594   case Intrinsic::x86_sse2_pslli_w:
9595   case Intrinsic::x86_sse2_pslli_d:
9596   case Intrinsic::x86_sse2_pslli_q:
9597   case Intrinsic::x86_sse2_psrli_w:
9598   case Intrinsic::x86_sse2_psrli_d:
9599   case Intrinsic::x86_sse2_psrli_q:
9600   case Intrinsic::x86_sse2_psrai_w:
9601   case Intrinsic::x86_sse2_psrai_d:
9602   case Intrinsic::x86_mmx_pslli_w:
9603   case Intrinsic::x86_mmx_pslli_d:
9604   case Intrinsic::x86_mmx_pslli_q:
9605   case Intrinsic::x86_mmx_psrli_w:
9606   case Intrinsic::x86_mmx_psrli_d:
9607   case Intrinsic::x86_mmx_psrli_q:
9608   case Intrinsic::x86_mmx_psrai_w:
9609   case Intrinsic::x86_mmx_psrai_d: {
9610     SDValue ShAmt = Op.getOperand(2);
9611     if (isa<ConstantSDNode>(ShAmt))
9612       return SDValue();
9613
9614     unsigned NewIntNo = 0;
9615     EVT ShAmtVT = MVT::v4i32;
9616     switch (IntNo) {
9617     case Intrinsic::x86_sse2_pslli_w:
9618       NewIntNo = Intrinsic::x86_sse2_psll_w;
9619       break;
9620     case Intrinsic::x86_sse2_pslli_d:
9621       NewIntNo = Intrinsic::x86_sse2_psll_d;
9622       break;
9623     case Intrinsic::x86_sse2_pslli_q:
9624       NewIntNo = Intrinsic::x86_sse2_psll_q;
9625       break;
9626     case Intrinsic::x86_sse2_psrli_w:
9627       NewIntNo = Intrinsic::x86_sse2_psrl_w;
9628       break;
9629     case Intrinsic::x86_sse2_psrli_d:
9630       NewIntNo = Intrinsic::x86_sse2_psrl_d;
9631       break;
9632     case Intrinsic::x86_sse2_psrli_q:
9633       NewIntNo = Intrinsic::x86_sse2_psrl_q;
9634       break;
9635     case Intrinsic::x86_sse2_psrai_w:
9636       NewIntNo = Intrinsic::x86_sse2_psra_w;
9637       break;
9638     case Intrinsic::x86_sse2_psrai_d:
9639       NewIntNo = Intrinsic::x86_sse2_psra_d;
9640       break;
9641     case Intrinsic::x86_avx2_pslli_w:
9642       NewIntNo = Intrinsic::x86_avx2_psll_w;
9643       break;
9644     case Intrinsic::x86_avx2_pslli_d:
9645       NewIntNo = Intrinsic::x86_avx2_psll_d;
9646       break;
9647     case Intrinsic::x86_avx2_pslli_q:
9648       NewIntNo = Intrinsic::x86_avx2_psll_q;
9649       break;
9650     case Intrinsic::x86_avx2_psrli_w:
9651       NewIntNo = Intrinsic::x86_avx2_psrl_w;
9652       break;
9653     case Intrinsic::x86_avx2_psrli_d:
9654       NewIntNo = Intrinsic::x86_avx2_psrl_d;
9655       break;
9656     case Intrinsic::x86_avx2_psrli_q:
9657       NewIntNo = Intrinsic::x86_avx2_psrl_q;
9658       break;
9659     case Intrinsic::x86_avx2_psrai_w:
9660       NewIntNo = Intrinsic::x86_avx2_psra_w;
9661       break;
9662     case Intrinsic::x86_avx2_psrai_d:
9663       NewIntNo = Intrinsic::x86_avx2_psra_d;
9664       break;
9665     default: {
9666       ShAmtVT = MVT::v2i32;
9667       switch (IntNo) {
9668       case Intrinsic::x86_mmx_pslli_w:
9669         NewIntNo = Intrinsic::x86_mmx_psll_w;
9670         break;
9671       case Intrinsic::x86_mmx_pslli_d:
9672         NewIntNo = Intrinsic::x86_mmx_psll_d;
9673         break;
9674       case Intrinsic::x86_mmx_pslli_q:
9675         NewIntNo = Intrinsic::x86_mmx_psll_q;
9676         break;
9677       case Intrinsic::x86_mmx_psrli_w:
9678         NewIntNo = Intrinsic::x86_mmx_psrl_w;
9679         break;
9680       case Intrinsic::x86_mmx_psrli_d:
9681         NewIntNo = Intrinsic::x86_mmx_psrl_d;
9682         break;
9683       case Intrinsic::x86_mmx_psrli_q:
9684         NewIntNo = Intrinsic::x86_mmx_psrl_q;
9685         break;
9686       case Intrinsic::x86_mmx_psrai_w:
9687         NewIntNo = Intrinsic::x86_mmx_psra_w;
9688         break;
9689       case Intrinsic::x86_mmx_psrai_d:
9690         NewIntNo = Intrinsic::x86_mmx_psra_d;
9691         break;
9692       default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9693       }
9694       break;
9695     }
9696     }
9697
9698     // The vector shift intrinsics with scalars uses 32b shift amounts but
9699     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
9700     // to be zero.
9701     SDValue ShOps[4];
9702     ShOps[0] = ShAmt;
9703     ShOps[1] = DAG.getConstant(0, MVT::i32);
9704     if (ShAmtVT == MVT::v4i32) {
9705       ShOps[2] = DAG.getUNDEF(MVT::i32);
9706       ShOps[3] = DAG.getUNDEF(MVT::i32);
9707       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
9708     } else {
9709       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
9710 // FIXME this must be lowered to get rid of the invalid type.
9711     }
9712
9713     EVT VT = Op.getValueType();
9714     ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
9715     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9716                        DAG.getConstant(NewIntNo, MVT::i32),
9717                        Op.getOperand(1), ShAmt);
9718   }
9719   }
9720 }
9721
9722 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
9723                                            SelectionDAG &DAG) const {
9724   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9725   MFI->setReturnAddressIsTaken(true);
9726
9727   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9728   DebugLoc dl = Op.getDebugLoc();
9729
9730   if (Depth > 0) {
9731     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
9732     SDValue Offset =
9733       DAG.getConstant(TD->getPointerSize(),
9734                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
9735     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9736                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
9737                                    FrameAddr, Offset),
9738                        MachinePointerInfo(), false, false, false, 0);
9739   }
9740
9741   // Just load the return address.
9742   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
9743   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9744                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
9745 }
9746
9747 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
9748   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9749   MFI->setFrameAddressIsTaken(true);
9750
9751   EVT VT = Op.getValueType();
9752   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
9753   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9754   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
9755   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
9756   while (Depth--)
9757     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
9758                             MachinePointerInfo(),
9759                             false, false, false, 0);
9760   return FrameAddr;
9761 }
9762
9763 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
9764                                                      SelectionDAG &DAG) const {
9765   return DAG.getIntPtrConstant(2*TD->getPointerSize());
9766 }
9767
9768 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
9769   MachineFunction &MF = DAG.getMachineFunction();
9770   SDValue Chain     = Op.getOperand(0);
9771   SDValue Offset    = Op.getOperand(1);
9772   SDValue Handler   = Op.getOperand(2);
9773   DebugLoc dl       = Op.getDebugLoc();
9774
9775   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
9776                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
9777                                      getPointerTy());
9778   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
9779
9780   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
9781                                   DAG.getIntPtrConstant(TD->getPointerSize()));
9782   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
9783   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
9784                        false, false, 0);
9785   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
9786   MF.getRegInfo().addLiveOut(StoreAddrReg);
9787
9788   return DAG.getNode(X86ISD::EH_RETURN, dl,
9789                      MVT::Other,
9790                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
9791 }
9792
9793 SDValue X86TargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
9794                                                   SelectionDAG &DAG) const {
9795   return Op.getOperand(0);
9796 }
9797
9798 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
9799                                                 SelectionDAG &DAG) const {
9800   SDValue Root = Op.getOperand(0);
9801   SDValue Trmp = Op.getOperand(1); // trampoline
9802   SDValue FPtr = Op.getOperand(2); // nested function
9803   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
9804   DebugLoc dl  = Op.getDebugLoc();
9805
9806   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9807
9808   if (Subtarget->is64Bit()) {
9809     SDValue OutChains[6];
9810
9811     // Large code-model.
9812     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
9813     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
9814
9815     const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10);
9816     const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11);
9817
9818     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
9819
9820     // Load the pointer to the nested function into R11.
9821     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
9822     SDValue Addr = Trmp;
9823     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9824                                 Addr, MachinePointerInfo(TrmpAddr),
9825                                 false, false, 0);
9826
9827     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9828                        DAG.getConstant(2, MVT::i64));
9829     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
9830                                 MachinePointerInfo(TrmpAddr, 2),
9831                                 false, false, 2);
9832
9833     // Load the 'nest' parameter value into R10.
9834     // R10 is specified in X86CallingConv.td
9835     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
9836     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9837                        DAG.getConstant(10, MVT::i64));
9838     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9839                                 Addr, MachinePointerInfo(TrmpAddr, 10),
9840                                 false, false, 0);
9841
9842     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9843                        DAG.getConstant(12, MVT::i64));
9844     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
9845                                 MachinePointerInfo(TrmpAddr, 12),
9846                                 false, false, 2);
9847
9848     // Jump to the nested function.
9849     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
9850     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9851                        DAG.getConstant(20, MVT::i64));
9852     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9853                                 Addr, MachinePointerInfo(TrmpAddr, 20),
9854                                 false, false, 0);
9855
9856     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
9857     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9858                        DAG.getConstant(22, MVT::i64));
9859     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
9860                                 MachinePointerInfo(TrmpAddr, 22),
9861                                 false, false, 0);
9862
9863     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
9864   } else {
9865     const Function *Func =
9866       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
9867     CallingConv::ID CC = Func->getCallingConv();
9868     unsigned NestReg;
9869
9870     switch (CC) {
9871     default:
9872       llvm_unreachable("Unsupported calling convention");
9873     case CallingConv::C:
9874     case CallingConv::X86_StdCall: {
9875       // Pass 'nest' parameter in ECX.
9876       // Must be kept in sync with X86CallingConv.td
9877       NestReg = X86::ECX;
9878
9879       // Check that ECX wasn't needed by an 'inreg' parameter.
9880       FunctionType *FTy = Func->getFunctionType();
9881       const AttrListPtr &Attrs = Func->getAttributes();
9882
9883       if (!Attrs.isEmpty() && !Func->isVarArg()) {
9884         unsigned InRegCount = 0;
9885         unsigned Idx = 1;
9886
9887         for (FunctionType::param_iterator I = FTy->param_begin(),
9888              E = FTy->param_end(); I != E; ++I, ++Idx)
9889           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
9890             // FIXME: should only count parameters that are lowered to integers.
9891             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
9892
9893         if (InRegCount > 2) {
9894           report_fatal_error("Nest register in use - reduce number of inreg"
9895                              " parameters!");
9896         }
9897       }
9898       break;
9899     }
9900     case CallingConv::X86_FastCall:
9901     case CallingConv::X86_ThisCall:
9902     case CallingConv::Fast:
9903       // Pass 'nest' parameter in EAX.
9904       // Must be kept in sync with X86CallingConv.td
9905       NestReg = X86::EAX;
9906       break;
9907     }
9908
9909     SDValue OutChains[4];
9910     SDValue Addr, Disp;
9911
9912     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9913                        DAG.getConstant(10, MVT::i32));
9914     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
9915
9916     // This is storing the opcode for MOV32ri.
9917     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
9918     const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg);
9919     OutChains[0] = DAG.getStore(Root, dl,
9920                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
9921                                 Trmp, MachinePointerInfo(TrmpAddr),
9922                                 false, false, 0);
9923
9924     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9925                        DAG.getConstant(1, MVT::i32));
9926     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
9927                                 MachinePointerInfo(TrmpAddr, 1),
9928                                 false, false, 1);
9929
9930     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
9931     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9932                        DAG.getConstant(5, MVT::i32));
9933     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
9934                                 MachinePointerInfo(TrmpAddr, 5),
9935                                 false, false, 1);
9936
9937     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9938                        DAG.getConstant(6, MVT::i32));
9939     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
9940                                 MachinePointerInfo(TrmpAddr, 6),
9941                                 false, false, 1);
9942
9943     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
9944   }
9945 }
9946
9947 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
9948                                             SelectionDAG &DAG) const {
9949   /*
9950    The rounding mode is in bits 11:10 of FPSR, and has the following
9951    settings:
9952      00 Round to nearest
9953      01 Round to -inf
9954      10 Round to +inf
9955      11 Round to 0
9956
9957   FLT_ROUNDS, on the other hand, expects the following:
9958     -1 Undefined
9959      0 Round to 0
9960      1 Round to nearest
9961      2 Round to +inf
9962      3 Round to -inf
9963
9964   To perform the conversion, we do:
9965     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
9966   */
9967
9968   MachineFunction &MF = DAG.getMachineFunction();
9969   const TargetMachine &TM = MF.getTarget();
9970   const TargetFrameLowering &TFI = *TM.getFrameLowering();
9971   unsigned StackAlignment = TFI.getStackAlignment();
9972   EVT VT = Op.getValueType();
9973   DebugLoc DL = Op.getDebugLoc();
9974
9975   // Save FP Control Word to stack slot
9976   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
9977   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9978
9979
9980   MachineMemOperand *MMO =
9981    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9982                            MachineMemOperand::MOStore, 2, 2);
9983
9984   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
9985   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
9986                                           DAG.getVTList(MVT::Other),
9987                                           Ops, 2, MVT::i16, MMO);
9988
9989   // Load FP Control Word from stack slot
9990   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
9991                             MachinePointerInfo(), false, false, false, 0);
9992
9993   // Transform as necessary
9994   SDValue CWD1 =
9995     DAG.getNode(ISD::SRL, DL, MVT::i16,
9996                 DAG.getNode(ISD::AND, DL, MVT::i16,
9997                             CWD, DAG.getConstant(0x800, MVT::i16)),
9998                 DAG.getConstant(11, MVT::i8));
9999   SDValue CWD2 =
10000     DAG.getNode(ISD::SRL, DL, MVT::i16,
10001                 DAG.getNode(ISD::AND, DL, MVT::i16,
10002                             CWD, DAG.getConstant(0x400, MVT::i16)),
10003                 DAG.getConstant(9, MVT::i8));
10004
10005   SDValue RetVal =
10006     DAG.getNode(ISD::AND, DL, MVT::i16,
10007                 DAG.getNode(ISD::ADD, DL, MVT::i16,
10008                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
10009                             DAG.getConstant(1, MVT::i16)),
10010                 DAG.getConstant(3, MVT::i16));
10011
10012
10013   return DAG.getNode((VT.getSizeInBits() < 16 ?
10014                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
10015 }
10016
10017 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
10018   EVT VT = Op.getValueType();
10019   EVT OpVT = VT;
10020   unsigned NumBits = VT.getSizeInBits();
10021   DebugLoc dl = Op.getDebugLoc();
10022
10023   Op = Op.getOperand(0);
10024   if (VT == MVT::i8) {
10025     // Zero extend to i32 since there is not an i8 bsr.
10026     OpVT = MVT::i32;
10027     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10028   }
10029
10030   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
10031   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10032   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10033
10034   // If src is zero (i.e. bsr sets ZF), returns NumBits.
10035   SDValue Ops[] = {
10036     Op,
10037     DAG.getConstant(NumBits+NumBits-1, OpVT),
10038     DAG.getConstant(X86::COND_E, MVT::i8),
10039     Op.getValue(1)
10040   };
10041   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
10042
10043   // Finally xor with NumBits-1.
10044   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10045
10046   if (VT == MVT::i8)
10047     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10048   return Op;
10049 }
10050
10051 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
10052   EVT VT = Op.getValueType();
10053   EVT OpVT = VT;
10054   unsigned NumBits = VT.getSizeInBits();
10055   DebugLoc dl = Op.getDebugLoc();
10056
10057   Op = Op.getOperand(0);
10058   if (VT == MVT::i8) {
10059     OpVT = MVT::i32;
10060     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10061   }
10062
10063   // Issue a bsf (scan bits forward) which also sets EFLAGS.
10064   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10065   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
10066
10067   // If src is zero (i.e. bsf sets ZF), returns NumBits.
10068   SDValue Ops[] = {
10069     Op,
10070     DAG.getConstant(NumBits, OpVT),
10071     DAG.getConstant(X86::COND_E, MVT::i8),
10072     Op.getValue(1)
10073   };
10074   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
10075
10076   if (VT == MVT::i8)
10077     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10078   return Op;
10079 }
10080
10081 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
10082 // ones, and then concatenate the result back.
10083 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
10084   EVT VT = Op.getValueType();
10085
10086   assert(VT.getSizeInBits() == 256 && VT.isInteger() &&
10087          "Unsupported value type for operation");
10088
10089   int NumElems = VT.getVectorNumElements();
10090   DebugLoc dl = Op.getDebugLoc();
10091   SDValue Idx0 = DAG.getConstant(0, MVT::i32);
10092   SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
10093
10094   // Extract the LHS vectors
10095   SDValue LHS = Op.getOperand(0);
10096   SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
10097   SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
10098
10099   // Extract the RHS vectors
10100   SDValue RHS = Op.getOperand(1);
10101   SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl);
10102   SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl);
10103
10104   MVT EltVT = VT.getVectorElementType().getSimpleVT();
10105   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10106
10107   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10108                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
10109                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
10110 }
10111
10112 SDValue X86TargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const {
10113   assert(Op.getValueType().getSizeInBits() == 256 &&
10114          Op.getValueType().isInteger() &&
10115          "Only handle AVX 256-bit vector integer operation");
10116   return Lower256IntArith(Op, DAG);
10117 }
10118
10119 SDValue X86TargetLowering::LowerSUB(SDValue Op, SelectionDAG &DAG) const {
10120   assert(Op.getValueType().getSizeInBits() == 256 &&
10121          Op.getValueType().isInteger() &&
10122          "Only handle AVX 256-bit vector integer operation");
10123   return Lower256IntArith(Op, DAG);
10124 }
10125
10126 SDValue X86TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10127   EVT VT = Op.getValueType();
10128
10129   // Decompose 256-bit ops into smaller 128-bit ops.
10130   if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2())
10131     return Lower256IntArith(Op, DAG);
10132
10133   DebugLoc dl = Op.getDebugLoc();
10134
10135   SDValue A = Op.getOperand(0);
10136   SDValue B = Op.getOperand(1);
10137
10138   if (VT == MVT::v4i64) {
10139     assert(Subtarget->hasAVX2() && "Lowering v4i64 multiply requires AVX2");
10140
10141     //  ulong2 Ahi = __builtin_ia32_psrlqi256( a, 32);
10142     //  ulong2 Bhi = __builtin_ia32_psrlqi256( b, 32);
10143     //  ulong2 AloBlo = __builtin_ia32_pmuludq256( a, b );
10144     //  ulong2 AloBhi = __builtin_ia32_pmuludq256( a, Bhi );
10145     //  ulong2 AhiBlo = __builtin_ia32_pmuludq256( Ahi, b );
10146     //
10147     //  AloBhi = __builtin_ia32_psllqi256( AloBhi, 32 );
10148     //  AhiBlo = __builtin_ia32_psllqi256( AhiBlo, 32 );
10149     //  return AloBlo + AloBhi + AhiBlo;
10150
10151     SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10152                          DAG.getConstant(Intrinsic::x86_avx2_psrli_q, MVT::i32),
10153                          A, DAG.getConstant(32, MVT::i32));
10154     SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10155                          DAG.getConstant(Intrinsic::x86_avx2_psrli_q, MVT::i32),
10156                          B, DAG.getConstant(32, MVT::i32));
10157     SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10158                          DAG.getConstant(Intrinsic::x86_avx2_pmulu_dq, MVT::i32),
10159                          A, B);
10160     SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10161                          DAG.getConstant(Intrinsic::x86_avx2_pmulu_dq, MVT::i32),
10162                          A, Bhi);
10163     SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10164                          DAG.getConstant(Intrinsic::x86_avx2_pmulu_dq, MVT::i32),
10165                          Ahi, B);
10166     AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10167                          DAG.getConstant(Intrinsic::x86_avx2_pslli_q, MVT::i32),
10168                          AloBhi, DAG.getConstant(32, MVT::i32));
10169     AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10170                          DAG.getConstant(Intrinsic::x86_avx2_pslli_q, MVT::i32),
10171                          AhiBlo, DAG.getConstant(32, MVT::i32));
10172     SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
10173     Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10174     return Res;
10175   }
10176
10177   assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
10178
10179   //  ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
10180   //  ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
10181   //  ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
10182   //  ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
10183   //  ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
10184   //
10185   //  AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
10186   //  AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
10187   //  return AloBlo + AloBhi + AhiBlo;
10188
10189   SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10190                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
10191                        A, DAG.getConstant(32, MVT::i32));
10192   SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10193                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
10194                        B, DAG.getConstant(32, MVT::i32));
10195   SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10196                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
10197                        A, B);
10198   SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10199                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
10200                        A, Bhi);
10201   SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10202                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
10203                        Ahi, B);
10204   AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10205                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
10206                        AloBhi, DAG.getConstant(32, MVT::i32));
10207   AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10208                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
10209                        AhiBlo, DAG.getConstant(32, MVT::i32));
10210   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
10211   Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10212   return Res;
10213 }
10214
10215 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
10216
10217   EVT VT = Op.getValueType();
10218   DebugLoc dl = Op.getDebugLoc();
10219   SDValue R = Op.getOperand(0);
10220   SDValue Amt = Op.getOperand(1);
10221   LLVMContext *Context = DAG.getContext();
10222
10223   if (!Subtarget->hasXMMInt())
10224     return SDValue();
10225
10226   // Optimize shl/srl/sra with constant shift amount.
10227   if (isSplatVector(Amt.getNode())) {
10228     SDValue SclrAmt = Amt->getOperand(0);
10229     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
10230       uint64_t ShiftAmt = C->getZExtValue();
10231
10232       if (VT == MVT::v16i8 && Op.getOpcode() == ISD::SHL) {
10233         // Make a large shift.
10234         SDValue SHL =
10235           DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10236                       DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10237                       R, DAG.getConstant(ShiftAmt, MVT::i32));
10238         // Zero out the rightmost bits.
10239         SmallVector<SDValue, 16> V(16, DAG.getConstant(uint8_t(-1U << ShiftAmt),
10240                                                        MVT::i8));
10241         return DAG.getNode(ISD::AND, dl, VT, SHL,
10242                            DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10243       }
10244
10245       if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SHL)
10246        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10247                      DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
10248                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10249
10250       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SHL)
10251        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10252                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
10253                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10254
10255       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SHL)
10256        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10257                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10258                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10259
10260       if (VT == MVT::v16i8 && Op.getOpcode() == ISD::SRL) {
10261         // Make a large shift.
10262         SDValue SRL =
10263           DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10264                       DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
10265                       R, DAG.getConstant(ShiftAmt, MVT::i32));
10266         // Zero out the leftmost bits.
10267         SmallVector<SDValue, 16> V(16, DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10268                                                        MVT::i8));
10269         return DAG.getNode(ISD::AND, dl, VT, SRL,
10270                            DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10271       }
10272
10273       if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SRL)
10274        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10275                      DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
10276                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10277
10278       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRL)
10279        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10280                      DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
10281                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10282
10283       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRL)
10284        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10285                      DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
10286                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10287
10288       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRA)
10289        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10290                      DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
10291                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10292
10293       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRA)
10294        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10295                      DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
10296                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10297
10298       if (VT == MVT::v16i8 && Op.getOpcode() == ISD::SRA) {
10299         if (ShiftAmt == 7) {
10300           // R s>> 7  ===  R s< 0
10301           SDValue Zeros = getZeroVector(VT, true /* HasXMMInt */, DAG, dl);
10302           return DAG.getNode(X86ISD::PCMPGTB, dl, VT, Zeros, R);
10303         }
10304
10305         // R s>> a === ((R u>> a) ^ m) - m
10306         SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10307         SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
10308                                                        MVT::i8));
10309         SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
10310         Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10311         Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10312         return Res;
10313       }
10314
10315       if (Subtarget->hasAVX2()) {
10316         if (VT == MVT::v4i64 && Op.getOpcode() == ISD::SHL)
10317          return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10318                        DAG.getConstant(Intrinsic::x86_avx2_pslli_q, MVT::i32),
10319                        R, DAG.getConstant(ShiftAmt, MVT::i32));
10320
10321         if (VT == MVT::v8i32 && Op.getOpcode() == ISD::SHL)
10322          return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10323                        DAG.getConstant(Intrinsic::x86_avx2_pslli_d, MVT::i32),
10324                        R, DAG.getConstant(ShiftAmt, MVT::i32));
10325
10326         if (VT == MVT::v16i16 && Op.getOpcode() == ISD::SHL)
10327          return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10328                        DAG.getConstant(Intrinsic::x86_avx2_pslli_w, MVT::i32),
10329                        R, DAG.getConstant(ShiftAmt, MVT::i32));
10330
10331         if (VT == MVT::v4i64 && Op.getOpcode() == ISD::SRL)
10332          return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10333                        DAG.getConstant(Intrinsic::x86_avx2_psrli_q, MVT::i32),
10334                        R, DAG.getConstant(ShiftAmt, MVT::i32));
10335
10336         if (VT == MVT::v8i32 && Op.getOpcode() == ISD::SRL)
10337          return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10338                        DAG.getConstant(Intrinsic::x86_avx2_psrli_d, MVT::i32),
10339                        R, DAG.getConstant(ShiftAmt, MVT::i32));
10340
10341         if (VT == MVT::v16i16 && Op.getOpcode() == ISD::SRL)
10342          return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10343                        DAG.getConstant(Intrinsic::x86_avx2_psrli_w, MVT::i32),
10344                        R, DAG.getConstant(ShiftAmt, MVT::i32));
10345
10346         if (VT == MVT::v8i32 && Op.getOpcode() == ISD::SRA)
10347          return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10348                        DAG.getConstant(Intrinsic::x86_avx2_psrai_d, MVT::i32),
10349                        R, DAG.getConstant(ShiftAmt, MVT::i32));
10350
10351         if (VT == MVT::v16i16 && Op.getOpcode() == ISD::SRA)
10352          return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10353                        DAG.getConstant(Intrinsic::x86_avx2_psrai_w, MVT::i32),
10354                        R, DAG.getConstant(ShiftAmt, MVT::i32));
10355         }
10356     }
10357   }
10358
10359   // Lower SHL with variable shift amount.
10360   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
10361     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10362                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
10363                      Op.getOperand(1), DAG.getConstant(23, MVT::i32));
10364
10365     ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
10366
10367     std::vector<Constant*> CV(4, CI);
10368     Constant *C = ConstantVector::get(CV);
10369     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10370     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10371                                  MachinePointerInfo::getConstantPool(),
10372                                  false, false, false, 16);
10373
10374     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
10375     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
10376     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
10377     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
10378   }
10379   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
10380     // a = a << 5;
10381     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10382                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10383                      Op.getOperand(1), DAG.getConstant(5, MVT::i32));
10384
10385     ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
10386     ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
10387
10388     std::vector<Constant*> CVM1(16, CM1);
10389     std::vector<Constant*> CVM2(16, CM2);
10390     Constant *C = ConstantVector::get(CVM1);
10391     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10392     SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10393                             MachinePointerInfo::getConstantPool(),
10394                             false, false, false, 16);
10395
10396     // r = pblendv(r, psllw(r & (char16)15, 4), a);
10397     M = DAG.getNode(ISD::AND, dl, VT, R, M);
10398     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10399                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
10400                     DAG.getConstant(4, MVT::i32));
10401     R = DAG.getNode(ISD::VSELECT, dl, VT, Op, R, M);
10402     // a += a
10403     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10404
10405     C = ConstantVector::get(CVM2);
10406     CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10407     M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10408                     MachinePointerInfo::getConstantPool(),
10409                     false, false, false, 16);
10410
10411     // r = pblendv(r, psllw(r & (char16)63, 2), a);
10412     M = DAG.getNode(ISD::AND, dl, VT, R, M);
10413     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10414                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
10415                     DAG.getConstant(2, MVT::i32));
10416     R = DAG.getNode(ISD::VSELECT, dl, VT, Op, R, M);
10417     // a += a
10418     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10419
10420     // return pblendv(r, r+r, a);
10421     R = DAG.getNode(ISD::VSELECT, dl, VT, Op,
10422                     R, DAG.getNode(ISD::ADD, dl, VT, R, R));
10423     return R;
10424   }
10425
10426   // Decompose 256-bit shifts into smaller 128-bit shifts.
10427   if (VT.getSizeInBits() == 256) {
10428     int NumElems = VT.getVectorNumElements();
10429     MVT EltVT = VT.getVectorElementType().getSimpleVT();
10430     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10431
10432     // Extract the two vectors
10433     SDValue V1 = Extract128BitVector(R, DAG.getConstant(0, MVT::i32), DAG, dl);
10434     SDValue V2 = Extract128BitVector(R, DAG.getConstant(NumElems/2, MVT::i32),
10435                                      DAG, dl);
10436
10437     // Recreate the shift amount vectors
10438     SDValue Amt1, Amt2;
10439     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
10440       // Constant shift amount
10441       SmallVector<SDValue, 4> Amt1Csts;
10442       SmallVector<SDValue, 4> Amt2Csts;
10443       for (int i = 0; i < NumElems/2; ++i)
10444         Amt1Csts.push_back(Amt->getOperand(i));
10445       for (int i = NumElems/2; i < NumElems; ++i)
10446         Amt2Csts.push_back(Amt->getOperand(i));
10447
10448       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10449                                  &Amt1Csts[0], NumElems/2);
10450       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10451                                  &Amt2Csts[0], NumElems/2);
10452     } else {
10453       // Variable shift amount
10454       Amt1 = Extract128BitVector(Amt, DAG.getConstant(0, MVT::i32), DAG, dl);
10455       Amt2 = Extract128BitVector(Amt, DAG.getConstant(NumElems/2, MVT::i32),
10456                                  DAG, dl);
10457     }
10458
10459     // Issue new vector shifts for the smaller types
10460     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
10461     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
10462
10463     // Concatenate the result back
10464     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
10465   }
10466
10467   return SDValue();
10468 }
10469
10470 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
10471   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
10472   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
10473   // looks for this combo and may remove the "setcc" instruction if the "setcc"
10474   // has only one use.
10475   SDNode *N = Op.getNode();
10476   SDValue LHS = N->getOperand(0);
10477   SDValue RHS = N->getOperand(1);
10478   unsigned BaseOp = 0;
10479   unsigned Cond = 0;
10480   DebugLoc DL = Op.getDebugLoc();
10481   switch (Op.getOpcode()) {
10482   default: llvm_unreachable("Unknown ovf instruction!");
10483   case ISD::SADDO:
10484     // A subtract of one will be selected as a INC. Note that INC doesn't
10485     // set CF, so we can't do this for UADDO.
10486     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10487       if (C->isOne()) {
10488         BaseOp = X86ISD::INC;
10489         Cond = X86::COND_O;
10490         break;
10491       }
10492     BaseOp = X86ISD::ADD;
10493     Cond = X86::COND_O;
10494     break;
10495   case ISD::UADDO:
10496     BaseOp = X86ISD::ADD;
10497     Cond = X86::COND_B;
10498     break;
10499   case ISD::SSUBO:
10500     // A subtract of one will be selected as a DEC. Note that DEC doesn't
10501     // set CF, so we can't do this for USUBO.
10502     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10503       if (C->isOne()) {
10504         BaseOp = X86ISD::DEC;
10505         Cond = X86::COND_O;
10506         break;
10507       }
10508     BaseOp = X86ISD::SUB;
10509     Cond = X86::COND_O;
10510     break;
10511   case ISD::USUBO:
10512     BaseOp = X86ISD::SUB;
10513     Cond = X86::COND_B;
10514     break;
10515   case ISD::SMULO:
10516     BaseOp = X86ISD::SMUL;
10517     Cond = X86::COND_O;
10518     break;
10519   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
10520     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
10521                                  MVT::i32);
10522     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
10523
10524     SDValue SetCC =
10525       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10526                   DAG.getConstant(X86::COND_O, MVT::i32),
10527                   SDValue(Sum.getNode(), 2));
10528
10529     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10530   }
10531   }
10532
10533   // Also sets EFLAGS.
10534   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
10535   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
10536
10537   SDValue SetCC =
10538     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
10539                 DAG.getConstant(Cond, MVT::i32),
10540                 SDValue(Sum.getNode(), 1));
10541
10542   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10543 }
10544
10545 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op, SelectionDAG &DAG) const{
10546   DebugLoc dl = Op.getDebugLoc();
10547   SDNode* Node = Op.getNode();
10548   EVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
10549   EVT VT = Node->getValueType(0);
10550   if (Subtarget->hasXMMInt() && VT.isVector()) {
10551     unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
10552                         ExtraVT.getScalarType().getSizeInBits();
10553     SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
10554
10555     unsigned SHLIntrinsicsID = 0;
10556     unsigned SRAIntrinsicsID = 0;
10557     switch (VT.getSimpleVT().SimpleTy) {
10558       default:
10559         return SDValue();
10560       case MVT::v4i32: {
10561         SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_d;
10562         SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_d;
10563         break;
10564       }
10565       case MVT::v8i16: {
10566         SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_w;
10567         SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_w;
10568         break;
10569       }
10570     }
10571
10572     SDValue Tmp1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10573                          DAG.getConstant(SHLIntrinsicsID, MVT::i32),
10574                          Node->getOperand(0), ShAmt);
10575
10576     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10577                        DAG.getConstant(SRAIntrinsicsID, MVT::i32),
10578                        Tmp1, ShAmt);
10579   }
10580
10581   return SDValue();
10582 }
10583
10584
10585 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
10586   DebugLoc dl = Op.getDebugLoc();
10587
10588   // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
10589   // There isn't any reason to disable it if the target processor supports it.
10590   if (!Subtarget->hasXMMInt() && !Subtarget->is64Bit()) {
10591     SDValue Chain = Op.getOperand(0);
10592     SDValue Zero = DAG.getConstant(0, MVT::i32);
10593     SDValue Ops[] = {
10594       DAG.getRegister(X86::ESP, MVT::i32), // Base
10595       DAG.getTargetConstant(1, MVT::i8),   // Scale
10596       DAG.getRegister(0, MVT::i32),        // Index
10597       DAG.getTargetConstant(0, MVT::i32),  // Disp
10598       DAG.getRegister(0, MVT::i32),        // Segment.
10599       Zero,
10600       Chain
10601     };
10602     SDNode *Res =
10603       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10604                           array_lengthof(Ops));
10605     return SDValue(Res, 0);
10606   }
10607
10608   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
10609   if (!isDev)
10610     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10611
10612   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10613   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
10614   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
10615   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
10616
10617   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
10618   if (!Op1 && !Op2 && !Op3 && Op4)
10619     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
10620
10621   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
10622   if (Op1 && !Op2 && !Op3 && !Op4)
10623     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
10624
10625   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
10626   //           (MFENCE)>;
10627   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10628 }
10629
10630 SDValue X86TargetLowering::LowerATOMIC_FENCE(SDValue Op,
10631                                              SelectionDAG &DAG) const {
10632   DebugLoc dl = Op.getDebugLoc();
10633   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
10634     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
10635   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
10636     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
10637
10638   // The only fence that needs an instruction is a sequentially-consistent
10639   // cross-thread fence.
10640   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
10641     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
10642     // no-sse2). There isn't any reason to disable it if the target processor
10643     // supports it.
10644     if (Subtarget->hasXMMInt() || Subtarget->is64Bit())
10645       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10646
10647     SDValue Chain = Op.getOperand(0);
10648     SDValue Zero = DAG.getConstant(0, MVT::i32);
10649     SDValue Ops[] = {
10650       DAG.getRegister(X86::ESP, MVT::i32), // Base
10651       DAG.getTargetConstant(1, MVT::i8),   // Scale
10652       DAG.getRegister(0, MVT::i32),        // Index
10653       DAG.getTargetConstant(0, MVT::i32),  // Disp
10654       DAG.getRegister(0, MVT::i32),        // Segment.
10655       Zero,
10656       Chain
10657     };
10658     SDNode *Res =
10659       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10660                          array_lengthof(Ops));
10661     return SDValue(Res, 0);
10662   }
10663
10664   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
10665   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10666 }
10667
10668
10669 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
10670   EVT T = Op.getValueType();
10671   DebugLoc DL = Op.getDebugLoc();
10672   unsigned Reg = 0;
10673   unsigned size = 0;
10674   switch(T.getSimpleVT().SimpleTy) {
10675   default:
10676     assert(false && "Invalid value type!");
10677   case MVT::i8:  Reg = X86::AL;  size = 1; break;
10678   case MVT::i16: Reg = X86::AX;  size = 2; break;
10679   case MVT::i32: Reg = X86::EAX; size = 4; break;
10680   case MVT::i64:
10681     assert(Subtarget->is64Bit() && "Node not type legal!");
10682     Reg = X86::RAX; size = 8;
10683     break;
10684   }
10685   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
10686                                     Op.getOperand(2), SDValue());
10687   SDValue Ops[] = { cpIn.getValue(0),
10688                     Op.getOperand(1),
10689                     Op.getOperand(3),
10690                     DAG.getTargetConstant(size, MVT::i8),
10691                     cpIn.getValue(1) };
10692   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10693   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
10694   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
10695                                            Ops, 5, T, MMO);
10696   SDValue cpOut =
10697     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
10698   return cpOut;
10699 }
10700
10701 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
10702                                                  SelectionDAG &DAG) const {
10703   assert(Subtarget->is64Bit() && "Result not type legalized?");
10704   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10705   SDValue TheChain = Op.getOperand(0);
10706   DebugLoc dl = Op.getDebugLoc();
10707   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10708   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
10709   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
10710                                    rax.getValue(2));
10711   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
10712                             DAG.getConstant(32, MVT::i8));
10713   SDValue Ops[] = {
10714     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
10715     rdx.getValue(1)
10716   };
10717   return DAG.getMergeValues(Ops, 2, dl);
10718 }
10719
10720 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
10721                                             SelectionDAG &DAG) const {
10722   EVT SrcVT = Op.getOperand(0).getValueType();
10723   EVT DstVT = Op.getValueType();
10724   assert(Subtarget->is64Bit() && !Subtarget->hasXMMInt() &&
10725          Subtarget->hasMMX() && "Unexpected custom BITCAST");
10726   assert((DstVT == MVT::i64 ||
10727           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
10728          "Unexpected custom BITCAST");
10729   // i64 <=> MMX conversions are Legal.
10730   if (SrcVT==MVT::i64 && DstVT.isVector())
10731     return Op;
10732   if (DstVT==MVT::i64 && SrcVT.isVector())
10733     return Op;
10734   // MMX <=> MMX conversions are Legal.
10735   if (SrcVT.isVector() && DstVT.isVector())
10736     return Op;
10737   // All other conversions need to be expanded.
10738   return SDValue();
10739 }
10740
10741 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
10742   SDNode *Node = Op.getNode();
10743   DebugLoc dl = Node->getDebugLoc();
10744   EVT T = Node->getValueType(0);
10745   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
10746                               DAG.getConstant(0, T), Node->getOperand(2));
10747   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
10748                        cast<AtomicSDNode>(Node)->getMemoryVT(),
10749                        Node->getOperand(0),
10750                        Node->getOperand(1), negOp,
10751                        cast<AtomicSDNode>(Node)->getSrcValue(),
10752                        cast<AtomicSDNode>(Node)->getAlignment(),
10753                        cast<AtomicSDNode>(Node)->getOrdering(),
10754                        cast<AtomicSDNode>(Node)->getSynchScope());
10755 }
10756
10757 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
10758   SDNode *Node = Op.getNode();
10759   DebugLoc dl = Node->getDebugLoc();
10760   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10761
10762   // Convert seq_cst store -> xchg
10763   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
10764   // FIXME: On 32-bit, store -> fist or movq would be more efficient
10765   //        (The only way to get a 16-byte store is cmpxchg16b)
10766   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
10767   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
10768       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
10769     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
10770                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
10771                                  Node->getOperand(0),
10772                                  Node->getOperand(1), Node->getOperand(2),
10773                                  cast<AtomicSDNode>(Node)->getMemOperand(),
10774                                  cast<AtomicSDNode>(Node)->getOrdering(),
10775                                  cast<AtomicSDNode>(Node)->getSynchScope());
10776     return Swap.getValue(1);
10777   }
10778   // Other atomic stores have a simple pattern.
10779   return Op;
10780 }
10781
10782 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
10783   EVT VT = Op.getNode()->getValueType(0);
10784
10785   // Let legalize expand this if it isn't a legal type yet.
10786   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10787     return SDValue();
10788
10789   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10790
10791   unsigned Opc;
10792   bool ExtraOp = false;
10793   switch (Op.getOpcode()) {
10794   default: assert(0 && "Invalid code");
10795   case ISD::ADDC: Opc = X86ISD::ADD; break;
10796   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
10797   case ISD::SUBC: Opc = X86ISD::SUB; break;
10798   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
10799   }
10800
10801   if (!ExtraOp)
10802     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10803                        Op.getOperand(1));
10804   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10805                      Op.getOperand(1), Op.getOperand(2));
10806 }
10807
10808 /// LowerOperation - Provide custom lowering hooks for some operations.
10809 ///
10810 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10811   switch (Op.getOpcode()) {
10812   default: llvm_unreachable("Should not custom lower this!");
10813   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
10814   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op,DAG);
10815   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op,DAG);
10816   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
10817   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
10818   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
10819   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
10820   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
10821   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
10822   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
10823   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
10824   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op, DAG);
10825   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, DAG);
10826   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
10827   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
10828   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
10829   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
10830   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
10831   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
10832   case ISD::SHL_PARTS:
10833   case ISD::SRA_PARTS:
10834   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
10835   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
10836   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
10837   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
10838   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
10839   case ISD::FABS:               return LowerFABS(Op, DAG);
10840   case ISD::FNEG:               return LowerFNEG(Op, DAG);
10841   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
10842   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
10843   case ISD::SETCC:              return LowerSETCC(Op, DAG);
10844   case ISD::SELECT:             return LowerSELECT(Op, DAG);
10845   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
10846   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
10847   case ISD::VASTART:            return LowerVASTART(Op, DAG);
10848   case ISD::VAARG:              return LowerVAARG(Op, DAG);
10849   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
10850   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10851   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
10852   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
10853   case ISD::FRAME_TO_ARGS_OFFSET:
10854                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
10855   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10856   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
10857   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
10858   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
10859   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
10860   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
10861   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
10862   case ISD::MUL:                return LowerMUL(Op, DAG);
10863   case ISD::SRA:
10864   case ISD::SRL:
10865   case ISD::SHL:                return LowerShift(Op, DAG);
10866   case ISD::SADDO:
10867   case ISD::UADDO:
10868   case ISD::SSUBO:
10869   case ISD::USUBO:
10870   case ISD::SMULO:
10871   case ISD::UMULO:              return LowerXALUO(Op, DAG);
10872   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
10873   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
10874   case ISD::ADDC:
10875   case ISD::ADDE:
10876   case ISD::SUBC:
10877   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
10878   case ISD::ADD:                return LowerADD(Op, DAG);
10879   case ISD::SUB:                return LowerSUB(Op, DAG);
10880   }
10881 }
10882
10883 static void ReplaceATOMIC_LOAD(SDNode *Node,
10884                                   SmallVectorImpl<SDValue> &Results,
10885                                   SelectionDAG &DAG) {
10886   DebugLoc dl = Node->getDebugLoc();
10887   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10888
10889   // Convert wide load -> cmpxchg8b/cmpxchg16b
10890   // FIXME: On 32-bit, load -> fild or movq would be more efficient
10891   //        (The only way to get a 16-byte load is cmpxchg16b)
10892   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
10893   SDValue Zero = DAG.getConstant(0, VT);
10894   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
10895                                Node->getOperand(0),
10896                                Node->getOperand(1), Zero, Zero,
10897                                cast<AtomicSDNode>(Node)->getMemOperand(),
10898                                cast<AtomicSDNode>(Node)->getOrdering(),
10899                                cast<AtomicSDNode>(Node)->getSynchScope());
10900   Results.push_back(Swap.getValue(0));
10901   Results.push_back(Swap.getValue(1));
10902 }
10903
10904 void X86TargetLowering::
10905 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
10906                         SelectionDAG &DAG, unsigned NewOp) const {
10907   DebugLoc dl = Node->getDebugLoc();
10908   assert (Node->getValueType(0) == MVT::i64 &&
10909           "Only know how to expand i64 atomics");
10910
10911   SDValue Chain = Node->getOperand(0);
10912   SDValue In1 = Node->getOperand(1);
10913   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10914                              Node->getOperand(2), DAG.getIntPtrConstant(0));
10915   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10916                              Node->getOperand(2), DAG.getIntPtrConstant(1));
10917   SDValue Ops[] = { Chain, In1, In2L, In2H };
10918   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
10919   SDValue Result =
10920     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
10921                             cast<MemSDNode>(Node)->getMemOperand());
10922   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
10923   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
10924   Results.push_back(Result.getValue(2));
10925 }
10926
10927 /// ReplaceNodeResults - Replace a node with an illegal result type
10928 /// with a new node built out of custom code.
10929 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
10930                                            SmallVectorImpl<SDValue>&Results,
10931                                            SelectionDAG &DAG) const {
10932   DebugLoc dl = N->getDebugLoc();
10933   switch (N->getOpcode()) {
10934   default:
10935     assert(false && "Do not know how to custom type legalize this operation!");
10936     return;
10937   case ISD::SIGN_EXTEND_INREG:
10938   case ISD::ADDC:
10939   case ISD::ADDE:
10940   case ISD::SUBC:
10941   case ISD::SUBE:
10942     // We don't want to expand or promote these.
10943     return;
10944   case ISD::FP_TO_SINT: {
10945     std::pair<SDValue,SDValue> Vals =
10946         FP_TO_INTHelper(SDValue(N, 0), DAG, true);
10947     SDValue FIST = Vals.first, StackSlot = Vals.second;
10948     if (FIST.getNode() != 0) {
10949       EVT VT = N->getValueType(0);
10950       // Return a load from the stack slot.
10951       Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
10952                                     MachinePointerInfo(), 
10953                                     false, false, false, 0));
10954     }
10955     return;
10956   }
10957   case ISD::READCYCLECOUNTER: {
10958     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10959     SDValue TheChain = N->getOperand(0);
10960     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10961     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
10962                                      rd.getValue(1));
10963     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
10964                                      eax.getValue(2));
10965     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
10966     SDValue Ops[] = { eax, edx };
10967     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
10968     Results.push_back(edx.getValue(1));
10969     return;
10970   }
10971   case ISD::ATOMIC_CMP_SWAP: {
10972     EVT T = N->getValueType(0);
10973     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
10974     bool Regs64bit = T == MVT::i128;
10975     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
10976     SDValue cpInL, cpInH;
10977     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
10978                         DAG.getConstant(0, HalfT));
10979     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
10980                         DAG.getConstant(1, HalfT));
10981     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
10982                              Regs64bit ? X86::RAX : X86::EAX,
10983                              cpInL, SDValue());
10984     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
10985                              Regs64bit ? X86::RDX : X86::EDX,
10986                              cpInH, cpInL.getValue(1));
10987     SDValue swapInL, swapInH;
10988     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
10989                           DAG.getConstant(0, HalfT));
10990     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
10991                           DAG.getConstant(1, HalfT));
10992     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
10993                                Regs64bit ? X86::RBX : X86::EBX,
10994                                swapInL, cpInH.getValue(1));
10995     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
10996                                Regs64bit ? X86::RCX : X86::ECX, 
10997                                swapInH, swapInL.getValue(1));
10998     SDValue Ops[] = { swapInH.getValue(0),
10999                       N->getOperand(1),
11000                       swapInH.getValue(1) };
11001     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11002     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
11003     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
11004                                   X86ISD::LCMPXCHG8_DAG;
11005     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
11006                                              Ops, 3, T, MMO);
11007     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
11008                                         Regs64bit ? X86::RAX : X86::EAX,
11009                                         HalfT, Result.getValue(1));
11010     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
11011                                         Regs64bit ? X86::RDX : X86::EDX,
11012                                         HalfT, cpOutL.getValue(2));
11013     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
11014     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
11015     Results.push_back(cpOutH.getValue(1));
11016     return;
11017   }
11018   case ISD::ATOMIC_LOAD_ADD:
11019     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
11020     return;
11021   case ISD::ATOMIC_LOAD_AND:
11022     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
11023     return;
11024   case ISD::ATOMIC_LOAD_NAND:
11025     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
11026     return;
11027   case ISD::ATOMIC_LOAD_OR:
11028     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
11029     return;
11030   case ISD::ATOMIC_LOAD_SUB:
11031     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
11032     return;
11033   case ISD::ATOMIC_LOAD_XOR:
11034     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
11035     return;
11036   case ISD::ATOMIC_SWAP:
11037     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
11038     return;
11039   case ISD::ATOMIC_LOAD:
11040     ReplaceATOMIC_LOAD(N, Results, DAG);
11041   }
11042 }
11043
11044 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
11045   switch (Opcode) {
11046   default: return NULL;
11047   case X86ISD::BSF:                return "X86ISD::BSF";
11048   case X86ISD::BSR:                return "X86ISD::BSR";
11049   case X86ISD::SHLD:               return "X86ISD::SHLD";
11050   case X86ISD::SHRD:               return "X86ISD::SHRD";
11051   case X86ISD::FAND:               return "X86ISD::FAND";
11052   case X86ISD::FOR:                return "X86ISD::FOR";
11053   case X86ISD::FXOR:               return "X86ISD::FXOR";
11054   case X86ISD::FSRL:               return "X86ISD::FSRL";
11055   case X86ISD::FILD:               return "X86ISD::FILD";
11056   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
11057   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
11058   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
11059   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
11060   case X86ISD::FLD:                return "X86ISD::FLD";
11061   case X86ISD::FST:                return "X86ISD::FST";
11062   case X86ISD::CALL:               return "X86ISD::CALL";
11063   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
11064   case X86ISD::BT:                 return "X86ISD::BT";
11065   case X86ISD::CMP:                return "X86ISD::CMP";
11066   case X86ISD::COMI:               return "X86ISD::COMI";
11067   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
11068   case X86ISD::SETCC:              return "X86ISD::SETCC";
11069   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
11070   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
11071   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
11072   case X86ISD::CMOV:               return "X86ISD::CMOV";
11073   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
11074   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
11075   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
11076   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
11077   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
11078   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
11079   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
11080   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
11081   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
11082   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
11083   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
11084   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
11085   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
11086   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
11087   case X86ISD::PSIGNB:             return "X86ISD::PSIGNB";
11088   case X86ISD::PSIGNW:             return "X86ISD::PSIGNW";
11089   case X86ISD::PSIGND:             return "X86ISD::PSIGND";
11090   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
11091   case X86ISD::FHADD:              return "X86ISD::FHADD";
11092   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
11093   case X86ISD::FMAX:               return "X86ISD::FMAX";
11094   case X86ISD::FMIN:               return "X86ISD::FMIN";
11095   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
11096   case X86ISD::FRCP:               return "X86ISD::FRCP";
11097   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
11098   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
11099   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
11100   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
11101   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
11102   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
11103   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
11104   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
11105   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
11106   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
11107   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
11108   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
11109   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
11110   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
11111   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
11112   case X86ISD::VSHL:               return "X86ISD::VSHL";
11113   case X86ISD::VSRL:               return "X86ISD::VSRL";
11114   case X86ISD::CMPPD:              return "X86ISD::CMPPD";
11115   case X86ISD::CMPPS:              return "X86ISD::CMPPS";
11116   case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
11117   case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
11118   case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
11119   case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
11120   case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
11121   case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
11122   case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
11123   case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
11124   case X86ISD::ADD:                return "X86ISD::ADD";
11125   case X86ISD::SUB:                return "X86ISD::SUB";
11126   case X86ISD::ADC:                return "X86ISD::ADC";
11127   case X86ISD::SBB:                return "X86ISD::SBB";
11128   case X86ISD::SMUL:               return "X86ISD::SMUL";
11129   case X86ISD::UMUL:               return "X86ISD::UMUL";
11130   case X86ISD::INC:                return "X86ISD::INC";
11131   case X86ISD::DEC:                return "X86ISD::DEC";
11132   case X86ISD::OR:                 return "X86ISD::OR";
11133   case X86ISD::XOR:                return "X86ISD::XOR";
11134   case X86ISD::AND:                return "X86ISD::AND";
11135   case X86ISD::ANDN:               return "X86ISD::ANDN";
11136   case X86ISD::BLSI:               return "X86ISD::BLSI";
11137   case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
11138   case X86ISD::BLSR:               return "X86ISD::BLSR";
11139   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
11140   case X86ISD::PTEST:              return "X86ISD::PTEST";
11141   case X86ISD::TESTP:              return "X86ISD::TESTP";
11142   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
11143   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
11144   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
11145   case X86ISD::PSHUFHW_LD:         return "X86ISD::PSHUFHW_LD";
11146   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
11147   case X86ISD::PSHUFLW_LD:         return "X86ISD::PSHUFLW_LD";
11148   case X86ISD::SHUFPS:             return "X86ISD::SHUFPS";
11149   case X86ISD::SHUFPD:             return "X86ISD::SHUFPD";
11150   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
11151   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
11152   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
11153   case X86ISD::MOVHLPD:            return "X86ISD::MOVHLPD";
11154   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
11155   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
11156   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
11157   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
11158   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
11159   case X86ISD::MOVSHDUP_LD:        return "X86ISD::MOVSHDUP_LD";
11160   case X86ISD::MOVSLDUP_LD:        return "X86ISD::MOVSLDUP_LD";
11161   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
11162   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
11163   case X86ISD::UNPCKLPS:           return "X86ISD::UNPCKLPS";
11164   case X86ISD::UNPCKLPD:           return "X86ISD::UNPCKLPD";
11165   case X86ISD::VUNPCKLPDY:         return "X86ISD::VUNPCKLPDY";
11166   case X86ISD::UNPCKHPS:           return "X86ISD::UNPCKHPS";
11167   case X86ISD::UNPCKHPD:           return "X86ISD::UNPCKHPD";
11168   case X86ISD::PUNPCKLBW:          return "X86ISD::PUNPCKLBW";
11169   case X86ISD::PUNPCKLWD:          return "X86ISD::PUNPCKLWD";
11170   case X86ISD::PUNPCKLDQ:          return "X86ISD::PUNPCKLDQ";
11171   case X86ISD::PUNPCKLQDQ:         return "X86ISD::PUNPCKLQDQ";
11172   case X86ISD::PUNPCKHBW:          return "X86ISD::PUNPCKHBW";
11173   case X86ISD::PUNPCKHWD:          return "X86ISD::PUNPCKHWD";
11174   case X86ISD::PUNPCKHDQ:          return "X86ISD::PUNPCKHDQ";
11175   case X86ISD::PUNPCKHQDQ:         return "X86ISD::PUNPCKHQDQ";
11176   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
11177   case X86ISD::VPERMILPS:          return "X86ISD::VPERMILPS";
11178   case X86ISD::VPERMILPSY:         return "X86ISD::VPERMILPSY";
11179   case X86ISD::VPERMILPD:          return "X86ISD::VPERMILPD";
11180   case X86ISD::VPERMILPDY:         return "X86ISD::VPERMILPDY";
11181   case X86ISD::VPERM2F128:         return "X86ISD::VPERM2F128";
11182   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
11183   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
11184   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
11185   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
11186   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
11187   }
11188 }
11189
11190 // isLegalAddressingMode - Return true if the addressing mode represented
11191 // by AM is legal for this target, for a load/store of the specified type.
11192 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
11193                                               Type *Ty) const {
11194   // X86 supports extremely general addressing modes.
11195   CodeModel::Model M = getTargetMachine().getCodeModel();
11196   Reloc::Model R = getTargetMachine().getRelocationModel();
11197
11198   // X86 allows a sign-extended 32-bit immediate field as a displacement.
11199   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
11200     return false;
11201
11202   if (AM.BaseGV) {
11203     unsigned GVFlags =
11204       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
11205
11206     // If a reference to this global requires an extra load, we can't fold it.
11207     if (isGlobalStubReference(GVFlags))
11208       return false;
11209
11210     // If BaseGV requires a register for the PIC base, we cannot also have a
11211     // BaseReg specified.
11212     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
11213       return false;
11214
11215     // If lower 4G is not available, then we must use rip-relative addressing.
11216     if ((M != CodeModel::Small || R != Reloc::Static) &&
11217         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
11218       return false;
11219   }
11220
11221   switch (AM.Scale) {
11222   case 0:
11223   case 1:
11224   case 2:
11225   case 4:
11226   case 8:
11227     // These scales always work.
11228     break;
11229   case 3:
11230   case 5:
11231   case 9:
11232     // These scales are formed with basereg+scalereg.  Only accept if there is
11233     // no basereg yet.
11234     if (AM.HasBaseReg)
11235       return false;
11236     break;
11237   default:  // Other stuff never works.
11238     return false;
11239   }
11240
11241   return true;
11242 }
11243
11244
11245 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11246   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11247     return false;
11248   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11249   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11250   if (NumBits1 <= NumBits2)
11251     return false;
11252   return true;
11253 }
11254
11255 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11256   if (!VT1.isInteger() || !VT2.isInteger())
11257     return false;
11258   unsigned NumBits1 = VT1.getSizeInBits();
11259   unsigned NumBits2 = VT2.getSizeInBits();
11260   if (NumBits1 <= NumBits2)
11261     return false;
11262   return true;
11263 }
11264
11265 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
11266   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11267   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
11268 }
11269
11270 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
11271   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11272   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
11273 }
11274
11275 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
11276   // i16 instructions are longer (0x66 prefix) and potentially slower.
11277   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
11278 }
11279
11280 /// isShuffleMaskLegal - Targets can use this to indicate that they only
11281 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
11282 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
11283 /// are assumed to be legal.
11284 bool
11285 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
11286                                       EVT VT) const {
11287   // Very little shuffling can be done for 64-bit vectors right now.
11288   if (VT.getSizeInBits() == 64)
11289     return isPALIGNRMask(M, VT, Subtarget->hasSSSE3() || Subtarget->hasAVX());
11290
11291   // FIXME: pshufb, blends, shifts.
11292   return (VT.getVectorNumElements() == 2 ||
11293           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
11294           isMOVLMask(M, VT) ||
11295           isSHUFPMask(M, VT) ||
11296           isPSHUFDMask(M, VT) ||
11297           isPSHUFHWMask(M, VT) ||
11298           isPSHUFLWMask(M, VT) ||
11299           isPALIGNRMask(M, VT, Subtarget->hasSSSE3() || Subtarget->hasAVX()) ||
11300           isUNPCKLMask(M, VT) ||
11301           isUNPCKHMask(M, VT) ||
11302           isUNPCKL_v_undef_Mask(M, VT) ||
11303           isUNPCKH_v_undef_Mask(M, VT));
11304 }
11305
11306 bool
11307 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
11308                                           EVT VT) const {
11309   unsigned NumElts = VT.getVectorNumElements();
11310   // FIXME: This collection of masks seems suspect.
11311   if (NumElts == 2)
11312     return true;
11313   if (NumElts == 4 && VT.getSizeInBits() == 128) {
11314     return (isMOVLMask(Mask, VT)  ||
11315             isCommutedMOVLMask(Mask, VT, true) ||
11316             isSHUFPMask(Mask, VT) ||
11317             isCommutedSHUFPMask(Mask, VT));
11318   }
11319   return false;
11320 }
11321
11322 //===----------------------------------------------------------------------===//
11323 //                           X86 Scheduler Hooks
11324 //===----------------------------------------------------------------------===//
11325
11326 // private utility function
11327 MachineBasicBlock *
11328 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
11329                                                        MachineBasicBlock *MBB,
11330                                                        unsigned regOpc,
11331                                                        unsigned immOpc,
11332                                                        unsigned LoadOpc,
11333                                                        unsigned CXchgOpc,
11334                                                        unsigned notOpc,
11335                                                        unsigned EAXreg,
11336                                                        TargetRegisterClass *RC,
11337                                                        bool invSrc) const {
11338   // For the atomic bitwise operator, we generate
11339   //   thisMBB:
11340   //   newMBB:
11341   //     ld  t1 = [bitinstr.addr]
11342   //     op  t2 = t1, [bitinstr.val]
11343   //     mov EAX = t1
11344   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
11345   //     bz  newMBB
11346   //     fallthrough -->nextMBB
11347   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11348   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11349   MachineFunction::iterator MBBIter = MBB;
11350   ++MBBIter;
11351
11352   /// First build the CFG
11353   MachineFunction *F = MBB->getParent();
11354   MachineBasicBlock *thisMBB = MBB;
11355   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11356   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11357   F->insert(MBBIter, newMBB);
11358   F->insert(MBBIter, nextMBB);
11359
11360   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11361   nextMBB->splice(nextMBB->begin(), thisMBB,
11362                   llvm::next(MachineBasicBlock::iterator(bInstr)),
11363                   thisMBB->end());
11364   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11365
11366   // Update thisMBB to fall through to newMBB
11367   thisMBB->addSuccessor(newMBB);
11368
11369   // newMBB jumps to itself and fall through to nextMBB
11370   newMBB->addSuccessor(nextMBB);
11371   newMBB->addSuccessor(newMBB);
11372
11373   // Insert instructions into newMBB based on incoming instruction
11374   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11375          "unexpected number of operands");
11376   DebugLoc dl = bInstr->getDebugLoc();
11377   MachineOperand& destOper = bInstr->getOperand(0);
11378   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11379   int numArgs = bInstr->getNumOperands() - 1;
11380   for (int i=0; i < numArgs; ++i)
11381     argOpers[i] = &bInstr->getOperand(i+1);
11382
11383   // x86 address has 4 operands: base, index, scale, and displacement
11384   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11385   int valArgIndx = lastAddrIndx + 1;
11386
11387   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11388   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
11389   for (int i=0; i <= lastAddrIndx; ++i)
11390     (*MIB).addOperand(*argOpers[i]);
11391
11392   unsigned tt = F->getRegInfo().createVirtualRegister(RC);
11393   if (invSrc) {
11394     MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
11395   }
11396   else
11397     tt = t1;
11398
11399   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11400   assert((argOpers[valArgIndx]->isReg() ||
11401           argOpers[valArgIndx]->isImm()) &&
11402          "invalid operand");
11403   if (argOpers[valArgIndx]->isReg())
11404     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
11405   else
11406     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
11407   MIB.addReg(tt);
11408   (*MIB).addOperand(*argOpers[valArgIndx]);
11409
11410   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
11411   MIB.addReg(t1);
11412
11413   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
11414   for (int i=0; i <= lastAddrIndx; ++i)
11415     (*MIB).addOperand(*argOpers[i]);
11416   MIB.addReg(t2);
11417   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11418   (*MIB).setMemRefs(bInstr->memoperands_begin(),
11419                     bInstr->memoperands_end());
11420
11421   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11422   MIB.addReg(EAXreg);
11423
11424   // insert branch
11425   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11426
11427   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
11428   return nextMBB;
11429 }
11430
11431 // private utility function:  64 bit atomics on 32 bit host.
11432 MachineBasicBlock *
11433 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
11434                                                        MachineBasicBlock *MBB,
11435                                                        unsigned regOpcL,
11436                                                        unsigned regOpcH,
11437                                                        unsigned immOpcL,
11438                                                        unsigned immOpcH,
11439                                                        bool invSrc) const {
11440   // For the atomic bitwise operator, we generate
11441   //   thisMBB (instructions are in pairs, except cmpxchg8b)
11442   //     ld t1,t2 = [bitinstr.addr]
11443   //   newMBB:
11444   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
11445   //     op  t5, t6 <- out1, out2, [bitinstr.val]
11446   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
11447   //     mov ECX, EBX <- t5, t6
11448   //     mov EAX, EDX <- t1, t2
11449   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
11450   //     mov t3, t4 <- EAX, EDX
11451   //     bz  newMBB
11452   //     result in out1, out2
11453   //     fallthrough -->nextMBB
11454
11455   const TargetRegisterClass *RC = X86::GR32RegisterClass;
11456   const unsigned LoadOpc = X86::MOV32rm;
11457   const unsigned NotOpc = X86::NOT32r;
11458   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11459   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11460   MachineFunction::iterator MBBIter = MBB;
11461   ++MBBIter;
11462
11463   /// First build the CFG
11464   MachineFunction *F = MBB->getParent();
11465   MachineBasicBlock *thisMBB = MBB;
11466   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11467   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11468   F->insert(MBBIter, newMBB);
11469   F->insert(MBBIter, nextMBB);
11470
11471   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11472   nextMBB->splice(nextMBB->begin(), thisMBB,
11473                   llvm::next(MachineBasicBlock::iterator(bInstr)),
11474                   thisMBB->end());
11475   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11476
11477   // Update thisMBB to fall through to newMBB
11478   thisMBB->addSuccessor(newMBB);
11479
11480   // newMBB jumps to itself and fall through to nextMBB
11481   newMBB->addSuccessor(nextMBB);
11482   newMBB->addSuccessor(newMBB);
11483
11484   DebugLoc dl = bInstr->getDebugLoc();
11485   // Insert instructions into newMBB based on incoming instruction
11486   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
11487   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
11488          "unexpected number of operands");
11489   MachineOperand& dest1Oper = bInstr->getOperand(0);
11490   MachineOperand& dest2Oper = bInstr->getOperand(1);
11491   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11492   for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
11493     argOpers[i] = &bInstr->getOperand(i+2);
11494
11495     // We use some of the operands multiple times, so conservatively just
11496     // clear any kill flags that might be present.
11497     if (argOpers[i]->isReg() && argOpers[i]->isUse())
11498       argOpers[i]->setIsKill(false);
11499   }
11500
11501   // x86 address has 5 operands: base, index, scale, displacement, and segment.
11502   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11503
11504   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11505   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
11506   for (int i=0; i <= lastAddrIndx; ++i)
11507     (*MIB).addOperand(*argOpers[i]);
11508   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11509   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
11510   // add 4 to displacement.
11511   for (int i=0; i <= lastAddrIndx-2; ++i)
11512     (*MIB).addOperand(*argOpers[i]);
11513   MachineOperand newOp3 = *(argOpers[3]);
11514   if (newOp3.isImm())
11515     newOp3.setImm(newOp3.getImm()+4);
11516   else
11517     newOp3.setOffset(newOp3.getOffset()+4);
11518   (*MIB).addOperand(newOp3);
11519   (*MIB).addOperand(*argOpers[lastAddrIndx]);
11520
11521   // t3/4 are defined later, at the bottom of the loop
11522   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11523   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
11524   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
11525     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
11526   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
11527     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
11528
11529   // The subsequent operations should be using the destination registers of
11530   //the PHI instructions.
11531   if (invSrc) {
11532     t1 = F->getRegInfo().createVirtualRegister(RC);
11533     t2 = F->getRegInfo().createVirtualRegister(RC);
11534     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
11535     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
11536   } else {
11537     t1 = dest1Oper.getReg();
11538     t2 = dest2Oper.getReg();
11539   }
11540
11541   int valArgIndx = lastAddrIndx + 1;
11542   assert((argOpers[valArgIndx]->isReg() ||
11543           argOpers[valArgIndx]->isImm()) &&
11544          "invalid operand");
11545   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
11546   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
11547   if (argOpers[valArgIndx]->isReg())
11548     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
11549   else
11550     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
11551   if (regOpcL != X86::MOV32rr)
11552     MIB.addReg(t1);
11553   (*MIB).addOperand(*argOpers[valArgIndx]);
11554   assert(argOpers[valArgIndx + 1]->isReg() ==
11555          argOpers[valArgIndx]->isReg());
11556   assert(argOpers[valArgIndx + 1]->isImm() ==
11557          argOpers[valArgIndx]->isImm());
11558   if (argOpers[valArgIndx + 1]->isReg())
11559     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
11560   else
11561     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
11562   if (regOpcH != X86::MOV32rr)
11563     MIB.addReg(t2);
11564   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
11565
11566   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11567   MIB.addReg(t1);
11568   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
11569   MIB.addReg(t2);
11570
11571   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
11572   MIB.addReg(t5);
11573   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
11574   MIB.addReg(t6);
11575
11576   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
11577   for (int i=0; i <= lastAddrIndx; ++i)
11578     (*MIB).addOperand(*argOpers[i]);
11579
11580   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11581   (*MIB).setMemRefs(bInstr->memoperands_begin(),
11582                     bInstr->memoperands_end());
11583
11584   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
11585   MIB.addReg(X86::EAX);
11586   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
11587   MIB.addReg(X86::EDX);
11588
11589   // insert branch
11590   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11591
11592   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
11593   return nextMBB;
11594 }
11595
11596 // private utility function
11597 MachineBasicBlock *
11598 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
11599                                                       MachineBasicBlock *MBB,
11600                                                       unsigned cmovOpc) const {
11601   // For the atomic min/max operator, we generate
11602   //   thisMBB:
11603   //   newMBB:
11604   //     ld t1 = [min/max.addr]
11605   //     mov t2 = [min/max.val]
11606   //     cmp  t1, t2
11607   //     cmov[cond] t2 = t1
11608   //     mov EAX = t1
11609   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
11610   //     bz   newMBB
11611   //     fallthrough -->nextMBB
11612   //
11613   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11614   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11615   MachineFunction::iterator MBBIter = MBB;
11616   ++MBBIter;
11617
11618   /// First build the CFG
11619   MachineFunction *F = MBB->getParent();
11620   MachineBasicBlock *thisMBB = MBB;
11621   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11622   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11623   F->insert(MBBIter, newMBB);
11624   F->insert(MBBIter, nextMBB);
11625
11626   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11627   nextMBB->splice(nextMBB->begin(), thisMBB,
11628                   llvm::next(MachineBasicBlock::iterator(mInstr)),
11629                   thisMBB->end());
11630   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11631
11632   // Update thisMBB to fall through to newMBB
11633   thisMBB->addSuccessor(newMBB);
11634
11635   // newMBB jumps to newMBB and fall through to nextMBB
11636   newMBB->addSuccessor(nextMBB);
11637   newMBB->addSuccessor(newMBB);
11638
11639   DebugLoc dl = mInstr->getDebugLoc();
11640   // Insert instructions into newMBB based on incoming instruction
11641   assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11642          "unexpected number of operands");
11643   MachineOperand& destOper = mInstr->getOperand(0);
11644   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11645   int numArgs = mInstr->getNumOperands() - 1;
11646   for (int i=0; i < numArgs; ++i)
11647     argOpers[i] = &mInstr->getOperand(i+1);
11648
11649   // x86 address has 4 operands: base, index, scale, and displacement
11650   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11651   int valArgIndx = lastAddrIndx + 1;
11652
11653   unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11654   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
11655   for (int i=0; i <= lastAddrIndx; ++i)
11656     (*MIB).addOperand(*argOpers[i]);
11657
11658   // We only support register and immediate values
11659   assert((argOpers[valArgIndx]->isReg() ||
11660           argOpers[valArgIndx]->isImm()) &&
11661          "invalid operand");
11662
11663   unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11664   if (argOpers[valArgIndx]->isReg())
11665     MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
11666   else
11667     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
11668   (*MIB).addOperand(*argOpers[valArgIndx]);
11669
11670   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11671   MIB.addReg(t1);
11672
11673   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
11674   MIB.addReg(t1);
11675   MIB.addReg(t2);
11676
11677   // Generate movc
11678   unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11679   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
11680   MIB.addReg(t2);
11681   MIB.addReg(t1);
11682
11683   // Cmp and exchange if none has modified the memory location
11684   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
11685   for (int i=0; i <= lastAddrIndx; ++i)
11686     (*MIB).addOperand(*argOpers[i]);
11687   MIB.addReg(t3);
11688   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11689   (*MIB).setMemRefs(mInstr->memoperands_begin(),
11690                     mInstr->memoperands_end());
11691
11692   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11693   MIB.addReg(X86::EAX);
11694
11695   // insert branch
11696   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11697
11698   mInstr->eraseFromParent();   // The pseudo instruction is gone now.
11699   return nextMBB;
11700 }
11701
11702 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
11703 // or XMM0_V32I8 in AVX all of this code can be replaced with that
11704 // in the .td file.
11705 MachineBasicBlock *
11706 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
11707                             unsigned numArgs, bool memArg) const {
11708   assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
11709          "Target must have SSE4.2 or AVX features enabled");
11710
11711   DebugLoc dl = MI->getDebugLoc();
11712   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11713   unsigned Opc;
11714   if (!Subtarget->hasAVX()) {
11715     if (memArg)
11716       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
11717     else
11718       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
11719   } else {
11720     if (memArg)
11721       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
11722     else
11723       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
11724   }
11725
11726   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
11727   for (unsigned i = 0; i < numArgs; ++i) {
11728     MachineOperand &Op = MI->getOperand(i+1);
11729     if (!(Op.isReg() && Op.isImplicit()))
11730       MIB.addOperand(Op);
11731   }
11732   BuildMI(*BB, MI, dl,
11733     TII->get(Subtarget->hasAVX() ? X86::VMOVAPSrr : X86::MOVAPSrr),
11734              MI->getOperand(0).getReg())
11735     .addReg(X86::XMM0);
11736
11737   MI->eraseFromParent();
11738   return BB;
11739 }
11740
11741 MachineBasicBlock *
11742 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
11743   DebugLoc dl = MI->getDebugLoc();
11744   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11745
11746   // Address into RAX/EAX, other two args into ECX, EDX.
11747   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
11748   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11749   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
11750   for (int i = 0; i < X86::AddrNumOperands; ++i)
11751     MIB.addOperand(MI->getOperand(i));
11752
11753   unsigned ValOps = X86::AddrNumOperands;
11754   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11755     .addReg(MI->getOperand(ValOps).getReg());
11756   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
11757     .addReg(MI->getOperand(ValOps+1).getReg());
11758
11759   // The instruction doesn't actually take any operands though.
11760   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
11761
11762   MI->eraseFromParent(); // The pseudo is gone now.
11763   return BB;
11764 }
11765
11766 MachineBasicBlock *
11767 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
11768   DebugLoc dl = MI->getDebugLoc();
11769   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11770
11771   // First arg in ECX, the second in EAX.
11772   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11773     .addReg(MI->getOperand(0).getReg());
11774   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
11775     .addReg(MI->getOperand(1).getReg());
11776
11777   // The instruction doesn't actually take any operands though.
11778   BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
11779
11780   MI->eraseFromParent(); // The pseudo is gone now.
11781   return BB;
11782 }
11783
11784 MachineBasicBlock *
11785 X86TargetLowering::EmitVAARG64WithCustomInserter(
11786                    MachineInstr *MI,
11787                    MachineBasicBlock *MBB) const {
11788   // Emit va_arg instruction on X86-64.
11789
11790   // Operands to this pseudo-instruction:
11791   // 0  ) Output        : destination address (reg)
11792   // 1-5) Input         : va_list address (addr, i64mem)
11793   // 6  ) ArgSize       : Size (in bytes) of vararg type
11794   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
11795   // 8  ) Align         : Alignment of type
11796   // 9  ) EFLAGS (implicit-def)
11797
11798   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
11799   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
11800
11801   unsigned DestReg = MI->getOperand(0).getReg();
11802   MachineOperand &Base = MI->getOperand(1);
11803   MachineOperand &Scale = MI->getOperand(2);
11804   MachineOperand &Index = MI->getOperand(3);
11805   MachineOperand &Disp = MI->getOperand(4);
11806   MachineOperand &Segment = MI->getOperand(5);
11807   unsigned ArgSize = MI->getOperand(6).getImm();
11808   unsigned ArgMode = MI->getOperand(7).getImm();
11809   unsigned Align = MI->getOperand(8).getImm();
11810
11811   // Memory Reference
11812   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
11813   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
11814   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
11815
11816   // Machine Information
11817   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11818   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
11819   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
11820   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
11821   DebugLoc DL = MI->getDebugLoc();
11822
11823   // struct va_list {
11824   //   i32   gp_offset
11825   //   i32   fp_offset
11826   //   i64   overflow_area (address)
11827   //   i64   reg_save_area (address)
11828   // }
11829   // sizeof(va_list) = 24
11830   // alignment(va_list) = 8
11831
11832   unsigned TotalNumIntRegs = 6;
11833   unsigned TotalNumXMMRegs = 8;
11834   bool UseGPOffset = (ArgMode == 1);
11835   bool UseFPOffset = (ArgMode == 2);
11836   unsigned MaxOffset = TotalNumIntRegs * 8 +
11837                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
11838
11839   /* Align ArgSize to a multiple of 8 */
11840   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
11841   bool NeedsAlign = (Align > 8);
11842
11843   MachineBasicBlock *thisMBB = MBB;
11844   MachineBasicBlock *overflowMBB;
11845   MachineBasicBlock *offsetMBB;
11846   MachineBasicBlock *endMBB;
11847
11848   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
11849   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
11850   unsigned OffsetReg = 0;
11851
11852   if (!UseGPOffset && !UseFPOffset) {
11853     // If we only pull from the overflow region, we don't create a branch.
11854     // We don't need to alter control flow.
11855     OffsetDestReg = 0; // unused
11856     OverflowDestReg = DestReg;
11857
11858     offsetMBB = NULL;
11859     overflowMBB = thisMBB;
11860     endMBB = thisMBB;
11861   } else {
11862     // First emit code to check if gp_offset (or fp_offset) is below the bound.
11863     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
11864     // If not, pull from overflow_area. (branch to overflowMBB)
11865     //
11866     //       thisMBB
11867     //         |     .
11868     //         |        .
11869     //     offsetMBB   overflowMBB
11870     //         |        .
11871     //         |     .
11872     //        endMBB
11873
11874     // Registers for the PHI in endMBB
11875     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
11876     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
11877
11878     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11879     MachineFunction *MF = MBB->getParent();
11880     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11881     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11882     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11883
11884     MachineFunction::iterator MBBIter = MBB;
11885     ++MBBIter;
11886
11887     // Insert the new basic blocks
11888     MF->insert(MBBIter, offsetMBB);
11889     MF->insert(MBBIter, overflowMBB);
11890     MF->insert(MBBIter, endMBB);
11891
11892     // Transfer the remainder of MBB and its successor edges to endMBB.
11893     endMBB->splice(endMBB->begin(), thisMBB,
11894                     llvm::next(MachineBasicBlock::iterator(MI)),
11895                     thisMBB->end());
11896     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11897
11898     // Make offsetMBB and overflowMBB successors of thisMBB
11899     thisMBB->addSuccessor(offsetMBB);
11900     thisMBB->addSuccessor(overflowMBB);
11901
11902     // endMBB is a successor of both offsetMBB and overflowMBB
11903     offsetMBB->addSuccessor(endMBB);
11904     overflowMBB->addSuccessor(endMBB);
11905
11906     // Load the offset value into a register
11907     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
11908     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
11909       .addOperand(Base)
11910       .addOperand(Scale)
11911       .addOperand(Index)
11912       .addDisp(Disp, UseFPOffset ? 4 : 0)
11913       .addOperand(Segment)
11914       .setMemRefs(MMOBegin, MMOEnd);
11915
11916     // Check if there is enough room left to pull this argument.
11917     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
11918       .addReg(OffsetReg)
11919       .addImm(MaxOffset + 8 - ArgSizeA8);
11920
11921     // Branch to "overflowMBB" if offset >= max
11922     // Fall through to "offsetMBB" otherwise
11923     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
11924       .addMBB(overflowMBB);
11925   }
11926
11927   // In offsetMBB, emit code to use the reg_save_area.
11928   if (offsetMBB) {
11929     assert(OffsetReg != 0);
11930
11931     // Read the reg_save_area address.
11932     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
11933     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
11934       .addOperand(Base)
11935       .addOperand(Scale)
11936       .addOperand(Index)
11937       .addDisp(Disp, 16)
11938       .addOperand(Segment)
11939       .setMemRefs(MMOBegin, MMOEnd);
11940
11941     // Zero-extend the offset
11942     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
11943       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
11944         .addImm(0)
11945         .addReg(OffsetReg)
11946         .addImm(X86::sub_32bit);
11947
11948     // Add the offset to the reg_save_area to get the final address.
11949     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
11950       .addReg(OffsetReg64)
11951       .addReg(RegSaveReg);
11952
11953     // Compute the offset for the next argument
11954     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
11955     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
11956       .addReg(OffsetReg)
11957       .addImm(UseFPOffset ? 16 : 8);
11958
11959     // Store it back into the va_list.
11960     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
11961       .addOperand(Base)
11962       .addOperand(Scale)
11963       .addOperand(Index)
11964       .addDisp(Disp, UseFPOffset ? 4 : 0)
11965       .addOperand(Segment)
11966       .addReg(NextOffsetReg)
11967       .setMemRefs(MMOBegin, MMOEnd);
11968
11969     // Jump to endMBB
11970     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
11971       .addMBB(endMBB);
11972   }
11973
11974   //
11975   // Emit code to use overflow area
11976   //
11977
11978   // Load the overflow_area address into a register.
11979   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
11980   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
11981     .addOperand(Base)
11982     .addOperand(Scale)
11983     .addOperand(Index)
11984     .addDisp(Disp, 8)
11985     .addOperand(Segment)
11986     .setMemRefs(MMOBegin, MMOEnd);
11987
11988   // If we need to align it, do so. Otherwise, just copy the address
11989   // to OverflowDestReg.
11990   if (NeedsAlign) {
11991     // Align the overflow address
11992     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
11993     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
11994
11995     // aligned_addr = (addr + (align-1)) & ~(align-1)
11996     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
11997       .addReg(OverflowAddrReg)
11998       .addImm(Align-1);
11999
12000     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
12001       .addReg(TmpReg)
12002       .addImm(~(uint64_t)(Align-1));
12003   } else {
12004     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
12005       .addReg(OverflowAddrReg);
12006   }
12007
12008   // Compute the next overflow address after this argument.
12009   // (the overflow address should be kept 8-byte aligned)
12010   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
12011   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
12012     .addReg(OverflowDestReg)
12013     .addImm(ArgSizeA8);
12014
12015   // Store the new overflow address.
12016   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
12017     .addOperand(Base)
12018     .addOperand(Scale)
12019     .addOperand(Index)
12020     .addDisp(Disp, 8)
12021     .addOperand(Segment)
12022     .addReg(NextAddrReg)
12023     .setMemRefs(MMOBegin, MMOEnd);
12024
12025   // If we branched, emit the PHI to the front of endMBB.
12026   if (offsetMBB) {
12027     BuildMI(*endMBB, endMBB->begin(), DL,
12028             TII->get(X86::PHI), DestReg)
12029       .addReg(OffsetDestReg).addMBB(offsetMBB)
12030       .addReg(OverflowDestReg).addMBB(overflowMBB);
12031   }
12032
12033   // Erase the pseudo instruction
12034   MI->eraseFromParent();
12035
12036   return endMBB;
12037 }
12038
12039 MachineBasicBlock *
12040 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
12041                                                  MachineInstr *MI,
12042                                                  MachineBasicBlock *MBB) const {
12043   // Emit code to save XMM registers to the stack. The ABI says that the
12044   // number of registers to save is given in %al, so it's theoretically
12045   // possible to do an indirect jump trick to avoid saving all of them,
12046   // however this code takes a simpler approach and just executes all
12047   // of the stores if %al is non-zero. It's less code, and it's probably
12048   // easier on the hardware branch predictor, and stores aren't all that
12049   // expensive anyway.
12050
12051   // Create the new basic blocks. One block contains all the XMM stores,
12052   // and one block is the final destination regardless of whether any
12053   // stores were performed.
12054   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12055   MachineFunction *F = MBB->getParent();
12056   MachineFunction::iterator MBBIter = MBB;
12057   ++MBBIter;
12058   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
12059   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
12060   F->insert(MBBIter, XMMSaveMBB);
12061   F->insert(MBBIter, EndMBB);
12062
12063   // Transfer the remainder of MBB and its successor edges to EndMBB.
12064   EndMBB->splice(EndMBB->begin(), MBB,
12065                  llvm::next(MachineBasicBlock::iterator(MI)),
12066                  MBB->end());
12067   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
12068
12069   // The original block will now fall through to the XMM save block.
12070   MBB->addSuccessor(XMMSaveMBB);
12071   // The XMMSaveMBB will fall through to the end block.
12072   XMMSaveMBB->addSuccessor(EndMBB);
12073
12074   // Now add the instructions.
12075   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12076   DebugLoc DL = MI->getDebugLoc();
12077
12078   unsigned CountReg = MI->getOperand(0).getReg();
12079   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
12080   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
12081
12082   if (!Subtarget->isTargetWin64()) {
12083     // If %al is 0, branch around the XMM save block.
12084     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
12085     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
12086     MBB->addSuccessor(EndMBB);
12087   }
12088
12089   unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
12090   // In the XMM save block, save all the XMM argument registers.
12091   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
12092     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
12093     MachineMemOperand *MMO =
12094       F->getMachineMemOperand(
12095           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
12096         MachineMemOperand::MOStore,
12097         /*Size=*/16, /*Align=*/16);
12098     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
12099       .addFrameIndex(RegSaveFrameIndex)
12100       .addImm(/*Scale=*/1)
12101       .addReg(/*IndexReg=*/0)
12102       .addImm(/*Disp=*/Offset)
12103       .addReg(/*Segment=*/0)
12104       .addReg(MI->getOperand(i).getReg())
12105       .addMemOperand(MMO);
12106   }
12107
12108   MI->eraseFromParent();   // The pseudo instruction is gone now.
12109
12110   return EndMBB;
12111 }
12112
12113 MachineBasicBlock *
12114 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
12115                                      MachineBasicBlock *BB) const {
12116   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12117   DebugLoc DL = MI->getDebugLoc();
12118
12119   // To "insert" a SELECT_CC instruction, we actually have to insert the
12120   // diamond control-flow pattern.  The incoming instruction knows the
12121   // destination vreg to set, the condition code register to branch on, the
12122   // true/false values to select between, and a branch opcode to use.
12123   const BasicBlock *LLVM_BB = BB->getBasicBlock();
12124   MachineFunction::iterator It = BB;
12125   ++It;
12126
12127   //  thisMBB:
12128   //  ...
12129   //   TrueVal = ...
12130   //   cmpTY ccX, r1, r2
12131   //   bCC copy1MBB
12132   //   fallthrough --> copy0MBB
12133   MachineBasicBlock *thisMBB = BB;
12134   MachineFunction *F = BB->getParent();
12135   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
12136   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12137   F->insert(It, copy0MBB);
12138   F->insert(It, sinkMBB);
12139
12140   // If the EFLAGS register isn't dead in the terminator, then claim that it's
12141   // live into the sink and copy blocks.
12142   if (!MI->killsRegister(X86::EFLAGS)) {
12143     copy0MBB->addLiveIn(X86::EFLAGS);
12144     sinkMBB->addLiveIn(X86::EFLAGS);
12145   }
12146
12147   // Transfer the remainder of BB and its successor edges to sinkMBB.
12148   sinkMBB->splice(sinkMBB->begin(), BB,
12149                   llvm::next(MachineBasicBlock::iterator(MI)),
12150                   BB->end());
12151   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12152
12153   // Add the true and fallthrough blocks as its successors.
12154   BB->addSuccessor(copy0MBB);
12155   BB->addSuccessor(sinkMBB);
12156
12157   // Create the conditional branch instruction.
12158   unsigned Opc =
12159     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
12160   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
12161
12162   //  copy0MBB:
12163   //   %FalseValue = ...
12164   //   # fallthrough to sinkMBB
12165   copy0MBB->addSuccessor(sinkMBB);
12166
12167   //  sinkMBB:
12168   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
12169   //  ...
12170   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12171           TII->get(X86::PHI), MI->getOperand(0).getReg())
12172     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
12173     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
12174
12175   MI->eraseFromParent();   // The pseudo instruction is gone now.
12176   return sinkMBB;
12177 }
12178
12179 MachineBasicBlock *
12180 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
12181                                         bool Is64Bit) const {
12182   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12183   DebugLoc DL = MI->getDebugLoc();
12184   MachineFunction *MF = BB->getParent();
12185   const BasicBlock *LLVM_BB = BB->getBasicBlock();
12186
12187   assert(EnableSegmentedStacks);
12188
12189   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
12190   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
12191
12192   // BB:
12193   //  ... [Till the alloca]
12194   // If stacklet is not large enough, jump to mallocMBB
12195   //
12196   // bumpMBB:
12197   //  Allocate by subtracting from RSP
12198   //  Jump to continueMBB
12199   //
12200   // mallocMBB:
12201   //  Allocate by call to runtime
12202   //
12203   // continueMBB:
12204   //  ...
12205   //  [rest of original BB]
12206   //
12207
12208   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12209   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12210   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12211
12212   MachineRegisterInfo &MRI = MF->getRegInfo();
12213   const TargetRegisterClass *AddrRegClass =
12214     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
12215
12216   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12217     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12218     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
12219     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
12220     sizeVReg = MI->getOperand(1).getReg(),
12221     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
12222
12223   MachineFunction::iterator MBBIter = BB;
12224   ++MBBIter;
12225
12226   MF->insert(MBBIter, bumpMBB);
12227   MF->insert(MBBIter, mallocMBB);
12228   MF->insert(MBBIter, continueMBB);
12229
12230   continueMBB->splice(continueMBB->begin(), BB, llvm::next
12231                       (MachineBasicBlock::iterator(MI)), BB->end());
12232   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
12233
12234   // Add code to the main basic block to check if the stack limit has been hit,
12235   // and if so, jump to mallocMBB otherwise to bumpMBB.
12236   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
12237   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
12238     .addReg(tmpSPVReg).addReg(sizeVReg);
12239   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
12240     .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg)
12241     .addReg(SPLimitVReg);
12242   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
12243
12244   // bumpMBB simply decreases the stack pointer, since we know the current
12245   // stacklet has enough space.
12246   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
12247     .addReg(SPLimitVReg);
12248   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
12249     .addReg(SPLimitVReg);
12250   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12251
12252   // Calls into a routine in libgcc to allocate more space from the heap.
12253   if (Is64Bit) {
12254     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
12255       .addReg(sizeVReg);
12256     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
12257     .addExternalSymbol("__morestack_allocate_stack_space").addReg(X86::RDI);
12258   } else {
12259     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
12260       .addImm(12);
12261     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
12262     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
12263       .addExternalSymbol("__morestack_allocate_stack_space");
12264   }
12265
12266   if (!Is64Bit)
12267     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
12268       .addImm(16);
12269
12270   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
12271     .addReg(Is64Bit ? X86::RAX : X86::EAX);
12272   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12273
12274   // Set up the CFG correctly.
12275   BB->addSuccessor(bumpMBB);
12276   BB->addSuccessor(mallocMBB);
12277   mallocMBB->addSuccessor(continueMBB);
12278   bumpMBB->addSuccessor(continueMBB);
12279
12280   // Take care of the PHI nodes.
12281   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
12282           MI->getOperand(0).getReg())
12283     .addReg(mallocPtrVReg).addMBB(mallocMBB)
12284     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
12285
12286   // Delete the original pseudo instruction.
12287   MI->eraseFromParent();
12288
12289   // And we're done.
12290   return continueMBB;
12291 }
12292
12293 MachineBasicBlock *
12294 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
12295                                           MachineBasicBlock *BB) const {
12296   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12297   DebugLoc DL = MI->getDebugLoc();
12298
12299   assert(!Subtarget->isTargetEnvMacho());
12300
12301   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
12302   // non-trivial part is impdef of ESP.
12303
12304   if (Subtarget->isTargetWin64()) {
12305     if (Subtarget->isTargetCygMing()) {
12306       // ___chkstk(Mingw64):
12307       // Clobbers R10, R11, RAX and EFLAGS.
12308       // Updates RSP.
12309       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12310         .addExternalSymbol("___chkstk")
12311         .addReg(X86::RAX, RegState::Implicit)
12312         .addReg(X86::RSP, RegState::Implicit)
12313         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
12314         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
12315         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12316     } else {
12317       // __chkstk(MSVCRT): does not update stack pointer.
12318       // Clobbers R10, R11 and EFLAGS.
12319       // FIXME: RAX(allocated size) might be reused and not killed.
12320       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12321         .addExternalSymbol("__chkstk")
12322         .addReg(X86::RAX, RegState::Implicit)
12323         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12324       // RAX has the offset to subtracted from RSP.
12325       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
12326         .addReg(X86::RSP)
12327         .addReg(X86::RAX);
12328     }
12329   } else {
12330     const char *StackProbeSymbol =
12331       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
12332
12333     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
12334       .addExternalSymbol(StackProbeSymbol)
12335       .addReg(X86::EAX, RegState::Implicit)
12336       .addReg(X86::ESP, RegState::Implicit)
12337       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
12338       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
12339       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12340   }
12341
12342   MI->eraseFromParent();   // The pseudo instruction is gone now.
12343   return BB;
12344 }
12345
12346 MachineBasicBlock *
12347 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
12348                                       MachineBasicBlock *BB) const {
12349   // This is pretty easy.  We're taking the value that we received from
12350   // our load from the relocation, sticking it in either RDI (x86-64)
12351   // or EAX and doing an indirect call.  The return value will then
12352   // be in the normal return register.
12353   const X86InstrInfo *TII
12354     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
12355   DebugLoc DL = MI->getDebugLoc();
12356   MachineFunction *F = BB->getParent();
12357
12358   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
12359   assert(MI->getOperand(3).isGlobal() && "This should be a global");
12360
12361   if (Subtarget->is64Bit()) {
12362     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12363                                       TII->get(X86::MOV64rm), X86::RDI)
12364     .addReg(X86::RIP)
12365     .addImm(0).addReg(0)
12366     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12367                       MI->getOperand(3).getTargetFlags())
12368     .addReg(0);
12369     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
12370     addDirectMem(MIB, X86::RDI);
12371   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
12372     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12373                                       TII->get(X86::MOV32rm), X86::EAX)
12374     .addReg(0)
12375     .addImm(0).addReg(0)
12376     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12377                       MI->getOperand(3).getTargetFlags())
12378     .addReg(0);
12379     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12380     addDirectMem(MIB, X86::EAX);
12381   } else {
12382     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12383                                       TII->get(X86::MOV32rm), X86::EAX)
12384     .addReg(TII->getGlobalBaseReg(F))
12385     .addImm(0).addReg(0)
12386     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12387                       MI->getOperand(3).getTargetFlags())
12388     .addReg(0);
12389     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12390     addDirectMem(MIB, X86::EAX);
12391   }
12392
12393   MI->eraseFromParent(); // The pseudo instruction is gone now.
12394   return BB;
12395 }
12396
12397 MachineBasicBlock *
12398 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
12399                                                MachineBasicBlock *BB) const {
12400   switch (MI->getOpcode()) {
12401   default: assert(0 && "Unexpected instr type to insert");
12402   case X86::TAILJMPd64:
12403   case X86::TAILJMPr64:
12404   case X86::TAILJMPm64:
12405     assert(0 && "TAILJMP64 would not be touched here.");
12406   case X86::TCRETURNdi64:
12407   case X86::TCRETURNri64:
12408   case X86::TCRETURNmi64:
12409     // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset.
12410     // On AMD64, additional defs should be added before register allocation.
12411     if (!Subtarget->isTargetWin64()) {
12412       MI->addRegisterDefined(X86::RSI);
12413       MI->addRegisterDefined(X86::RDI);
12414       MI->addRegisterDefined(X86::XMM6);
12415       MI->addRegisterDefined(X86::XMM7);
12416       MI->addRegisterDefined(X86::XMM8);
12417       MI->addRegisterDefined(X86::XMM9);
12418       MI->addRegisterDefined(X86::XMM10);
12419       MI->addRegisterDefined(X86::XMM11);
12420       MI->addRegisterDefined(X86::XMM12);
12421       MI->addRegisterDefined(X86::XMM13);
12422       MI->addRegisterDefined(X86::XMM14);
12423       MI->addRegisterDefined(X86::XMM15);
12424     }
12425     return BB;
12426   case X86::WIN_ALLOCA:
12427     return EmitLoweredWinAlloca(MI, BB);
12428   case X86::SEG_ALLOCA_32:
12429     return EmitLoweredSegAlloca(MI, BB, false);
12430   case X86::SEG_ALLOCA_64:
12431     return EmitLoweredSegAlloca(MI, BB, true);
12432   case X86::TLSCall_32:
12433   case X86::TLSCall_64:
12434     return EmitLoweredTLSCall(MI, BB);
12435   case X86::CMOV_GR8:
12436   case X86::CMOV_FR32:
12437   case X86::CMOV_FR64:
12438   case X86::CMOV_V4F32:
12439   case X86::CMOV_V2F64:
12440   case X86::CMOV_V2I64:
12441   case X86::CMOV_V8F32:
12442   case X86::CMOV_V4F64:
12443   case X86::CMOV_V4I64:
12444   case X86::CMOV_GR16:
12445   case X86::CMOV_GR32:
12446   case X86::CMOV_RFP32:
12447   case X86::CMOV_RFP64:
12448   case X86::CMOV_RFP80:
12449     return EmitLoweredSelect(MI, BB);
12450
12451   case X86::FP32_TO_INT16_IN_MEM:
12452   case X86::FP32_TO_INT32_IN_MEM:
12453   case X86::FP32_TO_INT64_IN_MEM:
12454   case X86::FP64_TO_INT16_IN_MEM:
12455   case X86::FP64_TO_INT32_IN_MEM:
12456   case X86::FP64_TO_INT64_IN_MEM:
12457   case X86::FP80_TO_INT16_IN_MEM:
12458   case X86::FP80_TO_INT32_IN_MEM:
12459   case X86::FP80_TO_INT64_IN_MEM: {
12460     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12461     DebugLoc DL = MI->getDebugLoc();
12462
12463     // Change the floating point control register to use "round towards zero"
12464     // mode when truncating to an integer value.
12465     MachineFunction *F = BB->getParent();
12466     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
12467     addFrameReference(BuildMI(*BB, MI, DL,
12468                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
12469
12470     // Load the old value of the high byte of the control word...
12471     unsigned OldCW =
12472       F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
12473     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
12474                       CWFrameIdx);
12475
12476     // Set the high part to be round to zero...
12477     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
12478       .addImm(0xC7F);
12479
12480     // Reload the modified control word now...
12481     addFrameReference(BuildMI(*BB, MI, DL,
12482                               TII->get(X86::FLDCW16m)), CWFrameIdx);
12483
12484     // Restore the memory image of control word to original value
12485     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
12486       .addReg(OldCW);
12487
12488     // Get the X86 opcode to use.
12489     unsigned Opc;
12490     switch (MI->getOpcode()) {
12491     default: llvm_unreachable("illegal opcode!");
12492     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
12493     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
12494     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
12495     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
12496     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
12497     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
12498     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
12499     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
12500     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
12501     }
12502
12503     X86AddressMode AM;
12504     MachineOperand &Op = MI->getOperand(0);
12505     if (Op.isReg()) {
12506       AM.BaseType = X86AddressMode::RegBase;
12507       AM.Base.Reg = Op.getReg();
12508     } else {
12509       AM.BaseType = X86AddressMode::FrameIndexBase;
12510       AM.Base.FrameIndex = Op.getIndex();
12511     }
12512     Op = MI->getOperand(1);
12513     if (Op.isImm())
12514       AM.Scale = Op.getImm();
12515     Op = MI->getOperand(2);
12516     if (Op.isImm())
12517       AM.IndexReg = Op.getImm();
12518     Op = MI->getOperand(3);
12519     if (Op.isGlobal()) {
12520       AM.GV = Op.getGlobal();
12521     } else {
12522       AM.Disp = Op.getImm();
12523     }
12524     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
12525                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
12526
12527     // Reload the original control word now.
12528     addFrameReference(BuildMI(*BB, MI, DL,
12529                               TII->get(X86::FLDCW16m)), CWFrameIdx);
12530
12531     MI->eraseFromParent();   // The pseudo instruction is gone now.
12532     return BB;
12533   }
12534     // String/text processing lowering.
12535   case X86::PCMPISTRM128REG:
12536   case X86::VPCMPISTRM128REG:
12537     return EmitPCMP(MI, BB, 3, false /* in-mem */);
12538   case X86::PCMPISTRM128MEM:
12539   case X86::VPCMPISTRM128MEM:
12540     return EmitPCMP(MI, BB, 3, true /* in-mem */);
12541   case X86::PCMPESTRM128REG:
12542   case X86::VPCMPESTRM128REG:
12543     return EmitPCMP(MI, BB, 5, false /* in mem */);
12544   case X86::PCMPESTRM128MEM:
12545   case X86::VPCMPESTRM128MEM:
12546     return EmitPCMP(MI, BB, 5, true /* in mem */);
12547
12548     // Thread synchronization.
12549   case X86::MONITOR:
12550     return EmitMonitor(MI, BB);
12551   case X86::MWAIT:
12552     return EmitMwait(MI, BB);
12553
12554     // Atomic Lowering.
12555   case X86::ATOMAND32:
12556     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12557                                                X86::AND32ri, X86::MOV32rm,
12558                                                X86::LCMPXCHG32,
12559                                                X86::NOT32r, X86::EAX,
12560                                                X86::GR32RegisterClass);
12561   case X86::ATOMOR32:
12562     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
12563                                                X86::OR32ri, X86::MOV32rm,
12564                                                X86::LCMPXCHG32,
12565                                                X86::NOT32r, X86::EAX,
12566                                                X86::GR32RegisterClass);
12567   case X86::ATOMXOR32:
12568     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
12569                                                X86::XOR32ri, X86::MOV32rm,
12570                                                X86::LCMPXCHG32,
12571                                                X86::NOT32r, X86::EAX,
12572                                                X86::GR32RegisterClass);
12573   case X86::ATOMNAND32:
12574     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12575                                                X86::AND32ri, X86::MOV32rm,
12576                                                X86::LCMPXCHG32,
12577                                                X86::NOT32r, X86::EAX,
12578                                                X86::GR32RegisterClass, true);
12579   case X86::ATOMMIN32:
12580     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
12581   case X86::ATOMMAX32:
12582     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
12583   case X86::ATOMUMIN32:
12584     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
12585   case X86::ATOMUMAX32:
12586     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
12587
12588   case X86::ATOMAND16:
12589     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12590                                                X86::AND16ri, X86::MOV16rm,
12591                                                X86::LCMPXCHG16,
12592                                                X86::NOT16r, X86::AX,
12593                                                X86::GR16RegisterClass);
12594   case X86::ATOMOR16:
12595     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
12596                                                X86::OR16ri, X86::MOV16rm,
12597                                                X86::LCMPXCHG16,
12598                                                X86::NOT16r, X86::AX,
12599                                                X86::GR16RegisterClass);
12600   case X86::ATOMXOR16:
12601     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
12602                                                X86::XOR16ri, X86::MOV16rm,
12603                                                X86::LCMPXCHG16,
12604                                                X86::NOT16r, X86::AX,
12605                                                X86::GR16RegisterClass);
12606   case X86::ATOMNAND16:
12607     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12608                                                X86::AND16ri, X86::MOV16rm,
12609                                                X86::LCMPXCHG16,
12610                                                X86::NOT16r, X86::AX,
12611                                                X86::GR16RegisterClass, true);
12612   case X86::ATOMMIN16:
12613     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
12614   case X86::ATOMMAX16:
12615     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
12616   case X86::ATOMUMIN16:
12617     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
12618   case X86::ATOMUMAX16:
12619     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
12620
12621   case X86::ATOMAND8:
12622     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12623                                                X86::AND8ri, X86::MOV8rm,
12624                                                X86::LCMPXCHG8,
12625                                                X86::NOT8r, X86::AL,
12626                                                X86::GR8RegisterClass);
12627   case X86::ATOMOR8:
12628     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
12629                                                X86::OR8ri, X86::MOV8rm,
12630                                                X86::LCMPXCHG8,
12631                                                X86::NOT8r, X86::AL,
12632                                                X86::GR8RegisterClass);
12633   case X86::ATOMXOR8:
12634     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
12635                                                X86::XOR8ri, X86::MOV8rm,
12636                                                X86::LCMPXCHG8,
12637                                                X86::NOT8r, X86::AL,
12638                                                X86::GR8RegisterClass);
12639   case X86::ATOMNAND8:
12640     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12641                                                X86::AND8ri, X86::MOV8rm,
12642                                                X86::LCMPXCHG8,
12643                                                X86::NOT8r, X86::AL,
12644                                                X86::GR8RegisterClass, true);
12645   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
12646   // This group is for 64-bit host.
12647   case X86::ATOMAND64:
12648     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12649                                                X86::AND64ri32, X86::MOV64rm,
12650                                                X86::LCMPXCHG64,
12651                                                X86::NOT64r, X86::RAX,
12652                                                X86::GR64RegisterClass);
12653   case X86::ATOMOR64:
12654     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
12655                                                X86::OR64ri32, X86::MOV64rm,
12656                                                X86::LCMPXCHG64,
12657                                                X86::NOT64r, X86::RAX,
12658                                                X86::GR64RegisterClass);
12659   case X86::ATOMXOR64:
12660     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
12661                                                X86::XOR64ri32, X86::MOV64rm,
12662                                                X86::LCMPXCHG64,
12663                                                X86::NOT64r, X86::RAX,
12664                                                X86::GR64RegisterClass);
12665   case X86::ATOMNAND64:
12666     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12667                                                X86::AND64ri32, X86::MOV64rm,
12668                                                X86::LCMPXCHG64,
12669                                                X86::NOT64r, X86::RAX,
12670                                                X86::GR64RegisterClass, true);
12671   case X86::ATOMMIN64:
12672     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
12673   case X86::ATOMMAX64:
12674     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
12675   case X86::ATOMUMIN64:
12676     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
12677   case X86::ATOMUMAX64:
12678     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
12679
12680   // This group does 64-bit operations on a 32-bit host.
12681   case X86::ATOMAND6432:
12682     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12683                                                X86::AND32rr, X86::AND32rr,
12684                                                X86::AND32ri, X86::AND32ri,
12685                                                false);
12686   case X86::ATOMOR6432:
12687     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12688                                                X86::OR32rr, X86::OR32rr,
12689                                                X86::OR32ri, X86::OR32ri,
12690                                                false);
12691   case X86::ATOMXOR6432:
12692     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12693                                                X86::XOR32rr, X86::XOR32rr,
12694                                                X86::XOR32ri, X86::XOR32ri,
12695                                                false);
12696   case X86::ATOMNAND6432:
12697     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12698                                                X86::AND32rr, X86::AND32rr,
12699                                                X86::AND32ri, X86::AND32ri,
12700                                                true);
12701   case X86::ATOMADD6432:
12702     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12703                                                X86::ADD32rr, X86::ADC32rr,
12704                                                X86::ADD32ri, X86::ADC32ri,
12705                                                false);
12706   case X86::ATOMSUB6432:
12707     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12708                                                X86::SUB32rr, X86::SBB32rr,
12709                                                X86::SUB32ri, X86::SBB32ri,
12710                                                false);
12711   case X86::ATOMSWAP6432:
12712     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12713                                                X86::MOV32rr, X86::MOV32rr,
12714                                                X86::MOV32ri, X86::MOV32ri,
12715                                                false);
12716   case X86::VASTART_SAVE_XMM_REGS:
12717     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
12718
12719   case X86::VAARG_64:
12720     return EmitVAARG64WithCustomInserter(MI, BB);
12721   }
12722 }
12723
12724 //===----------------------------------------------------------------------===//
12725 //                           X86 Optimization Hooks
12726 //===----------------------------------------------------------------------===//
12727
12728 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
12729                                                        const APInt &Mask,
12730                                                        APInt &KnownZero,
12731                                                        APInt &KnownOne,
12732                                                        const SelectionDAG &DAG,
12733                                                        unsigned Depth) const {
12734   unsigned Opc = Op.getOpcode();
12735   assert((Opc >= ISD::BUILTIN_OP_END ||
12736           Opc == ISD::INTRINSIC_WO_CHAIN ||
12737           Opc == ISD::INTRINSIC_W_CHAIN ||
12738           Opc == ISD::INTRINSIC_VOID) &&
12739          "Should use MaskedValueIsZero if you don't know whether Op"
12740          " is a target node!");
12741
12742   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
12743   switch (Opc) {
12744   default: break;
12745   case X86ISD::ADD:
12746   case X86ISD::SUB:
12747   case X86ISD::ADC:
12748   case X86ISD::SBB:
12749   case X86ISD::SMUL:
12750   case X86ISD::UMUL:
12751   case X86ISD::INC:
12752   case X86ISD::DEC:
12753   case X86ISD::OR:
12754   case X86ISD::XOR:
12755   case X86ISD::AND:
12756     // These nodes' second result is a boolean.
12757     if (Op.getResNo() == 0)
12758       break;
12759     // Fallthrough
12760   case X86ISD::SETCC:
12761     KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
12762                                        Mask.getBitWidth() - 1);
12763     break;
12764   case ISD::INTRINSIC_WO_CHAIN: {
12765     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12766     unsigned NumLoBits = 0;
12767     switch (IntId) {
12768     default: break;
12769     case Intrinsic::x86_sse_movmsk_ps:
12770     case Intrinsic::x86_avx_movmsk_ps_256:
12771     case Intrinsic::x86_sse2_movmsk_pd:
12772     case Intrinsic::x86_avx_movmsk_pd_256:
12773     case Intrinsic::x86_mmx_pmovmskb:
12774     case Intrinsic::x86_sse2_pmovmskb_128: {
12775       // High bits of movmskp{s|d}, pmovmskb are known zero.
12776       switch (IntId) {
12777         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
12778         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
12779         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
12780         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
12781         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
12782         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
12783       }
12784       KnownZero = APInt::getHighBitsSet(Mask.getBitWidth(),
12785                                         Mask.getBitWidth() - NumLoBits);
12786       break;
12787     }
12788     }
12789     break;
12790   }
12791   }
12792 }
12793
12794 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
12795                                                          unsigned Depth) const {
12796   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
12797   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
12798     return Op.getValueType().getScalarType().getSizeInBits();
12799
12800   // Fallback case.
12801   return 1;
12802 }
12803
12804 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
12805 /// node is a GlobalAddress + offset.
12806 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
12807                                        const GlobalValue* &GA,
12808                                        int64_t &Offset) const {
12809   if (N->getOpcode() == X86ISD::Wrapper) {
12810     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
12811       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
12812       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
12813       return true;
12814     }
12815   }
12816   return TargetLowering::isGAPlusOffset(N, GA, Offset);
12817 }
12818
12819 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
12820 /// same as extracting the high 128-bit part of 256-bit vector and then
12821 /// inserting the result into the low part of a new 256-bit vector
12822 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
12823   EVT VT = SVOp->getValueType(0);
12824   int NumElems = VT.getVectorNumElements();
12825
12826   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
12827   for (int i = 0, j = NumElems/2; i < NumElems/2; ++i, ++j)
12828     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12829         SVOp->getMaskElt(j) >= 0)
12830       return false;
12831
12832   return true;
12833 }
12834
12835 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
12836 /// same as extracting the low 128-bit part of 256-bit vector and then
12837 /// inserting the result into the high part of a new 256-bit vector
12838 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
12839   EVT VT = SVOp->getValueType(0);
12840   int NumElems = VT.getVectorNumElements();
12841
12842   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
12843   for (int i = NumElems/2, j = 0; i < NumElems; ++i, ++j)
12844     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12845         SVOp->getMaskElt(j) >= 0)
12846       return false;
12847
12848   return true;
12849 }
12850
12851 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
12852 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
12853                                         TargetLowering::DAGCombinerInfo &DCI) {
12854   DebugLoc dl = N->getDebugLoc();
12855   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
12856   SDValue V1 = SVOp->getOperand(0);
12857   SDValue V2 = SVOp->getOperand(1);
12858   EVT VT = SVOp->getValueType(0);
12859   int NumElems = VT.getVectorNumElements();
12860
12861   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
12862       V2.getOpcode() == ISD::CONCAT_VECTORS) {
12863     //
12864     //                   0,0,0,...
12865     //                      |
12866     //    V      UNDEF    BUILD_VECTOR    UNDEF
12867     //     \      /           \           /
12868     //  CONCAT_VECTOR         CONCAT_VECTOR
12869     //         \                  /
12870     //          \                /
12871     //          RESULT: V + zero extended
12872     //
12873     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
12874         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
12875         V1.getOperand(1).getOpcode() != ISD::UNDEF)
12876       return SDValue();
12877
12878     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
12879       return SDValue();
12880
12881     // To match the shuffle mask, the first half of the mask should
12882     // be exactly the first vector, and all the rest a splat with the
12883     // first element of the second one.
12884     for (int i = 0; i < NumElems/2; ++i)
12885       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
12886           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
12887         return SDValue();
12888
12889     // Emit a zeroed vector and insert the desired subvector on its
12890     // first half.
12891     SDValue Zeros = getZeroVector(VT, true /* HasXMMInt */, DAG, dl);
12892     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0),
12893                          DAG.getConstant(0, MVT::i32), DAG, dl);
12894     return DCI.CombineTo(N, InsV);
12895   }
12896
12897   //===--------------------------------------------------------------------===//
12898   // Combine some shuffles into subvector extracts and inserts:
12899   //
12900
12901   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
12902   if (isShuffleHigh128VectorInsertLow(SVOp)) {
12903     SDValue V = Extract128BitVector(V1, DAG.getConstant(NumElems/2, MVT::i32),
12904                                     DAG, dl);
12905     SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT),
12906                                       V, DAG.getConstant(0, MVT::i32), DAG, dl);
12907     return DCI.CombineTo(N, InsV);
12908   }
12909
12910   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
12911   if (isShuffleLow128VectorInsertHigh(SVOp)) {
12912     SDValue V = Extract128BitVector(V1, DAG.getConstant(0, MVT::i32), DAG, dl);
12913     SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT),
12914                              V, DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
12915     return DCI.CombineTo(N, InsV);
12916   }
12917
12918   return SDValue();
12919 }
12920
12921 /// PerformShuffleCombine - Performs several different shuffle combines.
12922 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
12923                                      TargetLowering::DAGCombinerInfo &DCI,
12924                                      const X86Subtarget *Subtarget) {
12925   DebugLoc dl = N->getDebugLoc();
12926   EVT VT = N->getValueType(0);
12927
12928   // Don't create instructions with illegal types after legalize types has run.
12929   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12930   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
12931     return SDValue();
12932
12933   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
12934   if (Subtarget->hasAVX() && VT.getSizeInBits() == 256 &&
12935       N->getOpcode() == ISD::VECTOR_SHUFFLE)
12936     return PerformShuffleCombine256(N, DAG, DCI);
12937
12938   // Only handle 128 wide vector from here on.
12939   if (VT.getSizeInBits() != 128)
12940     return SDValue();
12941
12942   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
12943   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
12944   // consecutive, non-overlapping, and in the right order.
12945   SmallVector<SDValue, 16> Elts;
12946   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
12947     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
12948
12949   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
12950 }
12951
12952 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
12953 /// generation and convert it from being a bunch of shuffles and extracts
12954 /// to a simple store and scalar loads to extract the elements.
12955 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
12956                                                 const TargetLowering &TLI) {
12957   SDValue InputVector = N->getOperand(0);
12958
12959   // Only operate on vectors of 4 elements, where the alternative shuffling
12960   // gets to be more expensive.
12961   if (InputVector.getValueType() != MVT::v4i32)
12962     return SDValue();
12963
12964   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
12965   // single use which is a sign-extend or zero-extend, and all elements are
12966   // used.
12967   SmallVector<SDNode *, 4> Uses;
12968   unsigned ExtractedElements = 0;
12969   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
12970        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
12971     if (UI.getUse().getResNo() != InputVector.getResNo())
12972       return SDValue();
12973
12974     SDNode *Extract = *UI;
12975     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12976       return SDValue();
12977
12978     if (Extract->getValueType(0) != MVT::i32)
12979       return SDValue();
12980     if (!Extract->hasOneUse())
12981       return SDValue();
12982     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
12983         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
12984       return SDValue();
12985     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
12986       return SDValue();
12987
12988     // Record which element was extracted.
12989     ExtractedElements |=
12990       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
12991
12992     Uses.push_back(Extract);
12993   }
12994
12995   // If not all the elements were used, this may not be worthwhile.
12996   if (ExtractedElements != 15)
12997     return SDValue();
12998
12999   // Ok, we've now decided to do the transformation.
13000   DebugLoc dl = InputVector.getDebugLoc();
13001
13002   // Store the value to a temporary stack slot.
13003   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
13004   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
13005                             MachinePointerInfo(), false, false, 0);
13006
13007   // Replace each use (extract) with a load of the appropriate element.
13008   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
13009        UE = Uses.end(); UI != UE; ++UI) {
13010     SDNode *Extract = *UI;
13011
13012     // cOMpute the element's address.
13013     SDValue Idx = Extract->getOperand(1);
13014     unsigned EltSize =
13015         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
13016     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
13017     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
13018
13019     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
13020                                      StackPtr, OffsetVal);
13021
13022     // Load the scalar.
13023     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
13024                                      ScalarAddr, MachinePointerInfo(),
13025                                      false, false, false, 0);
13026
13027     // Replace the exact with the load.
13028     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
13029   }
13030
13031   // The replacement was made in place; don't return anything.
13032   return SDValue();
13033 }
13034
13035 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
13036 /// nodes.
13037 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
13038                                     const X86Subtarget *Subtarget) {
13039   DebugLoc DL = N->getDebugLoc();
13040   SDValue Cond = N->getOperand(0);
13041   // Get the LHS/RHS of the select.
13042   SDValue LHS = N->getOperand(1);
13043   SDValue RHS = N->getOperand(2);
13044   EVT VT = LHS.getValueType();
13045
13046   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
13047   // instructions match the semantics of the common C idiom x<y?x:y but not
13048   // x<=y?x:y, because of how they handle negative zero (which can be
13049   // ignored in unsafe-math mode).
13050   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
13051       VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
13052       (Subtarget->hasXMMInt() ||
13053        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
13054     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
13055
13056     unsigned Opcode = 0;
13057     // Check for x CC y ? x : y.
13058     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
13059         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
13060       switch (CC) {
13061       default: break;
13062       case ISD::SETULT:
13063         // Converting this to a min would handle NaNs incorrectly, and swapping
13064         // the operands would cause it to handle comparisons between positive
13065         // and negative zero incorrectly.
13066         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13067           if (!UnsafeFPMath &&
13068               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13069             break;
13070           std::swap(LHS, RHS);
13071         }
13072         Opcode = X86ISD::FMIN;
13073         break;
13074       case ISD::SETOLE:
13075         // Converting this to a min would handle comparisons between positive
13076         // and negative zero incorrectly.
13077         if (!UnsafeFPMath &&
13078             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13079           break;
13080         Opcode = X86ISD::FMIN;
13081         break;
13082       case ISD::SETULE:
13083         // Converting this to a min would handle both negative zeros and NaNs
13084         // incorrectly, but we can swap the operands to fix both.
13085         std::swap(LHS, RHS);
13086       case ISD::SETOLT:
13087       case ISD::SETLT:
13088       case ISD::SETLE:
13089         Opcode = X86ISD::FMIN;
13090         break;
13091
13092       case ISD::SETOGE:
13093         // Converting this to a max would handle comparisons between positive
13094         // and negative zero incorrectly.
13095         if (!UnsafeFPMath &&
13096             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13097           break;
13098         Opcode = X86ISD::FMAX;
13099         break;
13100       case ISD::SETUGT:
13101         // Converting this to a max would handle NaNs incorrectly, and swapping
13102         // the operands would cause it to handle comparisons between positive
13103         // and negative zero incorrectly.
13104         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13105           if (!UnsafeFPMath &&
13106               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13107             break;
13108           std::swap(LHS, RHS);
13109         }
13110         Opcode = X86ISD::FMAX;
13111         break;
13112       case ISD::SETUGE:
13113         // Converting this to a max would handle both negative zeros and NaNs
13114         // incorrectly, but we can swap the operands to fix both.
13115         std::swap(LHS, RHS);
13116       case ISD::SETOGT:
13117       case ISD::SETGT:
13118       case ISD::SETGE:
13119         Opcode = X86ISD::FMAX;
13120         break;
13121       }
13122     // Check for x CC y ? y : x -- a min/max with reversed arms.
13123     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
13124                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
13125       switch (CC) {
13126       default: break;
13127       case ISD::SETOGE:
13128         // Converting this to a min would handle comparisons between positive
13129         // and negative zero incorrectly, and swapping the operands would
13130         // cause it to handle NaNs incorrectly.
13131         if (!UnsafeFPMath &&
13132             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
13133           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13134             break;
13135           std::swap(LHS, RHS);
13136         }
13137         Opcode = X86ISD::FMIN;
13138         break;
13139       case ISD::SETUGT:
13140         // Converting this to a min would handle NaNs incorrectly.
13141         if (!UnsafeFPMath &&
13142             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
13143           break;
13144         Opcode = X86ISD::FMIN;
13145         break;
13146       case ISD::SETUGE:
13147         // Converting this to a min would handle both negative zeros and NaNs
13148         // incorrectly, but we can swap the operands to fix both.
13149         std::swap(LHS, RHS);
13150       case ISD::SETOGT:
13151       case ISD::SETGT:
13152       case ISD::SETGE:
13153         Opcode = X86ISD::FMIN;
13154         break;
13155
13156       case ISD::SETULT:
13157         // Converting this to a max would handle NaNs incorrectly.
13158         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13159           break;
13160         Opcode = X86ISD::FMAX;
13161         break;
13162       case ISD::SETOLE:
13163         // Converting this to a max would handle comparisons between positive
13164         // and negative zero incorrectly, and swapping the operands would
13165         // cause it to handle NaNs incorrectly.
13166         if (!UnsafeFPMath &&
13167             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
13168           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13169             break;
13170           std::swap(LHS, RHS);
13171         }
13172         Opcode = X86ISD::FMAX;
13173         break;
13174       case ISD::SETULE:
13175         // Converting this to a max would handle both negative zeros and NaNs
13176         // incorrectly, but we can swap the operands to fix both.
13177         std::swap(LHS, RHS);
13178       case ISD::SETOLT:
13179       case ISD::SETLT:
13180       case ISD::SETLE:
13181         Opcode = X86ISD::FMAX;
13182         break;
13183       }
13184     }
13185
13186     if (Opcode)
13187       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
13188   }
13189
13190   // If this is a select between two integer constants, try to do some
13191   // optimizations.
13192   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
13193     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
13194       // Don't do this for crazy integer types.
13195       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
13196         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
13197         // so that TrueC (the true value) is larger than FalseC.
13198         bool NeedsCondInvert = false;
13199
13200         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
13201             // Efficiently invertible.
13202             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
13203              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
13204               isa<ConstantSDNode>(Cond.getOperand(1))))) {
13205           NeedsCondInvert = true;
13206           std::swap(TrueC, FalseC);
13207         }
13208
13209         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
13210         if (FalseC->getAPIntValue() == 0 &&
13211             TrueC->getAPIntValue().isPowerOf2()) {
13212           if (NeedsCondInvert) // Invert the condition if needed.
13213             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13214                                DAG.getConstant(1, Cond.getValueType()));
13215
13216           // Zero extend the condition if needed.
13217           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
13218
13219           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13220           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
13221                              DAG.getConstant(ShAmt, MVT::i8));
13222         }
13223
13224         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
13225         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13226           if (NeedsCondInvert) // Invert the condition if needed.
13227             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13228                                DAG.getConstant(1, Cond.getValueType()));
13229
13230           // Zero extend the condition if needed.
13231           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13232                              FalseC->getValueType(0), Cond);
13233           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13234                              SDValue(FalseC, 0));
13235         }
13236
13237         // Optimize cases that will turn into an LEA instruction.  This requires
13238         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13239         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13240           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13241           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13242
13243           bool isFastMultiplier = false;
13244           if (Diff < 10) {
13245             switch ((unsigned char)Diff) {
13246               default: break;
13247               case 1:  // result = add base, cond
13248               case 2:  // result = lea base(    , cond*2)
13249               case 3:  // result = lea base(cond, cond*2)
13250               case 4:  // result = lea base(    , cond*4)
13251               case 5:  // result = lea base(cond, cond*4)
13252               case 8:  // result = lea base(    , cond*8)
13253               case 9:  // result = lea base(cond, cond*8)
13254                 isFastMultiplier = true;
13255                 break;
13256             }
13257           }
13258
13259           if (isFastMultiplier) {
13260             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13261             if (NeedsCondInvert) // Invert the condition if needed.
13262               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13263                                  DAG.getConstant(1, Cond.getValueType()));
13264
13265             // Zero extend the condition if needed.
13266             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13267                                Cond);
13268             // Scale the condition by the difference.
13269             if (Diff != 1)
13270               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13271                                  DAG.getConstant(Diff, Cond.getValueType()));
13272
13273             // Add the base if non-zero.
13274             if (FalseC->getAPIntValue() != 0)
13275               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13276                                  SDValue(FalseC, 0));
13277             return Cond;
13278           }
13279         }
13280       }
13281   }
13282
13283   return SDValue();
13284 }
13285
13286 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
13287 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
13288                                   TargetLowering::DAGCombinerInfo &DCI) {
13289   DebugLoc DL = N->getDebugLoc();
13290
13291   // If the flag operand isn't dead, don't touch this CMOV.
13292   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
13293     return SDValue();
13294
13295   SDValue FalseOp = N->getOperand(0);
13296   SDValue TrueOp = N->getOperand(1);
13297   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
13298   SDValue Cond = N->getOperand(3);
13299   if (CC == X86::COND_E || CC == X86::COND_NE) {
13300     switch (Cond.getOpcode()) {
13301     default: break;
13302     case X86ISD::BSR:
13303     case X86ISD::BSF:
13304       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
13305       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
13306         return (CC == X86::COND_E) ? FalseOp : TrueOp;
13307     }
13308   }
13309
13310   // If this is a select between two integer constants, try to do some
13311   // optimizations.  Note that the operands are ordered the opposite of SELECT
13312   // operands.
13313   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
13314     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
13315       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
13316       // larger than FalseC (the false value).
13317       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
13318         CC = X86::GetOppositeBranchCondition(CC);
13319         std::swap(TrueC, FalseC);
13320       }
13321
13322       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
13323       // This is efficient for any integer data type (including i8/i16) and
13324       // shift amount.
13325       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
13326         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13327                            DAG.getConstant(CC, MVT::i8), Cond);
13328
13329         // Zero extend the condition if needed.
13330         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
13331
13332         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13333         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
13334                            DAG.getConstant(ShAmt, MVT::i8));
13335         if (N->getNumValues() == 2)  // Dead flag value?
13336           return DCI.CombineTo(N, Cond, SDValue());
13337         return Cond;
13338       }
13339
13340       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
13341       // for any integer data type, including i8/i16.
13342       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13343         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13344                            DAG.getConstant(CC, MVT::i8), Cond);
13345
13346         // Zero extend the condition if needed.
13347         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13348                            FalseC->getValueType(0), Cond);
13349         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13350                            SDValue(FalseC, 0));
13351
13352         if (N->getNumValues() == 2)  // Dead flag value?
13353           return DCI.CombineTo(N, Cond, SDValue());
13354         return Cond;
13355       }
13356
13357       // Optimize cases that will turn into an LEA instruction.  This requires
13358       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13359       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13360         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13361         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13362
13363         bool isFastMultiplier = false;
13364         if (Diff < 10) {
13365           switch ((unsigned char)Diff) {
13366           default: break;
13367           case 1:  // result = add base, cond
13368           case 2:  // result = lea base(    , cond*2)
13369           case 3:  // result = lea base(cond, cond*2)
13370           case 4:  // result = lea base(    , cond*4)
13371           case 5:  // result = lea base(cond, cond*4)
13372           case 8:  // result = lea base(    , cond*8)
13373           case 9:  // result = lea base(cond, cond*8)
13374             isFastMultiplier = true;
13375             break;
13376           }
13377         }
13378
13379         if (isFastMultiplier) {
13380           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13381           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13382                              DAG.getConstant(CC, MVT::i8), Cond);
13383           // Zero extend the condition if needed.
13384           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13385                              Cond);
13386           // Scale the condition by the difference.
13387           if (Diff != 1)
13388             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13389                                DAG.getConstant(Diff, Cond.getValueType()));
13390
13391           // Add the base if non-zero.
13392           if (FalseC->getAPIntValue() != 0)
13393             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13394                                SDValue(FalseC, 0));
13395           if (N->getNumValues() == 2)  // Dead flag value?
13396             return DCI.CombineTo(N, Cond, SDValue());
13397           return Cond;
13398         }
13399       }
13400     }
13401   }
13402   return SDValue();
13403 }
13404
13405
13406 /// PerformMulCombine - Optimize a single multiply with constant into two
13407 /// in order to implement it with two cheaper instructions, e.g.
13408 /// LEA + SHL, LEA + LEA.
13409 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
13410                                  TargetLowering::DAGCombinerInfo &DCI) {
13411   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
13412     return SDValue();
13413
13414   EVT VT = N->getValueType(0);
13415   if (VT != MVT::i64)
13416     return SDValue();
13417
13418   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
13419   if (!C)
13420     return SDValue();
13421   uint64_t MulAmt = C->getZExtValue();
13422   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
13423     return SDValue();
13424
13425   uint64_t MulAmt1 = 0;
13426   uint64_t MulAmt2 = 0;
13427   if ((MulAmt % 9) == 0) {
13428     MulAmt1 = 9;
13429     MulAmt2 = MulAmt / 9;
13430   } else if ((MulAmt % 5) == 0) {
13431     MulAmt1 = 5;
13432     MulAmt2 = MulAmt / 5;
13433   } else if ((MulAmt % 3) == 0) {
13434     MulAmt1 = 3;
13435     MulAmt2 = MulAmt / 3;
13436   }
13437   if (MulAmt2 &&
13438       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
13439     DebugLoc DL = N->getDebugLoc();
13440
13441     if (isPowerOf2_64(MulAmt2) &&
13442         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
13443       // If second multiplifer is pow2, issue it first. We want the multiply by
13444       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
13445       // is an add.
13446       std::swap(MulAmt1, MulAmt2);
13447
13448     SDValue NewMul;
13449     if (isPowerOf2_64(MulAmt1))
13450       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
13451                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
13452     else
13453       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
13454                            DAG.getConstant(MulAmt1, VT));
13455
13456     if (isPowerOf2_64(MulAmt2))
13457       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
13458                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
13459     else
13460       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
13461                            DAG.getConstant(MulAmt2, VT));
13462
13463     // Do not add new nodes to DAG combiner worklist.
13464     DCI.CombineTo(N, NewMul, false);
13465   }
13466   return SDValue();
13467 }
13468
13469 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
13470   SDValue N0 = N->getOperand(0);
13471   SDValue N1 = N->getOperand(1);
13472   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
13473   EVT VT = N0.getValueType();
13474
13475   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
13476   // since the result of setcc_c is all zero's or all ones.
13477   if (VT.isInteger() && !VT.isVector() &&
13478       N1C && N0.getOpcode() == ISD::AND &&
13479       N0.getOperand(1).getOpcode() == ISD::Constant) {
13480     SDValue N00 = N0.getOperand(0);
13481     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
13482         ((N00.getOpcode() == ISD::ANY_EXTEND ||
13483           N00.getOpcode() == ISD::ZERO_EXTEND) &&
13484          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
13485       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
13486       APInt ShAmt = N1C->getAPIntValue();
13487       Mask = Mask.shl(ShAmt);
13488       if (Mask != 0)
13489         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
13490                            N00, DAG.getConstant(Mask, VT));
13491     }
13492   }
13493
13494
13495   // Hardware support for vector shifts is sparse which makes us scalarize the
13496   // vector operations in many cases. Also, on sandybridge ADD is faster than
13497   // shl.
13498   // (shl V, 1) -> add V,V
13499   if (isSplatVector(N1.getNode())) {
13500     assert(N0.getValueType().isVector() && "Invalid vector shift type");
13501     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
13502     // We shift all of the values by one. In many cases we do not have
13503     // hardware support for this operation. This is better expressed as an ADD
13504     // of two values.
13505     if (N1C && (1 == N1C->getZExtValue())) {
13506       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
13507     }
13508   }
13509
13510   return SDValue();
13511 }
13512
13513 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
13514 ///                       when possible.
13515 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
13516                                    const X86Subtarget *Subtarget) {
13517   EVT VT = N->getValueType(0);
13518   if (N->getOpcode() == ISD::SHL) {
13519     SDValue V = PerformSHLCombine(N, DAG);
13520     if (V.getNode()) return V;
13521   }
13522
13523   // On X86 with SSE2 support, we can transform this to a vector shift if
13524   // all elements are shifted by the same amount.  We can't do this in legalize
13525   // because the a constant vector is typically transformed to a constant pool
13526   // so we have no knowledge of the shift amount.
13527   if (!Subtarget->hasXMMInt())
13528     return SDValue();
13529
13530   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
13531       (!Subtarget->hasAVX2() ||
13532        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
13533     return SDValue();
13534
13535   SDValue ShAmtOp = N->getOperand(1);
13536   EVT EltVT = VT.getVectorElementType();
13537   DebugLoc DL = N->getDebugLoc();
13538   SDValue BaseShAmt = SDValue();
13539   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
13540     unsigned NumElts = VT.getVectorNumElements();
13541     unsigned i = 0;
13542     for (; i != NumElts; ++i) {
13543       SDValue Arg = ShAmtOp.getOperand(i);
13544       if (Arg.getOpcode() == ISD::UNDEF) continue;
13545       BaseShAmt = Arg;
13546       break;
13547     }
13548     for (; i != NumElts; ++i) {
13549       SDValue Arg = ShAmtOp.getOperand(i);
13550       if (Arg.getOpcode() == ISD::UNDEF) continue;
13551       if (Arg != BaseShAmt) {
13552         return SDValue();
13553       }
13554     }
13555   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
13556              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
13557     SDValue InVec = ShAmtOp.getOperand(0);
13558     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13559       unsigned NumElts = InVec.getValueType().getVectorNumElements();
13560       unsigned i = 0;
13561       for (; i != NumElts; ++i) {
13562         SDValue Arg = InVec.getOperand(i);
13563         if (Arg.getOpcode() == ISD::UNDEF) continue;
13564         BaseShAmt = Arg;
13565         break;
13566       }
13567     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13568        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13569          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
13570          if (C->getZExtValue() == SplatIdx)
13571            BaseShAmt = InVec.getOperand(1);
13572        }
13573     }
13574     if (BaseShAmt.getNode() == 0)
13575       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
13576                               DAG.getIntPtrConstant(0));
13577   } else
13578     return SDValue();
13579
13580   // The shift amount is an i32.
13581   if (EltVT.bitsGT(MVT::i32))
13582     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
13583   else if (EltVT.bitsLT(MVT::i32))
13584     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
13585
13586   // The shift amount is identical so we can do a vector shift.
13587   SDValue  ValOp = N->getOperand(0);
13588   switch (N->getOpcode()) {
13589   default:
13590     llvm_unreachable("Unknown shift opcode!");
13591     break;
13592   case ISD::SHL:
13593     if (VT == MVT::v2i64)
13594       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13595                          DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
13596                          ValOp, BaseShAmt);
13597     if (VT == MVT::v4i32)
13598       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13599                          DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
13600                          ValOp, BaseShAmt);
13601     if (VT == MVT::v8i16)
13602       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13603                          DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
13604                          ValOp, BaseShAmt);
13605     if (VT == MVT::v4i64)
13606       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13607                          DAG.getConstant(Intrinsic::x86_avx2_pslli_q, MVT::i32),
13608                          ValOp, BaseShAmt);
13609     if (VT == MVT::v8i32)
13610       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13611                          DAG.getConstant(Intrinsic::x86_avx2_pslli_d, MVT::i32),
13612                          ValOp, BaseShAmt);
13613     if (VT == MVT::v16i16)
13614       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13615                          DAG.getConstant(Intrinsic::x86_avx2_pslli_w, MVT::i32),
13616                          ValOp, BaseShAmt);
13617     break;
13618   case ISD::SRA:
13619     if (VT == MVT::v4i32)
13620       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13621                          DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
13622                          ValOp, BaseShAmt);
13623     if (VT == MVT::v8i16)
13624       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13625                          DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
13626                          ValOp, BaseShAmt);
13627     if (VT == MVT::v8i32)
13628       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13629                          DAG.getConstant(Intrinsic::x86_avx2_psrai_d, MVT::i32),
13630                          ValOp, BaseShAmt);
13631     if (VT == MVT::v16i16)
13632       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13633                          DAG.getConstant(Intrinsic::x86_avx2_psrai_w, MVT::i32),
13634                          ValOp, BaseShAmt);
13635     break;
13636   case ISD::SRL:
13637     if (VT == MVT::v2i64)
13638       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13639                          DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
13640                          ValOp, BaseShAmt);
13641     if (VT == MVT::v4i32)
13642       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13643                          DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
13644                          ValOp, BaseShAmt);
13645     if (VT ==  MVT::v8i16)
13646       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13647                          DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
13648                          ValOp, BaseShAmt);
13649     if (VT == MVT::v4i64)
13650       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13651                          DAG.getConstant(Intrinsic::x86_avx2_psrli_q, MVT::i32),
13652                          ValOp, BaseShAmt);
13653     if (VT == MVT::v8i32)
13654       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13655                          DAG.getConstant(Intrinsic::x86_avx2_psrli_d, MVT::i32),
13656                          ValOp, BaseShAmt);
13657     if (VT ==  MVT::v16i16)
13658       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13659                          DAG.getConstant(Intrinsic::x86_avx2_psrli_w, MVT::i32),
13660                          ValOp, BaseShAmt);
13661     break;
13662   }
13663   return SDValue();
13664 }
13665
13666
13667 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
13668 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
13669 // and friends.  Likewise for OR -> CMPNEQSS.
13670 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
13671                             TargetLowering::DAGCombinerInfo &DCI,
13672                             const X86Subtarget *Subtarget) {
13673   unsigned opcode;
13674
13675   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
13676   // we're requiring SSE2 for both.
13677   if (Subtarget->hasXMMInt() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
13678     SDValue N0 = N->getOperand(0);
13679     SDValue N1 = N->getOperand(1);
13680     SDValue CMP0 = N0->getOperand(1);
13681     SDValue CMP1 = N1->getOperand(1);
13682     DebugLoc DL = N->getDebugLoc();
13683
13684     // The SETCCs should both refer to the same CMP.
13685     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
13686       return SDValue();
13687
13688     SDValue CMP00 = CMP0->getOperand(0);
13689     SDValue CMP01 = CMP0->getOperand(1);
13690     EVT     VT    = CMP00.getValueType();
13691
13692     if (VT == MVT::f32 || VT == MVT::f64) {
13693       bool ExpectingFlags = false;
13694       // Check for any users that want flags:
13695       for (SDNode::use_iterator UI = N->use_begin(),
13696              UE = N->use_end();
13697            !ExpectingFlags && UI != UE; ++UI)
13698         switch (UI->getOpcode()) {
13699         default:
13700         case ISD::BR_CC:
13701         case ISD::BRCOND:
13702         case ISD::SELECT:
13703           ExpectingFlags = true;
13704           break;
13705         case ISD::CopyToReg:
13706         case ISD::SIGN_EXTEND:
13707         case ISD::ZERO_EXTEND:
13708         case ISD::ANY_EXTEND:
13709           break;
13710         }
13711
13712       if (!ExpectingFlags) {
13713         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
13714         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
13715
13716         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
13717           X86::CondCode tmp = cc0;
13718           cc0 = cc1;
13719           cc1 = tmp;
13720         }
13721
13722         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
13723             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
13724           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
13725           X86ISD::NodeType NTOperator = is64BitFP ?
13726             X86ISD::FSETCCsd : X86ISD::FSETCCss;
13727           // FIXME: need symbolic constants for these magic numbers.
13728           // See X86ATTInstPrinter.cpp:printSSECC().
13729           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
13730           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
13731                                               DAG.getConstant(x86cc, MVT::i8));
13732           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
13733                                               OnesOrZeroesF);
13734           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
13735                                       DAG.getConstant(1, MVT::i32));
13736           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
13737           return OneBitOfTruth;
13738         }
13739       }
13740     }
13741   }
13742   return SDValue();
13743 }
13744
13745 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
13746 /// so it can be folded inside ANDNP.
13747 static bool CanFoldXORWithAllOnes(const SDNode *N) {
13748   EVT VT = N->getValueType(0);
13749
13750   // Match direct AllOnes for 128 and 256-bit vectors
13751   if (ISD::isBuildVectorAllOnes(N))
13752     return true;
13753
13754   // Look through a bit convert.
13755   if (N->getOpcode() == ISD::BITCAST)
13756     N = N->getOperand(0).getNode();
13757
13758   // Sometimes the operand may come from a insert_subvector building a 256-bit
13759   // allones vector
13760   if (VT.getSizeInBits() == 256 &&
13761       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
13762     SDValue V1 = N->getOperand(0);
13763     SDValue V2 = N->getOperand(1);
13764
13765     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
13766         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
13767         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
13768         ISD::isBuildVectorAllOnes(V2.getNode()))
13769       return true;
13770   }
13771
13772   return false;
13773 }
13774
13775 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
13776                                  TargetLowering::DAGCombinerInfo &DCI,
13777                                  const X86Subtarget *Subtarget) {
13778   if (DCI.isBeforeLegalizeOps())
13779     return SDValue();
13780
13781   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
13782   if (R.getNode())
13783     return R;
13784
13785   EVT VT = N->getValueType(0);
13786
13787   // Create ANDN, BLSI, and BLSR instructions
13788   // BLSI is X & (-X)
13789   // BLSR is X & (X-1)
13790   if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
13791     SDValue N0 = N->getOperand(0);
13792     SDValue N1 = N->getOperand(1);
13793     DebugLoc DL = N->getDebugLoc();
13794
13795     // Check LHS for not
13796     if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1)))
13797       return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1);
13798     // Check RHS for not
13799     if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1)))
13800       return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
13801
13802     // Check LHS for neg
13803     if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
13804         isZero(N0.getOperand(0)))
13805       return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
13806
13807     // Check RHS for neg
13808     if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
13809         isZero(N1.getOperand(0)))
13810       return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
13811
13812     // Check LHS for X-1
13813     if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
13814         isAllOnes(N0.getOperand(1)))
13815       return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
13816
13817     // Check RHS for X-1
13818     if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
13819         isAllOnes(N1.getOperand(1)))
13820       return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
13821
13822     return SDValue();
13823   }
13824
13825   // Want to form ANDNP nodes:
13826   // 1) In the hopes of then easily combining them with OR and AND nodes
13827   //    to form PBLEND/PSIGN.
13828   // 2) To match ANDN packed intrinsics
13829   if (VT != MVT::v2i64 && VT != MVT::v4i64)
13830     return SDValue();
13831
13832   SDValue N0 = N->getOperand(0);
13833   SDValue N1 = N->getOperand(1);
13834   DebugLoc DL = N->getDebugLoc();
13835
13836   // Check LHS for vnot
13837   if (N0.getOpcode() == ISD::XOR &&
13838       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
13839       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
13840     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
13841
13842   // Check RHS for vnot
13843   if (N1.getOpcode() == ISD::XOR &&
13844       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
13845       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
13846     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
13847
13848   return SDValue();
13849 }
13850
13851 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
13852                                 TargetLowering::DAGCombinerInfo &DCI,
13853                                 const X86Subtarget *Subtarget) {
13854   if (DCI.isBeforeLegalizeOps())
13855     return SDValue();
13856
13857   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
13858   if (R.getNode())
13859     return R;
13860
13861   EVT VT = N->getValueType(0);
13862
13863   SDValue N0 = N->getOperand(0);
13864   SDValue N1 = N->getOperand(1);
13865
13866   // look for psign/blend
13867   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
13868     if (!(Subtarget->hasSSSE3() || Subtarget->hasAVX()) ||
13869         (VT == MVT::v4i64 && !Subtarget->hasAVX2()))
13870       return SDValue();
13871
13872     // Canonicalize pandn to RHS
13873     if (N0.getOpcode() == X86ISD::ANDNP)
13874       std::swap(N0, N1);
13875     // or (and (m, x), (pandn m, y))
13876     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
13877       SDValue Mask = N1.getOperand(0);
13878       SDValue X    = N1.getOperand(1);
13879       SDValue Y;
13880       if (N0.getOperand(0) == Mask)
13881         Y = N0.getOperand(1);
13882       if (N0.getOperand(1) == Mask)
13883         Y = N0.getOperand(0);
13884
13885       // Check to see if the mask appeared in both the AND and ANDNP and
13886       if (!Y.getNode())
13887         return SDValue();
13888
13889       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
13890       if (Mask.getOpcode() != ISD::BITCAST ||
13891           X.getOpcode() != ISD::BITCAST ||
13892           Y.getOpcode() != ISD::BITCAST)
13893         return SDValue();
13894
13895       // Look through mask bitcast.
13896       Mask = Mask.getOperand(0);
13897       EVT MaskVT = Mask.getValueType();
13898
13899       // Validate that the Mask operand is a vector sra node.  The sra node
13900       // will be an intrinsic.
13901       if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
13902         return SDValue();
13903
13904       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
13905       // there is no psrai.b
13906       switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
13907       case Intrinsic::x86_sse2_psrai_w:
13908       case Intrinsic::x86_sse2_psrai_d:
13909       case Intrinsic::x86_avx2_psrai_w:
13910       case Intrinsic::x86_avx2_psrai_d:
13911         break;
13912       default: return SDValue();
13913       }
13914
13915       // Check that the SRA is all signbits.
13916       SDValue SraC = Mask.getOperand(2);
13917       unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
13918       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
13919       if ((SraAmt + 1) != EltBits)
13920         return SDValue();
13921
13922       DebugLoc DL = N->getDebugLoc();
13923
13924       // Now we know we at least have a plendvb with the mask val.  See if
13925       // we can form a psignb/w/d.
13926       // psign = x.type == y.type == mask.type && y = sub(0, x);
13927       X = X.getOperand(0);
13928       Y = Y.getOperand(0);
13929       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
13930           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
13931           X.getValueType() == MaskVT && X.getValueType() == Y.getValueType()){
13932         unsigned Opc = 0;
13933         switch (EltBits) {
13934         case 8: Opc = X86ISD::PSIGNB; break;
13935         case 16: Opc = X86ISD::PSIGNW; break;
13936         case 32: Opc = X86ISD::PSIGND; break;
13937         default: break;
13938         }
13939         if (Opc) {
13940           SDValue Sign = DAG.getNode(Opc, DL, MaskVT, X, Mask.getOperand(1));
13941           return DAG.getNode(ISD::BITCAST, DL, VT, Sign);
13942         }
13943       }
13944       // PBLENDVB only available on SSE 4.1
13945       if (!(Subtarget->hasSSE41() || Subtarget->hasAVX()))
13946         return SDValue();
13947
13948       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
13949
13950       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
13951       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
13952       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
13953       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, X, Y);
13954       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
13955     }
13956   }
13957
13958   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
13959     return SDValue();
13960
13961   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
13962   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
13963     std::swap(N0, N1);
13964   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
13965     return SDValue();
13966   if (!N0.hasOneUse() || !N1.hasOneUse())
13967     return SDValue();
13968
13969   SDValue ShAmt0 = N0.getOperand(1);
13970   if (ShAmt0.getValueType() != MVT::i8)
13971     return SDValue();
13972   SDValue ShAmt1 = N1.getOperand(1);
13973   if (ShAmt1.getValueType() != MVT::i8)
13974     return SDValue();
13975   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
13976     ShAmt0 = ShAmt0.getOperand(0);
13977   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
13978     ShAmt1 = ShAmt1.getOperand(0);
13979
13980   DebugLoc DL = N->getDebugLoc();
13981   unsigned Opc = X86ISD::SHLD;
13982   SDValue Op0 = N0.getOperand(0);
13983   SDValue Op1 = N1.getOperand(0);
13984   if (ShAmt0.getOpcode() == ISD::SUB) {
13985     Opc = X86ISD::SHRD;
13986     std::swap(Op0, Op1);
13987     std::swap(ShAmt0, ShAmt1);
13988   }
13989
13990   unsigned Bits = VT.getSizeInBits();
13991   if (ShAmt1.getOpcode() == ISD::SUB) {
13992     SDValue Sum = ShAmt1.getOperand(0);
13993     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
13994       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
13995       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
13996         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
13997       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
13998         return DAG.getNode(Opc, DL, VT,
13999                            Op0, Op1,
14000                            DAG.getNode(ISD::TRUNCATE, DL,
14001                                        MVT::i8, ShAmt0));
14002     }
14003   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
14004     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
14005     if (ShAmt0C &&
14006         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
14007       return DAG.getNode(Opc, DL, VT,
14008                          N0.getOperand(0), N1.getOperand(0),
14009                          DAG.getNode(ISD::TRUNCATE, DL,
14010                                        MVT::i8, ShAmt0));
14011   }
14012
14013   return SDValue();
14014 }
14015
14016 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
14017                                  TargetLowering::DAGCombinerInfo &DCI,
14018                                  const X86Subtarget *Subtarget) {
14019   if (DCI.isBeforeLegalizeOps())
14020     return SDValue();
14021
14022   EVT VT = N->getValueType(0);
14023
14024   if (VT != MVT::i32 && VT != MVT::i64)
14025     return SDValue();
14026
14027   // Create BLSMSK instructions by finding X ^ (X-1)
14028   SDValue N0 = N->getOperand(0);
14029   SDValue N1 = N->getOperand(1);
14030   DebugLoc DL = N->getDebugLoc();
14031
14032   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
14033       isAllOnes(N0.getOperand(1)))
14034     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
14035
14036   if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
14037       isAllOnes(N1.getOperand(1)))
14038     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
14039
14040   return SDValue();
14041 }
14042
14043 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
14044 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
14045                                    const X86Subtarget *Subtarget) {
14046   LoadSDNode *Ld = cast<LoadSDNode>(N);
14047   EVT RegVT = Ld->getValueType(0);
14048   EVT MemVT = Ld->getMemoryVT();
14049   DebugLoc dl = Ld->getDebugLoc();
14050   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14051
14052   ISD::LoadExtType Ext = Ld->getExtensionType();
14053
14054   // If this is a vector EXT Load then attempt to optimize it using a
14055   // shuffle. We need SSE4 for the shuffles.
14056   // TODO: It is possible to support ZExt by zeroing the undef values
14057   // during the shuffle phase or after the shuffle.
14058   if (RegVT.isVector() && Ext == ISD::EXTLOAD && Subtarget->hasSSE41()) {
14059     assert(MemVT != RegVT && "Cannot extend to the same type");
14060     assert(MemVT.isVector() && "Must load a vector from memory");
14061
14062     unsigned NumElems = RegVT.getVectorNumElements();
14063     unsigned RegSz = RegVT.getSizeInBits();
14064     unsigned MemSz = MemVT.getSizeInBits();
14065     assert(RegSz > MemSz && "Register size must be greater than the mem size");
14066     // All sizes must be a power of two
14067     if (!isPowerOf2_32(RegSz * MemSz * NumElems)) return SDValue();
14068
14069     // Attempt to load the original value using a single load op.
14070     // Find a scalar type which is equal to the loaded word size.
14071     MVT SclrLoadTy = MVT::i8;
14072     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
14073          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
14074       MVT Tp = (MVT::SimpleValueType)tp;
14075       if (TLI.isTypeLegal(Tp) &&  Tp.getSizeInBits() == MemSz) {
14076         SclrLoadTy = Tp;
14077         break;
14078       }
14079     }
14080
14081     // Proceed if a load word is found.
14082     if (SclrLoadTy.getSizeInBits() != MemSz) return SDValue();
14083
14084     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
14085       RegSz/SclrLoadTy.getSizeInBits());
14086
14087     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14088                                   RegSz/MemVT.getScalarType().getSizeInBits());
14089     // Can't shuffle using an illegal type.
14090     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
14091
14092     // Perform a single load.
14093     SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
14094                                   Ld->getBasePtr(),
14095                                   Ld->getPointerInfo(), Ld->isVolatile(),
14096                                   Ld->isNonTemporal(), Ld->isInvariant(),
14097                                   Ld->getAlignment());
14098
14099     // Insert the word loaded into a vector.
14100     SDValue ScalarInVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
14101       LoadUnitVecVT, ScalarLoad);
14102
14103     // Bitcast the loaded value to a vector of the original element type, in
14104     // the size of the target vector type.
14105     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, ScalarInVector);
14106     unsigned SizeRatio = RegSz/MemSz;
14107
14108     // Redistribute the loaded elements into the different locations.
14109     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
14110     for (unsigned i = 0; i < NumElems; i++) ShuffleVec[i*SizeRatio] = i;
14111
14112     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14113                                 DAG.getUNDEF(SlicedVec.getValueType()),
14114                                 ShuffleVec.data());
14115
14116     // Bitcast to the requested type.
14117     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
14118     // Replace the original load with the new sequence
14119     // and return the new chain.
14120     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Shuff);
14121     return SDValue(ScalarLoad.getNode(), 1);
14122   }
14123
14124   return SDValue();
14125 }
14126
14127 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
14128 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
14129                                    const X86Subtarget *Subtarget) {
14130   StoreSDNode *St = cast<StoreSDNode>(N);
14131   EVT VT = St->getValue().getValueType();
14132   EVT StVT = St->getMemoryVT();
14133   DebugLoc dl = St->getDebugLoc();
14134   SDValue StoredVal = St->getOperand(1);
14135   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14136
14137   // If we are saving a concatination of two XMM registers, perform two stores.
14138   // This is better in Sandy Bridge cause one 256-bit mem op is done via two
14139   // 128-bit ones. If in the future the cost becomes only one memory access the
14140   // first version would be better.
14141   if (VT.getSizeInBits() == 256 &&
14142     StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
14143     StoredVal.getNumOperands() == 2) {
14144
14145     SDValue Value0 = StoredVal.getOperand(0);
14146     SDValue Value1 = StoredVal.getOperand(1);
14147
14148     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
14149     SDValue Ptr0 = St->getBasePtr();
14150     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
14151
14152     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
14153                                 St->getPointerInfo(), St->isVolatile(),
14154                                 St->isNonTemporal(), St->getAlignment());
14155     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
14156                                 St->getPointerInfo(), St->isVolatile(),
14157                                 St->isNonTemporal(), St->getAlignment());
14158     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
14159   }
14160
14161   // Optimize trunc store (of multiple scalars) to shuffle and store.
14162   // First, pack all of the elements in one place. Next, store to memory
14163   // in fewer chunks.
14164   if (St->isTruncatingStore() && VT.isVector()) {
14165     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14166     unsigned NumElems = VT.getVectorNumElements();
14167     assert(StVT != VT && "Cannot truncate to the same type");
14168     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
14169     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
14170
14171     // From, To sizes and ElemCount must be pow of two
14172     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
14173     // We are going to use the original vector elt for storing.
14174     // Accumulated smaller vector elements must be a multiple of the store size.
14175     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
14176
14177     unsigned SizeRatio  = FromSz / ToSz;
14178
14179     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
14180
14181     // Create a type on which we perform the shuffle
14182     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
14183             StVT.getScalarType(), NumElems*SizeRatio);
14184
14185     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
14186
14187     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
14188     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
14189     for (unsigned i = 0; i < NumElems; i++ ) ShuffleVec[i] = i * SizeRatio;
14190
14191     // Can't shuffle using an illegal type
14192     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
14193
14194     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
14195                                 DAG.getUNDEF(WideVec.getValueType()),
14196                                 ShuffleVec.data());
14197     // At this point all of the data is stored at the bottom of the
14198     // register. We now need to save it to mem.
14199
14200     // Find the largest store unit
14201     MVT StoreType = MVT::i8;
14202     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
14203          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
14204       MVT Tp = (MVT::SimpleValueType)tp;
14205       if (TLI.isTypeLegal(Tp) && StoreType.getSizeInBits() < NumElems * ToSz)
14206         StoreType = Tp;
14207     }
14208
14209     // Bitcast the original vector into a vector of store-size units
14210     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
14211             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
14212     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
14213     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
14214     SmallVector<SDValue, 8> Chains;
14215     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
14216                                         TLI.getPointerTy());
14217     SDValue Ptr = St->getBasePtr();
14218
14219     // Perform one or more big stores into memory.
14220     for (unsigned i = 0; i < (ToSz*NumElems)/StoreType.getSizeInBits() ; i++) {
14221       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
14222                                    StoreType, ShuffWide,
14223                                    DAG.getIntPtrConstant(i));
14224       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
14225                                 St->getPointerInfo(), St->isVolatile(),
14226                                 St->isNonTemporal(), St->getAlignment());
14227       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14228       Chains.push_back(Ch);
14229     }
14230
14231     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
14232                                Chains.size());
14233   }
14234
14235
14236   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
14237   // the FP state in cases where an emms may be missing.
14238   // A preferable solution to the general problem is to figure out the right
14239   // places to insert EMMS.  This qualifies as a quick hack.
14240
14241   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
14242   if (VT.getSizeInBits() != 64)
14243     return SDValue();
14244
14245   const Function *F = DAG.getMachineFunction().getFunction();
14246   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
14247   bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
14248                      && Subtarget->hasXMMInt();
14249   if ((VT.isVector() ||
14250        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
14251       isa<LoadSDNode>(St->getValue()) &&
14252       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
14253       St->getChain().hasOneUse() && !St->isVolatile()) {
14254     SDNode* LdVal = St->getValue().getNode();
14255     LoadSDNode *Ld = 0;
14256     int TokenFactorIndex = -1;
14257     SmallVector<SDValue, 8> Ops;
14258     SDNode* ChainVal = St->getChain().getNode();
14259     // Must be a store of a load.  We currently handle two cases:  the load
14260     // is a direct child, and it's under an intervening TokenFactor.  It is
14261     // possible to dig deeper under nested TokenFactors.
14262     if (ChainVal == LdVal)
14263       Ld = cast<LoadSDNode>(St->getChain());
14264     else if (St->getValue().hasOneUse() &&
14265              ChainVal->getOpcode() == ISD::TokenFactor) {
14266       for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
14267         if (ChainVal->getOperand(i).getNode() == LdVal) {
14268           TokenFactorIndex = i;
14269           Ld = cast<LoadSDNode>(St->getValue());
14270         } else
14271           Ops.push_back(ChainVal->getOperand(i));
14272       }
14273     }
14274
14275     if (!Ld || !ISD::isNormalLoad(Ld))
14276       return SDValue();
14277
14278     // If this is not the MMX case, i.e. we are just turning i64 load/store
14279     // into f64 load/store, avoid the transformation if there are multiple
14280     // uses of the loaded value.
14281     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
14282       return SDValue();
14283
14284     DebugLoc LdDL = Ld->getDebugLoc();
14285     DebugLoc StDL = N->getDebugLoc();
14286     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
14287     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
14288     // pair instead.
14289     if (Subtarget->is64Bit() || F64IsLegal) {
14290       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
14291       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
14292                                   Ld->getPointerInfo(), Ld->isVolatile(),
14293                                   Ld->isNonTemporal(), Ld->isInvariant(),
14294                                   Ld->getAlignment());
14295       SDValue NewChain = NewLd.getValue(1);
14296       if (TokenFactorIndex != -1) {
14297         Ops.push_back(NewChain);
14298         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14299                                Ops.size());
14300       }
14301       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
14302                           St->getPointerInfo(),
14303                           St->isVolatile(), St->isNonTemporal(),
14304                           St->getAlignment());
14305     }
14306
14307     // Otherwise, lower to two pairs of 32-bit loads / stores.
14308     SDValue LoAddr = Ld->getBasePtr();
14309     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
14310                                  DAG.getConstant(4, MVT::i32));
14311
14312     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
14313                                Ld->getPointerInfo(),
14314                                Ld->isVolatile(), Ld->isNonTemporal(),
14315                                Ld->isInvariant(), Ld->getAlignment());
14316     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
14317                                Ld->getPointerInfo().getWithOffset(4),
14318                                Ld->isVolatile(), Ld->isNonTemporal(),
14319                                Ld->isInvariant(),
14320                                MinAlign(Ld->getAlignment(), 4));
14321
14322     SDValue NewChain = LoLd.getValue(1);
14323     if (TokenFactorIndex != -1) {
14324       Ops.push_back(LoLd);
14325       Ops.push_back(HiLd);
14326       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14327                              Ops.size());
14328     }
14329
14330     LoAddr = St->getBasePtr();
14331     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
14332                          DAG.getConstant(4, MVT::i32));
14333
14334     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
14335                                 St->getPointerInfo(),
14336                                 St->isVolatile(), St->isNonTemporal(),
14337                                 St->getAlignment());
14338     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
14339                                 St->getPointerInfo().getWithOffset(4),
14340                                 St->isVolatile(),
14341                                 St->isNonTemporal(),
14342                                 MinAlign(St->getAlignment(), 4));
14343     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
14344   }
14345   return SDValue();
14346 }
14347
14348 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
14349 /// and return the operands for the horizontal operation in LHS and RHS.  A
14350 /// horizontal operation performs the binary operation on successive elements
14351 /// of its first operand, then on successive elements of its second operand,
14352 /// returning the resulting values in a vector.  For example, if
14353 ///   A = < float a0, float a1, float a2, float a3 >
14354 /// and
14355 ///   B = < float b0, float b1, float b2, float b3 >
14356 /// then the result of doing a horizontal operation on A and B is
14357 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
14358 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
14359 /// A horizontal-op B, for some already available A and B, and if so then LHS is
14360 /// set to A, RHS to B, and the routine returns 'true'.
14361 /// Note that the binary operation should have the property that if one of the
14362 /// operands is UNDEF then the result is UNDEF.
14363 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool isCommutative) {
14364   // Look for the following pattern: if
14365   //   A = < float a0, float a1, float a2, float a3 >
14366   //   B = < float b0, float b1, float b2, float b3 >
14367   // and
14368   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
14369   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
14370   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
14371   // which is A horizontal-op B.
14372
14373   // At least one of the operands should be a vector shuffle.
14374   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
14375       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
14376     return false;
14377
14378   EVT VT = LHS.getValueType();
14379   unsigned N = VT.getVectorNumElements();
14380
14381   // View LHS in the form
14382   //   LHS = VECTOR_SHUFFLE A, B, LMask
14383   // If LHS is not a shuffle then pretend it is the shuffle
14384   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
14385   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
14386   // type VT.
14387   SDValue A, B;
14388   SmallVector<int, 8> LMask(N);
14389   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
14390     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
14391       A = LHS.getOperand(0);
14392     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
14393       B = LHS.getOperand(1);
14394     cast<ShuffleVectorSDNode>(LHS.getNode())->getMask(LMask);
14395   } else {
14396     if (LHS.getOpcode() != ISD::UNDEF)
14397       A = LHS;
14398     for (unsigned i = 0; i != N; ++i)
14399       LMask[i] = i;
14400   }
14401
14402   // Likewise, view RHS in the form
14403   //   RHS = VECTOR_SHUFFLE C, D, RMask
14404   SDValue C, D;
14405   SmallVector<int, 8> RMask(N);
14406   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
14407     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
14408       C = RHS.getOperand(0);
14409     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
14410       D = RHS.getOperand(1);
14411     cast<ShuffleVectorSDNode>(RHS.getNode())->getMask(RMask);
14412   } else {
14413     if (RHS.getOpcode() != ISD::UNDEF)
14414       C = RHS;
14415     for (unsigned i = 0; i != N; ++i)
14416       RMask[i] = i;
14417   }
14418
14419   // Check that the shuffles are both shuffling the same vectors.
14420   if (!(A == C && B == D) && !(A == D && B == C))
14421     return false;
14422
14423   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
14424   if (!A.getNode() && !B.getNode())
14425     return false;
14426
14427   // If A and B occur in reverse order in RHS, then "swap" them (which means
14428   // rewriting the mask).
14429   if (A != C)
14430     for (unsigned i = 0; i != N; ++i) {
14431       unsigned Idx = RMask[i];
14432       if (Idx < N)
14433         RMask[i] += N;
14434       else if (Idx < 2*N)
14435         RMask[i] -= N;
14436     }
14437
14438   // At this point LHS and RHS are equivalent to
14439   //   LHS = VECTOR_SHUFFLE A, B, LMask
14440   //   RHS = VECTOR_SHUFFLE A, B, RMask
14441   // Check that the masks correspond to performing a horizontal operation.
14442   for (unsigned i = 0; i != N; ++i) {
14443     unsigned LIdx = LMask[i], RIdx = RMask[i];
14444
14445     // Ignore any UNDEF components.
14446     if (LIdx >= 2*N || RIdx >= 2*N || (!A.getNode() && (LIdx < N || RIdx < N))
14447         || (!B.getNode() && (LIdx >= N || RIdx >= N)))
14448       continue;
14449
14450     // Check that successive elements are being operated on.  If not, this is
14451     // not a horizontal operation.
14452     if (!(LIdx == 2*i && RIdx == 2*i + 1) &&
14453         !(isCommutative && LIdx == 2*i + 1 && RIdx == 2*i))
14454       return false;
14455   }
14456
14457   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
14458   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
14459   return true;
14460 }
14461
14462 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
14463 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
14464                                   const X86Subtarget *Subtarget) {
14465   EVT VT = N->getValueType(0);
14466   SDValue LHS = N->getOperand(0);
14467   SDValue RHS = N->getOperand(1);
14468
14469   // Try to synthesize horizontal adds from adds of shuffles.
14470   if ((Subtarget->hasSSE3() || Subtarget->hasAVX()) &&
14471       (VT == MVT::v4f32 || VT == MVT::v2f64) &&
14472       isHorizontalBinOp(LHS, RHS, true))
14473     return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
14474   return SDValue();
14475 }
14476
14477 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
14478 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
14479                                   const X86Subtarget *Subtarget) {
14480   EVT VT = N->getValueType(0);
14481   SDValue LHS = N->getOperand(0);
14482   SDValue RHS = N->getOperand(1);
14483
14484   // Try to synthesize horizontal subs from subs of shuffles.
14485   if ((Subtarget->hasSSE3() || Subtarget->hasAVX()) &&
14486       (VT == MVT::v4f32 || VT == MVT::v2f64) &&
14487       isHorizontalBinOp(LHS, RHS, false))
14488     return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
14489   return SDValue();
14490 }
14491
14492 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
14493 /// X86ISD::FXOR nodes.
14494 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
14495   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
14496   // F[X]OR(0.0, x) -> x
14497   // F[X]OR(x, 0.0) -> x
14498   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
14499     if (C->getValueAPF().isPosZero())
14500       return N->getOperand(1);
14501   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
14502     if (C->getValueAPF().isPosZero())
14503       return N->getOperand(0);
14504   return SDValue();
14505 }
14506
14507 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
14508 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
14509   // FAND(0.0, x) -> 0.0
14510   // FAND(x, 0.0) -> 0.0
14511   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
14512     if (C->getValueAPF().isPosZero())
14513       return N->getOperand(0);
14514   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
14515     if (C->getValueAPF().isPosZero())
14516       return N->getOperand(1);
14517   return SDValue();
14518 }
14519
14520 static SDValue PerformBTCombine(SDNode *N,
14521                                 SelectionDAG &DAG,
14522                                 TargetLowering::DAGCombinerInfo &DCI) {
14523   // BT ignores high bits in the bit index operand.
14524   SDValue Op1 = N->getOperand(1);
14525   if (Op1.hasOneUse()) {
14526     unsigned BitWidth = Op1.getValueSizeInBits();
14527     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
14528     APInt KnownZero, KnownOne;
14529     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
14530                                           !DCI.isBeforeLegalizeOps());
14531     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14532     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
14533         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
14534       DCI.CommitTargetLoweringOpt(TLO);
14535   }
14536   return SDValue();
14537 }
14538
14539 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
14540   SDValue Op = N->getOperand(0);
14541   if (Op.getOpcode() == ISD::BITCAST)
14542     Op = Op.getOperand(0);
14543   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
14544   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
14545       VT.getVectorElementType().getSizeInBits() ==
14546       OpVT.getVectorElementType().getSizeInBits()) {
14547     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
14548   }
14549   return SDValue();
14550 }
14551
14552 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
14553   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
14554   //           (and (i32 x86isd::setcc_carry), 1)
14555   // This eliminates the zext. This transformation is necessary because
14556   // ISD::SETCC is always legalized to i8.
14557   DebugLoc dl = N->getDebugLoc();
14558   SDValue N0 = N->getOperand(0);
14559   EVT VT = N->getValueType(0);
14560   if (N0.getOpcode() == ISD::AND &&
14561       N0.hasOneUse() &&
14562       N0.getOperand(0).hasOneUse()) {
14563     SDValue N00 = N0.getOperand(0);
14564     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
14565       return SDValue();
14566     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
14567     if (!C || C->getZExtValue() != 1)
14568       return SDValue();
14569     return DAG.getNode(ISD::AND, dl, VT,
14570                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
14571                                    N00.getOperand(0), N00.getOperand(1)),
14572                        DAG.getConstant(1, VT));
14573   }
14574
14575   return SDValue();
14576 }
14577
14578 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
14579 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
14580   unsigned X86CC = N->getConstantOperandVal(0);
14581   SDValue EFLAG = N->getOperand(1);
14582   DebugLoc DL = N->getDebugLoc();
14583
14584   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
14585   // a zext and produces an all-ones bit which is more useful than 0/1 in some
14586   // cases.
14587   if (X86CC == X86::COND_B)
14588     return DAG.getNode(ISD::AND, DL, MVT::i8,
14589                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
14590                                    DAG.getConstant(X86CC, MVT::i8), EFLAG),
14591                        DAG.getConstant(1, MVT::i8));
14592
14593   return SDValue();
14594 }
14595
14596 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
14597                                         const X86TargetLowering *XTLI) {
14598   SDValue Op0 = N->getOperand(0);
14599   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
14600   // a 32-bit target where SSE doesn't support i64->FP operations.
14601   if (Op0.getOpcode() == ISD::LOAD) {
14602     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
14603     EVT VT = Ld->getValueType(0);
14604     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
14605         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
14606         !XTLI->getSubtarget()->is64Bit() &&
14607         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14608       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
14609                                           Ld->getChain(), Op0, DAG);
14610       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
14611       return FILDChain;
14612     }
14613   }
14614   return SDValue();
14615 }
14616
14617 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
14618 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
14619                                  X86TargetLowering::DAGCombinerInfo &DCI) {
14620   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
14621   // the result is either zero or one (depending on the input carry bit).
14622   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
14623   if (X86::isZeroNode(N->getOperand(0)) &&
14624       X86::isZeroNode(N->getOperand(1)) &&
14625       // We don't have a good way to replace an EFLAGS use, so only do this when
14626       // dead right now.
14627       SDValue(N, 1).use_empty()) {
14628     DebugLoc DL = N->getDebugLoc();
14629     EVT VT = N->getValueType(0);
14630     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
14631     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
14632                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
14633                                            DAG.getConstant(X86::COND_B,MVT::i8),
14634                                            N->getOperand(2)),
14635                                DAG.getConstant(1, VT));
14636     return DCI.CombineTo(N, Res1, CarryOut);
14637   }
14638
14639   return SDValue();
14640 }
14641
14642 // fold (add Y, (sete  X, 0)) -> adc  0, Y
14643 //      (add Y, (setne X, 0)) -> sbb -1, Y
14644 //      (sub (sete  X, 0), Y) -> sbb  0, Y
14645 //      (sub (setne X, 0), Y) -> adc -1, Y
14646 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
14647   DebugLoc DL = N->getDebugLoc();
14648
14649   // Look through ZExts.
14650   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
14651   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
14652     return SDValue();
14653
14654   SDValue SetCC = Ext.getOperand(0);
14655   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
14656     return SDValue();
14657
14658   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
14659   if (CC != X86::COND_E && CC != X86::COND_NE)
14660     return SDValue();
14661
14662   SDValue Cmp = SetCC.getOperand(1);
14663   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
14664       !X86::isZeroNode(Cmp.getOperand(1)) ||
14665       !Cmp.getOperand(0).getValueType().isInteger())
14666     return SDValue();
14667
14668   SDValue CmpOp0 = Cmp.getOperand(0);
14669   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
14670                                DAG.getConstant(1, CmpOp0.getValueType()));
14671
14672   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
14673   if (CC == X86::COND_NE)
14674     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
14675                        DL, OtherVal.getValueType(), OtherVal,
14676                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
14677   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
14678                      DL, OtherVal.getValueType(), OtherVal,
14679                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
14680 }
14681
14682 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG) {
14683   SDValue Op0 = N->getOperand(0);
14684   SDValue Op1 = N->getOperand(1);
14685
14686   // X86 can't encode an immediate LHS of a sub. See if we can push the
14687   // negation into a preceding instruction.
14688   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
14689     // If the RHS of the sub is a XOR with one use and a constant, invert the
14690     // immediate. Then add one to the LHS of the sub so we can turn
14691     // X-Y -> X+~Y+1, saving one register.
14692     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
14693         isa<ConstantSDNode>(Op1.getOperand(1))) {
14694       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
14695       EVT VT = Op0.getValueType();
14696       SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
14697                                    Op1.getOperand(0),
14698                                    DAG.getConstant(~XorC, VT));
14699       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
14700                          DAG.getConstant(C->getAPIntValue()+1, VT));
14701     }
14702   }
14703
14704   return OptimizeConditionalInDecrement(N, DAG);
14705 }
14706
14707 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
14708                                              DAGCombinerInfo &DCI) const {
14709   SelectionDAG &DAG = DCI.DAG;
14710   switch (N->getOpcode()) {
14711   default: break;
14712   case ISD::EXTRACT_VECTOR_ELT:
14713     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
14714   case ISD::VSELECT:
14715   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
14716   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
14717   case ISD::ADD:            return OptimizeConditionalInDecrement(N, DAG);
14718   case ISD::SUB:            return PerformSubCombine(N, DAG);
14719   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
14720   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
14721   case ISD::SHL:
14722   case ISD::SRA:
14723   case ISD::SRL:            return PerformShiftCombine(N, DAG, Subtarget);
14724   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
14725   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
14726   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
14727   case ISD::LOAD:           return PerformLOADCombine(N, DAG, Subtarget);
14728   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
14729   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
14730   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
14731   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
14732   case X86ISD::FXOR:
14733   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
14734   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
14735   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
14736   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
14737   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG);
14738   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG);
14739   case X86ISD::SHUFPS:      // Handle all target specific shuffles
14740   case X86ISD::SHUFPD:
14741   case X86ISD::PALIGN:
14742   case X86ISD::PUNPCKHBW:
14743   case X86ISD::PUNPCKHWD:
14744   case X86ISD::PUNPCKHDQ:
14745   case X86ISD::PUNPCKHQDQ:
14746   case X86ISD::UNPCKHPS:
14747   case X86ISD::UNPCKHPD:
14748   case X86ISD::VUNPCKHPSY:
14749   case X86ISD::VUNPCKHPDY:
14750   case X86ISD::PUNPCKLBW:
14751   case X86ISD::PUNPCKLWD:
14752   case X86ISD::PUNPCKLDQ:
14753   case X86ISD::PUNPCKLQDQ:
14754   case X86ISD::UNPCKLPS:
14755   case X86ISD::UNPCKLPD:
14756   case X86ISD::VUNPCKLPSY:
14757   case X86ISD::VUNPCKLPDY:
14758   case X86ISD::MOVHLPS:
14759   case X86ISD::MOVLHPS:
14760   case X86ISD::PSHUFD:
14761   case X86ISD::PSHUFHW:
14762   case X86ISD::PSHUFLW:
14763   case X86ISD::MOVSS:
14764   case X86ISD::MOVSD:
14765   case X86ISD::VPERMILPS:
14766   case X86ISD::VPERMILPSY:
14767   case X86ISD::VPERMILPD:
14768   case X86ISD::VPERMILPDY:
14769   case X86ISD::VPERM2F128:
14770   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
14771   }
14772
14773   return SDValue();
14774 }
14775
14776 /// isTypeDesirableForOp - Return true if the target has native support for
14777 /// the specified value type and it is 'desirable' to use the type for the
14778 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
14779 /// instruction encodings are longer and some i16 instructions are slow.
14780 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
14781   if (!isTypeLegal(VT))
14782     return false;
14783   if (VT != MVT::i16)
14784     return true;
14785
14786   switch (Opc) {
14787   default:
14788     return true;
14789   case ISD::LOAD:
14790   case ISD::SIGN_EXTEND:
14791   case ISD::ZERO_EXTEND:
14792   case ISD::ANY_EXTEND:
14793   case ISD::SHL:
14794   case ISD::SRL:
14795   case ISD::SUB:
14796   case ISD::ADD:
14797   case ISD::MUL:
14798   case ISD::AND:
14799   case ISD::OR:
14800   case ISD::XOR:
14801     return false;
14802   }
14803 }
14804
14805 /// IsDesirableToPromoteOp - This method query the target whether it is
14806 /// beneficial for dag combiner to promote the specified node. If true, it
14807 /// should return the desired promotion type by reference.
14808 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
14809   EVT VT = Op.getValueType();
14810   if (VT != MVT::i16)
14811     return false;
14812
14813   bool Promote = false;
14814   bool Commute = false;
14815   switch (Op.getOpcode()) {
14816   default: break;
14817   case ISD::LOAD: {
14818     LoadSDNode *LD = cast<LoadSDNode>(Op);
14819     // If the non-extending load has a single use and it's not live out, then it
14820     // might be folded.
14821     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
14822                                                      Op.hasOneUse()*/) {
14823       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
14824              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
14825         // The only case where we'd want to promote LOAD (rather then it being
14826         // promoted as an operand is when it's only use is liveout.
14827         if (UI->getOpcode() != ISD::CopyToReg)
14828           return false;
14829       }
14830     }
14831     Promote = true;
14832     break;
14833   }
14834   case ISD::SIGN_EXTEND:
14835   case ISD::ZERO_EXTEND:
14836   case ISD::ANY_EXTEND:
14837     Promote = true;
14838     break;
14839   case ISD::SHL:
14840   case ISD::SRL: {
14841     SDValue N0 = Op.getOperand(0);
14842     // Look out for (store (shl (load), x)).
14843     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
14844       return false;
14845     Promote = true;
14846     break;
14847   }
14848   case ISD::ADD:
14849   case ISD::MUL:
14850   case ISD::AND:
14851   case ISD::OR:
14852   case ISD::XOR:
14853     Commute = true;
14854     // fallthrough
14855   case ISD::SUB: {
14856     SDValue N0 = Op.getOperand(0);
14857     SDValue N1 = Op.getOperand(1);
14858     if (!Commute && MayFoldLoad(N1))
14859       return false;
14860     // Avoid disabling potential load folding opportunities.
14861     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
14862       return false;
14863     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
14864       return false;
14865     Promote = true;
14866   }
14867   }
14868
14869   PVT = MVT::i32;
14870   return Promote;
14871 }
14872
14873 //===----------------------------------------------------------------------===//
14874 //                           X86 Inline Assembly Support
14875 //===----------------------------------------------------------------------===//
14876
14877 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
14878   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
14879
14880   std::string AsmStr = IA->getAsmString();
14881
14882   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
14883   SmallVector<StringRef, 4> AsmPieces;
14884   SplitString(AsmStr, AsmPieces, ";\n");
14885
14886   switch (AsmPieces.size()) {
14887   default: return false;
14888   case 1:
14889     AsmStr = AsmPieces[0];
14890     AsmPieces.clear();
14891     SplitString(AsmStr, AsmPieces, " \t");  // Split with whitespace.
14892
14893     // FIXME: this should verify that we are targeting a 486 or better.  If not,
14894     // we will turn this bswap into something that will be lowered to logical ops
14895     // instead of emitting the bswap asm.  For now, we don't support 486 or lower
14896     // so don't worry about this.
14897     // bswap $0
14898     if (AsmPieces.size() == 2 &&
14899         (AsmPieces[0] == "bswap" ||
14900          AsmPieces[0] == "bswapq" ||
14901          AsmPieces[0] == "bswapl") &&
14902         (AsmPieces[1] == "$0" ||
14903          AsmPieces[1] == "${0:q}")) {
14904       // No need to check constraints, nothing other than the equivalent of
14905       // "=r,0" would be valid here.
14906       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14907       if (!Ty || Ty->getBitWidth() % 16 != 0)
14908         return false;
14909       return IntrinsicLowering::LowerToByteSwap(CI);
14910     }
14911     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
14912     if (CI->getType()->isIntegerTy(16) &&
14913         AsmPieces.size() == 3 &&
14914         (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
14915         AsmPieces[1] == "$$8," &&
14916         AsmPieces[2] == "${0:w}" &&
14917         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
14918       AsmPieces.clear();
14919       const std::string &ConstraintsStr = IA->getConstraintString();
14920       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
14921       std::sort(AsmPieces.begin(), AsmPieces.end());
14922       if (AsmPieces.size() == 4 &&
14923           AsmPieces[0] == "~{cc}" &&
14924           AsmPieces[1] == "~{dirflag}" &&
14925           AsmPieces[2] == "~{flags}" &&
14926           AsmPieces[3] == "~{fpsr}") {
14927         IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14928         if (!Ty || Ty->getBitWidth() % 16 != 0)
14929           return false;
14930         return IntrinsicLowering::LowerToByteSwap(CI);
14931       }
14932     }
14933     break;
14934   case 3:
14935     if (CI->getType()->isIntegerTy(32) &&
14936         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
14937       SmallVector<StringRef, 4> Words;
14938       SplitString(AsmPieces[0], Words, " \t,");
14939       if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
14940           Words[2] == "${0:w}") {
14941         Words.clear();
14942         SplitString(AsmPieces[1], Words, " \t,");
14943         if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" &&
14944             Words[2] == "$0") {
14945           Words.clear();
14946           SplitString(AsmPieces[2], Words, " \t,");
14947           if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
14948               Words[2] == "${0:w}") {
14949             AsmPieces.clear();
14950             const std::string &ConstraintsStr = IA->getConstraintString();
14951             SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
14952             std::sort(AsmPieces.begin(), AsmPieces.end());
14953             if (AsmPieces.size() == 4 &&
14954                 AsmPieces[0] == "~{cc}" &&
14955                 AsmPieces[1] == "~{dirflag}" &&
14956                 AsmPieces[2] == "~{flags}" &&
14957                 AsmPieces[3] == "~{fpsr}") {
14958               IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14959               if (!Ty || Ty->getBitWidth() % 16 != 0)
14960                 return false;
14961               return IntrinsicLowering::LowerToByteSwap(CI);
14962             }
14963           }
14964         }
14965       }
14966     }
14967
14968     if (CI->getType()->isIntegerTy(64)) {
14969       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
14970       if (Constraints.size() >= 2 &&
14971           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
14972           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
14973         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
14974         SmallVector<StringRef, 4> Words;
14975         SplitString(AsmPieces[0], Words, " \t");
14976         if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
14977           Words.clear();
14978           SplitString(AsmPieces[1], Words, " \t");
14979           if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
14980             Words.clear();
14981             SplitString(AsmPieces[2], Words, " \t,");
14982             if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
14983                 Words[2] == "%edx") {
14984               IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14985               if (!Ty || Ty->getBitWidth() % 16 != 0)
14986                 return false;
14987               return IntrinsicLowering::LowerToByteSwap(CI);
14988             }
14989           }
14990         }
14991       }
14992     }
14993     break;
14994   }
14995   return false;
14996 }
14997
14998
14999
15000 /// getConstraintType - Given a constraint letter, return the type of
15001 /// constraint it is for this target.
15002 X86TargetLowering::ConstraintType
15003 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
15004   if (Constraint.size() == 1) {
15005     switch (Constraint[0]) {
15006     case 'R':
15007     case 'q':
15008     case 'Q':
15009     case 'f':
15010     case 't':
15011     case 'u':
15012     case 'y':
15013     case 'x':
15014     case 'Y':
15015     case 'l':
15016       return C_RegisterClass;
15017     case 'a':
15018     case 'b':
15019     case 'c':
15020     case 'd':
15021     case 'S':
15022     case 'D':
15023     case 'A':
15024       return C_Register;
15025     case 'I':
15026     case 'J':
15027     case 'K':
15028     case 'L':
15029     case 'M':
15030     case 'N':
15031     case 'G':
15032     case 'C':
15033     case 'e':
15034     case 'Z':
15035       return C_Other;
15036     default:
15037       break;
15038     }
15039   }
15040   return TargetLowering::getConstraintType(Constraint);
15041 }
15042
15043 /// Examine constraint type and operand type and determine a weight value.
15044 /// This object must already have been set up with the operand type
15045 /// and the current alternative constraint selected.
15046 TargetLowering::ConstraintWeight
15047   X86TargetLowering::getSingleConstraintMatchWeight(
15048     AsmOperandInfo &info, const char *constraint) const {
15049   ConstraintWeight weight = CW_Invalid;
15050   Value *CallOperandVal = info.CallOperandVal;
15051     // If we don't have a value, we can't do a match,
15052     // but allow it at the lowest weight.
15053   if (CallOperandVal == NULL)
15054     return CW_Default;
15055   Type *type = CallOperandVal->getType();
15056   // Look at the constraint type.
15057   switch (*constraint) {
15058   default:
15059     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
15060   case 'R':
15061   case 'q':
15062   case 'Q':
15063   case 'a':
15064   case 'b':
15065   case 'c':
15066   case 'd':
15067   case 'S':
15068   case 'D':
15069   case 'A':
15070     if (CallOperandVal->getType()->isIntegerTy())
15071       weight = CW_SpecificReg;
15072     break;
15073   case 'f':
15074   case 't':
15075   case 'u':
15076       if (type->isFloatingPointTy())
15077         weight = CW_SpecificReg;
15078       break;
15079   case 'y':
15080       if (type->isX86_MMXTy() && Subtarget->hasMMX())
15081         weight = CW_SpecificReg;
15082       break;
15083   case 'x':
15084   case 'Y':
15085     if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
15086       weight = CW_Register;
15087     break;
15088   case 'I':
15089     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
15090       if (C->getZExtValue() <= 31)
15091         weight = CW_Constant;
15092     }
15093     break;
15094   case 'J':
15095     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15096       if (C->getZExtValue() <= 63)
15097         weight = CW_Constant;
15098     }
15099     break;
15100   case 'K':
15101     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15102       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
15103         weight = CW_Constant;
15104     }
15105     break;
15106   case 'L':
15107     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15108       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
15109         weight = CW_Constant;
15110     }
15111     break;
15112   case 'M':
15113     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15114       if (C->getZExtValue() <= 3)
15115         weight = CW_Constant;
15116     }
15117     break;
15118   case 'N':
15119     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15120       if (C->getZExtValue() <= 0xff)
15121         weight = CW_Constant;
15122     }
15123     break;
15124   case 'G':
15125   case 'C':
15126     if (dyn_cast<ConstantFP>(CallOperandVal)) {
15127       weight = CW_Constant;
15128     }
15129     break;
15130   case 'e':
15131     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15132       if ((C->getSExtValue() >= -0x80000000LL) &&
15133           (C->getSExtValue() <= 0x7fffffffLL))
15134         weight = CW_Constant;
15135     }
15136     break;
15137   case 'Z':
15138     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15139       if (C->getZExtValue() <= 0xffffffff)
15140         weight = CW_Constant;
15141     }
15142     break;
15143   }
15144   return weight;
15145 }
15146
15147 /// LowerXConstraint - try to replace an X constraint, which matches anything,
15148 /// with another that has more specific requirements based on the type of the
15149 /// corresponding operand.
15150 const char *X86TargetLowering::
15151 LowerXConstraint(EVT ConstraintVT) const {
15152   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
15153   // 'f' like normal targets.
15154   if (ConstraintVT.isFloatingPoint()) {
15155     if (Subtarget->hasXMMInt())
15156       return "Y";
15157     if (Subtarget->hasXMM())
15158       return "x";
15159   }
15160
15161   return TargetLowering::LowerXConstraint(ConstraintVT);
15162 }
15163
15164 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
15165 /// vector.  If it is invalid, don't add anything to Ops.
15166 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
15167                                                      std::string &Constraint,
15168                                                      std::vector<SDValue>&Ops,
15169                                                      SelectionDAG &DAG) const {
15170   SDValue Result(0, 0);
15171
15172   // Only support length 1 constraints for now.
15173   if (Constraint.length() > 1) return;
15174
15175   char ConstraintLetter = Constraint[0];
15176   switch (ConstraintLetter) {
15177   default: break;
15178   case 'I':
15179     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15180       if (C->getZExtValue() <= 31) {
15181         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15182         break;
15183       }
15184     }
15185     return;
15186   case 'J':
15187     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15188       if (C->getZExtValue() <= 63) {
15189         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15190         break;
15191       }
15192     }
15193     return;
15194   case 'K':
15195     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15196       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
15197         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15198         break;
15199       }
15200     }
15201     return;
15202   case 'N':
15203     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15204       if (C->getZExtValue() <= 255) {
15205         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15206         break;
15207       }
15208     }
15209     return;
15210   case 'e': {
15211     // 32-bit signed value
15212     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15213       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
15214                                            C->getSExtValue())) {
15215         // Widen to 64 bits here to get it sign extended.
15216         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
15217         break;
15218       }
15219     // FIXME gcc accepts some relocatable values here too, but only in certain
15220     // memory models; it's complicated.
15221     }
15222     return;
15223   }
15224   case 'Z': {
15225     // 32-bit unsigned value
15226     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15227       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
15228                                            C->getZExtValue())) {
15229         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15230         break;
15231       }
15232     }
15233     // FIXME gcc accepts some relocatable values here too, but only in certain
15234     // memory models; it's complicated.
15235     return;
15236   }
15237   case 'i': {
15238     // Literal immediates are always ok.
15239     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
15240       // Widen to 64 bits here to get it sign extended.
15241       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
15242       break;
15243     }
15244
15245     // In any sort of PIC mode addresses need to be computed at runtime by
15246     // adding in a register or some sort of table lookup.  These can't
15247     // be used as immediates.
15248     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
15249       return;
15250
15251     // If we are in non-pic codegen mode, we allow the address of a global (with
15252     // an optional displacement) to be used with 'i'.
15253     GlobalAddressSDNode *GA = 0;
15254     int64_t Offset = 0;
15255
15256     // Match either (GA), (GA+C), (GA+C1+C2), etc.
15257     while (1) {
15258       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
15259         Offset += GA->getOffset();
15260         break;
15261       } else if (Op.getOpcode() == ISD::ADD) {
15262         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
15263           Offset += C->getZExtValue();
15264           Op = Op.getOperand(0);
15265           continue;
15266         }
15267       } else if (Op.getOpcode() == ISD::SUB) {
15268         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
15269           Offset += -C->getZExtValue();
15270           Op = Op.getOperand(0);
15271           continue;
15272         }
15273       }
15274
15275       // Otherwise, this isn't something we can handle, reject it.
15276       return;
15277     }
15278
15279     const GlobalValue *GV = GA->getGlobal();
15280     // If we require an extra load to get this address, as in PIC mode, we
15281     // can't accept it.
15282     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
15283                                                         getTargetMachine())))
15284       return;
15285
15286     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
15287                                         GA->getValueType(0), Offset);
15288     break;
15289   }
15290   }
15291
15292   if (Result.getNode()) {
15293     Ops.push_back(Result);
15294     return;
15295   }
15296   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
15297 }
15298
15299 std::pair<unsigned, const TargetRegisterClass*>
15300 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
15301                                                 EVT VT) const {
15302   // First, see if this is a constraint that directly corresponds to an LLVM
15303   // register class.
15304   if (Constraint.size() == 1) {
15305     // GCC Constraint Letters
15306     switch (Constraint[0]) {
15307     default: break;
15308       // TODO: Slight differences here in allocation order and leaving
15309       // RIP in the class. Do they matter any more here than they do
15310       // in the normal allocation?
15311     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
15312       if (Subtarget->is64Bit()) {
15313         if (VT == MVT::i32 || VT == MVT::f32)
15314           return std::make_pair(0U, X86::GR32RegisterClass);
15315         else if (VT == MVT::i16)
15316           return std::make_pair(0U, X86::GR16RegisterClass);
15317         else if (VT == MVT::i8 || VT == MVT::i1)
15318           return std::make_pair(0U, X86::GR8RegisterClass);
15319         else if (VT == MVT::i64 || VT == MVT::f64)
15320           return std::make_pair(0U, X86::GR64RegisterClass);
15321         break;
15322       }
15323       // 32-bit fallthrough
15324     case 'Q':   // Q_REGS
15325       if (VT == MVT::i32 || VT == MVT::f32)
15326         return std::make_pair(0U, X86::GR32_ABCDRegisterClass);
15327       else if (VT == MVT::i16)
15328         return std::make_pair(0U, X86::GR16_ABCDRegisterClass);
15329       else if (VT == MVT::i8 || VT == MVT::i1)
15330         return std::make_pair(0U, X86::GR8_ABCD_LRegisterClass);
15331       else if (VT == MVT::i64)
15332         return std::make_pair(0U, X86::GR64_ABCDRegisterClass);
15333       break;
15334     case 'r':   // GENERAL_REGS
15335     case 'l':   // INDEX_REGS
15336       if (VT == MVT::i8 || VT == MVT::i1)
15337         return std::make_pair(0U, X86::GR8RegisterClass);
15338       if (VT == MVT::i16)
15339         return std::make_pair(0U, X86::GR16RegisterClass);
15340       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
15341         return std::make_pair(0U, X86::GR32RegisterClass);
15342       return std::make_pair(0U, X86::GR64RegisterClass);
15343     case 'R':   // LEGACY_REGS
15344       if (VT == MVT::i8 || VT == MVT::i1)
15345         return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
15346       if (VT == MVT::i16)
15347         return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
15348       if (VT == MVT::i32 || !Subtarget->is64Bit())
15349         return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
15350       return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
15351     case 'f':  // FP Stack registers.
15352       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
15353       // value to the correct fpstack register class.
15354       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
15355         return std::make_pair(0U, X86::RFP32RegisterClass);
15356       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
15357         return std::make_pair(0U, X86::RFP64RegisterClass);
15358       return std::make_pair(0U, X86::RFP80RegisterClass);
15359     case 'y':   // MMX_REGS if MMX allowed.
15360       if (!Subtarget->hasMMX()) break;
15361       return std::make_pair(0U, X86::VR64RegisterClass);
15362     case 'Y':   // SSE_REGS if SSE2 allowed
15363       if (!Subtarget->hasXMMInt()) break;
15364       // FALL THROUGH.
15365     case 'x':   // SSE_REGS if SSE1 allowed
15366       if (!Subtarget->hasXMM()) break;
15367
15368       switch (VT.getSimpleVT().SimpleTy) {
15369       default: break;
15370       // Scalar SSE types.
15371       case MVT::f32:
15372       case MVT::i32:
15373         return std::make_pair(0U, X86::FR32RegisterClass);
15374       case MVT::f64:
15375       case MVT::i64:
15376         return std::make_pair(0U, X86::FR64RegisterClass);
15377       // Vector types.
15378       case MVT::v16i8:
15379       case MVT::v8i16:
15380       case MVT::v4i32:
15381       case MVT::v2i64:
15382       case MVT::v4f32:
15383       case MVT::v2f64:
15384         return std::make_pair(0U, X86::VR128RegisterClass);
15385       }
15386       break;
15387     }
15388   }
15389
15390   // Use the default implementation in TargetLowering to convert the register
15391   // constraint into a member of a register class.
15392   std::pair<unsigned, const TargetRegisterClass*> Res;
15393   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
15394
15395   // Not found as a standard register?
15396   if (Res.second == 0) {
15397     // Map st(0) -> st(7) -> ST0
15398     if (Constraint.size() == 7 && Constraint[0] == '{' &&
15399         tolower(Constraint[1]) == 's' &&
15400         tolower(Constraint[2]) == 't' &&
15401         Constraint[3] == '(' &&
15402         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
15403         Constraint[5] == ')' &&
15404         Constraint[6] == '}') {
15405
15406       Res.first = X86::ST0+Constraint[4]-'0';
15407       Res.second = X86::RFP80RegisterClass;
15408       return Res;
15409     }
15410
15411     // GCC allows "st(0)" to be called just plain "st".
15412     if (StringRef("{st}").equals_lower(Constraint)) {
15413       Res.first = X86::ST0;
15414       Res.second = X86::RFP80RegisterClass;
15415       return Res;
15416     }
15417
15418     // flags -> EFLAGS
15419     if (StringRef("{flags}").equals_lower(Constraint)) {
15420       Res.first = X86::EFLAGS;
15421       Res.second = X86::CCRRegisterClass;
15422       return Res;
15423     }
15424
15425     // 'A' means EAX + EDX.
15426     if (Constraint == "A") {
15427       Res.first = X86::EAX;
15428       Res.second = X86::GR32_ADRegisterClass;
15429       return Res;
15430     }
15431     return Res;
15432   }
15433
15434   // Otherwise, check to see if this is a register class of the wrong value
15435   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
15436   // turn into {ax},{dx}.
15437   if (Res.second->hasType(VT))
15438     return Res;   // Correct type already, nothing to do.
15439
15440   // All of the single-register GCC register classes map their values onto
15441   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
15442   // really want an 8-bit or 32-bit register, map to the appropriate register
15443   // class and return the appropriate register.
15444   if (Res.second == X86::GR16RegisterClass) {
15445     if (VT == MVT::i8) {
15446       unsigned DestReg = 0;
15447       switch (Res.first) {
15448       default: break;
15449       case X86::AX: DestReg = X86::AL; break;
15450       case X86::DX: DestReg = X86::DL; break;
15451       case X86::CX: DestReg = X86::CL; break;
15452       case X86::BX: DestReg = X86::BL; break;
15453       }
15454       if (DestReg) {
15455         Res.first = DestReg;
15456         Res.second = X86::GR8RegisterClass;
15457       }
15458     } else if (VT == MVT::i32) {
15459       unsigned DestReg = 0;
15460       switch (Res.first) {
15461       default: break;
15462       case X86::AX: DestReg = X86::EAX; break;
15463       case X86::DX: DestReg = X86::EDX; break;
15464       case X86::CX: DestReg = X86::ECX; break;
15465       case X86::BX: DestReg = X86::EBX; break;
15466       case X86::SI: DestReg = X86::ESI; break;
15467       case X86::DI: DestReg = X86::EDI; break;
15468       case X86::BP: DestReg = X86::EBP; break;
15469       case X86::SP: DestReg = X86::ESP; break;
15470       }
15471       if (DestReg) {
15472         Res.first = DestReg;
15473         Res.second = X86::GR32RegisterClass;
15474       }
15475     } else if (VT == MVT::i64) {
15476       unsigned DestReg = 0;
15477       switch (Res.first) {
15478       default: break;
15479       case X86::AX: DestReg = X86::RAX; break;
15480       case X86::DX: DestReg = X86::RDX; break;
15481       case X86::CX: DestReg = X86::RCX; break;
15482       case X86::BX: DestReg = X86::RBX; break;
15483       case X86::SI: DestReg = X86::RSI; break;
15484       case X86::DI: DestReg = X86::RDI; break;
15485       case X86::BP: DestReg = X86::RBP; break;
15486       case X86::SP: DestReg = X86::RSP; break;
15487       }
15488       if (DestReg) {
15489         Res.first = DestReg;
15490         Res.second = X86::GR64RegisterClass;
15491       }
15492     }
15493   } else if (Res.second == X86::FR32RegisterClass ||
15494              Res.second == X86::FR64RegisterClass ||
15495              Res.second == X86::VR128RegisterClass) {
15496     // Handle references to XMM physical registers that got mapped into the
15497     // wrong class.  This can happen with constraints like {xmm0} where the
15498     // target independent register mapper will just pick the first match it can
15499     // find, ignoring the required type.
15500     if (VT == MVT::f32)
15501       Res.second = X86::FR32RegisterClass;
15502     else if (VT == MVT::f64)
15503       Res.second = X86::FR64RegisterClass;
15504     else if (X86::VR128RegisterClass->hasType(VT))
15505       Res.second = X86::VR128RegisterClass;
15506   }
15507
15508   return Res;
15509 }