215e73572055dbd24c8ae735e9316b2fdd724b55
[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->hasSSE41orAVX()) {
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->hasSSE42orAVX())
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 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3419 /// the two vector operands have swapped position.
3420 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3421   unsigned NumElems = VT.getVectorNumElements();
3422   for (unsigned i = 0; i != NumElems; ++i) {
3423     int idx = Mask[i];
3424     if (idx < 0)
3425       continue;
3426     else if (idx < (int)NumElems)
3427       Mask[i] = idx + NumElems;
3428     else
3429       Mask[i] = idx - NumElems;
3430   }
3431 }
3432
3433 /// isCommutedVSHUFP() - Return true if swapping operands will 
3434 ///  allow to use the "vshufpd" or "vshufps" instruction 
3435 ///  for 256-bit vectors
3436 static bool isCommutedVSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT,
3437                                const X86Subtarget *Subtarget) {
3438
3439   unsigned NumElems = VT.getVectorNumElements();
3440   if ((VT.getSizeInBits() != 256) || ((NumElems != 4) && (NumElems != 8)))
3441     return false;
3442
3443   SmallVector<int, 8> CommutedMask;
3444   for (unsigned i = 0; i < NumElems; ++i)
3445     CommutedMask.push_back(Mask[i]);
3446
3447   CommuteVectorShuffleMask(CommutedMask, VT);
3448   return (NumElems == 4) ? isVSHUFPDYMask(CommutedMask, VT, Subtarget):
3449       isVSHUFPSYMask(CommutedMask, VT, Subtarget);
3450 }
3451
3452
3453 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3454 /// specifies a shuffle of elements that is suitable for input to 128-bit
3455 /// SHUFPS and SHUFPD.
3456 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3457   int NumElems = VT.getVectorNumElements();
3458
3459   if (VT.getSizeInBits() != 128)
3460     return false;
3461
3462   if (NumElems != 2 && NumElems != 4)
3463     return false;
3464
3465   int Half = NumElems / 2;
3466   for (int i = 0; i < Half; ++i)
3467     if (!isUndefOrInRange(Mask[i], 0, NumElems))
3468       return false;
3469   for (int i = Half; i < NumElems; ++i)
3470     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3471       return false;
3472
3473   return true;
3474 }
3475
3476 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
3477   SmallVector<int, 8> M;
3478   N->getMask(M);
3479   return ::isSHUFPMask(M, N->getValueType(0));
3480 }
3481
3482 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
3483 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
3484 /// half elements to come from vector 1 (which would equal the dest.) and
3485 /// the upper half to come from vector 2.
3486 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3487   int NumElems = VT.getVectorNumElements();
3488
3489   if (NumElems != 2 && NumElems != 4)
3490     return false;
3491
3492   int Half = NumElems / 2;
3493   for (int i = 0; i < Half; ++i)
3494     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3495       return false;
3496   for (int i = Half; i < NumElems; ++i)
3497     if (!isUndefOrInRange(Mask[i], 0, NumElems))
3498       return false;
3499   return true;
3500 }
3501
3502 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
3503   SmallVector<int, 8> M;
3504   N->getMask(M);
3505   return isCommutedSHUFPMask(M, N->getValueType(0));
3506 }
3507
3508 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3509 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3510 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3511   EVT VT = N->getValueType(0);
3512   unsigned NumElems = VT.getVectorNumElements();
3513
3514   if (VT.getSizeInBits() != 128)
3515     return false;
3516
3517   if (NumElems != 4)
3518     return false;
3519
3520   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3521   return isUndefOrEqual(N->getMaskElt(0), 6) &&
3522          isUndefOrEqual(N->getMaskElt(1), 7) &&
3523          isUndefOrEqual(N->getMaskElt(2), 2) &&
3524          isUndefOrEqual(N->getMaskElt(3), 3);
3525 }
3526
3527 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3528 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3529 /// <2, 3, 2, 3>
3530 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3531   EVT VT = N->getValueType(0);
3532   unsigned NumElems = VT.getVectorNumElements();
3533
3534   if (VT.getSizeInBits() != 128)
3535     return false;
3536
3537   if (NumElems != 4)
3538     return false;
3539
3540   return isUndefOrEqual(N->getMaskElt(0), 2) &&
3541          isUndefOrEqual(N->getMaskElt(1), 3) &&
3542          isUndefOrEqual(N->getMaskElt(2), 2) &&
3543          isUndefOrEqual(N->getMaskElt(3), 3);
3544 }
3545
3546 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3547 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3548 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3549   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3550
3551   if (NumElems != 2 && NumElems != 4)
3552     return false;
3553
3554   for (unsigned i = 0; i < NumElems/2; ++i)
3555     if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3556       return false;
3557
3558   for (unsigned i = NumElems/2; i < NumElems; ++i)
3559     if (!isUndefOrEqual(N->getMaskElt(i), i))
3560       return false;
3561
3562   return true;
3563 }
3564
3565 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3566 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3567 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3568   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3569
3570   if ((NumElems != 2 && NumElems != 4)
3571       || N->getValueType(0).getSizeInBits() > 128)
3572     return false;
3573
3574   for (unsigned i = 0; i < NumElems/2; ++i)
3575     if (!isUndefOrEqual(N->getMaskElt(i), i))
3576       return false;
3577
3578   for (unsigned i = 0; i < NumElems/2; ++i)
3579     if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3580       return false;
3581
3582   return true;
3583 }
3584
3585 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3586 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3587 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3588                          bool HasAVX2, bool V2IsSplat = false) {
3589   int NumElts = VT.getVectorNumElements();
3590
3591   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3592          "Unsupported vector type for unpckh");
3593
3594   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3595       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3596     return false;
3597
3598   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3599   // independently on 128-bit lanes.
3600   unsigned NumLanes = VT.getSizeInBits()/128;
3601   unsigned NumLaneElts = NumElts/NumLanes;
3602
3603   unsigned Start = 0;
3604   unsigned End = NumLaneElts;
3605   for (unsigned s = 0; s < NumLanes; ++s) {
3606     for (unsigned i = Start, j = s * NumLaneElts;
3607          i != End;
3608          i += 2, ++j) {
3609       int BitI  = Mask[i];
3610       int BitI1 = Mask[i+1];
3611       if (!isUndefOrEqual(BitI, j))
3612         return false;
3613       if (V2IsSplat) {
3614         if (!isUndefOrEqual(BitI1, NumElts))
3615           return false;
3616       } else {
3617         if (!isUndefOrEqual(BitI1, j + NumElts))
3618           return false;
3619       }
3620     }
3621     // Process the next 128 bits.
3622     Start += NumLaneElts;
3623     End += NumLaneElts;
3624   }
3625
3626   return true;
3627 }
3628
3629 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool HasAVX2, bool V2IsSplat) {
3630   SmallVector<int, 8> M;
3631   N->getMask(M);
3632   return ::isUNPCKLMask(M, N->getValueType(0), HasAVX2, V2IsSplat);
3633 }
3634
3635 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3636 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3637 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3638                          bool HasAVX2, bool V2IsSplat = false) {
3639   int NumElts = VT.getVectorNumElements();
3640
3641   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3642          "Unsupported vector type for unpckh");
3643
3644   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3645       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3646     return false;
3647
3648   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3649   // independently on 128-bit lanes.
3650   unsigned NumLanes = VT.getSizeInBits()/128;
3651   unsigned NumLaneElts = NumElts/NumLanes;
3652
3653   unsigned Start = 0;
3654   unsigned End = NumLaneElts;
3655   for (unsigned l = 0; l != NumLanes; ++l) {
3656     for (unsigned i = Start, j = (l*NumLaneElts)+NumLaneElts/2;
3657                              i != End; i += 2, ++j) {
3658       int BitI  = Mask[i];
3659       int BitI1 = Mask[i+1];
3660       if (!isUndefOrEqual(BitI, j))
3661         return false;
3662       if (V2IsSplat) {
3663         if (isUndefOrEqual(BitI1, NumElts))
3664           return false;
3665       } else {
3666         if (!isUndefOrEqual(BitI1, j+NumElts))
3667           return false;
3668       }
3669     }
3670     // Process the next 128 bits.
3671     Start += NumLaneElts;
3672     End += NumLaneElts;
3673   }
3674   return true;
3675 }
3676
3677 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool HasAVX2, bool V2IsSplat) {
3678   SmallVector<int, 8> M;
3679   N->getMask(M);
3680   return ::isUNPCKHMask(M, N->getValueType(0), HasAVX2, V2IsSplat);
3681 }
3682
3683 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3684 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3685 /// <0, 0, 1, 1>
3686 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3687   int NumElems = VT.getVectorNumElements();
3688   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3689     return false;
3690
3691   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3692   // FIXME: Need a better way to get rid of this, there's no latency difference
3693   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3694   // the former later. We should also remove the "_undef" special mask.
3695   if (NumElems == 4 && VT.getSizeInBits() == 256)
3696     return false;
3697
3698   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3699   // independently on 128-bit lanes.
3700   unsigned NumLanes = VT.getSizeInBits() / 128;
3701   unsigned NumLaneElts = NumElems / NumLanes;
3702
3703   for (unsigned s = 0; s < NumLanes; ++s) {
3704     for (unsigned i = s * NumLaneElts, j = s * NumLaneElts;
3705          i != NumLaneElts * (s + 1);
3706          i += 2, ++j) {
3707       int BitI  = Mask[i];
3708       int BitI1 = Mask[i+1];
3709
3710       if (!isUndefOrEqual(BitI, j))
3711         return false;
3712       if (!isUndefOrEqual(BitI1, j))
3713         return false;
3714     }
3715   }
3716
3717   return true;
3718 }
3719
3720 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3721   SmallVector<int, 8> M;
3722   N->getMask(M);
3723   return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3724 }
3725
3726 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3727 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3728 /// <2, 2, 3, 3>
3729 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3730   int NumElems = VT.getVectorNumElements();
3731   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3732     return false;
3733
3734   for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3735     int BitI  = Mask[i];
3736     int BitI1 = Mask[i+1];
3737     if (!isUndefOrEqual(BitI, j))
3738       return false;
3739     if (!isUndefOrEqual(BitI1, j))
3740       return false;
3741   }
3742   return true;
3743 }
3744
3745 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3746   SmallVector<int, 8> M;
3747   N->getMask(M);
3748   return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3749 }
3750
3751 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3752 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3753 /// MOVSD, and MOVD, i.e. setting the lowest element.
3754 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3755   if (VT.getVectorElementType().getSizeInBits() < 32)
3756     return false;
3757
3758   int NumElts = VT.getVectorNumElements();
3759
3760   if (!isUndefOrEqual(Mask[0], NumElts))
3761     return false;
3762
3763   for (int i = 1; i < NumElts; ++i)
3764     if (!isUndefOrEqual(Mask[i], i))
3765       return false;
3766
3767   return true;
3768 }
3769
3770 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3771   SmallVector<int, 8> M;
3772   N->getMask(M);
3773   return ::isMOVLMask(M, N->getValueType(0));
3774 }
3775
3776 /// isVPERM2F128Mask - Match 256-bit shuffles where the elements are considered
3777 /// as permutations between 128-bit chunks or halves. As an example: this
3778 /// shuffle bellow:
3779 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3780 /// The first half comes from the second half of V1 and the second half from the
3781 /// the second half of V2.
3782 static bool isVPERM2F128Mask(const SmallVectorImpl<int> &Mask, EVT VT,
3783                              const X86Subtarget *Subtarget) {
3784   if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256)
3785     return false;
3786
3787   // The shuffle result is divided into half A and half B. In total the two
3788   // sources have 4 halves, namely: C, D, E, F. The final values of A and
3789   // B must come from C, D, E or F.
3790   int HalfSize = VT.getVectorNumElements()/2;
3791   bool MatchA = false, MatchB = false;
3792
3793   // Check if A comes from one of C, D, E, F.
3794   for (int Half = 0; Half < 4; ++Half) {
3795     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3796       MatchA = true;
3797       break;
3798     }
3799   }
3800
3801   // Check if B comes from one of C, D, E, F.
3802   for (int Half = 0; Half < 4; ++Half) {
3803     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3804       MatchB = true;
3805       break;
3806     }
3807   }
3808
3809   return MatchA && MatchB;
3810 }
3811
3812 /// getShuffleVPERM2F128Immediate - Return the appropriate immediate to shuffle
3813 /// the specified VECTOR_MASK mask with VPERM2F128 instructions.
3814 static unsigned getShuffleVPERM2F128Immediate(SDNode *N) {
3815   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3816   EVT VT = SVOp->getValueType(0);
3817
3818   int HalfSize = VT.getVectorNumElements()/2;
3819
3820   int FstHalf = 0, SndHalf = 0;
3821   for (int i = 0; i < HalfSize; ++i) {
3822     if (SVOp->getMaskElt(i) > 0) {
3823       FstHalf = SVOp->getMaskElt(i)/HalfSize;
3824       break;
3825     }
3826   }
3827   for (int i = HalfSize; i < HalfSize*2; ++i) {
3828     if (SVOp->getMaskElt(i) > 0) {
3829       SndHalf = SVOp->getMaskElt(i)/HalfSize;
3830       break;
3831     }
3832   }
3833
3834   return (FstHalf | (SndHalf << 4));
3835 }
3836
3837 /// isVPERMILPDMask - Return true if the specified VECTOR_SHUFFLE operand
3838 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3839 /// Note that VPERMIL mask matching is different depending whether theunderlying
3840 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3841 /// to the same elements of the low, but to the higher half of the source.
3842 /// In VPERMILPD the two lanes could be shuffled independently of each other
3843 /// with the same restriction that lanes can't be crossed.
3844 static bool isVPERMILPDMask(const SmallVectorImpl<int> &Mask, EVT VT,
3845                             const X86Subtarget *Subtarget) {
3846   int NumElts = VT.getVectorNumElements();
3847   int NumLanes = VT.getSizeInBits()/128;
3848
3849   if (!Subtarget->hasAVX())
3850     return false;
3851
3852   // Only match 256-bit with 64-bit types
3853   if (VT.getSizeInBits() != 256 || NumElts != 4)
3854     return false;
3855
3856   // The mask on the high lane is independent of the low. Both can match
3857   // any element in inside its own lane, but can't cross.
3858   int LaneSize = NumElts/NumLanes;
3859   for (int l = 0; l < NumLanes; ++l)
3860     for (int i = l*LaneSize; i < LaneSize*(l+1); ++i) {
3861       int LaneStart = l*LaneSize;
3862       if (!isUndefOrInRange(Mask[i], LaneStart, LaneStart+LaneSize))
3863         return false;
3864     }
3865
3866   return true;
3867 }
3868
3869 /// isVPERMILPSMask - Return true if the specified VECTOR_SHUFFLE operand
3870 /// specifies a shuffle of elements that is suitable for input to VPERMILPS*.
3871 /// Note that VPERMIL mask matching is different depending whether theunderlying
3872 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3873 /// to the same elements of the low, but to the higher half of the source.
3874 /// In VPERMILPD the two lanes could be shuffled independently of each other
3875 /// with the same restriction that lanes can't be crossed.
3876 static bool isVPERMILPSMask(const SmallVectorImpl<int> &Mask, EVT VT,
3877                             const X86Subtarget *Subtarget) {
3878   unsigned NumElts = VT.getVectorNumElements();
3879   unsigned NumLanes = VT.getSizeInBits()/128;
3880
3881   if (!Subtarget->hasAVX())
3882     return false;
3883
3884   // Only match 256-bit with 32-bit types
3885   if (VT.getSizeInBits() != 256 || NumElts != 8)
3886     return false;
3887
3888   // The mask on the high lane should be the same as the low. Actually,
3889   // they can differ if any of the corresponding index in a lane is undef
3890   // and the other stays in range.
3891   int LaneSize = NumElts/NumLanes;
3892   for (int i = 0; i < LaneSize; ++i) {
3893     int HighElt = i+LaneSize;
3894     bool HighValid = isUndefOrInRange(Mask[HighElt], LaneSize, NumElts);
3895     bool LowValid = isUndefOrInRange(Mask[i], 0, LaneSize);
3896
3897     if (!HighValid || !LowValid)
3898       return false;
3899     if (Mask[i] < 0 || Mask[HighElt] < 0)
3900       continue;
3901     if (Mask[HighElt]-Mask[i] != LaneSize)
3902       return false;
3903   }
3904
3905   return true;
3906 }
3907
3908 /// getShuffleVPERMILPSImmediate - Return the appropriate immediate to shuffle
3909 /// the specified VECTOR_MASK mask with VPERMILPS* instructions.
3910 static unsigned getShuffleVPERMILPSImmediate(SDNode *N) {
3911   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3912   EVT VT = SVOp->getValueType(0);
3913
3914   int NumElts = VT.getVectorNumElements();
3915   int NumLanes = VT.getSizeInBits()/128;
3916   int LaneSize = NumElts/NumLanes;
3917
3918   // Although the mask is equal for both lanes do it twice to get the cases
3919   // where a mask will match because the same mask element is undef on the
3920   // first half but valid on the second. This would get pathological cases
3921   // such as: shuffle <u, 0, 1, 2, 4, 4, 5, 6>, which is completely valid.
3922   unsigned Mask = 0;
3923   for (int l = 0; l < NumLanes; ++l) {
3924     for (int i = 0; i < LaneSize; ++i) {
3925       int MaskElt = SVOp->getMaskElt(i+(l*LaneSize));
3926       if (MaskElt < 0)
3927         continue;
3928       if (MaskElt >= LaneSize)
3929         MaskElt -= LaneSize;
3930       Mask |= MaskElt << (i*2);
3931     }
3932   }
3933
3934   return Mask;
3935 }
3936
3937 /// getShuffleVPERMILPDImmediate - Return the appropriate immediate to shuffle
3938 /// the specified VECTOR_MASK mask with VPERMILPD* instructions.
3939 static unsigned getShuffleVPERMILPDImmediate(SDNode *N) {
3940   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3941   EVT VT = SVOp->getValueType(0);
3942
3943   int NumElts = VT.getVectorNumElements();
3944   int NumLanes = VT.getSizeInBits()/128;
3945
3946   unsigned Mask = 0;
3947   int LaneSize = NumElts/NumLanes;
3948   for (int l = 0; l < NumLanes; ++l)
3949     for (int i = l*LaneSize; i < LaneSize*(l+1); ++i) {
3950       int MaskElt = SVOp->getMaskElt(i);
3951       if (MaskElt < 0)
3952         continue;
3953       Mask |= (MaskElt-l*LaneSize) << i;
3954     }
3955
3956   return Mask;
3957 }
3958
3959 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3960 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3961 /// element of vector 2 and the other elements to come from vector 1 in order.
3962 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3963                                bool V2IsSplat = false, bool V2IsUndef = false) {
3964   int NumOps = VT.getVectorNumElements();
3965   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3966     return false;
3967
3968   if (!isUndefOrEqual(Mask[0], 0))
3969     return false;
3970
3971   for (int i = 1; i < NumOps; ++i)
3972     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3973           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3974           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3975       return false;
3976
3977   return true;
3978 }
3979
3980 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3981                            bool V2IsUndef = false) {
3982   SmallVector<int, 8> M;
3983   N->getMask(M);
3984   return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3985 }
3986
3987 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3988 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3989 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3990 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N,
3991                          const X86Subtarget *Subtarget) {
3992   if (!Subtarget->hasSSE3orAVX())
3993     return false;
3994
3995   // The second vector must be undef
3996   if (N->getOperand(1).getOpcode() != ISD::UNDEF)
3997     return false;
3998
3999   EVT VT = N->getValueType(0);
4000   unsigned NumElems = VT.getVectorNumElements();
4001
4002   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
4003       (VT.getSizeInBits() == 256 && NumElems != 8))
4004     return false;
4005
4006   // "i+1" is the value the indexed mask element must have
4007   for (unsigned i = 0; i < NumElems; i += 2)
4008     if (!isUndefOrEqual(N->getMaskElt(i), i+1) ||
4009         !isUndefOrEqual(N->getMaskElt(i+1), i+1))
4010       return false;
4011
4012   return true;
4013 }
4014
4015 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4016 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4017 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4018 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N,
4019                          const X86Subtarget *Subtarget) {
4020   if (!Subtarget->hasSSE3orAVX())
4021     return false;
4022
4023   // The second vector must be undef
4024   if (N->getOperand(1).getOpcode() != ISD::UNDEF)
4025     return false;
4026
4027   EVT VT = N->getValueType(0);
4028   unsigned NumElems = VT.getVectorNumElements();
4029
4030   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
4031       (VT.getSizeInBits() == 256 && NumElems != 8))
4032     return false;
4033
4034   // "i" is the value the indexed mask element must have
4035   for (unsigned i = 0; i < NumElems; i += 2)
4036     if (!isUndefOrEqual(N->getMaskElt(i), i) ||
4037         !isUndefOrEqual(N->getMaskElt(i+1), i))
4038       return false;
4039
4040   return true;
4041 }
4042
4043 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4044 /// specifies a shuffle of elements that is suitable for input to 256-bit
4045 /// version of MOVDDUP.
4046 static bool isMOVDDUPYMask(ShuffleVectorSDNode *N,
4047                            const X86Subtarget *Subtarget) {
4048   EVT VT = N->getValueType(0);
4049   int NumElts = VT.getVectorNumElements();
4050   bool V2IsUndef = N->getOperand(1).getOpcode() == ISD::UNDEF;
4051
4052   if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256 ||
4053       !V2IsUndef || NumElts != 4)
4054     return false;
4055
4056   for (int i = 0; i != NumElts/2; ++i)
4057     if (!isUndefOrEqual(N->getMaskElt(i), 0))
4058       return false;
4059   for (int i = NumElts/2; i != NumElts; ++i)
4060     if (!isUndefOrEqual(N->getMaskElt(i), NumElts/2))
4061       return false;
4062   return true;
4063 }
4064
4065 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4066 /// specifies a shuffle of elements that is suitable for input to 128-bit
4067 /// version of MOVDDUP.
4068 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
4069   EVT VT = N->getValueType(0);
4070
4071   if (VT.getSizeInBits() != 128)
4072     return false;
4073
4074   int e = VT.getVectorNumElements() / 2;
4075   for (int i = 0; i < e; ++i)
4076     if (!isUndefOrEqual(N->getMaskElt(i), i))
4077       return false;
4078   for (int i = 0; i < e; ++i)
4079     if (!isUndefOrEqual(N->getMaskElt(e+i), i))
4080       return false;
4081   return true;
4082 }
4083
4084 /// isVEXTRACTF128Index - Return true if the specified
4085 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4086 /// suitable for input to VEXTRACTF128.
4087 bool X86::isVEXTRACTF128Index(SDNode *N) {
4088   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4089     return false;
4090
4091   // The index should be aligned on a 128-bit boundary.
4092   uint64_t Index =
4093     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4094
4095   unsigned VL = N->getValueType(0).getVectorNumElements();
4096   unsigned VBits = N->getValueType(0).getSizeInBits();
4097   unsigned ElSize = VBits / VL;
4098   bool Result = (Index * ElSize) % 128 == 0;
4099
4100   return Result;
4101 }
4102
4103 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
4104 /// operand specifies a subvector insert that is suitable for input to
4105 /// VINSERTF128.
4106 bool X86::isVINSERTF128Index(SDNode *N) {
4107   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4108     return false;
4109
4110   // The index should be aligned on a 128-bit boundary.
4111   uint64_t Index =
4112     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4113
4114   unsigned VL = N->getValueType(0).getVectorNumElements();
4115   unsigned VBits = N->getValueType(0).getSizeInBits();
4116   unsigned ElSize = VBits / VL;
4117   bool Result = (Index * ElSize) % 128 == 0;
4118
4119   return Result;
4120 }
4121
4122 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4123 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4124 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
4125   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4126   int NumOperands = SVOp->getValueType(0).getVectorNumElements();
4127
4128   unsigned Shift = (NumOperands == 4) ? 2 : 1;
4129   unsigned Mask = 0;
4130   for (int i = 0; i < NumOperands; ++i) {
4131     int Val = SVOp->getMaskElt(NumOperands-i-1);
4132     if (Val < 0) Val = 0;
4133     if (Val >= NumOperands) Val -= NumOperands;
4134     Mask |= Val;
4135     if (i != NumOperands - 1)
4136       Mask <<= Shift;
4137   }
4138   return Mask;
4139 }
4140
4141 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4142 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4143 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
4144   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4145   unsigned Mask = 0;
4146   // 8 nodes, but we only care about the last 4.
4147   for (unsigned i = 7; i >= 4; --i) {
4148     int Val = SVOp->getMaskElt(i);
4149     if (Val >= 0)
4150       Mask |= (Val - 4);
4151     if (i != 4)
4152       Mask <<= 2;
4153   }
4154   return Mask;
4155 }
4156
4157 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4158 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4159 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
4160   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4161   unsigned Mask = 0;
4162   // 8 nodes, but we only care about the first 4.
4163   for (int i = 3; i >= 0; --i) {
4164     int Val = SVOp->getMaskElt(i);
4165     if (Val >= 0)
4166       Mask |= Val;
4167     if (i != 0)
4168       Mask <<= 2;
4169   }
4170   return Mask;
4171 }
4172
4173 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4174 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4175 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
4176   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4177   EVT VVT = N->getValueType(0);
4178   unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
4179   int Val = 0;
4180
4181   unsigned i, e;
4182   for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
4183     Val = SVOp->getMaskElt(i);
4184     if (Val >= 0)
4185       break;
4186   }
4187   assert(Val - i > 0 && "PALIGNR imm should be positive");
4188   return (Val - i) * EltSize;
4189 }
4190
4191 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4192 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4193 /// instructions.
4194 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4195   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4196     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4197
4198   uint64_t Index =
4199     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4200
4201   EVT VecVT = N->getOperand(0).getValueType();
4202   EVT ElVT = VecVT.getVectorElementType();
4203
4204   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4205   return Index / NumElemsPerChunk;
4206 }
4207
4208 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4209 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4210 /// instructions.
4211 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4212   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4213     llvm_unreachable("Illegal insert subvector for VINSERTF128");
4214
4215   uint64_t Index =
4216     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4217
4218   EVT VecVT = N->getValueType(0);
4219   EVT ElVT = VecVT.getVectorElementType();
4220
4221   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4222   return Index / NumElemsPerChunk;
4223 }
4224
4225 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4226 /// constant +0.0.
4227 bool X86::isZeroNode(SDValue Elt) {
4228   return ((isa<ConstantSDNode>(Elt) &&
4229            cast<ConstantSDNode>(Elt)->isNullValue()) ||
4230           (isa<ConstantFPSDNode>(Elt) &&
4231            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4232 }
4233
4234 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4235 /// their permute mask.
4236 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4237                                     SelectionDAG &DAG) {
4238   EVT VT = SVOp->getValueType(0);
4239   unsigned NumElems = VT.getVectorNumElements();
4240   SmallVector<int, 8> MaskVec;
4241
4242   for (unsigned i = 0; i != NumElems; ++i) {
4243     int idx = SVOp->getMaskElt(i);
4244     if (idx < 0)
4245       MaskVec.push_back(idx);
4246     else if (idx < (int)NumElems)
4247       MaskVec.push_back(idx + NumElems);
4248     else
4249       MaskVec.push_back(idx - NumElems);
4250   }
4251   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4252                               SVOp->getOperand(0), &MaskVec[0]);
4253 }
4254
4255 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4256 /// match movhlps. The lower half elements should come from upper half of
4257 /// V1 (and in order), and the upper half elements should come from the upper
4258 /// half of V2 (and in order).
4259 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
4260   EVT VT = Op->getValueType(0);
4261   if (VT.getSizeInBits() != 128)
4262     return false;
4263   if (VT.getVectorNumElements() != 4)
4264     return false;
4265   for (unsigned i = 0, e = 2; i != e; ++i)
4266     if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
4267       return false;
4268   for (unsigned i = 2; i != 4; ++i)
4269     if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
4270       return false;
4271   return true;
4272 }
4273
4274 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4275 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4276 /// required.
4277 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4278   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4279     return false;
4280   N = N->getOperand(0).getNode();
4281   if (!ISD::isNON_EXTLoad(N))
4282     return false;
4283   if (LD)
4284     *LD = cast<LoadSDNode>(N);
4285   return true;
4286 }
4287
4288 // Test whether the given value is a vector value which will be legalized
4289 // into a load.
4290 static bool WillBeConstantPoolLoad(SDNode *N) {
4291   if (N->getOpcode() != ISD::BUILD_VECTOR)
4292     return false;
4293
4294   // Check for any non-constant elements.
4295   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4296     switch (N->getOperand(i).getNode()->getOpcode()) {
4297     case ISD::UNDEF:
4298     case ISD::ConstantFP:
4299     case ISD::Constant:
4300       break;
4301     default:
4302       return false;
4303     }
4304
4305   // Vectors of all-zeros and all-ones are materialized with special
4306   // instructions rather than being loaded.
4307   return !ISD::isBuildVectorAllZeros(N) &&
4308          !ISD::isBuildVectorAllOnes(N);
4309 }
4310
4311 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4312 /// match movlp{s|d}. The lower half elements should come from lower half of
4313 /// V1 (and in order), and the upper half elements should come from the upper
4314 /// half of V2 (and in order). And since V1 will become the source of the
4315 /// MOVLP, it must be either a vector load or a scalar load to vector.
4316 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4317                                ShuffleVectorSDNode *Op) {
4318   EVT VT = Op->getValueType(0);
4319   if (VT.getSizeInBits() != 128)
4320     return false;
4321
4322   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4323     return false;
4324   // Is V2 is a vector load, don't do this transformation. We will try to use
4325   // load folding shufps op.
4326   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4327     return false;
4328
4329   unsigned NumElems = VT.getVectorNumElements();
4330
4331   if (NumElems != 2 && NumElems != 4)
4332     return false;
4333   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4334     if (!isUndefOrEqual(Op->getMaskElt(i), i))
4335       return false;
4336   for (unsigned i = NumElems/2; i != NumElems; ++i)
4337     if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
4338       return false;
4339   return true;
4340 }
4341
4342 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4343 /// all the same.
4344 static bool isSplatVector(SDNode *N) {
4345   if (N->getOpcode() != ISD::BUILD_VECTOR)
4346     return false;
4347
4348   SDValue SplatValue = N->getOperand(0);
4349   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4350     if (N->getOperand(i) != SplatValue)
4351       return false;
4352   return true;
4353 }
4354
4355 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4356 /// to an zero vector.
4357 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4358 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4359   SDValue V1 = N->getOperand(0);
4360   SDValue V2 = N->getOperand(1);
4361   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4362   for (unsigned i = 0; i != NumElems; ++i) {
4363     int Idx = N->getMaskElt(i);
4364     if (Idx >= (int)NumElems) {
4365       unsigned Opc = V2.getOpcode();
4366       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4367         continue;
4368       if (Opc != ISD::BUILD_VECTOR ||
4369           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4370         return false;
4371     } else if (Idx >= 0) {
4372       unsigned Opc = V1.getOpcode();
4373       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4374         continue;
4375       if (Opc != ISD::BUILD_VECTOR ||
4376           !X86::isZeroNode(V1.getOperand(Idx)))
4377         return false;
4378     }
4379   }
4380   return true;
4381 }
4382
4383 /// getZeroVector - Returns a vector of specified type with all zero elements.
4384 ///
4385 static SDValue getZeroVector(EVT VT, bool HasXMMInt, SelectionDAG &DAG,
4386                              DebugLoc dl) {
4387   assert(VT.isVector() && "Expected a vector type");
4388
4389   // Always build SSE zero vectors as <4 x i32> bitcasted
4390   // to their dest type. This ensures they get CSE'd.
4391   SDValue Vec;
4392   if (VT.getSizeInBits() == 128) {  // SSE
4393     if (HasXMMInt) {  // SSE2
4394       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4395       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4396     } else { // SSE1
4397       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4398       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4399     }
4400   } else if (VT.getSizeInBits() == 256) { // AVX
4401     // 256-bit logic and arithmetic instructions in AVX are
4402     // all floating-point, no support for integer ops. Default
4403     // to emitting fp zeroed vectors then.
4404     SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4405     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4406     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4407   }
4408   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4409 }
4410
4411 /// getOnesVector - Returns a vector of specified type with all bits set.
4412 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4413 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4414 /// Then bitcast to their original type, ensuring they get CSE'd.
4415 static SDValue getOnesVector(EVT VT, bool HasAVX2, SelectionDAG &DAG,
4416                              DebugLoc dl) {
4417   assert(VT.isVector() && "Expected a vector type");
4418   assert((VT.is128BitVector() || VT.is256BitVector())
4419          && "Expected a 128-bit or 256-bit vector type");
4420
4421   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4422   SDValue Vec;
4423   if (VT.getSizeInBits() == 256) {
4424     if (HasAVX2) { // AVX2
4425       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4426       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4427     } else { // AVX
4428       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4429       SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, MVT::v8i32),
4430                                 Vec, DAG.getConstant(0, MVT::i32), DAG, dl);
4431       Vec = Insert128BitVector(InsV, Vec,
4432                     DAG.getConstant(4 /* NumElems/2 */, MVT::i32), DAG, dl);
4433     }
4434   } else {
4435     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4436   }
4437
4438   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4439 }
4440
4441 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4442 /// that point to V2 points to its first element.
4443 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4444   EVT VT = SVOp->getValueType(0);
4445   unsigned NumElems = VT.getVectorNumElements();
4446
4447   bool Changed = false;
4448   SmallVector<int, 8> MaskVec;
4449   SVOp->getMask(MaskVec);
4450
4451   for (unsigned i = 0; i != NumElems; ++i) {
4452     if (MaskVec[i] > (int)NumElems) {
4453       MaskVec[i] = NumElems;
4454       Changed = true;
4455     }
4456   }
4457   if (Changed)
4458     return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
4459                                 SVOp->getOperand(1), &MaskVec[0]);
4460   return SDValue(SVOp, 0);
4461 }
4462
4463 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4464 /// operation of specified width.
4465 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4466                        SDValue V2) {
4467   unsigned NumElems = VT.getVectorNumElements();
4468   SmallVector<int, 8> Mask;
4469   Mask.push_back(NumElems);
4470   for (unsigned i = 1; i != NumElems; ++i)
4471     Mask.push_back(i);
4472   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4473 }
4474
4475 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4476 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4477                           SDValue V2) {
4478   unsigned NumElems = VT.getVectorNumElements();
4479   SmallVector<int, 8> Mask;
4480   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4481     Mask.push_back(i);
4482     Mask.push_back(i + NumElems);
4483   }
4484   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4485 }
4486
4487 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4488 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4489                           SDValue V2) {
4490   unsigned NumElems = VT.getVectorNumElements();
4491   unsigned Half = NumElems/2;
4492   SmallVector<int, 8> Mask;
4493   for (unsigned i = 0; i != Half; ++i) {
4494     Mask.push_back(i + Half);
4495     Mask.push_back(i + NumElems + Half);
4496   }
4497   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4498 }
4499
4500 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4501 // a generic shuffle instruction because the target has no such instructions.
4502 // Generate shuffles which repeat i16 and i8 several times until they can be
4503 // represented by v4f32 and then be manipulated by target suported shuffles.
4504 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4505   EVT VT = V.getValueType();
4506   int NumElems = VT.getVectorNumElements();
4507   DebugLoc dl = V.getDebugLoc();
4508
4509   while (NumElems > 4) {
4510     if (EltNo < NumElems/2) {
4511       V = getUnpackl(DAG, dl, VT, V, V);
4512     } else {
4513       V = getUnpackh(DAG, dl, VT, V, V);
4514       EltNo -= NumElems/2;
4515     }
4516     NumElems >>= 1;
4517   }
4518   return V;
4519 }
4520
4521 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4522 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4523   EVT VT = V.getValueType();
4524   DebugLoc dl = V.getDebugLoc();
4525   assert((VT.getSizeInBits() == 128 || VT.getSizeInBits() == 256)
4526          && "Vector size not supported");
4527
4528   if (VT.getSizeInBits() == 128) {
4529     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4530     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4531     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4532                              &SplatMask[0]);
4533   } else {
4534     // To use VPERMILPS to splat scalars, the second half of indicies must
4535     // refer to the higher part, which is a duplication of the lower one,
4536     // because VPERMILPS can only handle in-lane permutations.
4537     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4538                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4539
4540     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4541     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4542                              &SplatMask[0]);
4543   }
4544
4545   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4546 }
4547
4548 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4549 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4550   EVT SrcVT = SV->getValueType(0);
4551   SDValue V1 = SV->getOperand(0);
4552   DebugLoc dl = SV->getDebugLoc();
4553
4554   int EltNo = SV->getSplatIndex();
4555   int NumElems = SrcVT.getVectorNumElements();
4556   unsigned Size = SrcVT.getSizeInBits();
4557
4558   assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4559           "Unknown how to promote splat for type");
4560
4561   // Extract the 128-bit part containing the splat element and update
4562   // the splat element index when it refers to the higher register.
4563   if (Size == 256) {
4564     unsigned Idx = (EltNo > NumElems/2) ? NumElems/2 : 0;
4565     V1 = Extract128BitVector(V1, DAG.getConstant(Idx, MVT::i32), DAG, dl);
4566     if (Idx > 0)
4567       EltNo -= NumElems/2;
4568   }
4569
4570   // All i16 and i8 vector types can't be used directly by a generic shuffle
4571   // instruction because the target has no such instruction. Generate shuffles
4572   // which repeat i16 and i8 several times until they fit in i32, and then can
4573   // be manipulated by target suported shuffles.
4574   EVT EltVT = SrcVT.getVectorElementType();
4575   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4576     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4577
4578   // Recreate the 256-bit vector and place the same 128-bit vector
4579   // into the low and high part. This is necessary because we want
4580   // to use VPERM* to shuffle the vectors
4581   if (Size == 256) {
4582     SDValue InsV = Insert128BitVector(DAG.getUNDEF(SrcVT), V1,
4583                          DAG.getConstant(0, MVT::i32), DAG, dl);
4584     V1 = Insert128BitVector(InsV, V1,
4585                DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
4586   }
4587
4588   return getLegalSplat(DAG, V1, EltNo);
4589 }
4590
4591 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4592 /// vector of zero or undef vector.  This produces a shuffle where the low
4593 /// element of V2 is swizzled into the zero/undef vector, landing at element
4594 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4595 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4596                                            bool isZero, bool HasXMMInt,
4597                                            SelectionDAG &DAG) {
4598   EVT VT = V2.getValueType();
4599   SDValue V1 = isZero
4600     ? getZeroVector(VT, HasXMMInt, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4601   unsigned NumElems = VT.getVectorNumElements();
4602   SmallVector<int, 16> MaskVec;
4603   for (unsigned i = 0; i != NumElems; ++i)
4604     // If this is the insertion idx, put the low elt of V2 here.
4605     MaskVec.push_back(i == Idx ? NumElems : i);
4606   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4607 }
4608
4609 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4610 /// element of the result of the vector shuffle.
4611 static SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
4612                                    unsigned Depth) {
4613   if (Depth == 6)
4614     return SDValue();  // Limit search depth.
4615
4616   SDValue V = SDValue(N, 0);
4617   EVT VT = V.getValueType();
4618   unsigned Opcode = V.getOpcode();
4619
4620   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4621   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4622     Index = SV->getMaskElt(Index);
4623
4624     if (Index < 0)
4625       return DAG.getUNDEF(VT.getVectorElementType());
4626
4627     int NumElems = VT.getVectorNumElements();
4628     SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
4629     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
4630   }
4631
4632   // Recurse into target specific vector shuffles to find scalars.
4633   if (isTargetShuffle(Opcode)) {
4634     int NumElems = VT.getVectorNumElements();
4635     SmallVector<unsigned, 16> ShuffleMask;
4636     SDValue ImmN;
4637
4638     switch(Opcode) {
4639     case X86ISD::SHUFPS:
4640     case X86ISD::SHUFPD:
4641       ImmN = N->getOperand(N->getNumOperands()-1);
4642       DecodeSHUFPSMask(NumElems,
4643                        cast<ConstantSDNode>(ImmN)->getZExtValue(),
4644                        ShuffleMask);
4645       break;
4646     case X86ISD::PUNPCKHBW:
4647     case X86ISD::PUNPCKHWD:
4648     case X86ISD::PUNPCKHDQ:
4649     case X86ISD::PUNPCKHQDQ:
4650       DecodePUNPCKHMask(NumElems, ShuffleMask);
4651       break;
4652     case X86ISD::UNPCKHPS:
4653     case X86ISD::UNPCKHPD:
4654     case X86ISD::VUNPCKHPSY:
4655     case X86ISD::VUNPCKHPDY:
4656       DecodeUNPCKHPMask(VT, ShuffleMask);
4657       break;
4658     case X86ISD::PUNPCKLBW:
4659     case X86ISD::PUNPCKLWD:
4660     case X86ISD::PUNPCKLDQ:
4661     case X86ISD::PUNPCKLQDQ:
4662       DecodePUNPCKLMask(VT, ShuffleMask);
4663       break;
4664     case X86ISD::UNPCKLPS:
4665     case X86ISD::UNPCKLPD:
4666     case X86ISD::VUNPCKLPSY:
4667     case X86ISD::VUNPCKLPDY:
4668       DecodeUNPCKLPMask(VT, ShuffleMask);
4669       break;
4670     case X86ISD::MOVHLPS:
4671       DecodeMOVHLPSMask(NumElems, ShuffleMask);
4672       break;
4673     case X86ISD::MOVLHPS:
4674       DecodeMOVLHPSMask(NumElems, ShuffleMask);
4675       break;
4676     case X86ISD::PSHUFD:
4677       ImmN = N->getOperand(N->getNumOperands()-1);
4678       DecodePSHUFMask(NumElems,
4679                       cast<ConstantSDNode>(ImmN)->getZExtValue(),
4680                       ShuffleMask);
4681       break;
4682     case X86ISD::PSHUFHW:
4683       ImmN = N->getOperand(N->getNumOperands()-1);
4684       DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4685                         ShuffleMask);
4686       break;
4687     case X86ISD::PSHUFLW:
4688       ImmN = N->getOperand(N->getNumOperands()-1);
4689       DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4690                         ShuffleMask);
4691       break;
4692     case X86ISD::MOVSS:
4693     case X86ISD::MOVSD: {
4694       // The index 0 always comes from the first element of the second source,
4695       // this is why MOVSS and MOVSD are used in the first place. The other
4696       // elements come from the other positions of the first source vector.
4697       unsigned OpNum = (Index == 0) ? 1 : 0;
4698       return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
4699                                  Depth+1);
4700     }
4701     case X86ISD::VPERMILPS:
4702       ImmN = N->getOperand(N->getNumOperands()-1);
4703       DecodeVPERMILPSMask(4, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4704                         ShuffleMask);
4705       break;
4706     case X86ISD::VPERMILPSY:
4707       ImmN = N->getOperand(N->getNumOperands()-1);
4708       DecodeVPERMILPSMask(8, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4709                         ShuffleMask);
4710       break;
4711     case X86ISD::VPERMILPD:
4712       ImmN = N->getOperand(N->getNumOperands()-1);
4713       DecodeVPERMILPDMask(2, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4714                         ShuffleMask);
4715       break;
4716     case X86ISD::VPERMILPDY:
4717       ImmN = N->getOperand(N->getNumOperands()-1);
4718       DecodeVPERMILPDMask(4, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4719                         ShuffleMask);
4720       break;
4721     case X86ISD::VPERM2F128:
4722       ImmN = N->getOperand(N->getNumOperands()-1);
4723       DecodeVPERM2F128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4724                            ShuffleMask);
4725       break;
4726     case X86ISD::MOVDDUP:
4727     case X86ISD::MOVLHPD:
4728     case X86ISD::MOVLPD:
4729     case X86ISD::MOVLPS:
4730     case X86ISD::MOVSHDUP:
4731     case X86ISD::MOVSLDUP:
4732     case X86ISD::PALIGN:
4733       return SDValue(); // Not yet implemented.
4734     default:
4735       assert(0 && "unknown target shuffle node");
4736       return SDValue();
4737     }
4738
4739     Index = ShuffleMask[Index];
4740     if (Index < 0)
4741       return DAG.getUNDEF(VT.getVectorElementType());
4742
4743     SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
4744     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
4745                                Depth+1);
4746   }
4747
4748   // Actual nodes that may contain scalar elements
4749   if (Opcode == ISD::BITCAST) {
4750     V = V.getOperand(0);
4751     EVT SrcVT = V.getValueType();
4752     unsigned NumElems = VT.getVectorNumElements();
4753
4754     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4755       return SDValue();
4756   }
4757
4758   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4759     return (Index == 0) ? V.getOperand(0)
4760                           : DAG.getUNDEF(VT.getVectorElementType());
4761
4762   if (V.getOpcode() == ISD::BUILD_VECTOR)
4763     return V.getOperand(Index);
4764
4765   return SDValue();
4766 }
4767
4768 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4769 /// shuffle operation which come from a consecutively from a zero. The
4770 /// search can start in two different directions, from left or right.
4771 static
4772 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
4773                                   bool ZerosFromLeft, SelectionDAG &DAG) {
4774   int i = 0;
4775
4776   while (i < NumElems) {
4777     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4778     SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
4779     if (!(Elt.getNode() &&
4780          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4781       break;
4782     ++i;
4783   }
4784
4785   return i;
4786 }
4787
4788 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
4789 /// MaskE correspond consecutively to elements from one of the vector operands,
4790 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4791 static
4792 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
4793                               int OpIdx, int NumElems, unsigned &OpNum) {
4794   bool SeenV1 = false;
4795   bool SeenV2 = false;
4796
4797   for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
4798     int Idx = SVOp->getMaskElt(i);
4799     // Ignore undef indicies
4800     if (Idx < 0)
4801       continue;
4802
4803     if (Idx < NumElems)
4804       SeenV1 = true;
4805     else
4806       SeenV2 = true;
4807
4808     // Only accept consecutive elements from the same vector
4809     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4810       return false;
4811   }
4812
4813   OpNum = SeenV1 ? 0 : 1;
4814   return true;
4815 }
4816
4817 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4818 /// logical left shift of a vector.
4819 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4820                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4821   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4822   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4823               false /* check zeros from right */, DAG);
4824   unsigned OpSrc;
4825
4826   if (!NumZeros)
4827     return false;
4828
4829   // Considering the elements in the mask that are not consecutive zeros,
4830   // check if they consecutively come from only one of the source vectors.
4831   //
4832   //               V1 = {X, A, B, C}     0
4833   //                         \  \  \    /
4834   //   vector_shuffle V1, V2 <1, 2, 3, X>
4835   //
4836   if (!isShuffleMaskConsecutive(SVOp,
4837             0,                   // Mask Start Index
4838             NumElems-NumZeros-1, // Mask End Index
4839             NumZeros,            // Where to start looking in the src vector
4840             NumElems,            // Number of elements in vector
4841             OpSrc))              // Which source operand ?
4842     return false;
4843
4844   isLeft = false;
4845   ShAmt = NumZeros;
4846   ShVal = SVOp->getOperand(OpSrc);
4847   return true;
4848 }
4849
4850 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4851 /// logical left shift of a vector.
4852 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4853                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4854   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4855   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4856               true /* check zeros from left */, DAG);
4857   unsigned OpSrc;
4858
4859   if (!NumZeros)
4860     return false;
4861
4862   // Considering the elements in the mask that are not consecutive zeros,
4863   // check if they consecutively come from only one of the source vectors.
4864   //
4865   //                           0    { A, B, X, X } = V2
4866   //                          / \    /  /
4867   //   vector_shuffle V1, V2 <X, X, 4, 5>
4868   //
4869   if (!isShuffleMaskConsecutive(SVOp,
4870             NumZeros,     // Mask Start Index
4871             NumElems-1,   // Mask End Index
4872             0,            // Where to start looking in the src vector
4873             NumElems,     // Number of elements in vector
4874             OpSrc))       // Which source operand ?
4875     return false;
4876
4877   isLeft = true;
4878   ShAmt = NumZeros;
4879   ShVal = SVOp->getOperand(OpSrc);
4880   return true;
4881 }
4882
4883 /// isVectorShift - Returns true if the shuffle can be implemented as a
4884 /// logical left or right shift of a vector.
4885 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4886                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4887   // Although the logic below support any bitwidth size, there are no
4888   // shift instructions which handle more than 128-bit vectors.
4889   if (SVOp->getValueType(0).getSizeInBits() > 128)
4890     return false;
4891
4892   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4893       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4894     return true;
4895
4896   return false;
4897 }
4898
4899 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4900 ///
4901 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4902                                        unsigned NumNonZero, unsigned NumZero,
4903                                        SelectionDAG &DAG,
4904                                        const TargetLowering &TLI) {
4905   if (NumNonZero > 8)
4906     return SDValue();
4907
4908   DebugLoc dl = Op.getDebugLoc();
4909   SDValue V(0, 0);
4910   bool First = true;
4911   for (unsigned i = 0; i < 16; ++i) {
4912     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4913     if (ThisIsNonZero && First) {
4914       if (NumZero)
4915         V = getZeroVector(MVT::v8i16, true, DAG, dl);
4916       else
4917         V = DAG.getUNDEF(MVT::v8i16);
4918       First = false;
4919     }
4920
4921     if ((i & 1) != 0) {
4922       SDValue ThisElt(0, 0), LastElt(0, 0);
4923       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4924       if (LastIsNonZero) {
4925         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4926                               MVT::i16, Op.getOperand(i-1));
4927       }
4928       if (ThisIsNonZero) {
4929         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4930         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4931                               ThisElt, DAG.getConstant(8, MVT::i8));
4932         if (LastIsNonZero)
4933           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4934       } else
4935         ThisElt = LastElt;
4936
4937       if (ThisElt.getNode())
4938         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4939                         DAG.getIntPtrConstant(i/2));
4940     }
4941   }
4942
4943   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4944 }
4945
4946 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4947 ///
4948 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4949                                      unsigned NumNonZero, unsigned NumZero,
4950                                      SelectionDAG &DAG,
4951                                      const TargetLowering &TLI) {
4952   if (NumNonZero > 4)
4953     return SDValue();
4954
4955   DebugLoc dl = Op.getDebugLoc();
4956   SDValue V(0, 0);
4957   bool First = true;
4958   for (unsigned i = 0; i < 8; ++i) {
4959     bool isNonZero = (NonZeros & (1 << i)) != 0;
4960     if (isNonZero) {
4961       if (First) {
4962         if (NumZero)
4963           V = getZeroVector(MVT::v8i16, true, DAG, dl);
4964         else
4965           V = DAG.getUNDEF(MVT::v8i16);
4966         First = false;
4967       }
4968       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4969                       MVT::v8i16, V, Op.getOperand(i),
4970                       DAG.getIntPtrConstant(i));
4971     }
4972   }
4973
4974   return V;
4975 }
4976
4977 /// getVShift - Return a vector logical shift node.
4978 ///
4979 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4980                          unsigned NumBits, SelectionDAG &DAG,
4981                          const TargetLowering &TLI, DebugLoc dl) {
4982   assert(VT.getSizeInBits() == 128 && "Unknown type for VShift");
4983   EVT ShVT = MVT::v2i64;
4984   unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
4985   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4986   return DAG.getNode(ISD::BITCAST, dl, VT,
4987                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4988                              DAG.getConstant(NumBits,
4989                                   TLI.getShiftAmountTy(SrcOp.getValueType()))));
4990 }
4991
4992 SDValue
4993 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4994                                           SelectionDAG &DAG) const {
4995
4996   // Check if the scalar load can be widened into a vector load. And if
4997   // the address is "base + cst" see if the cst can be "absorbed" into
4998   // the shuffle mask.
4999   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5000     SDValue Ptr = LD->getBasePtr();
5001     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5002       return SDValue();
5003     EVT PVT = LD->getValueType(0);
5004     if (PVT != MVT::i32 && PVT != MVT::f32)
5005       return SDValue();
5006
5007     int FI = -1;
5008     int64_t Offset = 0;
5009     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5010       FI = FINode->getIndex();
5011       Offset = 0;
5012     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5013                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5014       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5015       Offset = Ptr.getConstantOperandVal(1);
5016       Ptr = Ptr.getOperand(0);
5017     } else {
5018       return SDValue();
5019     }
5020
5021     // FIXME: 256-bit vector instructions don't require a strict alignment,
5022     // improve this code to support it better.
5023     unsigned RequiredAlign = VT.getSizeInBits()/8;
5024     SDValue Chain = LD->getChain();
5025     // Make sure the stack object alignment is at least 16 or 32.
5026     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5027     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5028       if (MFI->isFixedObjectIndex(FI)) {
5029         // Can't change the alignment. FIXME: It's possible to compute
5030         // the exact stack offset and reference FI + adjust offset instead.
5031         // If someone *really* cares about this. That's the way to implement it.
5032         return SDValue();
5033       } else {
5034         MFI->setObjectAlignment(FI, RequiredAlign);
5035       }
5036     }
5037
5038     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5039     // Ptr + (Offset & ~15).
5040     if (Offset < 0)
5041       return SDValue();
5042     if ((Offset % RequiredAlign) & 3)
5043       return SDValue();
5044     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5045     if (StartOffset)
5046       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
5047                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5048
5049     int EltNo = (Offset - StartOffset) >> 2;
5050     int NumElems = VT.getVectorNumElements();
5051
5052     EVT CanonVT = VT.getSizeInBits() == 128 ? MVT::v4i32 : MVT::v8i32;
5053     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5054     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5055                              LD->getPointerInfo().getWithOffset(StartOffset),
5056                              false, false, false, 0);
5057
5058     // Canonicalize it to a v4i32 or v8i32 shuffle.
5059     SmallVector<int, 8> Mask;
5060     for (int i = 0; i < NumElems; ++i)
5061       Mask.push_back(EltNo);
5062
5063     V1 = DAG.getNode(ISD::BITCAST, dl, CanonVT, V1);
5064     return DAG.getNode(ISD::BITCAST, dl, NVT,
5065                        DAG.getVectorShuffle(CanonVT, dl, V1,
5066                                             DAG.getUNDEF(CanonVT),&Mask[0]));
5067   }
5068
5069   return SDValue();
5070 }
5071
5072 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5073 /// vector of type 'VT', see if the elements can be replaced by a single large
5074 /// load which has the same value as a build_vector whose operands are 'elts'.
5075 ///
5076 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5077 ///
5078 /// FIXME: we'd also like to handle the case where the last elements are zero
5079 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5080 /// There's even a handy isZeroNode for that purpose.
5081 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5082                                         DebugLoc &DL, SelectionDAG &DAG) {
5083   EVT EltVT = VT.getVectorElementType();
5084   unsigned NumElems = Elts.size();
5085
5086   LoadSDNode *LDBase = NULL;
5087   unsigned LastLoadedElt = -1U;
5088
5089   // For each element in the initializer, see if we've found a load or an undef.
5090   // If we don't find an initial load element, or later load elements are
5091   // non-consecutive, bail out.
5092   for (unsigned i = 0; i < NumElems; ++i) {
5093     SDValue Elt = Elts[i];
5094
5095     if (!Elt.getNode() ||
5096         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5097       return SDValue();
5098     if (!LDBase) {
5099       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5100         return SDValue();
5101       LDBase = cast<LoadSDNode>(Elt.getNode());
5102       LastLoadedElt = i;
5103       continue;
5104     }
5105     if (Elt.getOpcode() == ISD::UNDEF)
5106       continue;
5107
5108     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5109     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5110       return SDValue();
5111     LastLoadedElt = i;
5112   }
5113
5114   // If we have found an entire vector of loads and undefs, then return a large
5115   // load of the entire vector width starting at the base pointer.  If we found
5116   // consecutive loads for the low half, generate a vzext_load node.
5117   if (LastLoadedElt == NumElems - 1) {
5118     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5119       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5120                          LDBase->getPointerInfo(),
5121                          LDBase->isVolatile(), LDBase->isNonTemporal(),
5122                          LDBase->isInvariant(), 0);
5123     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5124                        LDBase->getPointerInfo(),
5125                        LDBase->isVolatile(), LDBase->isNonTemporal(),
5126                        LDBase->isInvariant(), LDBase->getAlignment());
5127   } else if (NumElems == 4 && LastLoadedElt == 1 &&
5128              DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5129     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5130     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5131     SDValue ResNode =
5132         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
5133                                 LDBase->getPointerInfo(),
5134                                 LDBase->getAlignment(),
5135                                 false/*isVolatile*/, true/*ReadMem*/,
5136                                 false/*WriteMem*/);
5137     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5138   }
5139   return SDValue();
5140 }
5141
5142 /// isVectorBroadcast - Check if the node chain is suitable to be xformed to
5143 /// a vbroadcast node. We support two patterns:
5144 /// 1. A splat BUILD_VECTOR which uses a single scalar load.
5145 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5146 /// a scalar load.
5147 /// The scalar load node is returned when a pattern is found,
5148 /// or SDValue() otherwise.
5149 static SDValue isVectorBroadcast(SDValue &Op, bool hasAVX2) {
5150   EVT VT = Op.getValueType();
5151   SDValue V = Op;
5152
5153   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5154     V = V.getOperand(0);
5155
5156   //A suspected load to be broadcasted.
5157   SDValue Ld;
5158
5159   switch (V.getOpcode()) {
5160     default:
5161       // Unknown pattern found.
5162       return SDValue();
5163
5164     case ISD::BUILD_VECTOR: {
5165       // The BUILD_VECTOR node must be a splat.
5166       if (!isSplatVector(V.getNode()))
5167         return SDValue();
5168
5169       Ld = V.getOperand(0);
5170
5171       // The suspected load node has several users. Make sure that all
5172       // of its users are from the BUILD_VECTOR node.
5173       if (!Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5174         return SDValue();
5175       break;
5176     }
5177
5178     case ISD::VECTOR_SHUFFLE: {
5179       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5180
5181       // Shuffles must have a splat mask where the first element is
5182       // broadcasted.
5183       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5184         return SDValue();
5185
5186       SDValue Sc = Op.getOperand(0);
5187       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR)
5188         return SDValue();
5189
5190       Ld = Sc.getOperand(0);
5191
5192       // The scalar_to_vector node and the suspected
5193       // load node must have exactly one user.
5194       if (!Sc.hasOneUse() || !Ld.hasOneUse())
5195         return SDValue();
5196       break;
5197     }
5198   }
5199
5200   // The scalar source must be a normal load.
5201   if (!ISD::isNormalLoad(Ld.getNode()))
5202     return SDValue();
5203
5204   bool Is256 = VT.getSizeInBits() == 256;
5205   bool Is128 = VT.getSizeInBits() == 128;
5206   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5207
5208   if (hasAVX2) {
5209     // VBroadcast to YMM
5210     if (Is256 && (ScalarSize == 8  || ScalarSize == 16 ||
5211                   ScalarSize == 32 || ScalarSize == 64 ))
5212       return Ld;
5213
5214     // VBroadcast to XMM
5215     if (Is128 && (ScalarSize ==  8 || ScalarSize == 32 ||
5216                   ScalarSize == 16 || ScalarSize == 64 ))
5217       return Ld;
5218   }
5219
5220   // VBroadcast to YMM
5221   if (Is256 && (ScalarSize == 32 || ScalarSize == 64))
5222     return Ld;
5223
5224   // VBroadcast to XMM
5225   if (Is128 && (ScalarSize == 32))
5226     return Ld;
5227
5228
5229   // Unsupported broadcast.
5230   return SDValue();
5231 }
5232
5233 SDValue
5234 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5235   DebugLoc dl = Op.getDebugLoc();
5236
5237   EVT VT = Op.getValueType();
5238   EVT ExtVT = VT.getVectorElementType();
5239   unsigned NumElems = Op.getNumOperands();
5240
5241   // Vectors containing all zeros can be matched by pxor and xorps later
5242   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5243     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5244     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5245     if (Op.getValueType() == MVT::v4i32 ||
5246         Op.getValueType() == MVT::v8i32)
5247       return Op;
5248
5249     return getZeroVector(Op.getValueType(), Subtarget->hasXMMInt(), DAG, dl);
5250   }
5251
5252   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5253   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5254   // vpcmpeqd on 256-bit vectors.
5255   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5256     if (Op.getValueType() == MVT::v4i32 ||
5257         (Op.getValueType() == MVT::v8i32 && Subtarget->hasAVX2()))
5258       return Op;
5259
5260     return getOnesVector(Op.getValueType(), Subtarget->hasAVX2(), DAG, dl);
5261   }
5262
5263   SDValue LD = isVectorBroadcast(Op, Subtarget->hasAVX2());
5264   if (Subtarget->hasAVX() && LD.getNode())
5265       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, LD);
5266
5267   unsigned EVTBits = ExtVT.getSizeInBits();
5268
5269   unsigned NumZero  = 0;
5270   unsigned NumNonZero = 0;
5271   unsigned NonZeros = 0;
5272   bool IsAllConstants = true;
5273   SmallSet<SDValue, 8> Values;
5274   for (unsigned i = 0; i < NumElems; ++i) {
5275     SDValue Elt = Op.getOperand(i);
5276     if (Elt.getOpcode() == ISD::UNDEF)
5277       continue;
5278     Values.insert(Elt);
5279     if (Elt.getOpcode() != ISD::Constant &&
5280         Elt.getOpcode() != ISD::ConstantFP)
5281       IsAllConstants = false;
5282     if (X86::isZeroNode(Elt))
5283       NumZero++;
5284     else {
5285       NonZeros |= (1 << i);
5286       NumNonZero++;
5287     }
5288   }
5289
5290   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5291   if (NumNonZero == 0)
5292     return DAG.getUNDEF(VT);
5293
5294   // Special case for single non-zero, non-undef, element.
5295   if (NumNonZero == 1) {
5296     unsigned Idx = CountTrailingZeros_32(NonZeros);
5297     SDValue Item = Op.getOperand(Idx);
5298
5299     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5300     // the value are obviously zero, truncate the value to i32 and do the
5301     // insertion that way.  Only do this if the value is non-constant or if the
5302     // value is a constant being inserted into element 0.  It is cheaper to do
5303     // a constant pool load than it is to do a movd + shuffle.
5304     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5305         (!IsAllConstants || Idx == 0)) {
5306       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5307         // Handle SSE only.
5308         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5309         EVT VecVT = MVT::v4i32;
5310         unsigned VecElts = 4;
5311
5312         // Truncate the value (which may itself be a constant) to i32, and
5313         // convert it to a vector with movd (S2V+shuffle to zero extend).
5314         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5315         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5316         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
5317                                            Subtarget->hasXMMInt(), DAG);
5318
5319         // Now we have our 32-bit value zero extended in the low element of
5320         // a vector.  If Idx != 0, swizzle it into place.
5321         if (Idx != 0) {
5322           SmallVector<int, 4> Mask;
5323           Mask.push_back(Idx);
5324           for (unsigned i = 1; i != VecElts; ++i)
5325             Mask.push_back(i);
5326           Item = DAG.getVectorShuffle(VecVT, dl, Item,
5327                                       DAG.getUNDEF(Item.getValueType()),
5328                                       &Mask[0]);
5329         }
5330         return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
5331       }
5332     }
5333
5334     // If we have a constant or non-constant insertion into the low element of
5335     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5336     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5337     // depending on what the source datatype is.
5338     if (Idx == 0) {
5339       if (NumZero == 0) {
5340         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5341       } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5342           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5343         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5344         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5345         return getShuffleVectorZeroOrUndef(Item, 0, true,Subtarget->hasXMMInt(),
5346                                            DAG);
5347       } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5348         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5349         assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
5350         EVT MiddleVT = MVT::v4i32;
5351         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
5352         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
5353                                            Subtarget->hasXMMInt(), DAG);
5354         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5355       }
5356     }
5357
5358     // Is it a vector logical left shift?
5359     if (NumElems == 2 && Idx == 1 &&
5360         X86::isZeroNode(Op.getOperand(0)) &&
5361         !X86::isZeroNode(Op.getOperand(1))) {
5362       unsigned NumBits = VT.getSizeInBits();
5363       return getVShift(true, VT,
5364                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5365                                    VT, Op.getOperand(1)),
5366                        NumBits/2, DAG, *this, dl);
5367     }
5368
5369     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5370       return SDValue();
5371
5372     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5373     // is a non-constant being inserted into an element other than the low one,
5374     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5375     // movd/movss) to move this into the low element, then shuffle it into
5376     // place.
5377     if (EVTBits == 32) {
5378       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5379
5380       // Turn it into a shuffle of zero and zero-extended scalar to vector.
5381       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
5382                                          Subtarget->hasXMMInt(), DAG);
5383       SmallVector<int, 8> MaskVec;
5384       for (unsigned i = 0; i < NumElems; i++)
5385         MaskVec.push_back(i == Idx ? 0 : 1);
5386       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5387     }
5388   }
5389
5390   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5391   if (Values.size() == 1) {
5392     if (EVTBits == 32) {
5393       // Instead of a shuffle like this:
5394       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5395       // Check if it's possible to issue this instead.
5396       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5397       unsigned Idx = CountTrailingZeros_32(NonZeros);
5398       SDValue Item = Op.getOperand(Idx);
5399       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5400         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5401     }
5402     return SDValue();
5403   }
5404
5405   // A vector full of immediates; various special cases are already
5406   // handled, so this is best done with a single constant-pool load.
5407   if (IsAllConstants)
5408     return SDValue();
5409
5410   // For AVX-length vectors, build the individual 128-bit pieces and use
5411   // shuffles to put them in place.
5412   if (VT.getSizeInBits() == 256 && !ISD::isBuildVectorAllZeros(Op.getNode())) {
5413     SmallVector<SDValue, 32> V;
5414     for (unsigned i = 0; i < NumElems; ++i)
5415       V.push_back(Op.getOperand(i));
5416
5417     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5418
5419     // Build both the lower and upper subvector.
5420     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5421     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5422                                 NumElems/2);
5423
5424     // Recreate the wider vector with the lower and upper part.
5425     SDValue Vec = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), Lower,
5426                                 DAG.getConstant(0, MVT::i32), DAG, dl);
5427     return Insert128BitVector(Vec, Upper, DAG.getConstant(NumElems/2, MVT::i32),
5428                               DAG, dl);
5429   }
5430
5431   // Let legalizer expand 2-wide build_vectors.
5432   if (EVTBits == 64) {
5433     if (NumNonZero == 1) {
5434       // One half is zero or undef.
5435       unsigned Idx = CountTrailingZeros_32(NonZeros);
5436       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5437                                  Op.getOperand(Idx));
5438       return getShuffleVectorZeroOrUndef(V2, Idx, true,
5439                                          Subtarget->hasXMMInt(), DAG);
5440     }
5441     return SDValue();
5442   }
5443
5444   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5445   if (EVTBits == 8 && NumElems == 16) {
5446     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5447                                         *this);
5448     if (V.getNode()) return V;
5449   }
5450
5451   if (EVTBits == 16 && NumElems == 8) {
5452     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5453                                       *this);
5454     if (V.getNode()) return V;
5455   }
5456
5457   // If element VT is == 32 bits, turn it into a number of shuffles.
5458   SmallVector<SDValue, 8> V;
5459   V.resize(NumElems);
5460   if (NumElems == 4 && NumZero > 0) {
5461     for (unsigned i = 0; i < 4; ++i) {
5462       bool isZero = !(NonZeros & (1 << i));
5463       if (isZero)
5464         V[i] = getZeroVector(VT, Subtarget->hasXMMInt(), DAG, dl);
5465       else
5466         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5467     }
5468
5469     for (unsigned i = 0; i < 2; ++i) {
5470       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5471         default: break;
5472         case 0:
5473           V[i] = V[i*2];  // Must be a zero vector.
5474           break;
5475         case 1:
5476           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5477           break;
5478         case 2:
5479           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5480           break;
5481         case 3:
5482           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5483           break;
5484       }
5485     }
5486
5487     SmallVector<int, 8> MaskVec;
5488     bool Reverse = (NonZeros & 0x3) == 2;
5489     for (unsigned i = 0; i < 2; ++i)
5490       MaskVec.push_back(Reverse ? 1-i : i);
5491     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5492     for (unsigned i = 0; i < 2; ++i)
5493       MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
5494     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5495   }
5496
5497   if (Values.size() > 1 && VT.getSizeInBits() == 128) {
5498     // Check for a build vector of consecutive loads.
5499     for (unsigned i = 0; i < NumElems; ++i)
5500       V[i] = Op.getOperand(i);
5501
5502     // Check for elements which are consecutive loads.
5503     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5504     if (LD.getNode())
5505       return LD;
5506
5507     // For SSE 4.1, use insertps to put the high elements into the low element.
5508     if (getSubtarget()->hasSSE41orAVX()) {
5509       SDValue Result;
5510       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5511         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5512       else
5513         Result = DAG.getUNDEF(VT);
5514
5515       for (unsigned i = 1; i < NumElems; ++i) {
5516         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5517         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5518                              Op.getOperand(i), DAG.getIntPtrConstant(i));
5519       }
5520       return Result;
5521     }
5522
5523     // Otherwise, expand into a number of unpckl*, start by extending each of
5524     // our (non-undef) elements to the full vector width with the element in the
5525     // bottom slot of the vector (which generates no code for SSE).
5526     for (unsigned i = 0; i < NumElems; ++i) {
5527       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5528         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5529       else
5530         V[i] = DAG.getUNDEF(VT);
5531     }
5532
5533     // Next, we iteratively mix elements, e.g. for v4f32:
5534     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5535     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5536     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5537     unsigned EltStride = NumElems >> 1;
5538     while (EltStride != 0) {
5539       for (unsigned i = 0; i < EltStride; ++i) {
5540         // If V[i+EltStride] is undef and this is the first round of mixing,
5541         // then it is safe to just drop this shuffle: V[i] is already in the
5542         // right place, the one element (since it's the first round) being
5543         // inserted as undef can be dropped.  This isn't safe for successive
5544         // rounds because they will permute elements within both vectors.
5545         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5546             EltStride == NumElems/2)
5547           continue;
5548
5549         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5550       }
5551       EltStride >>= 1;
5552     }
5553     return V[0];
5554   }
5555   return SDValue();
5556 }
5557
5558 // LowerMMXCONCAT_VECTORS - We support concatenate two MMX registers and place
5559 // them in a MMX register.  This is better than doing a stack convert.
5560 static SDValue LowerMMXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5561   DebugLoc dl = Op.getDebugLoc();
5562   EVT ResVT = Op.getValueType();
5563
5564   assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
5565          ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
5566   int Mask[2];
5567   SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
5568   SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5569   InVec = Op.getOperand(1);
5570   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5571     unsigned NumElts = ResVT.getVectorNumElements();
5572     VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5573     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
5574                        InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
5575   } else {
5576     InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
5577     SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5578     Mask[0] = 0; Mask[1] = 2;
5579     VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
5580   }
5581   return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5582 }
5583
5584 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5585 // to create 256-bit vectors from two other 128-bit ones.
5586 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5587   DebugLoc dl = Op.getDebugLoc();
5588   EVT ResVT = Op.getValueType();
5589
5590   assert(ResVT.getSizeInBits() == 256 && "Value type must be 256-bit wide");
5591
5592   SDValue V1 = Op.getOperand(0);
5593   SDValue V2 = Op.getOperand(1);
5594   unsigned NumElems = ResVT.getVectorNumElements();
5595
5596   SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, ResVT), V1,
5597                                  DAG.getConstant(0, MVT::i32), DAG, dl);
5598   return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32),
5599                             DAG, dl);
5600 }
5601
5602 SDValue
5603 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
5604   EVT ResVT = Op.getValueType();
5605
5606   assert(Op.getNumOperands() == 2);
5607   assert((ResVT.getSizeInBits() == 128 || ResVT.getSizeInBits() == 256) &&
5608          "Unsupported CONCAT_VECTORS for value type");
5609
5610   // We support concatenate two MMX registers and place them in a MMX register.
5611   // This is better than doing a stack convert.
5612   if (ResVT.is128BitVector())
5613     return LowerMMXCONCAT_VECTORS(Op, DAG);
5614
5615   // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5616   // from two other 128-bit ones.
5617   return LowerAVXCONCAT_VECTORS(Op, DAG);
5618 }
5619
5620 // v8i16 shuffles - Prefer shuffles in the following order:
5621 // 1. [all]   pshuflw, pshufhw, optional move
5622 // 2. [ssse3] 1 x pshufb
5623 // 3. [ssse3] 2 x pshufb + 1 x por
5624 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5625 SDValue
5626 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
5627                                             SelectionDAG &DAG) const {
5628   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5629   SDValue V1 = SVOp->getOperand(0);
5630   SDValue V2 = SVOp->getOperand(1);
5631   DebugLoc dl = SVOp->getDebugLoc();
5632   SmallVector<int, 8> MaskVals;
5633
5634   // Determine if more than 1 of the words in each of the low and high quadwords
5635   // of the result come from the same quadword of one of the two inputs.  Undef
5636   // mask values count as coming from any quadword, for better codegen.
5637   unsigned LoQuad[] = { 0, 0, 0, 0 };
5638   unsigned HiQuad[] = { 0, 0, 0, 0 };
5639   BitVector InputQuads(4);
5640   for (unsigned i = 0; i < 8; ++i) {
5641     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5642     int EltIdx = SVOp->getMaskElt(i);
5643     MaskVals.push_back(EltIdx);
5644     if (EltIdx < 0) {
5645       ++Quad[0];
5646       ++Quad[1];
5647       ++Quad[2];
5648       ++Quad[3];
5649       continue;
5650     }
5651     ++Quad[EltIdx / 4];
5652     InputQuads.set(EltIdx / 4);
5653   }
5654
5655   int BestLoQuad = -1;
5656   unsigned MaxQuad = 1;
5657   for (unsigned i = 0; i < 4; ++i) {
5658     if (LoQuad[i] > MaxQuad) {
5659       BestLoQuad = i;
5660       MaxQuad = LoQuad[i];
5661     }
5662   }
5663
5664   int BestHiQuad = -1;
5665   MaxQuad = 1;
5666   for (unsigned i = 0; i < 4; ++i) {
5667     if (HiQuad[i] > MaxQuad) {
5668       BestHiQuad = i;
5669       MaxQuad = HiQuad[i];
5670     }
5671   }
5672
5673   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5674   // of the two input vectors, shuffle them into one input vector so only a
5675   // single pshufb instruction is necessary. If There are more than 2 input
5676   // quads, disable the next transformation since it does not help SSSE3.
5677   bool V1Used = InputQuads[0] || InputQuads[1];
5678   bool V2Used = InputQuads[2] || InputQuads[3];
5679   if (Subtarget->hasSSSE3orAVX()) {
5680     if (InputQuads.count() == 2 && V1Used && V2Used) {
5681       BestLoQuad = InputQuads.find_first();
5682       BestHiQuad = InputQuads.find_next(BestLoQuad);
5683     }
5684     if (InputQuads.count() > 2) {
5685       BestLoQuad = -1;
5686       BestHiQuad = -1;
5687     }
5688   }
5689
5690   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5691   // the shuffle mask.  If a quad is scored as -1, that means that it contains
5692   // words from all 4 input quadwords.
5693   SDValue NewV;
5694   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5695     SmallVector<int, 8> MaskV;
5696     MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
5697     MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
5698     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5699                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5700                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5701     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5702
5703     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5704     // source words for the shuffle, to aid later transformations.
5705     bool AllWordsInNewV = true;
5706     bool InOrder[2] = { true, true };
5707     for (unsigned i = 0; i != 8; ++i) {
5708       int idx = MaskVals[i];
5709       if (idx != (int)i)
5710         InOrder[i/4] = false;
5711       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5712         continue;
5713       AllWordsInNewV = false;
5714       break;
5715     }
5716
5717     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5718     if (AllWordsInNewV) {
5719       for (int i = 0; i != 8; ++i) {
5720         int idx = MaskVals[i];
5721         if (idx < 0)
5722           continue;
5723         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5724         if ((idx != i) && idx < 4)
5725           pshufhw = false;
5726         if ((idx != i) && idx > 3)
5727           pshuflw = false;
5728       }
5729       V1 = NewV;
5730       V2Used = false;
5731       BestLoQuad = 0;
5732       BestHiQuad = 1;
5733     }
5734
5735     // If we've eliminated the use of V2, and the new mask is a pshuflw or
5736     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
5737     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5738       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5739       unsigned TargetMask = 0;
5740       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5741                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5742       TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
5743                              X86::getShufflePSHUFLWImmediate(NewV.getNode());
5744       V1 = NewV.getOperand(0);
5745       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5746     }
5747   }
5748
5749   // If we have SSSE3, and all words of the result are from 1 input vector,
5750   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5751   // is present, fall back to case 4.
5752   if (Subtarget->hasSSSE3orAVX()) {
5753     SmallVector<SDValue,16> pshufbMask;
5754
5755     // If we have elements from both input vectors, set the high bit of the
5756     // shuffle mask element to zero out elements that come from V2 in the V1
5757     // mask, and elements that come from V1 in the V2 mask, so that the two
5758     // results can be OR'd together.
5759     bool TwoInputs = V1Used && V2Used;
5760     for (unsigned i = 0; i != 8; ++i) {
5761       int EltIdx = MaskVals[i] * 2;
5762       if (TwoInputs && (EltIdx >= 16)) {
5763         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5764         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5765         continue;
5766       }
5767       pshufbMask.push_back(DAG.getConstant(EltIdx,   MVT::i8));
5768       pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
5769     }
5770     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5771     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5772                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5773                                  MVT::v16i8, &pshufbMask[0], 16));
5774     if (!TwoInputs)
5775       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5776
5777     // Calculate the shuffle mask for the second input, shuffle it, and
5778     // OR it with the first shuffled input.
5779     pshufbMask.clear();
5780     for (unsigned i = 0; i != 8; ++i) {
5781       int EltIdx = MaskVals[i] * 2;
5782       if (EltIdx < 16) {
5783         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5784         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5785         continue;
5786       }
5787       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5788       pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
5789     }
5790     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5791     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5792                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5793                                  MVT::v16i8, &pshufbMask[0], 16));
5794     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5795     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5796   }
5797
5798   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5799   // and update MaskVals with new element order.
5800   BitVector InOrder(8);
5801   if (BestLoQuad >= 0) {
5802     SmallVector<int, 8> MaskV;
5803     for (int i = 0; i != 4; ++i) {
5804       int idx = MaskVals[i];
5805       if (idx < 0) {
5806         MaskV.push_back(-1);
5807         InOrder.set(i);
5808       } else if ((idx / 4) == BestLoQuad) {
5809         MaskV.push_back(idx & 3);
5810         InOrder.set(i);
5811       } else {
5812         MaskV.push_back(-1);
5813       }
5814     }
5815     for (unsigned i = 4; i != 8; ++i)
5816       MaskV.push_back(i);
5817     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5818                                 &MaskV[0]);
5819
5820     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3orAVX())
5821       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5822                                NewV.getOperand(0),
5823                                X86::getShufflePSHUFLWImmediate(NewV.getNode()),
5824                                DAG);
5825   }
5826
5827   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5828   // and update MaskVals with the new element order.
5829   if (BestHiQuad >= 0) {
5830     SmallVector<int, 8> MaskV;
5831     for (unsigned i = 0; i != 4; ++i)
5832       MaskV.push_back(i);
5833     for (unsigned i = 4; i != 8; ++i) {
5834       int idx = MaskVals[i];
5835       if (idx < 0) {
5836         MaskV.push_back(-1);
5837         InOrder.set(i);
5838       } else if ((idx / 4) == BestHiQuad) {
5839         MaskV.push_back((idx & 3) + 4);
5840         InOrder.set(i);
5841       } else {
5842         MaskV.push_back(-1);
5843       }
5844     }
5845     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5846                                 &MaskV[0]);
5847
5848     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3orAVX())
5849       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5850                               NewV.getOperand(0),
5851                               X86::getShufflePSHUFHWImmediate(NewV.getNode()),
5852                               DAG);
5853   }
5854
5855   // In case BestHi & BestLo were both -1, which means each quadword has a word
5856   // from each of the four input quadwords, calculate the InOrder bitvector now
5857   // before falling through to the insert/extract cleanup.
5858   if (BestLoQuad == -1 && BestHiQuad == -1) {
5859     NewV = V1;
5860     for (int i = 0; i != 8; ++i)
5861       if (MaskVals[i] < 0 || MaskVals[i] == i)
5862         InOrder.set(i);
5863   }
5864
5865   // The other elements are put in the right place using pextrw and pinsrw.
5866   for (unsigned i = 0; i != 8; ++i) {
5867     if (InOrder[i])
5868       continue;
5869     int EltIdx = MaskVals[i];
5870     if (EltIdx < 0)
5871       continue;
5872     SDValue ExtOp = (EltIdx < 8)
5873     ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5874                   DAG.getIntPtrConstant(EltIdx))
5875     : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5876                   DAG.getIntPtrConstant(EltIdx - 8));
5877     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5878                        DAG.getIntPtrConstant(i));
5879   }
5880   return NewV;
5881 }
5882
5883 // v16i8 shuffles - Prefer shuffles in the following order:
5884 // 1. [ssse3] 1 x pshufb
5885 // 2. [ssse3] 2 x pshufb + 1 x por
5886 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
5887 static
5888 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5889                                  SelectionDAG &DAG,
5890                                  const X86TargetLowering &TLI) {
5891   SDValue V1 = SVOp->getOperand(0);
5892   SDValue V2 = SVOp->getOperand(1);
5893   DebugLoc dl = SVOp->getDebugLoc();
5894   SmallVector<int, 16> MaskVals;
5895   SVOp->getMask(MaskVals);
5896
5897   // If we have SSSE3, case 1 is generated when all result bytes come from
5898   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
5899   // present, fall back to case 3.
5900   // FIXME: kill V2Only once shuffles are canonizalized by getNode.
5901   bool V1Only = true;
5902   bool V2Only = true;
5903   for (unsigned i = 0; i < 16; ++i) {
5904     int EltIdx = MaskVals[i];
5905     if (EltIdx < 0)
5906       continue;
5907     if (EltIdx < 16)
5908       V2Only = false;
5909     else
5910       V1Only = false;
5911   }
5912
5913   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5914   if (TLI.getSubtarget()->hasSSSE3orAVX()) {
5915     SmallVector<SDValue,16> pshufbMask;
5916
5917     // If all result elements are from one input vector, then only translate
5918     // undef mask values to 0x80 (zero out result) in the pshufb mask.
5919     //
5920     // Otherwise, we have elements from both input vectors, and must zero out
5921     // elements that come from V2 in the first mask, and V1 in the second mask
5922     // so that we can OR them together.
5923     bool TwoInputs = !(V1Only || V2Only);
5924     for (unsigned i = 0; i != 16; ++i) {
5925       int EltIdx = MaskVals[i];
5926       if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
5927         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5928         continue;
5929       }
5930       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5931     }
5932     // If all the elements are from V2, assign it to V1 and return after
5933     // building the first pshufb.
5934     if (V2Only)
5935       V1 = V2;
5936     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5937                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5938                                  MVT::v16i8, &pshufbMask[0], 16));
5939     if (!TwoInputs)
5940       return V1;
5941
5942     // Calculate the shuffle mask for the second input, shuffle it, and
5943     // OR it with the first shuffled input.
5944     pshufbMask.clear();
5945     for (unsigned i = 0; i != 16; ++i) {
5946       int EltIdx = MaskVals[i];
5947       if (EltIdx < 16) {
5948         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5949         continue;
5950       }
5951       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5952     }
5953     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5954                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5955                                  MVT::v16i8, &pshufbMask[0], 16));
5956     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5957   }
5958
5959   // No SSSE3 - Calculate in place words and then fix all out of place words
5960   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
5961   // the 16 different words that comprise the two doublequadword input vectors.
5962   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5963   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5964   SDValue NewV = V2Only ? V2 : V1;
5965   for (int i = 0; i != 8; ++i) {
5966     int Elt0 = MaskVals[i*2];
5967     int Elt1 = MaskVals[i*2+1];
5968
5969     // This word of the result is all undef, skip it.
5970     if (Elt0 < 0 && Elt1 < 0)
5971       continue;
5972
5973     // This word of the result is already in the correct place, skip it.
5974     if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
5975       continue;
5976     if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
5977       continue;
5978
5979     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5980     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5981     SDValue InsElt;
5982
5983     // If Elt0 and Elt1 are defined, are consecutive, and can be load
5984     // using a single extract together, load it and store it.
5985     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5986       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5987                            DAG.getIntPtrConstant(Elt1 / 2));
5988       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5989                         DAG.getIntPtrConstant(i));
5990       continue;
5991     }
5992
5993     // If Elt1 is defined, extract it from the appropriate source.  If the
5994     // source byte is not also odd, shift the extracted word left 8 bits
5995     // otherwise clear the bottom 8 bits if we need to do an or.
5996     if (Elt1 >= 0) {
5997       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5998                            DAG.getIntPtrConstant(Elt1 / 2));
5999       if ((Elt1 & 1) == 0)
6000         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6001                              DAG.getConstant(8,
6002                                   TLI.getShiftAmountTy(InsElt.getValueType())));
6003       else if (Elt0 >= 0)
6004         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6005                              DAG.getConstant(0xFF00, MVT::i16));
6006     }
6007     // If Elt0 is defined, extract it from the appropriate source.  If the
6008     // source byte is not also even, shift the extracted word right 8 bits. If
6009     // Elt1 was also defined, OR the extracted values together before
6010     // inserting them in the result.
6011     if (Elt0 >= 0) {
6012       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6013                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6014       if ((Elt0 & 1) != 0)
6015         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6016                               DAG.getConstant(8,
6017                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
6018       else if (Elt1 >= 0)
6019         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6020                              DAG.getConstant(0x00FF, MVT::i16));
6021       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6022                          : InsElt0;
6023     }
6024     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6025                        DAG.getIntPtrConstant(i));
6026   }
6027   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6028 }
6029
6030 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6031 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6032 /// done when every pair / quad of shuffle mask elements point to elements in
6033 /// the right sequence. e.g.
6034 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6035 static
6036 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6037                                  SelectionDAG &DAG, DebugLoc dl) {
6038   EVT VT = SVOp->getValueType(0);
6039   SDValue V1 = SVOp->getOperand(0);
6040   SDValue V2 = SVOp->getOperand(1);
6041   unsigned NumElems = VT.getVectorNumElements();
6042   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
6043   EVT NewVT;
6044   switch (VT.getSimpleVT().SimpleTy) {
6045   default: assert(false && "Unexpected!");
6046   case MVT::v4f32: NewVT = MVT::v2f64; break;
6047   case MVT::v4i32: NewVT = MVT::v2i64; break;
6048   case MVT::v8i16: NewVT = MVT::v4i32; break;
6049   case MVT::v16i8: NewVT = MVT::v4i32; break;
6050   }
6051
6052   int Scale = NumElems / NewWidth;
6053   SmallVector<int, 8> MaskVec;
6054   for (unsigned i = 0; i < NumElems; i += Scale) {
6055     int StartIdx = -1;
6056     for (int j = 0; j < Scale; ++j) {
6057       int EltIdx = SVOp->getMaskElt(i+j);
6058       if (EltIdx < 0)
6059         continue;
6060       if (StartIdx == -1)
6061         StartIdx = EltIdx - (EltIdx % Scale);
6062       if (EltIdx != StartIdx + j)
6063         return SDValue();
6064     }
6065     if (StartIdx == -1)
6066       MaskVec.push_back(-1);
6067     else
6068       MaskVec.push_back(StartIdx / Scale);
6069   }
6070
6071   V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
6072   V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
6073   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6074 }
6075
6076 /// getVZextMovL - Return a zero-extending vector move low node.
6077 ///
6078 static SDValue getVZextMovL(EVT VT, EVT OpVT,
6079                             SDValue SrcOp, SelectionDAG &DAG,
6080                             const X86Subtarget *Subtarget, DebugLoc dl) {
6081   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6082     LoadSDNode *LD = NULL;
6083     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6084       LD = dyn_cast<LoadSDNode>(SrcOp);
6085     if (!LD) {
6086       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6087       // instead.
6088       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6089       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6090           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6091           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6092           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6093         // PR2108
6094         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6095         return DAG.getNode(ISD::BITCAST, dl, VT,
6096                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6097                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6098                                                    OpVT,
6099                                                    SrcOp.getOperand(0)
6100                                                           .getOperand(0))));
6101       }
6102     }
6103   }
6104
6105   return DAG.getNode(ISD::BITCAST, dl, VT,
6106                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6107                                  DAG.getNode(ISD::BITCAST, dl,
6108                                              OpVT, SrcOp)));
6109 }
6110
6111 /// areShuffleHalvesWithinDisjointLanes - Check whether each half of a vector
6112 /// shuffle node referes to only one lane in the sources.
6113 static bool areShuffleHalvesWithinDisjointLanes(ShuffleVectorSDNode *SVOp) {
6114   EVT VT = SVOp->getValueType(0);
6115   int NumElems = VT.getVectorNumElements();
6116   int HalfSize = NumElems/2;
6117   SmallVector<int, 16> M;
6118   SVOp->getMask(M);
6119   bool MatchA = false, MatchB = false;
6120
6121   for (int l = 0; l < NumElems*2; l += HalfSize) {
6122     if (isUndefOrInRange(M, 0, HalfSize, l, l+HalfSize)) {
6123       MatchA = true;
6124       break;
6125     }
6126   }
6127
6128   for (int l = 0; l < NumElems*2; l += HalfSize) {
6129     if (isUndefOrInRange(M, HalfSize, HalfSize, l, l+HalfSize)) {
6130       MatchB = true;
6131       break;
6132     }
6133   }
6134
6135   return MatchA && MatchB;
6136 }
6137
6138 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6139 /// which could not be matched by any known target speficic shuffle
6140 static SDValue
6141 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6142   if (areShuffleHalvesWithinDisjointLanes(SVOp)) {
6143     // If each half of a vector shuffle node referes to only one lane in the
6144     // source vectors, extract each used 128-bit lane and shuffle them using
6145     // 128-bit shuffles. Then, concatenate the results. Otherwise leave
6146     // the work to the legalizer.
6147     DebugLoc dl = SVOp->getDebugLoc();
6148     EVT VT = SVOp->getValueType(0);
6149     int NumElems = VT.getVectorNumElements();
6150     int HalfSize = NumElems/2;
6151
6152     // Extract the reference for each half
6153     int FstVecExtractIdx = 0, SndVecExtractIdx = 0;
6154     int FstVecOpNum = 0, SndVecOpNum = 0;
6155     for (int i = 0; i < HalfSize; ++i) {
6156       int Elt = SVOp->getMaskElt(i);
6157       if (SVOp->getMaskElt(i) < 0)
6158         continue;
6159       FstVecOpNum = Elt/NumElems;
6160       FstVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize;
6161       break;
6162     }
6163     for (int i = HalfSize; i < NumElems; ++i) {
6164       int Elt = SVOp->getMaskElt(i);
6165       if (SVOp->getMaskElt(i) < 0)
6166         continue;
6167       SndVecOpNum = Elt/NumElems;
6168       SndVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize;
6169       break;
6170     }
6171
6172     // Extract the subvectors
6173     SDValue V1 = Extract128BitVector(SVOp->getOperand(FstVecOpNum),
6174                       DAG.getConstant(FstVecExtractIdx, MVT::i32), DAG, dl);
6175     SDValue V2 = Extract128BitVector(SVOp->getOperand(SndVecOpNum),
6176                       DAG.getConstant(SndVecExtractIdx, MVT::i32), DAG, dl);
6177
6178     // Generate 128-bit shuffles
6179     SmallVector<int, 16> MaskV1, MaskV2;
6180     for (int i = 0; i < HalfSize; ++i) {
6181       int Elt = SVOp->getMaskElt(i);
6182       MaskV1.push_back(Elt < 0 ? Elt : Elt % HalfSize);
6183     }
6184     for (int i = HalfSize; i < NumElems; ++i) {
6185       int Elt = SVOp->getMaskElt(i);
6186       MaskV2.push_back(Elt < 0 ? Elt : Elt % HalfSize);
6187     }
6188
6189     EVT NVT = V1.getValueType();
6190     V1 = DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &MaskV1[0]);
6191     V2 = DAG.getVectorShuffle(NVT, dl, V2, DAG.getUNDEF(NVT), &MaskV2[0]);
6192
6193     // Concatenate the result back
6194     SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), V1,
6195                                    DAG.getConstant(0, MVT::i32), DAG, dl);
6196     return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32),
6197                               DAG, dl);
6198   }
6199
6200   return SDValue();
6201 }
6202
6203 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6204 /// 4 elements, and match them with several different shuffle types.
6205 static SDValue
6206 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6207   SDValue V1 = SVOp->getOperand(0);
6208   SDValue V2 = SVOp->getOperand(1);
6209   DebugLoc dl = SVOp->getDebugLoc();
6210   EVT VT = SVOp->getValueType(0);
6211
6212   assert(VT.getSizeInBits() == 128 && "Unsupported vector size");
6213
6214   SmallVector<std::pair<int, int>, 8> Locs;
6215   Locs.resize(4);
6216   SmallVector<int, 8> Mask1(4U, -1);
6217   SmallVector<int, 8> PermMask;
6218   SVOp->getMask(PermMask);
6219
6220   unsigned NumHi = 0;
6221   unsigned NumLo = 0;
6222   for (unsigned i = 0; i != 4; ++i) {
6223     int Idx = PermMask[i];
6224     if (Idx < 0) {
6225       Locs[i] = std::make_pair(-1, -1);
6226     } else {
6227       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6228       if (Idx < 4) {
6229         Locs[i] = std::make_pair(0, NumLo);
6230         Mask1[NumLo] = Idx;
6231         NumLo++;
6232       } else {
6233         Locs[i] = std::make_pair(1, NumHi);
6234         if (2+NumHi < 4)
6235           Mask1[2+NumHi] = Idx;
6236         NumHi++;
6237       }
6238     }
6239   }
6240
6241   if (NumLo <= 2 && NumHi <= 2) {
6242     // If no more than two elements come from either vector. This can be
6243     // implemented with two shuffles. First shuffle gather the elements.
6244     // The second shuffle, which takes the first shuffle as both of its
6245     // vector operands, put the elements into the right order.
6246     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6247
6248     SmallVector<int, 8> Mask2(4U, -1);
6249
6250     for (unsigned i = 0; i != 4; ++i) {
6251       if (Locs[i].first == -1)
6252         continue;
6253       else {
6254         unsigned Idx = (i < 2) ? 0 : 4;
6255         Idx += Locs[i].first * 2 + Locs[i].second;
6256         Mask2[i] = Idx;
6257       }
6258     }
6259
6260     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6261   } else if (NumLo == 3 || NumHi == 3) {
6262     // Otherwise, we must have three elements from one vector, call it X, and
6263     // one element from the other, call it Y.  First, use a shufps to build an
6264     // intermediate vector with the one element from Y and the element from X
6265     // that will be in the same half in the final destination (the indexes don't
6266     // matter). Then, use a shufps to build the final vector, taking the half
6267     // containing the element from Y from the intermediate, and the other half
6268     // from X.
6269     if (NumHi == 3) {
6270       // Normalize it so the 3 elements come from V1.
6271       CommuteVectorShuffleMask(PermMask, VT);
6272       std::swap(V1, V2);
6273     }
6274
6275     // Find the element from V2.
6276     unsigned HiIndex;
6277     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6278       int Val = PermMask[HiIndex];
6279       if (Val < 0)
6280         continue;
6281       if (Val >= 4)
6282         break;
6283     }
6284
6285     Mask1[0] = PermMask[HiIndex];
6286     Mask1[1] = -1;
6287     Mask1[2] = PermMask[HiIndex^1];
6288     Mask1[3] = -1;
6289     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6290
6291     if (HiIndex >= 2) {
6292       Mask1[0] = PermMask[0];
6293       Mask1[1] = PermMask[1];
6294       Mask1[2] = HiIndex & 1 ? 6 : 4;
6295       Mask1[3] = HiIndex & 1 ? 4 : 6;
6296       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6297     } else {
6298       Mask1[0] = HiIndex & 1 ? 2 : 0;
6299       Mask1[1] = HiIndex & 1 ? 0 : 2;
6300       Mask1[2] = PermMask[2];
6301       Mask1[3] = PermMask[3];
6302       if (Mask1[2] >= 0)
6303         Mask1[2] += 4;
6304       if (Mask1[3] >= 0)
6305         Mask1[3] += 4;
6306       return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6307     }
6308   }
6309
6310   // Break it into (shuffle shuffle_hi, shuffle_lo).
6311   Locs.clear();
6312   Locs.resize(4);
6313   SmallVector<int,8> LoMask(4U, -1);
6314   SmallVector<int,8> HiMask(4U, -1);
6315
6316   SmallVector<int,8> *MaskPtr = &LoMask;
6317   unsigned MaskIdx = 0;
6318   unsigned LoIdx = 0;
6319   unsigned HiIdx = 2;
6320   for (unsigned i = 0; i != 4; ++i) {
6321     if (i == 2) {
6322       MaskPtr = &HiMask;
6323       MaskIdx = 1;
6324       LoIdx = 0;
6325       HiIdx = 2;
6326     }
6327     int Idx = PermMask[i];
6328     if (Idx < 0) {
6329       Locs[i] = std::make_pair(-1, -1);
6330     } else if (Idx < 4) {
6331       Locs[i] = std::make_pair(MaskIdx, LoIdx);
6332       (*MaskPtr)[LoIdx] = Idx;
6333       LoIdx++;
6334     } else {
6335       Locs[i] = std::make_pair(MaskIdx, HiIdx);
6336       (*MaskPtr)[HiIdx] = Idx;
6337       HiIdx++;
6338     }
6339   }
6340
6341   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6342   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6343   SmallVector<int, 8> MaskOps;
6344   for (unsigned i = 0; i != 4; ++i) {
6345     if (Locs[i].first == -1) {
6346       MaskOps.push_back(-1);
6347     } else {
6348       unsigned Idx = Locs[i].first * 4 + Locs[i].second;
6349       MaskOps.push_back(Idx);
6350     }
6351   }
6352   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6353 }
6354
6355 static bool MayFoldVectorLoad(SDValue V) {
6356   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6357     V = V.getOperand(0);
6358   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6359     V = V.getOperand(0);
6360   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6361       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6362     // BUILD_VECTOR (load), undef
6363     V = V.getOperand(0);
6364   if (MayFoldLoad(V))
6365     return true;
6366   return false;
6367 }
6368
6369 // FIXME: the version above should always be used. Since there's
6370 // a bug where several vector shuffles can't be folded because the
6371 // DAG is not updated during lowering and a node claims to have two
6372 // uses while it only has one, use this version, and let isel match
6373 // another instruction if the load really happens to have more than
6374 // one use. Remove this version after this bug get fixed.
6375 // rdar://8434668, PR8156
6376 static bool RelaxedMayFoldVectorLoad(SDValue V) {
6377   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6378     V = V.getOperand(0);
6379   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6380     V = V.getOperand(0);
6381   if (ISD::isNormalLoad(V.getNode()))
6382     return true;
6383   return false;
6384 }
6385
6386 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
6387 /// a vector extract, and if both can be later optimized into a single load.
6388 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
6389 /// here because otherwise a target specific shuffle node is going to be
6390 /// emitted for this shuffle, and the optimization not done.
6391 /// FIXME: This is probably not the best approach, but fix the problem
6392 /// until the right path is decided.
6393 static
6394 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
6395                                          const TargetLowering &TLI) {
6396   EVT VT = V.getValueType();
6397   ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
6398
6399   // Be sure that the vector shuffle is present in a pattern like this:
6400   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
6401   if (!V.hasOneUse())
6402     return false;
6403
6404   SDNode *N = *V.getNode()->use_begin();
6405   if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
6406     return false;
6407
6408   SDValue EltNo = N->getOperand(1);
6409   if (!isa<ConstantSDNode>(EltNo))
6410     return false;
6411
6412   // If the bit convert changed the number of elements, it is unsafe
6413   // to examine the mask.
6414   bool HasShuffleIntoBitcast = false;
6415   if (V.getOpcode() == ISD::BITCAST) {
6416     EVT SrcVT = V.getOperand(0).getValueType();
6417     if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
6418       return false;
6419     V = V.getOperand(0);
6420     HasShuffleIntoBitcast = true;
6421   }
6422
6423   // Select the input vector, guarding against out of range extract vector.
6424   unsigned NumElems = VT.getVectorNumElements();
6425   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6426   int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
6427   V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
6428
6429   // Skip one more bit_convert if necessary
6430   if (V.getOpcode() == ISD::BITCAST)
6431     V = V.getOperand(0);
6432
6433   if (ISD::isNormalLoad(V.getNode())) {
6434     // Is the original load suitable?
6435     LoadSDNode *LN0 = cast<LoadSDNode>(V);
6436
6437     // FIXME: avoid the multi-use bug that is preventing lots of
6438     // of foldings to be detected, this is still wrong of course, but
6439     // give the temporary desired behavior, and if it happens that
6440     // the load has real more uses, during isel it will not fold, and
6441     // will generate poor code.
6442     if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
6443       return false;
6444
6445     if (!HasShuffleIntoBitcast)
6446       return true;
6447
6448     // If there's a bitcast before the shuffle, check if the load type and
6449     // alignment is valid.
6450     unsigned Align = LN0->getAlignment();
6451     unsigned NewAlign =
6452       TLI.getTargetData()->getABITypeAlignment(
6453                                     VT.getTypeForEVT(*DAG.getContext()));
6454
6455     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
6456       return false;
6457   }
6458
6459   return true;
6460 }
6461
6462 static
6463 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6464   EVT VT = Op.getValueType();
6465
6466   // Canonizalize to v2f64.
6467   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6468   return DAG.getNode(ISD::BITCAST, dl, VT,
6469                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6470                                           V1, DAG));
6471 }
6472
6473 static
6474 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6475                         bool HasXMMInt) {
6476   SDValue V1 = Op.getOperand(0);
6477   SDValue V2 = Op.getOperand(1);
6478   EVT VT = Op.getValueType();
6479
6480   assert(VT != MVT::v2i64 && "unsupported shuffle type");
6481
6482   if (HasXMMInt && VT == MVT::v2f64)
6483     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6484
6485   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6486   return DAG.getNode(ISD::BITCAST, dl, VT,
6487                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6488                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6489                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6490 }
6491
6492 static
6493 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6494   SDValue V1 = Op.getOperand(0);
6495   SDValue V2 = Op.getOperand(1);
6496   EVT VT = Op.getValueType();
6497
6498   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6499          "unsupported shuffle type");
6500
6501   if (V2.getOpcode() == ISD::UNDEF)
6502     V2 = V1;
6503
6504   // v4i32 or v4f32
6505   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6506 }
6507
6508 static inline unsigned getSHUFPOpcode(EVT VT) {
6509   switch(VT.getSimpleVT().SimpleTy) {
6510   case MVT::v8i32: // Use fp unit for int unpack.
6511   case MVT::v8f32:
6512   case MVT::v4i32: // Use fp unit for int unpack.
6513   case MVT::v4f32: return X86ISD::SHUFPS;
6514   case MVT::v4i64: // Use fp unit for int unpack.
6515   case MVT::v4f64:
6516   case MVT::v2i64: // Use fp unit for int unpack.
6517   case MVT::v2f64: return X86ISD::SHUFPD;
6518   default:
6519     llvm_unreachable("Unknown type for shufp*");
6520   }
6521   return 0;
6522 }
6523
6524 static
6525 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasXMMInt) {
6526   SDValue V1 = Op.getOperand(0);
6527   SDValue V2 = Op.getOperand(1);
6528   EVT VT = Op.getValueType();
6529   unsigned NumElems = VT.getVectorNumElements();
6530
6531   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6532   // operand of these instructions is only memory, so check if there's a
6533   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6534   // same masks.
6535   bool CanFoldLoad = false;
6536
6537   // Trivial case, when V2 comes from a load.
6538   if (MayFoldVectorLoad(V2))
6539     CanFoldLoad = true;
6540
6541   // When V1 is a load, it can be folded later into a store in isel, example:
6542   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6543   //    turns into:
6544   //  (MOVLPSmr addr:$src1, VR128:$src2)
6545   // So, recognize this potential and also use MOVLPS or MOVLPD
6546   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6547     CanFoldLoad = true;
6548
6549   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6550   if (CanFoldLoad) {
6551     if (HasXMMInt && NumElems == 2)
6552       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6553
6554     if (NumElems == 4)
6555       // If we don't care about the second element, procede to use movss.
6556       if (SVOp->getMaskElt(1) != -1)
6557         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6558   }
6559
6560   // movl and movlp will both match v2i64, but v2i64 is never matched by
6561   // movl earlier because we make it strict to avoid messing with the movlp load
6562   // folding logic (see the code above getMOVLP call). Match it here then,
6563   // this is horrible, but will stay like this until we move all shuffle
6564   // matching to x86 specific nodes. Note that for the 1st condition all
6565   // types are matched with movsd.
6566   if (HasXMMInt) {
6567     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6568     // as to remove this logic from here, as much as possible
6569     if (NumElems == 2 || !X86::isMOVLMask(SVOp))
6570       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6571     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6572   }
6573
6574   assert(VT != MVT::v4i32 && "unsupported shuffle type");
6575
6576   // Invert the operand order and use SHUFPS to match it.
6577   return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V2, V1,
6578                               X86::getShuffleSHUFImmediate(SVOp), DAG);
6579 }
6580
6581 static inline unsigned getUNPCKLOpcode(EVT VT, bool HasAVX2) {
6582   switch(VT.getSimpleVT().SimpleTy) {
6583   case MVT::v4i32: return X86ISD::PUNPCKLDQ;
6584   case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
6585   case MVT::v4f32: return X86ISD::UNPCKLPS;
6586   case MVT::v2f64: return X86ISD::UNPCKLPD;
6587   case MVT::v8i32:
6588     if (HasAVX2)   return X86ISD::PUNPCKLDQ;
6589     // else use fp unit for int unpack.
6590   case MVT::v8f32: return X86ISD::VUNPCKLPSY;
6591   case MVT::v4i64:
6592     if (HasAVX2)   return X86ISD::PUNPCKLQDQ;
6593     // else use fp unit for int unpack.
6594   case MVT::v4f64: return X86ISD::VUNPCKLPDY;
6595   case MVT::v32i8:
6596   case MVT::v16i8: return X86ISD::PUNPCKLBW;
6597   case MVT::v16i16:
6598   case MVT::v8i16: return X86ISD::PUNPCKLWD;
6599   default:
6600     llvm_unreachable("Unknown type for unpckl");
6601   }
6602   return 0;
6603 }
6604
6605 static inline unsigned getUNPCKHOpcode(EVT VT, bool HasAVX2) {
6606   switch(VT.getSimpleVT().SimpleTy) {
6607   case MVT::v4i32: return X86ISD::PUNPCKHDQ;
6608   case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
6609   case MVT::v4f32: return X86ISD::UNPCKHPS;
6610   case MVT::v2f64: return X86ISD::UNPCKHPD;
6611   case MVT::v8i32:
6612     if (HasAVX2)   return X86ISD::PUNPCKHDQ;
6613     // else use fp unit for int unpack.
6614   case MVT::v8f32: return X86ISD::VUNPCKHPSY;
6615   case MVT::v4i64:
6616     if (HasAVX2)   return X86ISD::PUNPCKHQDQ;
6617     // else use fp unit for int unpack.
6618   case MVT::v4f64: return X86ISD::VUNPCKHPDY;
6619   case MVT::v32i8:
6620   case MVT::v16i8: return X86ISD::PUNPCKHBW;
6621   case MVT::v16i16:
6622   case MVT::v8i16: return X86ISD::PUNPCKHWD;
6623   default:
6624     llvm_unreachable("Unknown type for unpckh");
6625   }
6626   return 0;
6627 }
6628
6629 static inline unsigned getVPERMILOpcode(EVT VT) {
6630   switch(VT.getSimpleVT().SimpleTy) {
6631   case MVT::v4i32:
6632   case MVT::v4f32: return X86ISD::VPERMILPS;
6633   case MVT::v2i64:
6634   case MVT::v2f64: return X86ISD::VPERMILPD;
6635   case MVT::v8i32:
6636   case MVT::v8f32: return X86ISD::VPERMILPSY;
6637   case MVT::v4i64:
6638   case MVT::v4f64: return X86ISD::VPERMILPDY;
6639   default:
6640     llvm_unreachable("Unknown type for vpermil");
6641   }
6642   return 0;
6643 }
6644
6645 static
6646 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
6647                                const TargetLowering &TLI,
6648                                const X86Subtarget *Subtarget) {
6649   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6650   EVT VT = Op.getValueType();
6651   DebugLoc dl = Op.getDebugLoc();
6652   SDValue V1 = Op.getOperand(0);
6653   SDValue V2 = Op.getOperand(1);
6654
6655   if (isZeroShuffle(SVOp))
6656     return getZeroVector(VT, Subtarget->hasXMMInt(), DAG, dl);
6657
6658   // Handle splat operations
6659   if (SVOp->isSplat()) {
6660     unsigned NumElem = VT.getVectorNumElements();
6661     int Size = VT.getSizeInBits();
6662     // Special case, this is the only place now where it's allowed to return
6663     // a vector_shuffle operation without using a target specific node, because
6664     // *hopefully* it will be optimized away by the dag combiner. FIXME: should
6665     // this be moved to DAGCombine instead?
6666     if (NumElem <= 4 && CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
6667       return Op;
6668
6669     // Use vbroadcast whenever the splat comes from a foldable load
6670     SDValue LD = isVectorBroadcast(Op, Subtarget->hasAVX2());
6671     if (Subtarget->hasAVX() && LD.getNode())
6672       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, LD);
6673
6674     // Handle splats by matching through known shuffle masks
6675     if ((Size == 128 && NumElem <= 4) ||
6676         (Size == 256 && NumElem < 8))
6677       return SDValue();
6678
6679     // All remaning splats are promoted to target supported vector shuffles.
6680     return PromoteSplat(SVOp, DAG);
6681   }
6682
6683   // If the shuffle can be profitably rewritten as a narrower shuffle, then
6684   // do it!
6685   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
6686     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6687     if (NewOp.getNode())
6688       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6689   } else if ((VT == MVT::v4i32 ||
6690              (VT == MVT::v4f32 && Subtarget->hasXMMInt()))) {
6691     // FIXME: Figure out a cleaner way to do this.
6692     // Try to make use of movq to zero out the top part.
6693     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6694       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6695       if (NewOp.getNode()) {
6696         if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
6697           return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
6698                               DAG, Subtarget, dl);
6699       }
6700     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6701       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6702       if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
6703         return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
6704                             DAG, Subtarget, dl);
6705     }
6706   }
6707   return SDValue();
6708 }
6709
6710 SDValue
6711 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6712   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6713   SDValue V1 = Op.getOperand(0);
6714   SDValue V2 = Op.getOperand(1);
6715   EVT VT = Op.getValueType();
6716   DebugLoc dl = Op.getDebugLoc();
6717   unsigned NumElems = VT.getVectorNumElements();
6718   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6719   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6720   bool V1IsSplat = false;
6721   bool V2IsSplat = false;
6722   bool HasXMMInt = Subtarget->hasXMMInt();
6723   bool HasAVX2   = Subtarget->hasAVX2();
6724   MachineFunction &MF = DAG.getMachineFunction();
6725   bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
6726
6727   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6728
6729   // Vector shuffle lowering takes 3 steps:
6730   //
6731   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6732   //    narrowing and commutation of operands should be handled.
6733   // 2) Matching of shuffles with known shuffle masks to x86 target specific
6734   //    shuffle nodes.
6735   // 3) Rewriting of unmatched masks into new generic shuffle operations,
6736   //    so the shuffle can be broken into other shuffles and the legalizer can
6737   //    try the lowering again.
6738   //
6739   // The general idea is that no vector_shuffle operation should be left to
6740   // be matched during isel, all of them must be converted to a target specific
6741   // node here.
6742
6743   // Normalize the input vectors. Here splats, zeroed vectors, profitable
6744   // narrowing and commutation of operands should be handled. The actual code
6745   // doesn't include all of those, work in progress...
6746   SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
6747   if (NewOp.getNode())
6748     return NewOp;
6749
6750   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6751   // unpckh_undef). Only use pshufd if speed is more important than size.
6752   if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
6753     return getTargetShuffleNode(getUNPCKLOpcode(VT, HasAVX2), dl, VT, V1, V1,
6754                                 DAG);
6755   if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
6756     return getTargetShuffleNode(getUNPCKHOpcode(VT, HasAVX2), dl, VT, V1, V1,
6757                                 DAG);
6758
6759   if (X86::isMOVDDUPMask(SVOp) && Subtarget->hasSSE3orAVX() &&
6760       V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6761     return getMOVDDup(Op, dl, V1, DAG);
6762
6763   if (X86::isMOVHLPS_v_undef_Mask(SVOp))
6764     return getMOVHighToLow(Op, dl, DAG);
6765
6766   // Use to match splats
6767   if (HasXMMInt && X86::isUNPCKHMask(SVOp, HasAVX2) && V2IsUndef &&
6768       (VT == MVT::v2f64 || VT == MVT::v2i64))
6769     return getTargetShuffleNode(getUNPCKHOpcode(VT, HasAVX2), dl, VT, V1, V1,
6770                                 DAG);
6771
6772   if (X86::isPSHUFDMask(SVOp)) {
6773     // The actual implementation will match the mask in the if above and then
6774     // during isel it can match several different instructions, not only pshufd
6775     // as its name says, sad but true, emulate the behavior for now...
6776     if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6777         return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6778
6779     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
6780
6781     if (HasXMMInt && (VT == MVT::v4f32 || VT == MVT::v4i32))
6782       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6783
6784     return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V1,
6785                                 TargetMask, DAG);
6786   }
6787
6788   // Check if this can be converted into a logical shift.
6789   bool isLeft = false;
6790   unsigned ShAmt = 0;
6791   SDValue ShVal;
6792   bool isShift = HasXMMInt && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6793   if (isShift && ShVal.hasOneUse()) {
6794     // If the shifted value has multiple uses, it may be cheaper to use
6795     // v_set0 + movlhps or movhlps, etc.
6796     EVT EltVT = VT.getVectorElementType();
6797     ShAmt *= EltVT.getSizeInBits();
6798     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6799   }
6800
6801   if (X86::isMOVLMask(SVOp)) {
6802     if (V1IsUndef)
6803       return V2;
6804     if (ISD::isBuildVectorAllZeros(V1.getNode()))
6805       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6806     if (!X86::isMOVLPMask(SVOp)) {
6807       if (HasXMMInt && (VT == MVT::v2i64 || VT == MVT::v2f64))
6808         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6809
6810       if (VT == MVT::v4i32 || VT == MVT::v4f32)
6811         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6812     }
6813   }
6814
6815   // FIXME: fold these into legal mask.
6816   if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp, HasAVX2))
6817     return getMOVLowToHigh(Op, dl, DAG, HasXMMInt);
6818
6819   if (X86::isMOVHLPSMask(SVOp))
6820     return getMOVHighToLow(Op, dl, DAG);
6821
6822   if (X86::isMOVSHDUPMask(SVOp, Subtarget))
6823     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6824
6825   if (X86::isMOVSLDUPMask(SVOp, Subtarget))
6826     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6827
6828   if (X86::isMOVLPMask(SVOp))
6829     return getMOVLP(Op, dl, DAG, HasXMMInt);
6830
6831   if (ShouldXformToMOVHLPS(SVOp) ||
6832       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
6833     return CommuteVectorShuffle(SVOp, DAG);
6834
6835   if (isShift) {
6836     // No better options. Use a vshl / vsrl.
6837     EVT EltVT = VT.getVectorElementType();
6838     ShAmt *= EltVT.getSizeInBits();
6839     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6840   }
6841
6842   bool Commuted = false;
6843   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
6844   // 1,1,1,1 -> v8i16 though.
6845   V1IsSplat = isSplatVector(V1.getNode());
6846   V2IsSplat = isSplatVector(V2.getNode());
6847
6848   // Canonicalize the splat or undef, if present, to be on the RHS.
6849   if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
6850     Op = CommuteVectorShuffle(SVOp, DAG);
6851     SVOp = cast<ShuffleVectorSDNode>(Op);
6852     V1 = SVOp->getOperand(0);
6853     V2 = SVOp->getOperand(1);
6854     std::swap(V1IsSplat, V2IsSplat);
6855     std::swap(V1IsUndef, V2IsUndef);
6856     Commuted = true;
6857   }
6858
6859   if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
6860     // Shuffling low element of v1 into undef, just return v1.
6861     if (V2IsUndef)
6862       return V1;
6863     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6864     // the instruction selector will not match, so get a canonical MOVL with
6865     // swapped operands to undo the commute.
6866     return getMOVL(DAG, dl, VT, V2, V1);
6867   }
6868
6869   if (X86::isUNPCKLMask(SVOp, HasAVX2))
6870     return getTargetShuffleNode(getUNPCKLOpcode(VT, HasAVX2), dl, VT, V1, V2,
6871                                 DAG);
6872
6873   if (X86::isUNPCKHMask(SVOp, HasAVX2))
6874     return getTargetShuffleNode(getUNPCKHOpcode(VT, HasAVX2), dl, VT, V1, V2,
6875                                 DAG);
6876
6877   if (V2IsSplat) {
6878     // Normalize mask so all entries that point to V2 points to its first
6879     // element then try to match unpck{h|l} again. If match, return a
6880     // new vector_shuffle with the corrected mask.
6881     SDValue NewMask = NormalizeMask(SVOp, DAG);
6882     ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
6883     if (NSVOp != SVOp) {
6884       if (X86::isUNPCKLMask(NSVOp, HasAVX2, true)) {
6885         return NewMask;
6886       } else if (X86::isUNPCKHMask(NSVOp, HasAVX2, true)) {
6887         return NewMask;
6888       }
6889     }
6890   }
6891
6892   if (Commuted) {
6893     // Commute is back and try unpck* again.
6894     // FIXME: this seems wrong.
6895     SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
6896     ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
6897
6898     if (X86::isUNPCKLMask(NewSVOp, HasAVX2))
6899       return getTargetShuffleNode(getUNPCKLOpcode(VT, HasAVX2), dl, VT, V2, V1,
6900                                   DAG);
6901
6902     if (X86::isUNPCKHMask(NewSVOp, HasAVX2))
6903       return getTargetShuffleNode(getUNPCKHOpcode(VT, HasAVX2), dl, VT, V2, V1,
6904                                   DAG);
6905   }
6906
6907   // Normalize the node to match x86 shuffle ops if needed
6908   if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
6909     return CommuteVectorShuffle(SVOp, DAG);
6910
6911   // The checks below are all present in isShuffleMaskLegal, but they are
6912   // inlined here right now to enable us to directly emit target specific
6913   // nodes, and remove one by one until they don't return Op anymore.
6914   SmallVector<int, 16> M;
6915   SVOp->getMask(M);
6916
6917   if (isPALIGNRMask(M, VT, Subtarget->hasSSSE3orAVX()))
6918     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6919                                 X86::getShufflePALIGNRImmediate(SVOp),
6920                                 DAG);
6921
6922   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6923       SVOp->getSplatIndex() == 0 && V2IsUndef) {
6924     if (VT == MVT::v2f64)
6925       return getTargetShuffleNode(X86ISD::UNPCKLPD, dl, VT, V1, V1, DAG);
6926     if (VT == MVT::v2i64)
6927       return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
6928   }
6929
6930   if (isPSHUFHWMask(M, VT))
6931     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6932                                 X86::getShufflePSHUFHWImmediate(SVOp),
6933                                 DAG);
6934
6935   if (isPSHUFLWMask(M, VT))
6936     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6937                                 X86::getShufflePSHUFLWImmediate(SVOp),
6938                                 DAG);
6939
6940   if (isSHUFPMask(M, VT))
6941     return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6942                                 X86::getShuffleSHUFImmediate(SVOp), DAG);
6943
6944   if (X86::isUNPCKL_v_undef_Mask(SVOp))
6945     return getTargetShuffleNode(getUNPCKLOpcode(VT, HasAVX2), dl, VT, V1, V1,
6946                                 DAG);
6947   if (X86::isUNPCKH_v_undef_Mask(SVOp))
6948     return getTargetShuffleNode(getUNPCKHOpcode(VT, HasAVX2), dl, VT, V1, V1,
6949                                 DAG);
6950
6951   //===--------------------------------------------------------------------===//
6952   // Generate target specific nodes for 128 or 256-bit shuffles only
6953   // supported in the AVX instruction set.
6954   //
6955
6956   // Handle VMOVDDUPY permutations
6957   if (isMOVDDUPYMask(SVOp, Subtarget))
6958     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6959
6960   // Handle VPERMILPS* permutations
6961   if (isVPERMILPSMask(M, VT, Subtarget))
6962     return getTargetShuffleNode(getVPERMILOpcode(VT), dl, VT, V1,
6963                                 getShuffleVPERMILPSImmediate(SVOp), DAG);
6964
6965   // Handle VPERMILPD* permutations
6966   if (isVPERMILPDMask(M, VT, Subtarget))
6967     return getTargetShuffleNode(getVPERMILOpcode(VT), dl, VT, V1,
6968                                 getShuffleVPERMILPDImmediate(SVOp), DAG);
6969
6970   // Handle VPERM2F128 permutations
6971   if (isVPERM2F128Mask(M, VT, Subtarget))
6972     return getTargetShuffleNode(X86ISD::VPERM2F128, dl, VT, V1, V2,
6973                                 getShuffleVPERM2F128Immediate(SVOp), DAG);
6974
6975   // Handle VSHUFPSY permutations
6976   if (isVSHUFPSYMask(M, VT, Subtarget))
6977     return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6978                                 getShuffleVSHUFPSYImmediate(SVOp), DAG);
6979
6980   // Handle VSHUFPDY permutations
6981   if (isVSHUFPDYMask(M, VT, Subtarget))
6982     return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6983                                 getShuffleVSHUFPDYImmediate(SVOp), DAG);
6984
6985   // Try to swap operands in the node to match x86 shuffle ops
6986   if (isCommutedVSHUFPMask(M, VT, Subtarget)) {
6987     // Now we need to commute operands.
6988     SVOp = cast<ShuffleVectorSDNode>(CommuteVectorShuffle(SVOp, DAG));
6989     V1 = SVOp->getOperand(0);
6990     V2 = SVOp->getOperand(1);
6991     unsigned Immediate = (NumElems == 4) ? getShuffleVSHUFPDYImmediate(SVOp):
6992         getShuffleVSHUFPSYImmediate(SVOp);
6993     return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2, Immediate, DAG);
6994   }
6995
6996   //===--------------------------------------------------------------------===//
6997   // Since no target specific shuffle was selected for this generic one,
6998   // lower it into other known shuffles. FIXME: this isn't true yet, but
6999   // this is the plan.
7000   //
7001
7002   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7003   if (VT == MVT::v8i16) {
7004     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
7005     if (NewOp.getNode())
7006       return NewOp;
7007   }
7008
7009   if (VT == MVT::v16i8) {
7010     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
7011     if (NewOp.getNode())
7012       return NewOp;
7013   }
7014
7015   // Handle all 128-bit wide vectors with 4 elements, and match them with
7016   // several different shuffle types.
7017   if (NumElems == 4 && VT.getSizeInBits() == 128)
7018     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7019
7020   // Handle general 256-bit shuffles
7021   if (VT.is256BitVector())
7022     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7023
7024   return SDValue();
7025 }
7026
7027 SDValue
7028 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
7029                                                 SelectionDAG &DAG) const {
7030   EVT VT = Op.getValueType();
7031   DebugLoc dl = Op.getDebugLoc();
7032
7033   if (Op.getOperand(0).getValueType().getSizeInBits() != 128)
7034     return SDValue();
7035
7036   if (VT.getSizeInBits() == 8) {
7037     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7038                                     Op.getOperand(0), Op.getOperand(1));
7039     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7040                                     DAG.getValueType(VT));
7041     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7042   } else if (VT.getSizeInBits() == 16) {
7043     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7044     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7045     if (Idx == 0)
7046       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7047                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7048                                      DAG.getNode(ISD::BITCAST, dl,
7049                                                  MVT::v4i32,
7050                                                  Op.getOperand(0)),
7051                                      Op.getOperand(1)));
7052     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7053                                     Op.getOperand(0), Op.getOperand(1));
7054     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7055                                     DAG.getValueType(VT));
7056     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7057   } else if (VT == MVT::f32) {
7058     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7059     // the result back to FR32 register. It's only worth matching if the
7060     // result has a single use which is a store or a bitcast to i32.  And in
7061     // the case of a store, it's not worth it if the index is a constant 0,
7062     // because a MOVSSmr can be used instead, which is smaller and faster.
7063     if (!Op.hasOneUse())
7064       return SDValue();
7065     SDNode *User = *Op.getNode()->use_begin();
7066     if ((User->getOpcode() != ISD::STORE ||
7067          (isa<ConstantSDNode>(Op.getOperand(1)) &&
7068           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7069         (User->getOpcode() != ISD::BITCAST ||
7070          User->getValueType(0) != MVT::i32))
7071       return SDValue();
7072     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7073                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7074                                               Op.getOperand(0)),
7075                                               Op.getOperand(1));
7076     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7077   } else if (VT == MVT::i32 || VT == MVT::i64) {
7078     // ExtractPS/pextrq works with constant index.
7079     if (isa<ConstantSDNode>(Op.getOperand(1)))
7080       return Op;
7081   }
7082   return SDValue();
7083 }
7084
7085
7086 SDValue
7087 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7088                                            SelectionDAG &DAG) const {
7089   if (!isa<ConstantSDNode>(Op.getOperand(1)))
7090     return SDValue();
7091
7092   SDValue Vec = Op.getOperand(0);
7093   EVT VecVT = Vec.getValueType();
7094
7095   // If this is a 256-bit vector result, first extract the 128-bit vector and
7096   // then extract the element from the 128-bit vector.
7097   if (VecVT.getSizeInBits() == 256) {
7098     DebugLoc dl = Op.getNode()->getDebugLoc();
7099     unsigned NumElems = VecVT.getVectorNumElements();
7100     SDValue Idx = Op.getOperand(1);
7101     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7102
7103     // Get the 128-bit vector.
7104     bool Upper = IdxVal >= NumElems/2;
7105     Vec = Extract128BitVector(Vec,
7106                     DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32), DAG, dl);
7107
7108     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7109                     Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : Idx);
7110   }
7111
7112   assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
7113
7114   if (Subtarget->hasSSE41orAVX()) {
7115     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7116     if (Res.getNode())
7117       return Res;
7118   }
7119
7120   EVT VT = Op.getValueType();
7121   DebugLoc dl = Op.getDebugLoc();
7122   // TODO: handle v16i8.
7123   if (VT.getSizeInBits() == 16) {
7124     SDValue Vec = Op.getOperand(0);
7125     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7126     if (Idx == 0)
7127       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7128                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7129                                      DAG.getNode(ISD::BITCAST, dl,
7130                                                  MVT::v4i32, Vec),
7131                                      Op.getOperand(1)));
7132     // Transform it so it match pextrw which produces a 32-bit result.
7133     EVT EltVT = MVT::i32;
7134     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7135                                     Op.getOperand(0), Op.getOperand(1));
7136     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7137                                     DAG.getValueType(VT));
7138     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7139   } else if (VT.getSizeInBits() == 32) {
7140     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7141     if (Idx == 0)
7142       return Op;
7143
7144     // SHUFPS the element to the lowest double word, then movss.
7145     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7146     EVT VVT = Op.getOperand(0).getValueType();
7147     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7148                                        DAG.getUNDEF(VVT), Mask);
7149     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7150                        DAG.getIntPtrConstant(0));
7151   } else if (VT.getSizeInBits() == 64) {
7152     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7153     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7154     //        to match extract_elt for f64.
7155     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7156     if (Idx == 0)
7157       return Op;
7158
7159     // UNPCKHPD the element to the lowest double word, then movsd.
7160     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7161     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7162     int Mask[2] = { 1, -1 };
7163     EVT VVT = Op.getOperand(0).getValueType();
7164     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7165                                        DAG.getUNDEF(VVT), Mask);
7166     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7167                        DAG.getIntPtrConstant(0));
7168   }
7169
7170   return SDValue();
7171 }
7172
7173 SDValue
7174 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
7175                                                SelectionDAG &DAG) const {
7176   EVT VT = Op.getValueType();
7177   EVT EltVT = VT.getVectorElementType();
7178   DebugLoc dl = Op.getDebugLoc();
7179
7180   SDValue N0 = Op.getOperand(0);
7181   SDValue N1 = Op.getOperand(1);
7182   SDValue N2 = Op.getOperand(2);
7183
7184   if (VT.getSizeInBits() == 256)
7185     return SDValue();
7186
7187   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7188       isa<ConstantSDNode>(N2)) {
7189     unsigned Opc;
7190     if (VT == MVT::v8i16)
7191       Opc = X86ISD::PINSRW;
7192     else if (VT == MVT::v16i8)
7193       Opc = X86ISD::PINSRB;
7194     else
7195       Opc = X86ISD::PINSRB;
7196
7197     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7198     // argument.
7199     if (N1.getValueType() != MVT::i32)
7200       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7201     if (N2.getValueType() != MVT::i32)
7202       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7203     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7204   } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7205     // Bits [7:6] of the constant are the source select.  This will always be
7206     //  zero here.  The DAG Combiner may combine an extract_elt index into these
7207     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
7208     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
7209     // Bits [5:4] of the constant are the destination select.  This is the
7210     //  value of the incoming immediate.
7211     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
7212     //   combine either bitwise AND or insert of float 0.0 to set these bits.
7213     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7214     // Create this as a scalar to vector..
7215     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7216     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7217   } else if ((EltVT == MVT::i32 || EltVT == MVT::i64) && 
7218              isa<ConstantSDNode>(N2)) {
7219     // PINSR* works with constant index.
7220     return Op;
7221   }
7222   return SDValue();
7223 }
7224
7225 SDValue
7226 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7227   EVT VT = Op.getValueType();
7228   EVT EltVT = VT.getVectorElementType();
7229
7230   DebugLoc dl = Op.getDebugLoc();
7231   SDValue N0 = Op.getOperand(0);
7232   SDValue N1 = Op.getOperand(1);
7233   SDValue N2 = Op.getOperand(2);
7234
7235   // If this is a 256-bit vector result, first extract the 128-bit vector,
7236   // insert the element into the extracted half and then place it back.
7237   if (VT.getSizeInBits() == 256) {
7238     if (!isa<ConstantSDNode>(N2))
7239       return SDValue();
7240
7241     // Get the desired 128-bit vector half.
7242     unsigned NumElems = VT.getVectorNumElements();
7243     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7244     bool Upper = IdxVal >= NumElems/2;
7245     SDValue Ins128Idx = DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32);
7246     SDValue V = Extract128BitVector(N0, Ins128Idx, DAG, dl);
7247
7248     // Insert the element into the desired half.
7249     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V,
7250                  N1, Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : N2);
7251
7252     // Insert the changed part back to the 256-bit vector
7253     return Insert128BitVector(N0, V, Ins128Idx, DAG, dl);
7254   }
7255
7256   if (Subtarget->hasSSE41orAVX())
7257     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7258
7259   if (EltVT == MVT::i8)
7260     return SDValue();
7261
7262   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7263     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7264     // as its second argument.
7265     if (N1.getValueType() != MVT::i32)
7266       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7267     if (N2.getValueType() != MVT::i32)
7268       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7269     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7270   }
7271   return SDValue();
7272 }
7273
7274 SDValue
7275 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
7276   LLVMContext *Context = DAG.getContext();
7277   DebugLoc dl = Op.getDebugLoc();
7278   EVT OpVT = Op.getValueType();
7279
7280   // If this is a 256-bit vector result, first insert into a 128-bit
7281   // vector and then insert into the 256-bit vector.
7282   if (OpVT.getSizeInBits() > 128) {
7283     // Insert into a 128-bit vector.
7284     EVT VT128 = EVT::getVectorVT(*Context,
7285                                  OpVT.getVectorElementType(),
7286                                  OpVT.getVectorNumElements() / 2);
7287
7288     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7289
7290     // Insert the 128-bit vector.
7291     return Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, OpVT), Op,
7292                               DAG.getConstant(0, MVT::i32),
7293                               DAG, dl);
7294   }
7295
7296   if (Op.getValueType() == MVT::v1i64 &&
7297       Op.getOperand(0).getValueType() == MVT::i64)
7298     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7299
7300   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7301   assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
7302          "Expected an SSE type!");
7303   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
7304                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7305 }
7306
7307 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7308 // a simple subregister reference or explicit instructions to grab
7309 // upper bits of a vector.
7310 SDValue
7311 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7312   if (Subtarget->hasAVX()) {
7313     DebugLoc dl = Op.getNode()->getDebugLoc();
7314     SDValue Vec = Op.getNode()->getOperand(0);
7315     SDValue Idx = Op.getNode()->getOperand(1);
7316
7317     if (Op.getNode()->getValueType(0).getSizeInBits() == 128
7318         && Vec.getNode()->getValueType(0).getSizeInBits() == 256) {
7319         return Extract128BitVector(Vec, Idx, DAG, dl);
7320     }
7321   }
7322   return SDValue();
7323 }
7324
7325 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7326 // simple superregister reference or explicit instructions to insert
7327 // the upper bits of a vector.
7328 SDValue
7329 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7330   if (Subtarget->hasAVX()) {
7331     DebugLoc dl = Op.getNode()->getDebugLoc();
7332     SDValue Vec = Op.getNode()->getOperand(0);
7333     SDValue SubVec = Op.getNode()->getOperand(1);
7334     SDValue Idx = Op.getNode()->getOperand(2);
7335
7336     if (Op.getNode()->getValueType(0).getSizeInBits() == 256
7337         && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) {
7338       return Insert128BitVector(Vec, SubVec, Idx, DAG, dl);
7339     }
7340   }
7341   return SDValue();
7342 }
7343
7344 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7345 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7346 // one of the above mentioned nodes. It has to be wrapped because otherwise
7347 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7348 // be used to form addressing mode. These wrapped nodes will be selected
7349 // into MOV32ri.
7350 SDValue
7351 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7352   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7353
7354   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7355   // global base reg.
7356   unsigned char OpFlag = 0;
7357   unsigned WrapperKind = X86ISD::Wrapper;
7358   CodeModel::Model M = getTargetMachine().getCodeModel();
7359
7360   if (Subtarget->isPICStyleRIPRel() &&
7361       (M == CodeModel::Small || M == CodeModel::Kernel))
7362     WrapperKind = X86ISD::WrapperRIP;
7363   else if (Subtarget->isPICStyleGOT())
7364     OpFlag = X86II::MO_GOTOFF;
7365   else if (Subtarget->isPICStyleStubPIC())
7366     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7367
7368   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7369                                              CP->getAlignment(),
7370                                              CP->getOffset(), OpFlag);
7371   DebugLoc DL = CP->getDebugLoc();
7372   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7373   // With PIC, the address is actually $g + Offset.
7374   if (OpFlag) {
7375     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7376                          DAG.getNode(X86ISD::GlobalBaseReg,
7377                                      DebugLoc(), getPointerTy()),
7378                          Result);
7379   }
7380
7381   return Result;
7382 }
7383
7384 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7385   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7386
7387   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7388   // global base reg.
7389   unsigned char OpFlag = 0;
7390   unsigned WrapperKind = X86ISD::Wrapper;
7391   CodeModel::Model M = getTargetMachine().getCodeModel();
7392
7393   if (Subtarget->isPICStyleRIPRel() &&
7394       (M == CodeModel::Small || M == CodeModel::Kernel))
7395     WrapperKind = X86ISD::WrapperRIP;
7396   else if (Subtarget->isPICStyleGOT())
7397     OpFlag = X86II::MO_GOTOFF;
7398   else if (Subtarget->isPICStyleStubPIC())
7399     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7400
7401   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7402                                           OpFlag);
7403   DebugLoc DL = JT->getDebugLoc();
7404   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7405
7406   // With PIC, the address is actually $g + Offset.
7407   if (OpFlag)
7408     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7409                          DAG.getNode(X86ISD::GlobalBaseReg,
7410                                      DebugLoc(), getPointerTy()),
7411                          Result);
7412
7413   return Result;
7414 }
7415
7416 SDValue
7417 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7418   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7419
7420   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7421   // global base reg.
7422   unsigned char OpFlag = 0;
7423   unsigned WrapperKind = X86ISD::Wrapper;
7424   CodeModel::Model M = getTargetMachine().getCodeModel();
7425
7426   if (Subtarget->isPICStyleRIPRel() &&
7427       (M == CodeModel::Small || M == CodeModel::Kernel)) {
7428     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7429       OpFlag = X86II::MO_GOTPCREL;
7430     WrapperKind = X86ISD::WrapperRIP;
7431   } else if (Subtarget->isPICStyleGOT()) {
7432     OpFlag = X86II::MO_GOT;
7433   } else if (Subtarget->isPICStyleStubPIC()) {
7434     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7435   } else if (Subtarget->isPICStyleStubNoDynamic()) {
7436     OpFlag = X86II::MO_DARWIN_NONLAZY;
7437   }
7438
7439   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7440
7441   DebugLoc DL = Op.getDebugLoc();
7442   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7443
7444
7445   // With PIC, the address is actually $g + Offset.
7446   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7447       !Subtarget->is64Bit()) {
7448     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7449                          DAG.getNode(X86ISD::GlobalBaseReg,
7450                                      DebugLoc(), getPointerTy()),
7451                          Result);
7452   }
7453
7454   // For symbols that require a load from a stub to get the address, emit the
7455   // load.
7456   if (isGlobalStubReference(OpFlag))
7457     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7458                          MachinePointerInfo::getGOT(), false, false, false, 0);
7459
7460   return Result;
7461 }
7462
7463 SDValue
7464 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7465   // Create the TargetBlockAddressAddress node.
7466   unsigned char OpFlags =
7467     Subtarget->ClassifyBlockAddressReference();
7468   CodeModel::Model M = getTargetMachine().getCodeModel();
7469   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7470   DebugLoc dl = Op.getDebugLoc();
7471   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
7472                                        /*isTarget=*/true, OpFlags);
7473
7474   if (Subtarget->isPICStyleRIPRel() &&
7475       (M == CodeModel::Small || M == CodeModel::Kernel))
7476     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7477   else
7478     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7479
7480   // With PIC, the address is actually $g + Offset.
7481   if (isGlobalRelativeToPICBase(OpFlags)) {
7482     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7483                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7484                          Result);
7485   }
7486
7487   return Result;
7488 }
7489
7490 SDValue
7491 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7492                                       int64_t Offset,
7493                                       SelectionDAG &DAG) const {
7494   // Create the TargetGlobalAddress node, folding in the constant
7495   // offset if it is legal.
7496   unsigned char OpFlags =
7497     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7498   CodeModel::Model M = getTargetMachine().getCodeModel();
7499   SDValue Result;
7500   if (OpFlags == X86II::MO_NO_FLAG &&
7501       X86::isOffsetSuitableForCodeModel(Offset, M)) {
7502     // A direct static reference to a global.
7503     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7504     Offset = 0;
7505   } else {
7506     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7507   }
7508
7509   if (Subtarget->isPICStyleRIPRel() &&
7510       (M == CodeModel::Small || M == CodeModel::Kernel))
7511     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7512   else
7513     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7514
7515   // With PIC, the address is actually $g + Offset.
7516   if (isGlobalRelativeToPICBase(OpFlags)) {
7517     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7518                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7519                          Result);
7520   }
7521
7522   // For globals that require a load from a stub to get the address, emit the
7523   // load.
7524   if (isGlobalStubReference(OpFlags))
7525     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7526                          MachinePointerInfo::getGOT(), false, false, false, 0);
7527
7528   // If there was a non-zero offset that we didn't fold, create an explicit
7529   // addition for it.
7530   if (Offset != 0)
7531     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7532                          DAG.getConstant(Offset, getPointerTy()));
7533
7534   return Result;
7535 }
7536
7537 SDValue
7538 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7539   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7540   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7541   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7542 }
7543
7544 static SDValue
7545 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7546            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7547            unsigned char OperandFlags) {
7548   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7549   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7550   DebugLoc dl = GA->getDebugLoc();
7551   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7552                                            GA->getValueType(0),
7553                                            GA->getOffset(),
7554                                            OperandFlags);
7555   if (InFlag) {
7556     SDValue Ops[] = { Chain,  TGA, *InFlag };
7557     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
7558   } else {
7559     SDValue Ops[]  = { Chain, TGA };
7560     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
7561   }
7562
7563   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7564   MFI->setAdjustsStack(true);
7565
7566   SDValue Flag = Chain.getValue(1);
7567   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7568 }
7569
7570 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7571 static SDValue
7572 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7573                                 const EVT PtrVT) {
7574   SDValue InFlag;
7575   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
7576   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7577                                      DAG.getNode(X86ISD::GlobalBaseReg,
7578                                                  DebugLoc(), PtrVT), InFlag);
7579   InFlag = Chain.getValue(1);
7580
7581   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7582 }
7583
7584 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7585 static SDValue
7586 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7587                                 const EVT PtrVT) {
7588   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7589                     X86::RAX, X86II::MO_TLSGD);
7590 }
7591
7592 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
7593 // "local exec" model.
7594 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7595                                    const EVT PtrVT, TLSModel::Model model,
7596                                    bool is64Bit) {
7597   DebugLoc dl = GA->getDebugLoc();
7598
7599   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7600   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7601                                                          is64Bit ? 257 : 256));
7602
7603   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7604                                       DAG.getIntPtrConstant(0),
7605                                       MachinePointerInfo(Ptr),
7606                                       false, false, false, 0);
7607
7608   unsigned char OperandFlags = 0;
7609   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
7610   // initialexec.
7611   unsigned WrapperKind = X86ISD::Wrapper;
7612   if (model == TLSModel::LocalExec) {
7613     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7614   } else if (is64Bit) {
7615     assert(model == TLSModel::InitialExec);
7616     OperandFlags = X86II::MO_GOTTPOFF;
7617     WrapperKind = X86ISD::WrapperRIP;
7618   } else {
7619     assert(model == TLSModel::InitialExec);
7620     OperandFlags = X86II::MO_INDNTPOFF;
7621   }
7622
7623   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
7624   // exec)
7625   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7626                                            GA->getValueType(0),
7627                                            GA->getOffset(), OperandFlags);
7628   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7629
7630   if (model == TLSModel::InitialExec)
7631     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7632                          MachinePointerInfo::getGOT(), false, false, false, 0);
7633
7634   // The address of the thread local variable is the add of the thread
7635   // pointer with the offset of the variable.
7636   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7637 }
7638
7639 SDValue
7640 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7641
7642   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7643   const GlobalValue *GV = GA->getGlobal();
7644
7645   if (Subtarget->isTargetELF()) {
7646     // TODO: implement the "local dynamic" model
7647     // TODO: implement the "initial exec"model for pic executables
7648
7649     // If GV is an alias then use the aliasee for determining
7650     // thread-localness.
7651     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7652       GV = GA->resolveAliasedGlobal(false);
7653
7654     TLSModel::Model model
7655       = getTLSModel(GV, getTargetMachine().getRelocationModel());
7656
7657     switch (model) {
7658       case TLSModel::GeneralDynamic:
7659       case TLSModel::LocalDynamic: // not implemented
7660         if (Subtarget->is64Bit())
7661           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7662         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7663
7664       case TLSModel::InitialExec:
7665       case TLSModel::LocalExec:
7666         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7667                                    Subtarget->is64Bit());
7668     }
7669   } else if (Subtarget->isTargetDarwin()) {
7670     // Darwin only has one model of TLS.  Lower to that.
7671     unsigned char OpFlag = 0;
7672     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7673                            X86ISD::WrapperRIP : X86ISD::Wrapper;
7674
7675     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7676     // global base reg.
7677     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7678                   !Subtarget->is64Bit();
7679     if (PIC32)
7680       OpFlag = X86II::MO_TLVP_PIC_BASE;
7681     else
7682       OpFlag = X86II::MO_TLVP;
7683     DebugLoc DL = Op.getDebugLoc();
7684     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7685                                                 GA->getValueType(0),
7686                                                 GA->getOffset(), OpFlag);
7687     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7688
7689     // With PIC32, the address is actually $g + Offset.
7690     if (PIC32)
7691       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7692                            DAG.getNode(X86ISD::GlobalBaseReg,
7693                                        DebugLoc(), getPointerTy()),
7694                            Offset);
7695
7696     // Lowering the machine isd will make sure everything is in the right
7697     // location.
7698     SDValue Chain = DAG.getEntryNode();
7699     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7700     SDValue Args[] = { Chain, Offset };
7701     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7702
7703     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7704     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7705     MFI->setAdjustsStack(true);
7706
7707     // And our return value (tls address) is in the standard call return value
7708     // location.
7709     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7710     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7711                               Chain.getValue(1));
7712   }
7713
7714   assert(false &&
7715          "TLS not implemented for this target.");
7716
7717   llvm_unreachable("Unreachable");
7718   return SDValue();
7719 }
7720
7721
7722 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values and
7723 /// take a 2 x i32 value to shift plus a shift amount.
7724 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const {
7725   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7726   EVT VT = Op.getValueType();
7727   unsigned VTBits = VT.getSizeInBits();
7728   DebugLoc dl = Op.getDebugLoc();
7729   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7730   SDValue ShOpLo = Op.getOperand(0);
7731   SDValue ShOpHi = Op.getOperand(1);
7732   SDValue ShAmt  = Op.getOperand(2);
7733   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7734                                      DAG.getConstant(VTBits - 1, MVT::i8))
7735                        : DAG.getConstant(0, VT);
7736
7737   SDValue Tmp2, Tmp3;
7738   if (Op.getOpcode() == ISD::SHL_PARTS) {
7739     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7740     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7741   } else {
7742     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7743     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7744   }
7745
7746   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7747                                 DAG.getConstant(VTBits, MVT::i8));
7748   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7749                              AndNode, DAG.getConstant(0, MVT::i8));
7750
7751   SDValue Hi, Lo;
7752   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7753   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7754   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7755
7756   if (Op.getOpcode() == ISD::SHL_PARTS) {
7757     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7758     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7759   } else {
7760     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7761     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7762   }
7763
7764   SDValue Ops[2] = { Lo, Hi };
7765   return DAG.getMergeValues(Ops, 2, dl);
7766 }
7767
7768 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7769                                            SelectionDAG &DAG) const {
7770   EVT SrcVT = Op.getOperand(0).getValueType();
7771
7772   if (SrcVT.isVector())
7773     return SDValue();
7774
7775   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7776          "Unknown SINT_TO_FP to lower!");
7777
7778   // These are really Legal; return the operand so the caller accepts it as
7779   // Legal.
7780   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7781     return Op;
7782   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7783       Subtarget->is64Bit()) {
7784     return Op;
7785   }
7786
7787   DebugLoc dl = Op.getDebugLoc();
7788   unsigned Size = SrcVT.getSizeInBits()/8;
7789   MachineFunction &MF = DAG.getMachineFunction();
7790   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7791   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7792   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7793                                StackSlot,
7794                                MachinePointerInfo::getFixedStack(SSFI),
7795                                false, false, 0);
7796   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7797 }
7798
7799 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7800                                      SDValue StackSlot,
7801                                      SelectionDAG &DAG) const {
7802   // Build the FILD
7803   DebugLoc DL = Op.getDebugLoc();
7804   SDVTList Tys;
7805   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7806   if (useSSE)
7807     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7808   else
7809     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7810
7811   unsigned ByteSize = SrcVT.getSizeInBits()/8;
7812
7813   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7814   MachineMemOperand *MMO;
7815   if (FI) {
7816     int SSFI = FI->getIndex();
7817     MMO =
7818       DAG.getMachineFunction()
7819       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7820                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
7821   } else {
7822     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7823     StackSlot = StackSlot.getOperand(1);
7824   }
7825   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7826   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7827                                            X86ISD::FILD, DL,
7828                                            Tys, Ops, array_lengthof(Ops),
7829                                            SrcVT, MMO);
7830
7831   if (useSSE) {
7832     Chain = Result.getValue(1);
7833     SDValue InFlag = Result.getValue(2);
7834
7835     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7836     // shouldn't be necessary except that RFP cannot be live across
7837     // multiple blocks. When stackifier is fixed, they can be uncoupled.
7838     MachineFunction &MF = DAG.getMachineFunction();
7839     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7840     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7841     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7842     Tys = DAG.getVTList(MVT::Other);
7843     SDValue Ops[] = {
7844       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7845     };
7846     MachineMemOperand *MMO =
7847       DAG.getMachineFunction()
7848       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7849                             MachineMemOperand::MOStore, SSFISize, SSFISize);
7850
7851     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7852                                     Ops, array_lengthof(Ops),
7853                                     Op.getValueType(), MMO);
7854     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7855                          MachinePointerInfo::getFixedStack(SSFI),
7856                          false, false, false, 0);
7857   }
7858
7859   return Result;
7860 }
7861
7862 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7863 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7864                                                SelectionDAG &DAG) const {
7865   // This algorithm is not obvious. Here it is in C code, more or less:
7866   /*
7867     double uint64_to_double( uint32_t hi, uint32_t lo ) {
7868       static const __m128i exp = { 0x4330000045300000ULL, 0 };
7869       static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
7870
7871       // Copy ints to xmm registers.
7872       __m128i xh = _mm_cvtsi32_si128( hi );
7873       __m128i xl = _mm_cvtsi32_si128( lo );
7874
7875       // Combine into low half of a single xmm register.
7876       __m128i x = _mm_unpacklo_epi32( xh, xl );
7877       __m128d d;
7878       double sd;
7879
7880       // Merge in appropriate exponents to give the integer bits the right
7881       // magnitude.
7882       x = _mm_unpacklo_epi32( x, exp );
7883
7884       // Subtract away the biases to deal with the IEEE-754 double precision
7885       // implicit 1.
7886       d = _mm_sub_pd( (__m128d) x, bias );
7887
7888       // All conversions up to here are exact. The correctly rounded result is
7889       // calculated using the current rounding mode using the following
7890       // horizontal add.
7891       d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
7892       _mm_store_sd( &sd, d );   // Because we are returning doubles in XMM, this
7893                                 // store doesn't really need to be here (except
7894                                 // maybe to zero the other double)
7895       return sd;
7896     }
7897   */
7898
7899   DebugLoc dl = Op.getDebugLoc();
7900   LLVMContext *Context = DAG.getContext();
7901
7902   // Build some magic constants.
7903   std::vector<Constant*> CV0;
7904   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
7905   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
7906   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7907   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7908   Constant *C0 = ConstantVector::get(CV0);
7909   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7910
7911   std::vector<Constant*> CV1;
7912   CV1.push_back(
7913     ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7914   CV1.push_back(
7915     ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7916   Constant *C1 = ConstantVector::get(CV1);
7917   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7918
7919   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7920                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7921                                         Op.getOperand(0),
7922                                         DAG.getIntPtrConstant(1)));
7923   SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7924                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7925                                         Op.getOperand(0),
7926                                         DAG.getIntPtrConstant(0)));
7927   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
7928   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7929                               MachinePointerInfo::getConstantPool(),
7930                               false, false, false, 16);
7931   SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
7932   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
7933   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7934                               MachinePointerInfo::getConstantPool(),
7935                               false, false, false, 16);
7936   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7937
7938   // Add the halves; easiest way is to swap them into another reg first.
7939   int ShufMask[2] = { 1, -1 };
7940   SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
7941                                       DAG.getUNDEF(MVT::v2f64), ShufMask);
7942   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
7943   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
7944                      DAG.getIntPtrConstant(0));
7945 }
7946
7947 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7948 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7949                                                SelectionDAG &DAG) const {
7950   DebugLoc dl = Op.getDebugLoc();
7951   // FP constant to bias correct the final result.
7952   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7953                                    MVT::f64);
7954
7955   // Load the 32-bit value into an XMM register.
7956   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7957                              Op.getOperand(0));
7958
7959   // Zero out the upper parts of the register.
7960   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget->hasXMMInt(),
7961                                      DAG);
7962
7963   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7964                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7965                      DAG.getIntPtrConstant(0));
7966
7967   // Or the load with the bias.
7968   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7969                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7970                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7971                                                    MVT::v2f64, Load)),
7972                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7973                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7974                                                    MVT::v2f64, Bias)));
7975   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7976                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7977                    DAG.getIntPtrConstant(0));
7978
7979   // Subtract the bias.
7980   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7981
7982   // Handle final rounding.
7983   EVT DestVT = Op.getValueType();
7984
7985   if (DestVT.bitsLT(MVT::f64)) {
7986     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7987                        DAG.getIntPtrConstant(0));
7988   } else if (DestVT.bitsGT(MVT::f64)) {
7989     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7990   }
7991
7992   // Handle final rounding.
7993   return Sub;
7994 }
7995
7996 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7997                                            SelectionDAG &DAG) const {
7998   SDValue N0 = Op.getOperand(0);
7999   DebugLoc dl = Op.getDebugLoc();
8000
8001   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8002   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8003   // the optimization here.
8004   if (DAG.SignBitIsZero(N0))
8005     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8006
8007   EVT SrcVT = N0.getValueType();
8008   EVT DstVT = Op.getValueType();
8009   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8010     return LowerUINT_TO_FP_i64(Op, DAG);
8011   else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8012     return LowerUINT_TO_FP_i32(Op, DAG);
8013
8014   // Make a 64-bit buffer, and use it to build an FILD.
8015   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8016   if (SrcVT == MVT::i32) {
8017     SDValue WordOff = DAG.getConstant(4, getPointerTy());
8018     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8019                                      getPointerTy(), StackSlot, WordOff);
8020     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8021                                   StackSlot, MachinePointerInfo(),
8022                                   false, false, 0);
8023     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8024                                   OffsetSlot, MachinePointerInfo(),
8025                                   false, false, 0);
8026     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8027     return Fild;
8028   }
8029
8030   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8031   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8032                                 StackSlot, MachinePointerInfo(),
8033                                false, false, 0);
8034   // For i64 source, we need to add the appropriate power of 2 if the input
8035   // was negative.  This is the same as the optimization in
8036   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8037   // we must be careful to do the computation in x87 extended precision, not
8038   // in SSE. (The generic code can't know it's OK to do this, or how to.)
8039   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8040   MachineMemOperand *MMO =
8041     DAG.getMachineFunction()
8042     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8043                           MachineMemOperand::MOLoad, 8, 8);
8044
8045   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8046   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8047   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
8048                                          MVT::i64, MMO);
8049
8050   APInt FF(32, 0x5F800000ULL);
8051
8052   // Check whether the sign bit is set.
8053   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
8054                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8055                                  ISD::SETLT);
8056
8057   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8058   SDValue FudgePtr = DAG.getConstantPool(
8059                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8060                                          getPointerTy());
8061
8062   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8063   SDValue Zero = DAG.getIntPtrConstant(0);
8064   SDValue Four = DAG.getIntPtrConstant(4);
8065   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8066                                Zero, Four);
8067   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8068
8069   // Load the value out, extending it from f32 to f80.
8070   // FIXME: Avoid the extend by constructing the right constant pool?
8071   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8072                                  FudgePtr, MachinePointerInfo::getConstantPool(),
8073                                  MVT::f32, false, false, 4);
8074   // Extend everything to 80 bits to force it to be done on x87.
8075   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8076   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8077 }
8078
8079 std::pair<SDValue,SDValue> X86TargetLowering::
8080 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
8081   DebugLoc DL = Op.getDebugLoc();
8082
8083   EVT DstTy = Op.getValueType();
8084
8085   if (!IsSigned) {
8086     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8087     DstTy = MVT::i64;
8088   }
8089
8090   assert(DstTy.getSimpleVT() <= MVT::i64 &&
8091          DstTy.getSimpleVT() >= MVT::i16 &&
8092          "Unknown FP_TO_SINT to lower!");
8093
8094   // These are really Legal.
8095   if (DstTy == MVT::i32 &&
8096       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8097     return std::make_pair(SDValue(), SDValue());
8098   if (Subtarget->is64Bit() &&
8099       DstTy == MVT::i64 &&
8100       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8101     return std::make_pair(SDValue(), SDValue());
8102
8103   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
8104   // stack slot.
8105   MachineFunction &MF = DAG.getMachineFunction();
8106   unsigned MemSize = DstTy.getSizeInBits()/8;
8107   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8108   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8109
8110
8111
8112   unsigned Opc;
8113   switch (DstTy.getSimpleVT().SimpleTy) {
8114   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8115   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8116   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8117   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8118   }
8119
8120   SDValue Chain = DAG.getEntryNode();
8121   SDValue Value = Op.getOperand(0);
8122   EVT TheVT = Op.getOperand(0).getValueType();
8123   if (isScalarFPTypeInSSEReg(TheVT)) {
8124     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8125     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8126                          MachinePointerInfo::getFixedStack(SSFI),
8127                          false, false, 0);
8128     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8129     SDValue Ops[] = {
8130       Chain, StackSlot, DAG.getValueType(TheVT)
8131     };
8132
8133     MachineMemOperand *MMO =
8134       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8135                               MachineMemOperand::MOLoad, MemSize, MemSize);
8136     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
8137                                     DstTy, MMO);
8138     Chain = Value.getValue(1);
8139     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8140     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8141   }
8142
8143   MachineMemOperand *MMO =
8144     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8145                             MachineMemOperand::MOStore, MemSize, MemSize);
8146
8147   // Build the FP_TO_INT*_IN_MEM
8148   SDValue Ops[] = { Chain, Value, StackSlot };
8149   SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8150                                          Ops, 3, DstTy, MMO);
8151
8152   return std::make_pair(FIST, StackSlot);
8153 }
8154
8155 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8156                                            SelectionDAG &DAG) const {
8157   if (Op.getValueType().isVector())
8158     return SDValue();
8159
8160   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
8161   SDValue FIST = Vals.first, StackSlot = Vals.second;
8162   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8163   if (FIST.getNode() == 0) return Op;
8164
8165   // Load the result.
8166   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8167                      FIST, StackSlot, MachinePointerInfo(),
8168                      false, false, false, 0);
8169 }
8170
8171 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8172                                            SelectionDAG &DAG) const {
8173   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
8174   SDValue FIST = Vals.first, StackSlot = Vals.second;
8175   assert(FIST.getNode() && "Unexpected failure");
8176
8177   // Load the result.
8178   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8179                      FIST, StackSlot, MachinePointerInfo(),
8180                      false, false, false, 0);
8181 }
8182
8183 SDValue X86TargetLowering::LowerFABS(SDValue Op,
8184                                      SelectionDAG &DAG) const {
8185   LLVMContext *Context = DAG.getContext();
8186   DebugLoc dl = Op.getDebugLoc();
8187   EVT VT = Op.getValueType();
8188   EVT EltVT = VT;
8189   if (VT.isVector())
8190     EltVT = VT.getVectorElementType();
8191   std::vector<Constant*> CV;
8192   if (EltVT == MVT::f64) {
8193     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
8194     CV.push_back(C);
8195     CV.push_back(C);
8196   } else {
8197     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
8198     CV.push_back(C);
8199     CV.push_back(C);
8200     CV.push_back(C);
8201     CV.push_back(C);
8202   }
8203   Constant *C = ConstantVector::get(CV);
8204   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8205   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8206                              MachinePointerInfo::getConstantPool(),
8207                              false, false, false, 16);
8208   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8209 }
8210
8211 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8212   LLVMContext *Context = DAG.getContext();
8213   DebugLoc dl = Op.getDebugLoc();
8214   EVT VT = Op.getValueType();
8215   EVT EltVT = VT;
8216   if (VT.isVector())
8217     EltVT = VT.getVectorElementType();
8218   std::vector<Constant*> CV;
8219   if (EltVT == MVT::f64) {
8220     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8221     CV.push_back(C);
8222     CV.push_back(C);
8223   } else {
8224     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8225     CV.push_back(C);
8226     CV.push_back(C);
8227     CV.push_back(C);
8228     CV.push_back(C);
8229   }
8230   Constant *C = ConstantVector::get(CV);
8231   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8232   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8233                              MachinePointerInfo::getConstantPool(),
8234                              false, false, false, 16);
8235   if (VT.isVector()) {
8236     return DAG.getNode(ISD::BITCAST, dl, VT,
8237                        DAG.getNode(ISD::XOR, dl, MVT::v2i64,
8238                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8239                                 Op.getOperand(0)),
8240                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask)));
8241   } else {
8242     return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8243   }
8244 }
8245
8246 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8247   LLVMContext *Context = DAG.getContext();
8248   SDValue Op0 = Op.getOperand(0);
8249   SDValue Op1 = Op.getOperand(1);
8250   DebugLoc dl = Op.getDebugLoc();
8251   EVT VT = Op.getValueType();
8252   EVT SrcVT = Op1.getValueType();
8253
8254   // If second operand is smaller, extend it first.
8255   if (SrcVT.bitsLT(VT)) {
8256     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8257     SrcVT = VT;
8258   }
8259   // And if it is bigger, shrink it first.
8260   if (SrcVT.bitsGT(VT)) {
8261     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8262     SrcVT = VT;
8263   }
8264
8265   // At this point the operands and the result should have the same
8266   // type, and that won't be f80 since that is not custom lowered.
8267
8268   // First get the sign bit of second operand.
8269   std::vector<Constant*> CV;
8270   if (SrcVT == MVT::f64) {
8271     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8272     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8273   } else {
8274     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8275     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8276     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8277     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8278   }
8279   Constant *C = ConstantVector::get(CV);
8280   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8281   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8282                               MachinePointerInfo::getConstantPool(),
8283                               false, false, false, 16);
8284   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8285
8286   // Shift sign bit right or left if the two operands have different types.
8287   if (SrcVT.bitsGT(VT)) {
8288     // Op0 is MVT::f32, Op1 is MVT::f64.
8289     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8290     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8291                           DAG.getConstant(32, MVT::i32));
8292     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8293     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8294                           DAG.getIntPtrConstant(0));
8295   }
8296
8297   // Clear first operand sign bit.
8298   CV.clear();
8299   if (VT == MVT::f64) {
8300     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8301     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8302   } else {
8303     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8304     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8305     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8306     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8307   }
8308   C = ConstantVector::get(CV);
8309   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8310   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8311                               MachinePointerInfo::getConstantPool(),
8312                               false, false, false, 16);
8313   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8314
8315   // Or the value with the sign bit.
8316   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8317 }
8318
8319 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
8320   SDValue N0 = Op.getOperand(0);
8321   DebugLoc dl = Op.getDebugLoc();
8322   EVT VT = Op.getValueType();
8323
8324   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8325   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8326                                   DAG.getConstant(1, VT));
8327   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8328 }
8329
8330 /// Emit nodes that will be selected as "test Op0,Op0", or something
8331 /// equivalent.
8332 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8333                                     SelectionDAG &DAG) const {
8334   DebugLoc dl = Op.getDebugLoc();
8335
8336   // CF and OF aren't always set the way we want. Determine which
8337   // of these we need.
8338   bool NeedCF = false;
8339   bool NeedOF = false;
8340   switch (X86CC) {
8341   default: break;
8342   case X86::COND_A: case X86::COND_AE:
8343   case X86::COND_B: case X86::COND_BE:
8344     NeedCF = true;
8345     break;
8346   case X86::COND_G: case X86::COND_GE:
8347   case X86::COND_L: case X86::COND_LE:
8348   case X86::COND_O: case X86::COND_NO:
8349     NeedOF = true;
8350     break;
8351   }
8352
8353   // See if we can use the EFLAGS value from the operand instead of
8354   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8355   // we prove that the arithmetic won't overflow, we can't use OF or CF.
8356   if (Op.getResNo() != 0 || NeedOF || NeedCF)
8357     // Emit a CMP with 0, which is the TEST pattern.
8358     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8359                        DAG.getConstant(0, Op.getValueType()));
8360
8361   unsigned Opcode = 0;
8362   unsigned NumOperands = 0;
8363   switch (Op.getNode()->getOpcode()) {
8364   case ISD::ADD:
8365     // Due to an isel shortcoming, be conservative if this add is likely to be
8366     // selected as part of a load-modify-store instruction. When the root node
8367     // in a match is a store, isel doesn't know how to remap non-chain non-flag
8368     // uses of other nodes in the match, such as the ADD in this case. This
8369     // leads to the ADD being left around and reselected, with the result being
8370     // two adds in the output.  Alas, even if none our users are stores, that
8371     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
8372     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
8373     // climbing the DAG back to the root, and it doesn't seem to be worth the
8374     // effort.
8375     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8376          UE = Op.getNode()->use_end(); UI != UE; ++UI)
8377       if (UI->getOpcode() != ISD::CopyToReg &&
8378           UI->getOpcode() != ISD::SETCC &&
8379           UI->getOpcode() != ISD::STORE)
8380         goto default_case;
8381
8382     if (ConstantSDNode *C =
8383         dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
8384       // An add of one will be selected as an INC.
8385       if (C->getAPIntValue() == 1) {
8386         Opcode = X86ISD::INC;
8387         NumOperands = 1;
8388         break;
8389       }
8390
8391       // An add of negative one (subtract of one) will be selected as a DEC.
8392       if (C->getAPIntValue().isAllOnesValue()) {
8393         Opcode = X86ISD::DEC;
8394         NumOperands = 1;
8395         break;
8396       }
8397     }
8398
8399     // Otherwise use a regular EFLAGS-setting add.
8400     Opcode = X86ISD::ADD;
8401     NumOperands = 2;
8402     break;
8403   case ISD::AND: {
8404     // If the primary and result isn't used, don't bother using X86ISD::AND,
8405     // because a TEST instruction will be better.
8406     bool NonFlagUse = false;
8407     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8408            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8409       SDNode *User = *UI;
8410       unsigned UOpNo = UI.getOperandNo();
8411       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8412         // Look pass truncate.
8413         UOpNo = User->use_begin().getOperandNo();
8414         User = *User->use_begin();
8415       }
8416
8417       if (User->getOpcode() != ISD::BRCOND &&
8418           User->getOpcode() != ISD::SETCC &&
8419           (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
8420         NonFlagUse = true;
8421         break;
8422       }
8423     }
8424
8425     if (!NonFlagUse)
8426       break;
8427   }
8428     // FALL THROUGH
8429   case ISD::SUB:
8430   case ISD::OR:
8431   case ISD::XOR:
8432     // Due to the ISEL shortcoming noted above, be conservative if this op is
8433     // likely to be selected as part of a load-modify-store instruction.
8434     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8435            UE = Op.getNode()->use_end(); UI != UE; ++UI)
8436       if (UI->getOpcode() == ISD::STORE)
8437         goto default_case;
8438
8439     // Otherwise use a regular EFLAGS-setting instruction.
8440     switch (Op.getNode()->getOpcode()) {
8441     default: llvm_unreachable("unexpected operator!");
8442     case ISD::SUB: Opcode = X86ISD::SUB; break;
8443     case ISD::OR:  Opcode = X86ISD::OR;  break;
8444     case ISD::XOR: Opcode = X86ISD::XOR; break;
8445     case ISD::AND: Opcode = X86ISD::AND; break;
8446     }
8447
8448     NumOperands = 2;
8449     break;
8450   case X86ISD::ADD:
8451   case X86ISD::SUB:
8452   case X86ISD::INC:
8453   case X86ISD::DEC:
8454   case X86ISD::OR:
8455   case X86ISD::XOR:
8456   case X86ISD::AND:
8457     return SDValue(Op.getNode(), 1);
8458   default:
8459   default_case:
8460     break;
8461   }
8462
8463   if (Opcode == 0)
8464     // Emit a CMP with 0, which is the TEST pattern.
8465     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8466                        DAG.getConstant(0, Op.getValueType()));
8467
8468   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8469   SmallVector<SDValue, 4> Ops;
8470   for (unsigned i = 0; i != NumOperands; ++i)
8471     Ops.push_back(Op.getOperand(i));
8472
8473   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8474   DAG.ReplaceAllUsesWith(Op, New);
8475   return SDValue(New.getNode(), 1);
8476 }
8477
8478 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8479 /// equivalent.
8480 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8481                                    SelectionDAG &DAG) const {
8482   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8483     if (C->getAPIntValue() == 0)
8484       return EmitTest(Op0, X86CC, DAG);
8485
8486   DebugLoc dl = Op0.getDebugLoc();
8487   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8488 }
8489
8490 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8491 /// if it's possible.
8492 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8493                                      DebugLoc dl, SelectionDAG &DAG) const {
8494   SDValue Op0 = And.getOperand(0);
8495   SDValue Op1 = And.getOperand(1);
8496   if (Op0.getOpcode() == ISD::TRUNCATE)
8497     Op0 = Op0.getOperand(0);
8498   if (Op1.getOpcode() == ISD::TRUNCATE)
8499     Op1 = Op1.getOperand(0);
8500
8501   SDValue LHS, RHS;
8502   if (Op1.getOpcode() == ISD::SHL)
8503     std::swap(Op0, Op1);
8504   if (Op0.getOpcode() == ISD::SHL) {
8505     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8506       if (And00C->getZExtValue() == 1) {
8507         // If we looked past a truncate, check that it's only truncating away
8508         // known zeros.
8509         unsigned BitWidth = Op0.getValueSizeInBits();
8510         unsigned AndBitWidth = And.getValueSizeInBits();
8511         if (BitWidth > AndBitWidth) {
8512           APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
8513           DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
8514           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8515             return SDValue();
8516         }
8517         LHS = Op1;
8518         RHS = Op0.getOperand(1);
8519       }
8520   } else if (Op1.getOpcode() == ISD::Constant) {
8521     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8522     uint64_t AndRHSVal = AndRHS->getZExtValue();
8523     SDValue AndLHS = Op0;
8524
8525     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
8526       LHS = AndLHS.getOperand(0);
8527       RHS = AndLHS.getOperand(1);
8528     }
8529
8530     // Use BT if the immediate can't be encoded in a TEST instruction.
8531     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
8532       LHS = AndLHS;
8533       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
8534     }
8535   }
8536
8537   if (LHS.getNode()) {
8538     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
8539     // instruction.  Since the shift amount is in-range-or-undefined, we know
8540     // that doing a bittest on the i32 value is ok.  We extend to i32 because
8541     // the encoding for the i16 version is larger than the i32 version.
8542     // Also promote i16 to i32 for performance / code size reason.
8543     if (LHS.getValueType() == MVT::i8 ||
8544         LHS.getValueType() == MVT::i16)
8545       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8546
8547     // If the operand types disagree, extend the shift amount to match.  Since
8548     // BT ignores high bits (like shifts) we can use anyextend.
8549     if (LHS.getValueType() != RHS.getValueType())
8550       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8551
8552     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8553     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8554     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8555                        DAG.getConstant(Cond, MVT::i8), BT);
8556   }
8557
8558   return SDValue();
8559 }
8560
8561 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8562
8563   if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8564
8565   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8566   SDValue Op0 = Op.getOperand(0);
8567   SDValue Op1 = Op.getOperand(1);
8568   DebugLoc dl = Op.getDebugLoc();
8569   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8570
8571   // Optimize to BT if possible.
8572   // Lower (X & (1 << N)) == 0 to BT(X, N).
8573   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8574   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8575   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8576       Op1.getOpcode() == ISD::Constant &&
8577       cast<ConstantSDNode>(Op1)->isNullValue() &&
8578       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8579     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8580     if (NewSetCC.getNode())
8581       return NewSetCC;
8582   }
8583
8584   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
8585   // these.
8586   if (Op1.getOpcode() == ISD::Constant &&
8587       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8588        cast<ConstantSDNode>(Op1)->isNullValue()) &&
8589       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8590
8591     // If the input is a setcc, then reuse the input setcc or use a new one with
8592     // the inverted condition.
8593     if (Op0.getOpcode() == X86ISD::SETCC) {
8594       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8595       bool Invert = (CC == ISD::SETNE) ^
8596         cast<ConstantSDNode>(Op1)->isNullValue();
8597       if (!Invert) return Op0;
8598
8599       CCode = X86::GetOppositeBranchCondition(CCode);
8600       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8601                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8602     }
8603   }
8604
8605   bool isFP = Op1.getValueType().isFloatingPoint();
8606   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8607   if (X86CC == X86::COND_INVALID)
8608     return SDValue();
8609
8610   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8611   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8612                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8613 }
8614
8615 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8616 // ones, and then concatenate the result back.
8617 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
8618   EVT VT = Op.getValueType();
8619
8620   assert(VT.getSizeInBits() == 256 && Op.getOpcode() == ISD::SETCC &&
8621          "Unsupported value type for operation");
8622
8623   int NumElems = VT.getVectorNumElements();
8624   DebugLoc dl = Op.getDebugLoc();
8625   SDValue CC = Op.getOperand(2);
8626   SDValue Idx0 = DAG.getConstant(0, MVT::i32);
8627   SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
8628
8629   // Extract the LHS vectors
8630   SDValue LHS = Op.getOperand(0);
8631   SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
8632   SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
8633
8634   // Extract the RHS vectors
8635   SDValue RHS = Op.getOperand(1);
8636   SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl);
8637   SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl);
8638
8639   // Issue the operation on the smaller types and concatenate the result back
8640   MVT EltVT = VT.getVectorElementType().getSimpleVT();
8641   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8642   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8643                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8644                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8645 }
8646
8647
8648 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8649   SDValue Cond;
8650   SDValue Op0 = Op.getOperand(0);
8651   SDValue Op1 = Op.getOperand(1);
8652   SDValue CC = Op.getOperand(2);
8653   EVT VT = Op.getValueType();
8654   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8655   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8656   DebugLoc dl = Op.getDebugLoc();
8657
8658   if (isFP) {
8659     unsigned SSECC = 8;
8660     EVT EltVT = Op0.getValueType().getVectorElementType();
8661     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
8662
8663     unsigned Opc = EltVT == MVT::f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
8664     bool Swap = false;
8665
8666     // SSE Condition code mapping:
8667     //  0 - EQ
8668     //  1 - LT
8669     //  2 - LE
8670     //  3 - UNORD
8671     //  4 - NEQ
8672     //  5 - NLT
8673     //  6 - NLE
8674     //  7 - ORD
8675     switch (SetCCOpcode) {
8676     default: break;
8677     case ISD::SETOEQ:
8678     case ISD::SETEQ:  SSECC = 0; break;
8679     case ISD::SETOGT:
8680     case ISD::SETGT: Swap = true; // Fallthrough
8681     case ISD::SETLT:
8682     case ISD::SETOLT: SSECC = 1; break;
8683     case ISD::SETOGE:
8684     case ISD::SETGE: Swap = true; // Fallthrough
8685     case ISD::SETLE:
8686     case ISD::SETOLE: SSECC = 2; break;
8687     case ISD::SETUO:  SSECC = 3; break;
8688     case ISD::SETUNE:
8689     case ISD::SETNE:  SSECC = 4; break;
8690     case ISD::SETULE: Swap = true;
8691     case ISD::SETUGE: SSECC = 5; break;
8692     case ISD::SETULT: Swap = true;
8693     case ISD::SETUGT: SSECC = 6; break;
8694     case ISD::SETO:   SSECC = 7; break;
8695     }
8696     if (Swap)
8697       std::swap(Op0, Op1);
8698
8699     // In the two special cases we can't handle, emit two comparisons.
8700     if (SSECC == 8) {
8701       if (SetCCOpcode == ISD::SETUEQ) {
8702         SDValue UNORD, EQ;
8703         UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
8704         EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
8705         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
8706       } else if (SetCCOpcode == ISD::SETONE) {
8707         SDValue ORD, NEQ;
8708         ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
8709         NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
8710         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
8711       }
8712       llvm_unreachable("Illegal FP comparison");
8713     }
8714     // Handle all other FP comparisons here.
8715     return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
8716   }
8717
8718   // Break 256-bit integer vector compare into smaller ones.
8719   if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2())
8720     return Lower256IntVSETCC(Op, DAG);
8721
8722   // We are handling one of the integer comparisons here.  Since SSE only has
8723   // GT and EQ comparisons for integer, swapping operands and multiple
8724   // operations may be required for some comparisons.
8725   unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
8726   bool Swap = false, Invert = false, FlipSigns = false;
8727
8728   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
8729   default: break;
8730   case MVT::i8:   EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
8731   case MVT::i16:  EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
8732   case MVT::i32:  EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
8733   case MVT::i64:  EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
8734   }
8735
8736   switch (SetCCOpcode) {
8737   default: break;
8738   case ISD::SETNE:  Invert = true;
8739   case ISD::SETEQ:  Opc = EQOpc; break;
8740   case ISD::SETLT:  Swap = true;
8741   case ISD::SETGT:  Opc = GTOpc; break;
8742   case ISD::SETGE:  Swap = true;
8743   case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
8744   case ISD::SETULT: Swap = true;
8745   case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
8746   case ISD::SETUGE: Swap = true;
8747   case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
8748   }
8749   if (Swap)
8750     std::swap(Op0, Op1);
8751
8752   // Check that the operation in question is available (most are plain SSE2,
8753   // but PCMPGTQ and PCMPEQQ have different requirements).
8754   if (Opc == X86ISD::PCMPGTQ && !Subtarget->hasSSE42orAVX())
8755     return SDValue();
8756   if (Opc == X86ISD::PCMPEQQ && !Subtarget->hasSSE41orAVX())
8757     return SDValue();
8758
8759   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
8760   // bits of the inputs before performing those operations.
8761   if (FlipSigns) {
8762     EVT EltVT = VT.getVectorElementType();
8763     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
8764                                       EltVT);
8765     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
8766     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
8767                                     SignBits.size());
8768     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
8769     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
8770   }
8771
8772   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
8773
8774   // If the logical-not of the result is required, perform that now.
8775   if (Invert)
8776     Result = DAG.getNOT(dl, Result, VT);
8777
8778   return Result;
8779 }
8780
8781 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
8782 static bool isX86LogicalCmp(SDValue Op) {
8783   unsigned Opc = Op.getNode()->getOpcode();
8784   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
8785     return true;
8786   if (Op.getResNo() == 1 &&
8787       (Opc == X86ISD::ADD ||
8788        Opc == X86ISD::SUB ||
8789        Opc == X86ISD::ADC ||
8790        Opc == X86ISD::SBB ||
8791        Opc == X86ISD::SMUL ||
8792        Opc == X86ISD::UMUL ||
8793        Opc == X86ISD::INC ||
8794        Opc == X86ISD::DEC ||
8795        Opc == X86ISD::OR ||
8796        Opc == X86ISD::XOR ||
8797        Opc == X86ISD::AND))
8798     return true;
8799
8800   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
8801     return true;
8802
8803   return false;
8804 }
8805
8806 static bool isZero(SDValue V) {
8807   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8808   return C && C->isNullValue();
8809 }
8810
8811 static bool isAllOnes(SDValue V) {
8812   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8813   return C && C->isAllOnesValue();
8814 }
8815
8816 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8817   bool addTest = true;
8818   SDValue Cond  = Op.getOperand(0);
8819   SDValue Op1 = Op.getOperand(1);
8820   SDValue Op2 = Op.getOperand(2);
8821   DebugLoc DL = Op.getDebugLoc();
8822   SDValue CC;
8823
8824   if (Cond.getOpcode() == ISD::SETCC) {
8825     SDValue NewCond = LowerSETCC(Cond, DAG);
8826     if (NewCond.getNode())
8827       Cond = NewCond;
8828   }
8829
8830   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
8831   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
8832   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
8833   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
8834   if (Cond.getOpcode() == X86ISD::SETCC &&
8835       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
8836       isZero(Cond.getOperand(1).getOperand(1))) {
8837     SDValue Cmp = Cond.getOperand(1);
8838
8839     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
8840
8841     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
8842         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
8843       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
8844
8845       SDValue CmpOp0 = Cmp.getOperand(0);
8846       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
8847                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
8848
8849       SDValue Res =   // Res = 0 or -1.
8850         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8851                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
8852
8853       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
8854         Res = DAG.getNOT(DL, Res, Res.getValueType());
8855
8856       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
8857       if (N2C == 0 || !N2C->isNullValue())
8858         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
8859       return Res;
8860     }
8861   }
8862
8863   // Look past (and (setcc_carry (cmp ...)), 1).
8864   if (Cond.getOpcode() == ISD::AND &&
8865       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8866     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8867     if (C && C->getAPIntValue() == 1)
8868       Cond = Cond.getOperand(0);
8869   }
8870
8871   // If condition flag is set by a X86ISD::CMP, then use it as the condition
8872   // setting operand in place of the X86ISD::SETCC.
8873   unsigned CondOpcode = Cond.getOpcode();
8874   if (CondOpcode == X86ISD::SETCC ||
8875       CondOpcode == X86ISD::SETCC_CARRY) {
8876     CC = Cond.getOperand(0);
8877
8878     SDValue Cmp = Cond.getOperand(1);
8879     unsigned Opc = Cmp.getOpcode();
8880     EVT VT = Op.getValueType();
8881
8882     bool IllegalFPCMov = false;
8883     if (VT.isFloatingPoint() && !VT.isVector() &&
8884         !isScalarFPTypeInSSEReg(VT))  // FPStack?
8885       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
8886
8887     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
8888         Opc == X86ISD::BT) { // FIXME
8889       Cond = Cmp;
8890       addTest = false;
8891     }
8892   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
8893              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
8894              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
8895               Cond.getOperand(0).getValueType() != MVT::i8)) {
8896     SDValue LHS = Cond.getOperand(0);
8897     SDValue RHS = Cond.getOperand(1);
8898     unsigned X86Opcode;
8899     unsigned X86Cond;
8900     SDVTList VTs;
8901     switch (CondOpcode) {
8902     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
8903     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
8904     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
8905     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
8906     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
8907     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
8908     default: llvm_unreachable("unexpected overflowing operator");
8909     }
8910     if (CondOpcode == ISD::UMULO)
8911       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
8912                           MVT::i32);
8913     else
8914       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
8915
8916     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
8917
8918     if (CondOpcode == ISD::UMULO)
8919       Cond = X86Op.getValue(2);
8920     else
8921       Cond = X86Op.getValue(1);
8922
8923     CC = DAG.getConstant(X86Cond, MVT::i8);
8924     addTest = false;
8925   }
8926
8927   if (addTest) {
8928     // Look pass the truncate.
8929     if (Cond.getOpcode() == ISD::TRUNCATE)
8930       Cond = Cond.getOperand(0);
8931
8932     // We know the result of AND is compared against zero. Try to match
8933     // it to BT.
8934     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8935       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
8936       if (NewSetCC.getNode()) {
8937         CC = NewSetCC.getOperand(0);
8938         Cond = NewSetCC.getOperand(1);
8939         addTest = false;
8940       }
8941     }
8942   }
8943
8944   if (addTest) {
8945     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8946     Cond = EmitTest(Cond, X86::COND_NE, DAG);
8947   }
8948
8949   // a <  b ? -1 :  0 -> RES = ~setcc_carry
8950   // a <  b ?  0 : -1 -> RES = setcc_carry
8951   // a >= b ? -1 :  0 -> RES = setcc_carry
8952   // a >= b ?  0 : -1 -> RES = ~setcc_carry
8953   if (Cond.getOpcode() == X86ISD::CMP) {
8954     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
8955
8956     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
8957         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
8958       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8959                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
8960       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
8961         return DAG.getNOT(DL, Res, Res.getValueType());
8962       return Res;
8963     }
8964   }
8965
8966   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
8967   // condition is true.
8968   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
8969   SDValue Ops[] = { Op2, Op1, CC, Cond };
8970   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
8971 }
8972
8973 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
8974 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
8975 // from the AND / OR.
8976 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
8977   Opc = Op.getOpcode();
8978   if (Opc != ISD::OR && Opc != ISD::AND)
8979     return false;
8980   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8981           Op.getOperand(0).hasOneUse() &&
8982           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
8983           Op.getOperand(1).hasOneUse());
8984 }
8985
8986 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
8987 // 1 and that the SETCC node has a single use.
8988 static bool isXor1OfSetCC(SDValue Op) {
8989   if (Op.getOpcode() != ISD::XOR)
8990     return false;
8991   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8992   if (N1C && N1C->getAPIntValue() == 1) {
8993     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8994       Op.getOperand(0).hasOneUse();
8995   }
8996   return false;
8997 }
8998
8999 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
9000   bool addTest = true;
9001   SDValue Chain = Op.getOperand(0);
9002   SDValue Cond  = Op.getOperand(1);
9003   SDValue Dest  = Op.getOperand(2);
9004   DebugLoc dl = Op.getDebugLoc();
9005   SDValue CC;
9006   bool Inverted = false;
9007
9008   if (Cond.getOpcode() == ISD::SETCC) {
9009     // Check for setcc([su]{add,sub,mul}o == 0).
9010     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
9011         isa<ConstantSDNode>(Cond.getOperand(1)) &&
9012         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
9013         Cond.getOperand(0).getResNo() == 1 &&
9014         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
9015          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
9016          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
9017          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
9018          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
9019          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
9020       Inverted = true;
9021       Cond = Cond.getOperand(0);
9022     } else {
9023       SDValue NewCond = LowerSETCC(Cond, DAG);
9024       if (NewCond.getNode())
9025         Cond = NewCond;
9026     }
9027   }
9028 #if 0
9029   // FIXME: LowerXALUO doesn't handle these!!
9030   else if (Cond.getOpcode() == X86ISD::ADD  ||
9031            Cond.getOpcode() == X86ISD::SUB  ||
9032            Cond.getOpcode() == X86ISD::SMUL ||
9033            Cond.getOpcode() == X86ISD::UMUL)
9034     Cond = LowerXALUO(Cond, DAG);
9035 #endif
9036
9037   // Look pass (and (setcc_carry (cmp ...)), 1).
9038   if (Cond.getOpcode() == ISD::AND &&
9039       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9040     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9041     if (C && C->getAPIntValue() == 1)
9042       Cond = Cond.getOperand(0);
9043   }
9044
9045   // If condition flag is set by a X86ISD::CMP, then use it as the condition
9046   // setting operand in place of the X86ISD::SETCC.
9047   unsigned CondOpcode = Cond.getOpcode();
9048   if (CondOpcode == X86ISD::SETCC ||
9049       CondOpcode == X86ISD::SETCC_CARRY) {
9050     CC = Cond.getOperand(0);
9051
9052     SDValue Cmp = Cond.getOperand(1);
9053     unsigned Opc = Cmp.getOpcode();
9054     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9055     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9056       Cond = Cmp;
9057       addTest = false;
9058     } else {
9059       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9060       default: break;
9061       case X86::COND_O:
9062       case X86::COND_B:
9063         // These can only come from an arithmetic instruction with overflow,
9064         // e.g. SADDO, UADDO.
9065         Cond = Cond.getNode()->getOperand(1);
9066         addTest = false;
9067         break;
9068       }
9069     }
9070   }
9071   CondOpcode = Cond.getOpcode();
9072   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9073       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9074       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9075        Cond.getOperand(0).getValueType() != MVT::i8)) {
9076     SDValue LHS = Cond.getOperand(0);
9077     SDValue RHS = Cond.getOperand(1);
9078     unsigned X86Opcode;
9079     unsigned X86Cond;
9080     SDVTList VTs;
9081     switch (CondOpcode) {
9082     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9083     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9084     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9085     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9086     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9087     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9088     default: llvm_unreachable("unexpected overflowing operator");
9089     }
9090     if (Inverted)
9091       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9092     if (CondOpcode == ISD::UMULO)
9093       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9094                           MVT::i32);
9095     else
9096       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9097
9098     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9099
9100     if (CondOpcode == ISD::UMULO)
9101       Cond = X86Op.getValue(2);
9102     else
9103       Cond = X86Op.getValue(1);
9104
9105     CC = DAG.getConstant(X86Cond, MVT::i8);
9106     addTest = false;
9107   } else {
9108     unsigned CondOpc;
9109     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9110       SDValue Cmp = Cond.getOperand(0).getOperand(1);
9111       if (CondOpc == ISD::OR) {
9112         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9113         // two branches instead of an explicit OR instruction with a
9114         // separate test.
9115         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9116             isX86LogicalCmp(Cmp)) {
9117           CC = Cond.getOperand(0).getOperand(0);
9118           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9119                               Chain, Dest, CC, Cmp);
9120           CC = Cond.getOperand(1).getOperand(0);
9121           Cond = Cmp;
9122           addTest = false;
9123         }
9124       } else { // ISD::AND
9125         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9126         // two branches instead of an explicit AND instruction with a
9127         // separate test. However, we only do this if this block doesn't
9128         // have a fall-through edge, because this requires an explicit
9129         // jmp when the condition is false.
9130         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9131             isX86LogicalCmp(Cmp) &&
9132             Op.getNode()->hasOneUse()) {
9133           X86::CondCode CCode =
9134             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9135           CCode = X86::GetOppositeBranchCondition(CCode);
9136           CC = DAG.getConstant(CCode, MVT::i8);
9137           SDNode *User = *Op.getNode()->use_begin();
9138           // Look for an unconditional branch following this conditional branch.
9139           // We need this because we need to reverse the successors in order
9140           // to implement FCMP_OEQ.
9141           if (User->getOpcode() == ISD::BR) {
9142             SDValue FalseBB = User->getOperand(1);
9143             SDNode *NewBR =
9144               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9145             assert(NewBR == User);
9146             (void)NewBR;
9147             Dest = FalseBB;
9148
9149             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9150                                 Chain, Dest, CC, Cmp);
9151             X86::CondCode CCode =
9152               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9153             CCode = X86::GetOppositeBranchCondition(CCode);
9154             CC = DAG.getConstant(CCode, MVT::i8);
9155             Cond = Cmp;
9156             addTest = false;
9157           }
9158         }
9159       }
9160     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9161       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9162       // It should be transformed during dag combiner except when the condition
9163       // is set by a arithmetics with overflow node.
9164       X86::CondCode CCode =
9165         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9166       CCode = X86::GetOppositeBranchCondition(CCode);
9167       CC = DAG.getConstant(CCode, MVT::i8);
9168       Cond = Cond.getOperand(0).getOperand(1);
9169       addTest = false;
9170     } else if (Cond.getOpcode() == ISD::SETCC &&
9171                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9172       // For FCMP_OEQ, we can emit
9173       // two branches instead of an explicit AND instruction with a
9174       // separate test. However, we only do this if this block doesn't
9175       // have a fall-through edge, because this requires an explicit
9176       // jmp when the condition is false.
9177       if (Op.getNode()->hasOneUse()) {
9178         SDNode *User = *Op.getNode()->use_begin();
9179         // Look for an unconditional branch following this conditional branch.
9180         // We need this because we need to reverse the successors in order
9181         // to implement FCMP_OEQ.
9182         if (User->getOpcode() == ISD::BR) {
9183           SDValue FalseBB = User->getOperand(1);
9184           SDNode *NewBR =
9185             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9186           assert(NewBR == User);
9187           (void)NewBR;
9188           Dest = FalseBB;
9189
9190           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9191                                     Cond.getOperand(0), Cond.getOperand(1));
9192           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9193           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9194                               Chain, Dest, CC, Cmp);
9195           CC = DAG.getConstant(X86::COND_P, MVT::i8);
9196           Cond = Cmp;
9197           addTest = false;
9198         }
9199       }
9200     } else if (Cond.getOpcode() == ISD::SETCC &&
9201                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9202       // For FCMP_UNE, we can emit
9203       // two branches instead of an explicit AND instruction with a
9204       // separate test. However, we only do this if this block doesn't
9205       // have a fall-through edge, because this requires an explicit
9206       // jmp when the condition is false.
9207       if (Op.getNode()->hasOneUse()) {
9208         SDNode *User = *Op.getNode()->use_begin();
9209         // Look for an unconditional branch following this conditional branch.
9210         // We need this because we need to reverse the successors in order
9211         // to implement FCMP_UNE.
9212         if (User->getOpcode() == ISD::BR) {
9213           SDValue FalseBB = User->getOperand(1);
9214           SDNode *NewBR =
9215             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9216           assert(NewBR == User);
9217           (void)NewBR;
9218
9219           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9220                                     Cond.getOperand(0), Cond.getOperand(1));
9221           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9222           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9223                               Chain, Dest, CC, Cmp);
9224           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9225           Cond = Cmp;
9226           addTest = false;
9227           Dest = FalseBB;
9228         }
9229       }
9230     }
9231   }
9232
9233   if (addTest) {
9234     // Look pass the truncate.
9235     if (Cond.getOpcode() == ISD::TRUNCATE)
9236       Cond = Cond.getOperand(0);
9237
9238     // We know the result of AND is compared against zero. Try to match
9239     // it to BT.
9240     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9241       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9242       if (NewSetCC.getNode()) {
9243         CC = NewSetCC.getOperand(0);
9244         Cond = NewSetCC.getOperand(1);
9245         addTest = false;
9246       }
9247     }
9248   }
9249
9250   if (addTest) {
9251     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9252     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9253   }
9254   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9255                      Chain, Dest, CC, Cond);
9256 }
9257
9258
9259 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
9260 // Calls to _alloca is needed to probe the stack when allocating more than 4k
9261 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
9262 // that the guard pages used by the OS virtual memory manager are allocated in
9263 // correct sequence.
9264 SDValue
9265 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9266                                            SelectionDAG &DAG) const {
9267   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
9268           EnableSegmentedStacks) &&
9269          "This should be used only on Windows targets or when segmented stacks "
9270          "are being used");
9271   assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
9272   DebugLoc dl = Op.getDebugLoc();
9273
9274   // Get the inputs.
9275   SDValue Chain = Op.getOperand(0);
9276   SDValue Size  = Op.getOperand(1);
9277   // FIXME: Ensure alignment here
9278
9279   bool Is64Bit = Subtarget->is64Bit();
9280   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
9281
9282   if (EnableSegmentedStacks) {
9283     MachineFunction &MF = DAG.getMachineFunction();
9284     MachineRegisterInfo &MRI = MF.getRegInfo();
9285
9286     if (Is64Bit) {
9287       // The 64 bit implementation of segmented stacks needs to clobber both r10
9288       // r11. This makes it impossible to use it along with nested parameters.
9289       const Function *F = MF.getFunction();
9290
9291       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9292            I != E; I++)
9293         if (I->hasNestAttr())
9294           report_fatal_error("Cannot use segmented stacks with functions that "
9295                              "have nested arguments.");
9296     }
9297
9298     const TargetRegisterClass *AddrRegClass =
9299       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9300     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9301     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9302     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9303                                 DAG.getRegister(Vreg, SPTy));
9304     SDValue Ops1[2] = { Value, Chain };
9305     return DAG.getMergeValues(Ops1, 2, dl);
9306   } else {
9307     SDValue Flag;
9308     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9309
9310     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9311     Flag = Chain.getValue(1);
9312     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9313
9314     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
9315     Flag = Chain.getValue(1);
9316
9317     Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
9318
9319     SDValue Ops1[2] = { Chain.getValue(0), Chain };
9320     return DAG.getMergeValues(Ops1, 2, dl);
9321   }
9322 }
9323
9324 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9325   MachineFunction &MF = DAG.getMachineFunction();
9326   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9327
9328   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9329   DebugLoc DL = Op.getDebugLoc();
9330
9331   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9332     // vastart just stores the address of the VarArgsFrameIndex slot into the
9333     // memory location argument.
9334     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9335                                    getPointerTy());
9336     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9337                         MachinePointerInfo(SV), false, false, 0);
9338   }
9339
9340   // __va_list_tag:
9341   //   gp_offset         (0 - 6 * 8)
9342   //   fp_offset         (48 - 48 + 8 * 16)
9343   //   overflow_arg_area (point to parameters coming in memory).
9344   //   reg_save_area
9345   SmallVector<SDValue, 8> MemOps;
9346   SDValue FIN = Op.getOperand(1);
9347   // Store gp_offset
9348   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9349                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9350                                                MVT::i32),
9351                                FIN, MachinePointerInfo(SV), false, false, 0);
9352   MemOps.push_back(Store);
9353
9354   // Store fp_offset
9355   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9356                     FIN, DAG.getIntPtrConstant(4));
9357   Store = DAG.getStore(Op.getOperand(0), DL,
9358                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9359                                        MVT::i32),
9360                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
9361   MemOps.push_back(Store);
9362
9363   // Store ptr to overflow_arg_area
9364   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9365                     FIN, DAG.getIntPtrConstant(4));
9366   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9367                                     getPointerTy());
9368   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9369                        MachinePointerInfo(SV, 8),
9370                        false, false, 0);
9371   MemOps.push_back(Store);
9372
9373   // Store ptr to reg_save_area.
9374   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9375                     FIN, DAG.getIntPtrConstant(8));
9376   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9377                                     getPointerTy());
9378   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9379                        MachinePointerInfo(SV, 16), false, false, 0);
9380   MemOps.push_back(Store);
9381   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9382                      &MemOps[0], MemOps.size());
9383 }
9384
9385 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9386   assert(Subtarget->is64Bit() &&
9387          "LowerVAARG only handles 64-bit va_arg!");
9388   assert((Subtarget->isTargetLinux() ||
9389           Subtarget->isTargetDarwin()) &&
9390           "Unhandled target in LowerVAARG");
9391   assert(Op.getNode()->getNumOperands() == 4);
9392   SDValue Chain = Op.getOperand(0);
9393   SDValue SrcPtr = Op.getOperand(1);
9394   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9395   unsigned Align = Op.getConstantOperandVal(3);
9396   DebugLoc dl = Op.getDebugLoc();
9397
9398   EVT ArgVT = Op.getNode()->getValueType(0);
9399   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9400   uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
9401   uint8_t ArgMode;
9402
9403   // Decide which area this value should be read from.
9404   // TODO: Implement the AMD64 ABI in its entirety. This simple
9405   // selection mechanism works only for the basic types.
9406   if (ArgVT == MVT::f80) {
9407     llvm_unreachable("va_arg for f80 not yet implemented");
9408   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9409     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
9410   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9411     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
9412   } else {
9413     llvm_unreachable("Unhandled argument type in LowerVAARG");
9414   }
9415
9416   if (ArgMode == 2) {
9417     // Sanity Check: Make sure using fp_offset makes sense.
9418     assert(!UseSoftFloat &&
9419            !(DAG.getMachineFunction()
9420                 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
9421            Subtarget->hasXMM());
9422   }
9423
9424   // Insert VAARG_64 node into the DAG
9425   // VAARG_64 returns two values: Variable Argument Address, Chain
9426   SmallVector<SDValue, 11> InstOps;
9427   InstOps.push_back(Chain);
9428   InstOps.push_back(SrcPtr);
9429   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9430   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9431   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9432   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9433   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9434                                           VTs, &InstOps[0], InstOps.size(),
9435                                           MVT::i64,
9436                                           MachinePointerInfo(SV),
9437                                           /*Align=*/0,
9438                                           /*Volatile=*/false,
9439                                           /*ReadMem=*/true,
9440                                           /*WriteMem=*/true);
9441   Chain = VAARG.getValue(1);
9442
9443   // Load the next argument and return it
9444   return DAG.getLoad(ArgVT, dl,
9445                      Chain,
9446                      VAARG,
9447                      MachinePointerInfo(),
9448                      false, false, false, 0);
9449 }
9450
9451 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
9452   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9453   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9454   SDValue Chain = Op.getOperand(0);
9455   SDValue DstPtr = Op.getOperand(1);
9456   SDValue SrcPtr = Op.getOperand(2);
9457   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9458   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9459   DebugLoc DL = Op.getDebugLoc();
9460
9461   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9462                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9463                        false,
9464                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9465 }
9466
9467 SDValue
9468 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
9469   DebugLoc dl = Op.getDebugLoc();
9470   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9471   switch (IntNo) {
9472   default: return SDValue();    // Don't custom lower most intrinsics.
9473   // Comparison intrinsics.
9474   case Intrinsic::x86_sse_comieq_ss:
9475   case Intrinsic::x86_sse_comilt_ss:
9476   case Intrinsic::x86_sse_comile_ss:
9477   case Intrinsic::x86_sse_comigt_ss:
9478   case Intrinsic::x86_sse_comige_ss:
9479   case Intrinsic::x86_sse_comineq_ss:
9480   case Intrinsic::x86_sse_ucomieq_ss:
9481   case Intrinsic::x86_sse_ucomilt_ss:
9482   case Intrinsic::x86_sse_ucomile_ss:
9483   case Intrinsic::x86_sse_ucomigt_ss:
9484   case Intrinsic::x86_sse_ucomige_ss:
9485   case Intrinsic::x86_sse_ucomineq_ss:
9486   case Intrinsic::x86_sse2_comieq_sd:
9487   case Intrinsic::x86_sse2_comilt_sd:
9488   case Intrinsic::x86_sse2_comile_sd:
9489   case Intrinsic::x86_sse2_comigt_sd:
9490   case Intrinsic::x86_sse2_comige_sd:
9491   case Intrinsic::x86_sse2_comineq_sd:
9492   case Intrinsic::x86_sse2_ucomieq_sd:
9493   case Intrinsic::x86_sse2_ucomilt_sd:
9494   case Intrinsic::x86_sse2_ucomile_sd:
9495   case Intrinsic::x86_sse2_ucomigt_sd:
9496   case Intrinsic::x86_sse2_ucomige_sd:
9497   case Intrinsic::x86_sse2_ucomineq_sd: {
9498     unsigned Opc = 0;
9499     ISD::CondCode CC = ISD::SETCC_INVALID;
9500     switch (IntNo) {
9501     default: break;
9502     case Intrinsic::x86_sse_comieq_ss:
9503     case Intrinsic::x86_sse2_comieq_sd:
9504       Opc = X86ISD::COMI;
9505       CC = ISD::SETEQ;
9506       break;
9507     case Intrinsic::x86_sse_comilt_ss:
9508     case Intrinsic::x86_sse2_comilt_sd:
9509       Opc = X86ISD::COMI;
9510       CC = ISD::SETLT;
9511       break;
9512     case Intrinsic::x86_sse_comile_ss:
9513     case Intrinsic::x86_sse2_comile_sd:
9514       Opc = X86ISD::COMI;
9515       CC = ISD::SETLE;
9516       break;
9517     case Intrinsic::x86_sse_comigt_ss:
9518     case Intrinsic::x86_sse2_comigt_sd:
9519       Opc = X86ISD::COMI;
9520       CC = ISD::SETGT;
9521       break;
9522     case Intrinsic::x86_sse_comige_ss:
9523     case Intrinsic::x86_sse2_comige_sd:
9524       Opc = X86ISD::COMI;
9525       CC = ISD::SETGE;
9526       break;
9527     case Intrinsic::x86_sse_comineq_ss:
9528     case Intrinsic::x86_sse2_comineq_sd:
9529       Opc = X86ISD::COMI;
9530       CC = ISD::SETNE;
9531       break;
9532     case Intrinsic::x86_sse_ucomieq_ss:
9533     case Intrinsic::x86_sse2_ucomieq_sd:
9534       Opc = X86ISD::UCOMI;
9535       CC = ISD::SETEQ;
9536       break;
9537     case Intrinsic::x86_sse_ucomilt_ss:
9538     case Intrinsic::x86_sse2_ucomilt_sd:
9539       Opc = X86ISD::UCOMI;
9540       CC = ISD::SETLT;
9541       break;
9542     case Intrinsic::x86_sse_ucomile_ss:
9543     case Intrinsic::x86_sse2_ucomile_sd:
9544       Opc = X86ISD::UCOMI;
9545       CC = ISD::SETLE;
9546       break;
9547     case Intrinsic::x86_sse_ucomigt_ss:
9548     case Intrinsic::x86_sse2_ucomigt_sd:
9549       Opc = X86ISD::UCOMI;
9550       CC = ISD::SETGT;
9551       break;
9552     case Intrinsic::x86_sse_ucomige_ss:
9553     case Intrinsic::x86_sse2_ucomige_sd:
9554       Opc = X86ISD::UCOMI;
9555       CC = ISD::SETGE;
9556       break;
9557     case Intrinsic::x86_sse_ucomineq_ss:
9558     case Intrinsic::x86_sse2_ucomineq_sd:
9559       Opc = X86ISD::UCOMI;
9560       CC = ISD::SETNE;
9561       break;
9562     }
9563
9564     SDValue LHS = Op.getOperand(1);
9565     SDValue RHS = Op.getOperand(2);
9566     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
9567     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
9568     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
9569     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9570                                 DAG.getConstant(X86CC, MVT::i8), Cond);
9571     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9572   }
9573   // Arithmetic intrinsics.
9574   case Intrinsic::x86_sse3_hadd_ps:
9575   case Intrinsic::x86_sse3_hadd_pd:
9576   case Intrinsic::x86_avx_hadd_ps_256:
9577   case Intrinsic::x86_avx_hadd_pd_256:
9578     return DAG.getNode(X86ISD::FHADD, dl, Op.getValueType(),
9579                        Op.getOperand(1), Op.getOperand(2));
9580   case Intrinsic::x86_sse3_hsub_ps:
9581   case Intrinsic::x86_sse3_hsub_pd:
9582   case Intrinsic::x86_avx_hsub_ps_256:
9583   case Intrinsic::x86_avx_hsub_pd_256:
9584     return DAG.getNode(X86ISD::FHSUB, dl, Op.getValueType(),
9585                        Op.getOperand(1), Op.getOperand(2));
9586   case Intrinsic::x86_avx2_psllv_d:
9587   case Intrinsic::x86_avx2_psllv_q:
9588   case Intrinsic::x86_avx2_psllv_d_256:
9589   case Intrinsic::x86_avx2_psllv_q_256:
9590     return DAG.getNode(ISD::SHL, dl, Op.getValueType(),
9591                       Op.getOperand(1), Op.getOperand(2));
9592   case Intrinsic::x86_avx2_psrlv_d:
9593   case Intrinsic::x86_avx2_psrlv_q:
9594   case Intrinsic::x86_avx2_psrlv_d_256:
9595   case Intrinsic::x86_avx2_psrlv_q_256:
9596     return DAG.getNode(ISD::SRL, dl, Op.getValueType(),
9597                       Op.getOperand(1), Op.getOperand(2));
9598   case Intrinsic::x86_avx2_psrav_d:
9599   case Intrinsic::x86_avx2_psrav_d_256:
9600     return DAG.getNode(ISD::SRA, dl, Op.getValueType(),
9601                       Op.getOperand(1), Op.getOperand(2));
9602
9603   // ptest and testp intrinsics. The intrinsic these come from are designed to
9604   // return an integer value, not just an instruction so lower it to the ptest
9605   // or testp pattern and a setcc for the result.
9606   case Intrinsic::x86_sse41_ptestz:
9607   case Intrinsic::x86_sse41_ptestc:
9608   case Intrinsic::x86_sse41_ptestnzc:
9609   case Intrinsic::x86_avx_ptestz_256:
9610   case Intrinsic::x86_avx_ptestc_256:
9611   case Intrinsic::x86_avx_ptestnzc_256:
9612   case Intrinsic::x86_avx_vtestz_ps:
9613   case Intrinsic::x86_avx_vtestc_ps:
9614   case Intrinsic::x86_avx_vtestnzc_ps:
9615   case Intrinsic::x86_avx_vtestz_pd:
9616   case Intrinsic::x86_avx_vtestc_pd:
9617   case Intrinsic::x86_avx_vtestnzc_pd:
9618   case Intrinsic::x86_avx_vtestz_ps_256:
9619   case Intrinsic::x86_avx_vtestc_ps_256:
9620   case Intrinsic::x86_avx_vtestnzc_ps_256:
9621   case Intrinsic::x86_avx_vtestz_pd_256:
9622   case Intrinsic::x86_avx_vtestc_pd_256:
9623   case Intrinsic::x86_avx_vtestnzc_pd_256: {
9624     bool IsTestPacked = false;
9625     unsigned X86CC = 0;
9626     switch (IntNo) {
9627     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
9628     case Intrinsic::x86_avx_vtestz_ps:
9629     case Intrinsic::x86_avx_vtestz_pd:
9630     case Intrinsic::x86_avx_vtestz_ps_256:
9631     case Intrinsic::x86_avx_vtestz_pd_256:
9632       IsTestPacked = true; // Fallthrough
9633     case Intrinsic::x86_sse41_ptestz:
9634     case Intrinsic::x86_avx_ptestz_256:
9635       // ZF = 1
9636       X86CC = X86::COND_E;
9637       break;
9638     case Intrinsic::x86_avx_vtestc_ps:
9639     case Intrinsic::x86_avx_vtestc_pd:
9640     case Intrinsic::x86_avx_vtestc_ps_256:
9641     case Intrinsic::x86_avx_vtestc_pd_256:
9642       IsTestPacked = true; // Fallthrough
9643     case Intrinsic::x86_sse41_ptestc:
9644     case Intrinsic::x86_avx_ptestc_256:
9645       // CF = 1
9646       X86CC = X86::COND_B;
9647       break;
9648     case Intrinsic::x86_avx_vtestnzc_ps:
9649     case Intrinsic::x86_avx_vtestnzc_pd:
9650     case Intrinsic::x86_avx_vtestnzc_ps_256:
9651     case Intrinsic::x86_avx_vtestnzc_pd_256:
9652       IsTestPacked = true; // Fallthrough
9653     case Intrinsic::x86_sse41_ptestnzc:
9654     case Intrinsic::x86_avx_ptestnzc_256:
9655       // ZF and CF = 0
9656       X86CC = X86::COND_A;
9657       break;
9658     }
9659
9660     SDValue LHS = Op.getOperand(1);
9661     SDValue RHS = Op.getOperand(2);
9662     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
9663     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
9664     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
9665     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
9666     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9667   }
9668
9669   // Fix vector shift instructions where the last operand is a non-immediate
9670   // i32 value.
9671   case Intrinsic::x86_avx2_pslli_w:
9672   case Intrinsic::x86_avx2_pslli_d:
9673   case Intrinsic::x86_avx2_pslli_q:
9674   case Intrinsic::x86_avx2_psrli_w:
9675   case Intrinsic::x86_avx2_psrli_d:
9676   case Intrinsic::x86_avx2_psrli_q:
9677   case Intrinsic::x86_avx2_psrai_w:
9678   case Intrinsic::x86_avx2_psrai_d:
9679   case Intrinsic::x86_sse2_pslli_w:
9680   case Intrinsic::x86_sse2_pslli_d:
9681   case Intrinsic::x86_sse2_pslli_q:
9682   case Intrinsic::x86_sse2_psrli_w:
9683   case Intrinsic::x86_sse2_psrli_d:
9684   case Intrinsic::x86_sse2_psrli_q:
9685   case Intrinsic::x86_sse2_psrai_w:
9686   case Intrinsic::x86_sse2_psrai_d:
9687   case Intrinsic::x86_mmx_pslli_w:
9688   case Intrinsic::x86_mmx_pslli_d:
9689   case Intrinsic::x86_mmx_pslli_q:
9690   case Intrinsic::x86_mmx_psrli_w:
9691   case Intrinsic::x86_mmx_psrli_d:
9692   case Intrinsic::x86_mmx_psrli_q:
9693   case Intrinsic::x86_mmx_psrai_w:
9694   case Intrinsic::x86_mmx_psrai_d: {
9695     SDValue ShAmt = Op.getOperand(2);
9696     if (isa<ConstantSDNode>(ShAmt))
9697       return SDValue();
9698
9699     unsigned NewIntNo = 0;
9700     EVT ShAmtVT = MVT::v4i32;
9701     switch (IntNo) {
9702     case Intrinsic::x86_sse2_pslli_w:
9703       NewIntNo = Intrinsic::x86_sse2_psll_w;
9704       break;
9705     case Intrinsic::x86_sse2_pslli_d:
9706       NewIntNo = Intrinsic::x86_sse2_psll_d;
9707       break;
9708     case Intrinsic::x86_sse2_pslli_q:
9709       NewIntNo = Intrinsic::x86_sse2_psll_q;
9710       break;
9711     case Intrinsic::x86_sse2_psrli_w:
9712       NewIntNo = Intrinsic::x86_sse2_psrl_w;
9713       break;
9714     case Intrinsic::x86_sse2_psrli_d:
9715       NewIntNo = Intrinsic::x86_sse2_psrl_d;
9716       break;
9717     case Intrinsic::x86_sse2_psrli_q:
9718       NewIntNo = Intrinsic::x86_sse2_psrl_q;
9719       break;
9720     case Intrinsic::x86_sse2_psrai_w:
9721       NewIntNo = Intrinsic::x86_sse2_psra_w;
9722       break;
9723     case Intrinsic::x86_sse2_psrai_d:
9724       NewIntNo = Intrinsic::x86_sse2_psra_d;
9725       break;
9726     case Intrinsic::x86_avx2_pslli_w:
9727       NewIntNo = Intrinsic::x86_avx2_psll_w;
9728       break;
9729     case Intrinsic::x86_avx2_pslli_d:
9730       NewIntNo = Intrinsic::x86_avx2_psll_d;
9731       break;
9732     case Intrinsic::x86_avx2_pslli_q:
9733       NewIntNo = Intrinsic::x86_avx2_psll_q;
9734       break;
9735     case Intrinsic::x86_avx2_psrli_w:
9736       NewIntNo = Intrinsic::x86_avx2_psrl_w;
9737       break;
9738     case Intrinsic::x86_avx2_psrli_d:
9739       NewIntNo = Intrinsic::x86_avx2_psrl_d;
9740       break;
9741     case Intrinsic::x86_avx2_psrli_q:
9742       NewIntNo = Intrinsic::x86_avx2_psrl_q;
9743       break;
9744     case Intrinsic::x86_avx2_psrai_w:
9745       NewIntNo = Intrinsic::x86_avx2_psra_w;
9746       break;
9747     case Intrinsic::x86_avx2_psrai_d:
9748       NewIntNo = Intrinsic::x86_avx2_psra_d;
9749       break;
9750     default: {
9751       ShAmtVT = MVT::v2i32;
9752       switch (IntNo) {
9753       case Intrinsic::x86_mmx_pslli_w:
9754         NewIntNo = Intrinsic::x86_mmx_psll_w;
9755         break;
9756       case Intrinsic::x86_mmx_pslli_d:
9757         NewIntNo = Intrinsic::x86_mmx_psll_d;
9758         break;
9759       case Intrinsic::x86_mmx_pslli_q:
9760         NewIntNo = Intrinsic::x86_mmx_psll_q;
9761         break;
9762       case Intrinsic::x86_mmx_psrli_w:
9763         NewIntNo = Intrinsic::x86_mmx_psrl_w;
9764         break;
9765       case Intrinsic::x86_mmx_psrli_d:
9766         NewIntNo = Intrinsic::x86_mmx_psrl_d;
9767         break;
9768       case Intrinsic::x86_mmx_psrli_q:
9769         NewIntNo = Intrinsic::x86_mmx_psrl_q;
9770         break;
9771       case Intrinsic::x86_mmx_psrai_w:
9772         NewIntNo = Intrinsic::x86_mmx_psra_w;
9773         break;
9774       case Intrinsic::x86_mmx_psrai_d:
9775         NewIntNo = Intrinsic::x86_mmx_psra_d;
9776         break;
9777       default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9778       }
9779       break;
9780     }
9781     }
9782
9783     // The vector shift intrinsics with scalars uses 32b shift amounts but
9784     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
9785     // to be zero.
9786     SDValue ShOps[4];
9787     ShOps[0] = ShAmt;
9788     ShOps[1] = DAG.getConstant(0, MVT::i32);
9789     if (ShAmtVT == MVT::v4i32) {
9790       ShOps[2] = DAG.getUNDEF(MVT::i32);
9791       ShOps[3] = DAG.getUNDEF(MVT::i32);
9792       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
9793     } else {
9794       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
9795 // FIXME this must be lowered to get rid of the invalid type.
9796     }
9797
9798     EVT VT = Op.getValueType();
9799     ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
9800     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9801                        DAG.getConstant(NewIntNo, MVT::i32),
9802                        Op.getOperand(1), ShAmt);
9803   }
9804   }
9805 }
9806
9807 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
9808                                            SelectionDAG &DAG) const {
9809   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9810   MFI->setReturnAddressIsTaken(true);
9811
9812   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9813   DebugLoc dl = Op.getDebugLoc();
9814
9815   if (Depth > 0) {
9816     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
9817     SDValue Offset =
9818       DAG.getConstant(TD->getPointerSize(),
9819                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
9820     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9821                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
9822                                    FrameAddr, Offset),
9823                        MachinePointerInfo(), false, false, false, 0);
9824   }
9825
9826   // Just load the return address.
9827   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
9828   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9829                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
9830 }
9831
9832 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
9833   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9834   MFI->setFrameAddressIsTaken(true);
9835
9836   EVT VT = Op.getValueType();
9837   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
9838   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9839   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
9840   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
9841   while (Depth--)
9842     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
9843                             MachinePointerInfo(),
9844                             false, false, false, 0);
9845   return FrameAddr;
9846 }
9847
9848 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
9849                                                      SelectionDAG &DAG) const {
9850   return DAG.getIntPtrConstant(2*TD->getPointerSize());
9851 }
9852
9853 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
9854   MachineFunction &MF = DAG.getMachineFunction();
9855   SDValue Chain     = Op.getOperand(0);
9856   SDValue Offset    = Op.getOperand(1);
9857   SDValue Handler   = Op.getOperand(2);
9858   DebugLoc dl       = Op.getDebugLoc();
9859
9860   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
9861                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
9862                                      getPointerTy());
9863   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
9864
9865   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
9866                                   DAG.getIntPtrConstant(TD->getPointerSize()));
9867   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
9868   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
9869                        false, false, 0);
9870   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
9871   MF.getRegInfo().addLiveOut(StoreAddrReg);
9872
9873   return DAG.getNode(X86ISD::EH_RETURN, dl,
9874                      MVT::Other,
9875                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
9876 }
9877
9878 SDValue X86TargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
9879                                                   SelectionDAG &DAG) const {
9880   return Op.getOperand(0);
9881 }
9882
9883 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
9884                                                 SelectionDAG &DAG) const {
9885   SDValue Root = Op.getOperand(0);
9886   SDValue Trmp = Op.getOperand(1); // trampoline
9887   SDValue FPtr = Op.getOperand(2); // nested function
9888   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
9889   DebugLoc dl  = Op.getDebugLoc();
9890
9891   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9892
9893   if (Subtarget->is64Bit()) {
9894     SDValue OutChains[6];
9895
9896     // Large code-model.
9897     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
9898     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
9899
9900     const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10);
9901     const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11);
9902
9903     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
9904
9905     // Load the pointer to the nested function into R11.
9906     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
9907     SDValue Addr = Trmp;
9908     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9909                                 Addr, MachinePointerInfo(TrmpAddr),
9910                                 false, false, 0);
9911
9912     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9913                        DAG.getConstant(2, MVT::i64));
9914     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
9915                                 MachinePointerInfo(TrmpAddr, 2),
9916                                 false, false, 2);
9917
9918     // Load the 'nest' parameter value into R10.
9919     // R10 is specified in X86CallingConv.td
9920     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
9921     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9922                        DAG.getConstant(10, MVT::i64));
9923     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9924                                 Addr, MachinePointerInfo(TrmpAddr, 10),
9925                                 false, false, 0);
9926
9927     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9928                        DAG.getConstant(12, MVT::i64));
9929     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
9930                                 MachinePointerInfo(TrmpAddr, 12),
9931                                 false, false, 2);
9932
9933     // Jump to the nested function.
9934     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
9935     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9936                        DAG.getConstant(20, MVT::i64));
9937     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9938                                 Addr, MachinePointerInfo(TrmpAddr, 20),
9939                                 false, false, 0);
9940
9941     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
9942     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9943                        DAG.getConstant(22, MVT::i64));
9944     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
9945                                 MachinePointerInfo(TrmpAddr, 22),
9946                                 false, false, 0);
9947
9948     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
9949   } else {
9950     const Function *Func =
9951       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
9952     CallingConv::ID CC = Func->getCallingConv();
9953     unsigned NestReg;
9954
9955     switch (CC) {
9956     default:
9957       llvm_unreachable("Unsupported calling convention");
9958     case CallingConv::C:
9959     case CallingConv::X86_StdCall: {
9960       // Pass 'nest' parameter in ECX.
9961       // Must be kept in sync with X86CallingConv.td
9962       NestReg = X86::ECX;
9963
9964       // Check that ECX wasn't needed by an 'inreg' parameter.
9965       FunctionType *FTy = Func->getFunctionType();
9966       const AttrListPtr &Attrs = Func->getAttributes();
9967
9968       if (!Attrs.isEmpty() && !Func->isVarArg()) {
9969         unsigned InRegCount = 0;
9970         unsigned Idx = 1;
9971
9972         for (FunctionType::param_iterator I = FTy->param_begin(),
9973              E = FTy->param_end(); I != E; ++I, ++Idx)
9974           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
9975             // FIXME: should only count parameters that are lowered to integers.
9976             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
9977
9978         if (InRegCount > 2) {
9979           report_fatal_error("Nest register in use - reduce number of inreg"
9980                              " parameters!");
9981         }
9982       }
9983       break;
9984     }
9985     case CallingConv::X86_FastCall:
9986     case CallingConv::X86_ThisCall:
9987     case CallingConv::Fast:
9988       // Pass 'nest' parameter in EAX.
9989       // Must be kept in sync with X86CallingConv.td
9990       NestReg = X86::EAX;
9991       break;
9992     }
9993
9994     SDValue OutChains[4];
9995     SDValue Addr, Disp;
9996
9997     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9998                        DAG.getConstant(10, MVT::i32));
9999     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
10000
10001     // This is storing the opcode for MOV32ri.
10002     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
10003     const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg);
10004     OutChains[0] = DAG.getStore(Root, dl,
10005                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
10006                                 Trmp, MachinePointerInfo(TrmpAddr),
10007                                 false, false, 0);
10008
10009     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10010                        DAG.getConstant(1, MVT::i32));
10011     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
10012                                 MachinePointerInfo(TrmpAddr, 1),
10013                                 false, false, 1);
10014
10015     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
10016     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10017                        DAG.getConstant(5, MVT::i32));
10018     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
10019                                 MachinePointerInfo(TrmpAddr, 5),
10020                                 false, false, 1);
10021
10022     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10023                        DAG.getConstant(6, MVT::i32));
10024     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
10025                                 MachinePointerInfo(TrmpAddr, 6),
10026                                 false, false, 1);
10027
10028     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
10029   }
10030 }
10031
10032 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
10033                                             SelectionDAG &DAG) const {
10034   /*
10035    The rounding mode is in bits 11:10 of FPSR, and has the following
10036    settings:
10037      00 Round to nearest
10038      01 Round to -inf
10039      10 Round to +inf
10040      11 Round to 0
10041
10042   FLT_ROUNDS, on the other hand, expects the following:
10043     -1 Undefined
10044      0 Round to 0
10045      1 Round to nearest
10046      2 Round to +inf
10047      3 Round to -inf
10048
10049   To perform the conversion, we do:
10050     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
10051   */
10052
10053   MachineFunction &MF = DAG.getMachineFunction();
10054   const TargetMachine &TM = MF.getTarget();
10055   const TargetFrameLowering &TFI = *TM.getFrameLowering();
10056   unsigned StackAlignment = TFI.getStackAlignment();
10057   EVT VT = Op.getValueType();
10058   DebugLoc DL = Op.getDebugLoc();
10059
10060   // Save FP Control Word to stack slot
10061   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
10062   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10063
10064
10065   MachineMemOperand *MMO =
10066    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10067                            MachineMemOperand::MOStore, 2, 2);
10068
10069   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
10070   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
10071                                           DAG.getVTList(MVT::Other),
10072                                           Ops, 2, MVT::i16, MMO);
10073
10074   // Load FP Control Word from stack slot
10075   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
10076                             MachinePointerInfo(), false, false, false, 0);
10077
10078   // Transform as necessary
10079   SDValue CWD1 =
10080     DAG.getNode(ISD::SRL, DL, MVT::i16,
10081                 DAG.getNode(ISD::AND, DL, MVT::i16,
10082                             CWD, DAG.getConstant(0x800, MVT::i16)),
10083                 DAG.getConstant(11, MVT::i8));
10084   SDValue CWD2 =
10085     DAG.getNode(ISD::SRL, DL, MVT::i16,
10086                 DAG.getNode(ISD::AND, DL, MVT::i16,
10087                             CWD, DAG.getConstant(0x400, MVT::i16)),
10088                 DAG.getConstant(9, MVT::i8));
10089
10090   SDValue RetVal =
10091     DAG.getNode(ISD::AND, DL, MVT::i16,
10092                 DAG.getNode(ISD::ADD, DL, MVT::i16,
10093                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
10094                             DAG.getConstant(1, MVT::i16)),
10095                 DAG.getConstant(3, MVT::i16));
10096
10097
10098   return DAG.getNode((VT.getSizeInBits() < 16 ?
10099                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
10100 }
10101
10102 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
10103   EVT VT = Op.getValueType();
10104   EVT OpVT = VT;
10105   unsigned NumBits = VT.getSizeInBits();
10106   DebugLoc dl = Op.getDebugLoc();
10107
10108   Op = Op.getOperand(0);
10109   if (VT == MVT::i8) {
10110     // Zero extend to i32 since there is not an i8 bsr.
10111     OpVT = MVT::i32;
10112     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10113   }
10114
10115   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
10116   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10117   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10118
10119   // If src is zero (i.e. bsr sets ZF), returns NumBits.
10120   SDValue Ops[] = {
10121     Op,
10122     DAG.getConstant(NumBits+NumBits-1, OpVT),
10123     DAG.getConstant(X86::COND_E, MVT::i8),
10124     Op.getValue(1)
10125   };
10126   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
10127
10128   // Finally xor with NumBits-1.
10129   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10130
10131   if (VT == MVT::i8)
10132     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10133   return Op;
10134 }
10135
10136 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
10137   EVT VT = Op.getValueType();
10138   EVT OpVT = VT;
10139   unsigned NumBits = VT.getSizeInBits();
10140   DebugLoc dl = Op.getDebugLoc();
10141
10142   Op = Op.getOperand(0);
10143   if (VT == MVT::i8) {
10144     OpVT = MVT::i32;
10145     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10146   }
10147
10148   // Issue a bsf (scan bits forward) which also sets EFLAGS.
10149   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10150   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
10151
10152   // If src is zero (i.e. bsf sets ZF), returns NumBits.
10153   SDValue Ops[] = {
10154     Op,
10155     DAG.getConstant(NumBits, OpVT),
10156     DAG.getConstant(X86::COND_E, MVT::i8),
10157     Op.getValue(1)
10158   };
10159   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
10160
10161   if (VT == MVT::i8)
10162     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10163   return Op;
10164 }
10165
10166 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
10167 // ones, and then concatenate the result back.
10168 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
10169   EVT VT = Op.getValueType();
10170
10171   assert(VT.getSizeInBits() == 256 && VT.isInteger() &&
10172          "Unsupported value type for operation");
10173
10174   int NumElems = VT.getVectorNumElements();
10175   DebugLoc dl = Op.getDebugLoc();
10176   SDValue Idx0 = DAG.getConstant(0, MVT::i32);
10177   SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
10178
10179   // Extract the LHS vectors
10180   SDValue LHS = Op.getOperand(0);
10181   SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
10182   SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
10183
10184   // Extract the RHS vectors
10185   SDValue RHS = Op.getOperand(1);
10186   SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl);
10187   SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl);
10188
10189   MVT EltVT = VT.getVectorElementType().getSimpleVT();
10190   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10191
10192   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10193                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
10194                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
10195 }
10196
10197 SDValue X86TargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const {
10198   assert(Op.getValueType().getSizeInBits() == 256 &&
10199          Op.getValueType().isInteger() &&
10200          "Only handle AVX 256-bit vector integer operation");
10201   return Lower256IntArith(Op, DAG);
10202 }
10203
10204 SDValue X86TargetLowering::LowerSUB(SDValue Op, SelectionDAG &DAG) const {
10205   assert(Op.getValueType().getSizeInBits() == 256 &&
10206          Op.getValueType().isInteger() &&
10207          "Only handle AVX 256-bit vector integer operation");
10208   return Lower256IntArith(Op, DAG);
10209 }
10210
10211 SDValue X86TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10212   EVT VT = Op.getValueType();
10213
10214   // Decompose 256-bit ops into smaller 128-bit ops.
10215   if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2())
10216     return Lower256IntArith(Op, DAG);
10217
10218   DebugLoc dl = Op.getDebugLoc();
10219
10220   SDValue A = Op.getOperand(0);
10221   SDValue B = Op.getOperand(1);
10222
10223   if (VT == MVT::v4i64) {
10224     assert(Subtarget->hasAVX2() && "Lowering v4i64 multiply requires AVX2");
10225
10226     //  ulong2 Ahi = __builtin_ia32_psrlqi256( a, 32);
10227     //  ulong2 Bhi = __builtin_ia32_psrlqi256( b, 32);
10228     //  ulong2 AloBlo = __builtin_ia32_pmuludq256( a, b );
10229     //  ulong2 AloBhi = __builtin_ia32_pmuludq256( a, Bhi );
10230     //  ulong2 AhiBlo = __builtin_ia32_pmuludq256( Ahi, b );
10231     //
10232     //  AloBhi = __builtin_ia32_psllqi256( AloBhi, 32 );
10233     //  AhiBlo = __builtin_ia32_psllqi256( AhiBlo, 32 );
10234     //  return AloBlo + AloBhi + AhiBlo;
10235
10236     SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10237                          DAG.getConstant(Intrinsic::x86_avx2_psrli_q, MVT::i32),
10238                          A, DAG.getConstant(32, MVT::i32));
10239     SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10240                          DAG.getConstant(Intrinsic::x86_avx2_psrli_q, MVT::i32),
10241                          B, DAG.getConstant(32, MVT::i32));
10242     SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10243                          DAG.getConstant(Intrinsic::x86_avx2_pmulu_dq, MVT::i32),
10244                          A, B);
10245     SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10246                          DAG.getConstant(Intrinsic::x86_avx2_pmulu_dq, MVT::i32),
10247                          A, Bhi);
10248     SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10249                          DAG.getConstant(Intrinsic::x86_avx2_pmulu_dq, MVT::i32),
10250                          Ahi, B);
10251     AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10252                          DAG.getConstant(Intrinsic::x86_avx2_pslli_q, MVT::i32),
10253                          AloBhi, DAG.getConstant(32, MVT::i32));
10254     AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10255                          DAG.getConstant(Intrinsic::x86_avx2_pslli_q, MVT::i32),
10256                          AhiBlo, DAG.getConstant(32, MVT::i32));
10257     SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
10258     Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10259     return Res;
10260   }
10261
10262   assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
10263
10264   //  ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
10265   //  ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
10266   //  ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
10267   //  ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
10268   //  ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
10269   //
10270   //  AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
10271   //  AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
10272   //  return AloBlo + AloBhi + AhiBlo;
10273
10274   SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10275                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
10276                        A, DAG.getConstant(32, MVT::i32));
10277   SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10278                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
10279                        B, DAG.getConstant(32, MVT::i32));
10280   SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10281                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
10282                        A, B);
10283   SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10284                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
10285                        A, Bhi);
10286   SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10287                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
10288                        Ahi, B);
10289   AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10290                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
10291                        AloBhi, DAG.getConstant(32, MVT::i32));
10292   AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10293                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
10294                        AhiBlo, DAG.getConstant(32, MVT::i32));
10295   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
10296   Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10297   return Res;
10298 }
10299
10300 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
10301
10302   EVT VT = Op.getValueType();
10303   DebugLoc dl = Op.getDebugLoc();
10304   SDValue R = Op.getOperand(0);
10305   SDValue Amt = Op.getOperand(1);
10306   LLVMContext *Context = DAG.getContext();
10307
10308   if (!Subtarget->hasXMMInt())
10309     return SDValue();
10310
10311   // Optimize shl/srl/sra with constant shift amount.
10312   if (isSplatVector(Amt.getNode())) {
10313     SDValue SclrAmt = Amt->getOperand(0);
10314     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
10315       uint64_t ShiftAmt = C->getZExtValue();
10316
10317       if (VT == MVT::v16i8 && Op.getOpcode() == ISD::SHL) {
10318         // Make a large shift.
10319         SDValue SHL =
10320           DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10321                       DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10322                       R, DAG.getConstant(ShiftAmt, MVT::i32));
10323         // Zero out the rightmost bits.
10324         SmallVector<SDValue, 16> V(16, DAG.getConstant(uint8_t(-1U << ShiftAmt),
10325                                                        MVT::i8));
10326         return DAG.getNode(ISD::AND, dl, VT, SHL,
10327                            DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10328       }
10329
10330       if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SHL)
10331        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10332                      DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
10333                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10334
10335       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SHL)
10336        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10337                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
10338                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10339
10340       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SHL)
10341        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10342                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10343                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10344
10345       if (VT == MVT::v16i8 && Op.getOpcode() == ISD::SRL) {
10346         // Make a large shift.
10347         SDValue SRL =
10348           DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10349                       DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
10350                       R, DAG.getConstant(ShiftAmt, MVT::i32));
10351         // Zero out the leftmost bits.
10352         SmallVector<SDValue, 16> V(16, DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10353                                                        MVT::i8));
10354         return DAG.getNode(ISD::AND, dl, VT, SRL,
10355                            DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10356       }
10357
10358       if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SRL)
10359        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10360                      DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
10361                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10362
10363       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRL)
10364        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10365                      DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
10366                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10367
10368       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRL)
10369        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10370                      DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
10371                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10372
10373       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRA)
10374        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10375                      DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
10376                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10377
10378       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRA)
10379        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10380                      DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
10381                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10382
10383       if (VT == MVT::v16i8 && Op.getOpcode() == ISD::SRA) {
10384         if (ShiftAmt == 7) {
10385           // R s>> 7  ===  R s< 0
10386           SDValue Zeros = getZeroVector(VT, true /* HasXMMInt */, DAG, dl);
10387           return DAG.getNode(X86ISD::PCMPGTB, dl, VT, Zeros, R);
10388         }
10389
10390         // R s>> a === ((R u>> a) ^ m) - m
10391         SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10392         SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
10393                                                        MVT::i8));
10394         SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
10395         Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10396         Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10397         return Res;
10398       }
10399
10400       if (Subtarget->hasAVX2() && VT == MVT::v32i8) {
10401         if (Op.getOpcode() == ISD::SHL) {
10402           // Make a large shift.
10403           SDValue SHL =
10404             DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10405                         DAG.getConstant(Intrinsic::x86_avx2_pslli_w, MVT::i32),
10406                         R, DAG.getConstant(ShiftAmt, MVT::i32));
10407           // Zero out the rightmost bits.
10408           SmallVector<SDValue, 32> V(32, DAG.getConstant(uint8_t(-1U << ShiftAmt),
10409                                                          MVT::i8));
10410           return DAG.getNode(ISD::AND, dl, VT, SHL,
10411                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10412         }
10413         if (Op.getOpcode() == ISD::SRL) {
10414           // Make a large shift.
10415           SDValue SRL =
10416             DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10417                         DAG.getConstant(Intrinsic::x86_avx2_psrli_w, MVT::i32),
10418                         R, DAG.getConstant(ShiftAmt, MVT::i32));
10419           // Zero out the leftmost bits.
10420           SmallVector<SDValue, 32> V(32, DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10421                                                          MVT::i8));
10422           return DAG.getNode(ISD::AND, dl, VT, SRL,
10423                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10424         }
10425         if (Op.getOpcode() == ISD::SRA) {
10426           if (ShiftAmt == 7) {
10427             // R s>> 7  ===  R s< 0
10428             SDValue Zeros = getZeroVector(VT, true /* HasXMMInt */, DAG, dl);
10429             return DAG.getNode(X86ISD::PCMPGTB, dl, VT, Zeros, R);
10430           }
10431
10432           // R s>> a === ((R u>> a) ^ m) - m
10433           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10434           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
10435                                                          MVT::i8));
10436           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
10437           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10438           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10439           return Res;
10440         }
10441       }
10442     }
10443   }
10444
10445   // Lower SHL with variable shift amount.
10446   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
10447     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10448                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
10449                      Op.getOperand(1), DAG.getConstant(23, MVT::i32));
10450
10451     ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
10452
10453     std::vector<Constant*> CV(4, CI);
10454     Constant *C = ConstantVector::get(CV);
10455     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10456     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10457                                  MachinePointerInfo::getConstantPool(),
10458                                  false, false, false, 16);
10459
10460     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
10461     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
10462     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
10463     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
10464   }
10465   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
10466     // a = a << 5;
10467     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10468                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10469                      Op.getOperand(1), DAG.getConstant(5, MVT::i32));
10470
10471     ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
10472     ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
10473
10474     std::vector<Constant*> CVM1(16, CM1);
10475     std::vector<Constant*> CVM2(16, CM2);
10476     Constant *C = ConstantVector::get(CVM1);
10477     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10478     SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10479                             MachinePointerInfo::getConstantPool(),
10480                             false, false, false, 16);
10481
10482     // r = pblendv(r, psllw(r & (char16)15, 4), a);
10483     M = DAG.getNode(ISD::AND, dl, VT, R, M);
10484     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10485                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
10486                     DAG.getConstant(4, MVT::i32));
10487     R = DAG.getNode(ISD::VSELECT, dl, VT, Op, R, M);
10488     // a += a
10489     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10490
10491     C = ConstantVector::get(CVM2);
10492     CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10493     M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10494                     MachinePointerInfo::getConstantPool(),
10495                     false, false, false, 16);
10496
10497     // r = pblendv(r, psllw(r & (char16)63, 2), a);
10498     M = DAG.getNode(ISD::AND, dl, VT, R, M);
10499     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10500                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
10501                     DAG.getConstant(2, MVT::i32));
10502     R = DAG.getNode(ISD::VSELECT, dl, VT, Op, R, M);
10503     // a += a
10504     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10505
10506     // return pblendv(r, r+r, a);
10507     R = DAG.getNode(ISD::VSELECT, dl, VT, Op,
10508                     R, DAG.getNode(ISD::ADD, dl, VT, R, R));
10509     return R;
10510   }
10511
10512   // Decompose 256-bit shifts into smaller 128-bit shifts.
10513   if (VT.getSizeInBits() == 256) {
10514     int NumElems = VT.getVectorNumElements();
10515     MVT EltVT = VT.getVectorElementType().getSimpleVT();
10516     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10517
10518     // Extract the two vectors
10519     SDValue V1 = Extract128BitVector(R, DAG.getConstant(0, MVT::i32), DAG, dl);
10520     SDValue V2 = Extract128BitVector(R, DAG.getConstant(NumElems/2, MVT::i32),
10521                                      DAG, dl);
10522
10523     // Recreate the shift amount vectors
10524     SDValue Amt1, Amt2;
10525     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
10526       // Constant shift amount
10527       SmallVector<SDValue, 4> Amt1Csts;
10528       SmallVector<SDValue, 4> Amt2Csts;
10529       for (int i = 0; i < NumElems/2; ++i)
10530         Amt1Csts.push_back(Amt->getOperand(i));
10531       for (int i = NumElems/2; i < NumElems; ++i)
10532         Amt2Csts.push_back(Amt->getOperand(i));
10533
10534       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10535                                  &Amt1Csts[0], NumElems/2);
10536       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10537                                  &Amt2Csts[0], NumElems/2);
10538     } else {
10539       // Variable shift amount
10540       Amt1 = Extract128BitVector(Amt, DAG.getConstant(0, MVT::i32), DAG, dl);
10541       Amt2 = Extract128BitVector(Amt, DAG.getConstant(NumElems/2, MVT::i32),
10542                                  DAG, dl);
10543     }
10544
10545     // Issue new vector shifts for the smaller types
10546     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
10547     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
10548
10549     // Concatenate the result back
10550     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
10551   }
10552
10553   return SDValue();
10554 }
10555
10556 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
10557   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
10558   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
10559   // looks for this combo and may remove the "setcc" instruction if the "setcc"
10560   // has only one use.
10561   SDNode *N = Op.getNode();
10562   SDValue LHS = N->getOperand(0);
10563   SDValue RHS = N->getOperand(1);
10564   unsigned BaseOp = 0;
10565   unsigned Cond = 0;
10566   DebugLoc DL = Op.getDebugLoc();
10567   switch (Op.getOpcode()) {
10568   default: llvm_unreachable("Unknown ovf instruction!");
10569   case ISD::SADDO:
10570     // A subtract of one will be selected as a INC. Note that INC doesn't
10571     // set CF, so we can't do this for UADDO.
10572     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10573       if (C->isOne()) {
10574         BaseOp = X86ISD::INC;
10575         Cond = X86::COND_O;
10576         break;
10577       }
10578     BaseOp = X86ISD::ADD;
10579     Cond = X86::COND_O;
10580     break;
10581   case ISD::UADDO:
10582     BaseOp = X86ISD::ADD;
10583     Cond = X86::COND_B;
10584     break;
10585   case ISD::SSUBO:
10586     // A subtract of one will be selected as a DEC. Note that DEC doesn't
10587     // set CF, so we can't do this for USUBO.
10588     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10589       if (C->isOne()) {
10590         BaseOp = X86ISD::DEC;
10591         Cond = X86::COND_O;
10592         break;
10593       }
10594     BaseOp = X86ISD::SUB;
10595     Cond = X86::COND_O;
10596     break;
10597   case ISD::USUBO:
10598     BaseOp = X86ISD::SUB;
10599     Cond = X86::COND_B;
10600     break;
10601   case ISD::SMULO:
10602     BaseOp = X86ISD::SMUL;
10603     Cond = X86::COND_O;
10604     break;
10605   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
10606     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
10607                                  MVT::i32);
10608     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
10609
10610     SDValue SetCC =
10611       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10612                   DAG.getConstant(X86::COND_O, MVT::i32),
10613                   SDValue(Sum.getNode(), 2));
10614
10615     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10616   }
10617   }
10618
10619   // Also sets EFLAGS.
10620   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
10621   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
10622
10623   SDValue SetCC =
10624     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
10625                 DAG.getConstant(Cond, MVT::i32),
10626                 SDValue(Sum.getNode(), 1));
10627
10628   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10629 }
10630
10631 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op, SelectionDAG &DAG) const{
10632   DebugLoc dl = Op.getDebugLoc();
10633   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
10634   EVT VT = Op.getValueType();
10635
10636   if (Subtarget->hasXMMInt() && VT.isVector()) {
10637     unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
10638                         ExtraVT.getScalarType().getSizeInBits();
10639     SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
10640
10641     unsigned SHLIntrinsicsID = 0;
10642     unsigned SRAIntrinsicsID = 0;
10643     switch (VT.getSimpleVT().SimpleTy) {
10644       default:
10645         return SDValue();
10646       case MVT::v4i32:
10647         SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_d;
10648         SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_d;
10649         break;
10650       case MVT::v8i16:
10651         SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_w;
10652         SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_w;
10653         break;
10654       case MVT::v8i32:
10655       case MVT::v16i16:
10656         if (!Subtarget->hasAVX())
10657           return SDValue();
10658         if (!Subtarget->hasAVX2()) {
10659           // needs to be split
10660           int NumElems = VT.getVectorNumElements();
10661           SDValue Idx0 = DAG.getConstant(0, MVT::i32);
10662           SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
10663
10664           // Extract the LHS vectors
10665           SDValue LHS = Op.getOperand(0);
10666           SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
10667           SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
10668
10669           MVT EltVT = VT.getVectorElementType().getSimpleVT();
10670           EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10671
10672           EVT ExtraEltVT = ExtraVT.getVectorElementType();
10673           int ExtraNumElems = ExtraVT.getVectorNumElements();
10674           ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
10675                                      ExtraNumElems/2);
10676           SDValue Extra = DAG.getValueType(ExtraVT);
10677
10678           LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
10679           LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
10680
10681           return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);;
10682         }
10683         if (VT == MVT::v8i32) {
10684           SHLIntrinsicsID = Intrinsic::x86_avx2_pslli_d;
10685           SRAIntrinsicsID = Intrinsic::x86_avx2_psrai_d;
10686         } else {
10687           SHLIntrinsicsID = Intrinsic::x86_avx2_pslli_w;
10688           SRAIntrinsicsID = Intrinsic::x86_avx2_psrai_w;
10689         }
10690     }
10691
10692     SDValue Tmp1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10693                          DAG.getConstant(SHLIntrinsicsID, MVT::i32),
10694                          Op.getOperand(0), ShAmt);
10695
10696     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10697                        DAG.getConstant(SRAIntrinsicsID, MVT::i32),
10698                        Tmp1, ShAmt);
10699   }
10700
10701   return SDValue();
10702 }
10703
10704
10705 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
10706   DebugLoc dl = Op.getDebugLoc();
10707
10708   // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
10709   // There isn't any reason to disable it if the target processor supports it.
10710   if (!Subtarget->hasXMMInt() && !Subtarget->is64Bit()) {
10711     SDValue Chain = Op.getOperand(0);
10712     SDValue Zero = DAG.getConstant(0, MVT::i32);
10713     SDValue Ops[] = {
10714       DAG.getRegister(X86::ESP, MVT::i32), // Base
10715       DAG.getTargetConstant(1, MVT::i8),   // Scale
10716       DAG.getRegister(0, MVT::i32),        // Index
10717       DAG.getTargetConstant(0, MVT::i32),  // Disp
10718       DAG.getRegister(0, MVT::i32),        // Segment.
10719       Zero,
10720       Chain
10721     };
10722     SDNode *Res =
10723       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10724                           array_lengthof(Ops));
10725     return SDValue(Res, 0);
10726   }
10727
10728   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
10729   if (!isDev)
10730     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10731
10732   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10733   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
10734   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
10735   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
10736
10737   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
10738   if (!Op1 && !Op2 && !Op3 && Op4)
10739     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
10740
10741   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
10742   if (Op1 && !Op2 && !Op3 && !Op4)
10743     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
10744
10745   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
10746   //           (MFENCE)>;
10747   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10748 }
10749
10750 SDValue X86TargetLowering::LowerATOMIC_FENCE(SDValue Op,
10751                                              SelectionDAG &DAG) const {
10752   DebugLoc dl = Op.getDebugLoc();
10753   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
10754     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
10755   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
10756     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
10757
10758   // The only fence that needs an instruction is a sequentially-consistent
10759   // cross-thread fence.
10760   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
10761     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
10762     // no-sse2). There isn't any reason to disable it if the target processor
10763     // supports it.
10764     if (Subtarget->hasXMMInt() || Subtarget->is64Bit())
10765       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10766
10767     SDValue Chain = Op.getOperand(0);
10768     SDValue Zero = DAG.getConstant(0, MVT::i32);
10769     SDValue Ops[] = {
10770       DAG.getRegister(X86::ESP, MVT::i32), // Base
10771       DAG.getTargetConstant(1, MVT::i8),   // Scale
10772       DAG.getRegister(0, MVT::i32),        // Index
10773       DAG.getTargetConstant(0, MVT::i32),  // Disp
10774       DAG.getRegister(0, MVT::i32),        // Segment.
10775       Zero,
10776       Chain
10777     };
10778     SDNode *Res =
10779       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10780                          array_lengthof(Ops));
10781     return SDValue(Res, 0);
10782   }
10783
10784   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
10785   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10786 }
10787
10788
10789 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
10790   EVT T = Op.getValueType();
10791   DebugLoc DL = Op.getDebugLoc();
10792   unsigned Reg = 0;
10793   unsigned size = 0;
10794   switch(T.getSimpleVT().SimpleTy) {
10795   default:
10796     assert(false && "Invalid value type!");
10797   case MVT::i8:  Reg = X86::AL;  size = 1; break;
10798   case MVT::i16: Reg = X86::AX;  size = 2; break;
10799   case MVT::i32: Reg = X86::EAX; size = 4; break;
10800   case MVT::i64:
10801     assert(Subtarget->is64Bit() && "Node not type legal!");
10802     Reg = X86::RAX; size = 8;
10803     break;
10804   }
10805   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
10806                                     Op.getOperand(2), SDValue());
10807   SDValue Ops[] = { cpIn.getValue(0),
10808                     Op.getOperand(1),
10809                     Op.getOperand(3),
10810                     DAG.getTargetConstant(size, MVT::i8),
10811                     cpIn.getValue(1) };
10812   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10813   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
10814   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
10815                                            Ops, 5, T, MMO);
10816   SDValue cpOut =
10817     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
10818   return cpOut;
10819 }
10820
10821 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
10822                                                  SelectionDAG &DAG) const {
10823   assert(Subtarget->is64Bit() && "Result not type legalized?");
10824   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10825   SDValue TheChain = Op.getOperand(0);
10826   DebugLoc dl = Op.getDebugLoc();
10827   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10828   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
10829   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
10830                                    rax.getValue(2));
10831   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
10832                             DAG.getConstant(32, MVT::i8));
10833   SDValue Ops[] = {
10834     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
10835     rdx.getValue(1)
10836   };
10837   return DAG.getMergeValues(Ops, 2, dl);
10838 }
10839
10840 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
10841                                             SelectionDAG &DAG) const {
10842   EVT SrcVT = Op.getOperand(0).getValueType();
10843   EVT DstVT = Op.getValueType();
10844   assert(Subtarget->is64Bit() && !Subtarget->hasXMMInt() &&
10845          Subtarget->hasMMX() && "Unexpected custom BITCAST");
10846   assert((DstVT == MVT::i64 ||
10847           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
10848          "Unexpected custom BITCAST");
10849   // i64 <=> MMX conversions are Legal.
10850   if (SrcVT==MVT::i64 && DstVT.isVector())
10851     return Op;
10852   if (DstVT==MVT::i64 && SrcVT.isVector())
10853     return Op;
10854   // MMX <=> MMX conversions are Legal.
10855   if (SrcVT.isVector() && DstVT.isVector())
10856     return Op;
10857   // All other conversions need to be expanded.
10858   return SDValue();
10859 }
10860
10861 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
10862   SDNode *Node = Op.getNode();
10863   DebugLoc dl = Node->getDebugLoc();
10864   EVT T = Node->getValueType(0);
10865   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
10866                               DAG.getConstant(0, T), Node->getOperand(2));
10867   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
10868                        cast<AtomicSDNode>(Node)->getMemoryVT(),
10869                        Node->getOperand(0),
10870                        Node->getOperand(1), negOp,
10871                        cast<AtomicSDNode>(Node)->getSrcValue(),
10872                        cast<AtomicSDNode>(Node)->getAlignment(),
10873                        cast<AtomicSDNode>(Node)->getOrdering(),
10874                        cast<AtomicSDNode>(Node)->getSynchScope());
10875 }
10876
10877 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
10878   SDNode *Node = Op.getNode();
10879   DebugLoc dl = Node->getDebugLoc();
10880   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10881
10882   // Convert seq_cst store -> xchg
10883   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
10884   // FIXME: On 32-bit, store -> fist or movq would be more efficient
10885   //        (The only way to get a 16-byte store is cmpxchg16b)
10886   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
10887   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
10888       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
10889     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
10890                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
10891                                  Node->getOperand(0),
10892                                  Node->getOperand(1), Node->getOperand(2),
10893                                  cast<AtomicSDNode>(Node)->getMemOperand(),
10894                                  cast<AtomicSDNode>(Node)->getOrdering(),
10895                                  cast<AtomicSDNode>(Node)->getSynchScope());
10896     return Swap.getValue(1);
10897   }
10898   // Other atomic stores have a simple pattern.
10899   return Op;
10900 }
10901
10902 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
10903   EVT VT = Op.getNode()->getValueType(0);
10904
10905   // Let legalize expand this if it isn't a legal type yet.
10906   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10907     return SDValue();
10908
10909   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10910
10911   unsigned Opc;
10912   bool ExtraOp = false;
10913   switch (Op.getOpcode()) {
10914   default: assert(0 && "Invalid code");
10915   case ISD::ADDC: Opc = X86ISD::ADD; break;
10916   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
10917   case ISD::SUBC: Opc = X86ISD::SUB; break;
10918   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
10919   }
10920
10921   if (!ExtraOp)
10922     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10923                        Op.getOperand(1));
10924   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10925                      Op.getOperand(1), Op.getOperand(2));
10926 }
10927
10928 /// LowerOperation - Provide custom lowering hooks for some operations.
10929 ///
10930 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10931   switch (Op.getOpcode()) {
10932   default: llvm_unreachable("Should not custom lower this!");
10933   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
10934   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op,DAG);
10935   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op,DAG);
10936   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
10937   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
10938   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
10939   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
10940   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
10941   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
10942   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
10943   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
10944   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op, DAG);
10945   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, DAG);
10946   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
10947   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
10948   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
10949   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
10950   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
10951   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
10952   case ISD::SHL_PARTS:
10953   case ISD::SRA_PARTS:
10954   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
10955   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
10956   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
10957   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
10958   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
10959   case ISD::FABS:               return LowerFABS(Op, DAG);
10960   case ISD::FNEG:               return LowerFNEG(Op, DAG);
10961   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
10962   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
10963   case ISD::SETCC:              return LowerSETCC(Op, DAG);
10964   case ISD::SELECT:             return LowerSELECT(Op, DAG);
10965   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
10966   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
10967   case ISD::VASTART:            return LowerVASTART(Op, DAG);
10968   case ISD::VAARG:              return LowerVAARG(Op, DAG);
10969   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
10970   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10971   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
10972   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
10973   case ISD::FRAME_TO_ARGS_OFFSET:
10974                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
10975   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10976   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
10977   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
10978   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
10979   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
10980   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
10981   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
10982   case ISD::MUL:                return LowerMUL(Op, DAG);
10983   case ISD::SRA:
10984   case ISD::SRL:
10985   case ISD::SHL:                return LowerShift(Op, DAG);
10986   case ISD::SADDO:
10987   case ISD::UADDO:
10988   case ISD::SSUBO:
10989   case ISD::USUBO:
10990   case ISD::SMULO:
10991   case ISD::UMULO:              return LowerXALUO(Op, DAG);
10992   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
10993   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
10994   case ISD::ADDC:
10995   case ISD::ADDE:
10996   case ISD::SUBC:
10997   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
10998   case ISD::ADD:                return LowerADD(Op, DAG);
10999   case ISD::SUB:                return LowerSUB(Op, DAG);
11000   }
11001 }
11002
11003 static void ReplaceATOMIC_LOAD(SDNode *Node,
11004                                   SmallVectorImpl<SDValue> &Results,
11005                                   SelectionDAG &DAG) {
11006   DebugLoc dl = Node->getDebugLoc();
11007   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11008
11009   // Convert wide load -> cmpxchg8b/cmpxchg16b
11010   // FIXME: On 32-bit, load -> fild or movq would be more efficient
11011   //        (The only way to get a 16-byte load is cmpxchg16b)
11012   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
11013   SDValue Zero = DAG.getConstant(0, VT);
11014   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
11015                                Node->getOperand(0),
11016                                Node->getOperand(1), Zero, Zero,
11017                                cast<AtomicSDNode>(Node)->getMemOperand(),
11018                                cast<AtomicSDNode>(Node)->getOrdering(),
11019                                cast<AtomicSDNode>(Node)->getSynchScope());
11020   Results.push_back(Swap.getValue(0));
11021   Results.push_back(Swap.getValue(1));
11022 }
11023
11024 void X86TargetLowering::
11025 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
11026                         SelectionDAG &DAG, unsigned NewOp) const {
11027   DebugLoc dl = Node->getDebugLoc();
11028   assert (Node->getValueType(0) == MVT::i64 &&
11029           "Only know how to expand i64 atomics");
11030
11031   SDValue Chain = Node->getOperand(0);
11032   SDValue In1 = Node->getOperand(1);
11033   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11034                              Node->getOperand(2), DAG.getIntPtrConstant(0));
11035   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11036                              Node->getOperand(2), DAG.getIntPtrConstant(1));
11037   SDValue Ops[] = { Chain, In1, In2L, In2H };
11038   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
11039   SDValue Result =
11040     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
11041                             cast<MemSDNode>(Node)->getMemOperand());
11042   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
11043   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
11044   Results.push_back(Result.getValue(2));
11045 }
11046
11047 /// ReplaceNodeResults - Replace a node with an illegal result type
11048 /// with a new node built out of custom code.
11049 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
11050                                            SmallVectorImpl<SDValue>&Results,
11051                                            SelectionDAG &DAG) const {
11052   DebugLoc dl = N->getDebugLoc();
11053   switch (N->getOpcode()) {
11054   default:
11055     assert(false && "Do not know how to custom type legalize this operation!");
11056     return;
11057   case ISD::SIGN_EXTEND_INREG:
11058   case ISD::ADDC:
11059   case ISD::ADDE:
11060   case ISD::SUBC:
11061   case ISD::SUBE:
11062     // We don't want to expand or promote these.
11063     return;
11064   case ISD::FP_TO_SINT: {
11065     std::pair<SDValue,SDValue> Vals =
11066         FP_TO_INTHelper(SDValue(N, 0), DAG, true);
11067     SDValue FIST = Vals.first, StackSlot = Vals.second;
11068     if (FIST.getNode() != 0) {
11069       EVT VT = N->getValueType(0);
11070       // Return a load from the stack slot.
11071       Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
11072                                     MachinePointerInfo(), 
11073                                     false, false, false, 0));
11074     }
11075     return;
11076   }
11077   case ISD::READCYCLECOUNTER: {
11078     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11079     SDValue TheChain = N->getOperand(0);
11080     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11081     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
11082                                      rd.getValue(1));
11083     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
11084                                      eax.getValue(2));
11085     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
11086     SDValue Ops[] = { eax, edx };
11087     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
11088     Results.push_back(edx.getValue(1));
11089     return;
11090   }
11091   case ISD::ATOMIC_CMP_SWAP: {
11092     EVT T = N->getValueType(0);
11093     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
11094     bool Regs64bit = T == MVT::i128;
11095     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
11096     SDValue cpInL, cpInH;
11097     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11098                         DAG.getConstant(0, HalfT));
11099     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11100                         DAG.getConstant(1, HalfT));
11101     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
11102                              Regs64bit ? X86::RAX : X86::EAX,
11103                              cpInL, SDValue());
11104     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
11105                              Regs64bit ? X86::RDX : X86::EDX,
11106                              cpInH, cpInL.getValue(1));
11107     SDValue swapInL, swapInH;
11108     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11109                           DAG.getConstant(0, HalfT));
11110     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11111                           DAG.getConstant(1, HalfT));
11112     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
11113                                Regs64bit ? X86::RBX : X86::EBX,
11114                                swapInL, cpInH.getValue(1));
11115     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
11116                                Regs64bit ? X86::RCX : X86::ECX, 
11117                                swapInH, swapInL.getValue(1));
11118     SDValue Ops[] = { swapInH.getValue(0),
11119                       N->getOperand(1),
11120                       swapInH.getValue(1) };
11121     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11122     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
11123     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
11124                                   X86ISD::LCMPXCHG8_DAG;
11125     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
11126                                              Ops, 3, T, MMO);
11127     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
11128                                         Regs64bit ? X86::RAX : X86::EAX,
11129                                         HalfT, Result.getValue(1));
11130     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
11131                                         Regs64bit ? X86::RDX : X86::EDX,
11132                                         HalfT, cpOutL.getValue(2));
11133     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
11134     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
11135     Results.push_back(cpOutH.getValue(1));
11136     return;
11137   }
11138   case ISD::ATOMIC_LOAD_ADD:
11139     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
11140     return;
11141   case ISD::ATOMIC_LOAD_AND:
11142     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
11143     return;
11144   case ISD::ATOMIC_LOAD_NAND:
11145     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
11146     return;
11147   case ISD::ATOMIC_LOAD_OR:
11148     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
11149     return;
11150   case ISD::ATOMIC_LOAD_SUB:
11151     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
11152     return;
11153   case ISD::ATOMIC_LOAD_XOR:
11154     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
11155     return;
11156   case ISD::ATOMIC_SWAP:
11157     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
11158     return;
11159   case ISD::ATOMIC_LOAD:
11160     ReplaceATOMIC_LOAD(N, Results, DAG);
11161   }
11162 }
11163
11164 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
11165   switch (Opcode) {
11166   default: return NULL;
11167   case X86ISD::BSF:                return "X86ISD::BSF";
11168   case X86ISD::BSR:                return "X86ISD::BSR";
11169   case X86ISD::SHLD:               return "X86ISD::SHLD";
11170   case X86ISD::SHRD:               return "X86ISD::SHRD";
11171   case X86ISD::FAND:               return "X86ISD::FAND";
11172   case X86ISD::FOR:                return "X86ISD::FOR";
11173   case X86ISD::FXOR:               return "X86ISD::FXOR";
11174   case X86ISD::FSRL:               return "X86ISD::FSRL";
11175   case X86ISD::FILD:               return "X86ISD::FILD";
11176   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
11177   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
11178   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
11179   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
11180   case X86ISD::FLD:                return "X86ISD::FLD";
11181   case X86ISD::FST:                return "X86ISD::FST";
11182   case X86ISD::CALL:               return "X86ISD::CALL";
11183   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
11184   case X86ISD::BT:                 return "X86ISD::BT";
11185   case X86ISD::CMP:                return "X86ISD::CMP";
11186   case X86ISD::COMI:               return "X86ISD::COMI";
11187   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
11188   case X86ISD::SETCC:              return "X86ISD::SETCC";
11189   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
11190   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
11191   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
11192   case X86ISD::CMOV:               return "X86ISD::CMOV";
11193   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
11194   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
11195   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
11196   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
11197   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
11198   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
11199   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
11200   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
11201   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
11202   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
11203   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
11204   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
11205   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
11206   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
11207   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
11208   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
11209   case X86ISD::FHADD:              return "X86ISD::FHADD";
11210   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
11211   case X86ISD::FMAX:               return "X86ISD::FMAX";
11212   case X86ISD::FMIN:               return "X86ISD::FMIN";
11213   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
11214   case X86ISD::FRCP:               return "X86ISD::FRCP";
11215   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
11216   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
11217   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
11218   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
11219   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
11220   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
11221   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
11222   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
11223   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
11224   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
11225   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
11226   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
11227   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
11228   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
11229   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
11230   case X86ISD::VSHL:               return "X86ISD::VSHL";
11231   case X86ISD::VSRL:               return "X86ISD::VSRL";
11232   case X86ISD::CMPPD:              return "X86ISD::CMPPD";
11233   case X86ISD::CMPPS:              return "X86ISD::CMPPS";
11234   case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
11235   case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
11236   case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
11237   case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
11238   case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
11239   case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
11240   case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
11241   case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
11242   case X86ISD::ADD:                return "X86ISD::ADD";
11243   case X86ISD::SUB:                return "X86ISD::SUB";
11244   case X86ISD::ADC:                return "X86ISD::ADC";
11245   case X86ISD::SBB:                return "X86ISD::SBB";
11246   case X86ISD::SMUL:               return "X86ISD::SMUL";
11247   case X86ISD::UMUL:               return "X86ISD::UMUL";
11248   case X86ISD::INC:                return "X86ISD::INC";
11249   case X86ISD::DEC:                return "X86ISD::DEC";
11250   case X86ISD::OR:                 return "X86ISD::OR";
11251   case X86ISD::XOR:                return "X86ISD::XOR";
11252   case X86ISD::AND:                return "X86ISD::AND";
11253   case X86ISD::ANDN:               return "X86ISD::ANDN";
11254   case X86ISD::BLSI:               return "X86ISD::BLSI";
11255   case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
11256   case X86ISD::BLSR:               return "X86ISD::BLSR";
11257   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
11258   case X86ISD::PTEST:              return "X86ISD::PTEST";
11259   case X86ISD::TESTP:              return "X86ISD::TESTP";
11260   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
11261   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
11262   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
11263   case X86ISD::PSHUFHW_LD:         return "X86ISD::PSHUFHW_LD";
11264   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
11265   case X86ISD::PSHUFLW_LD:         return "X86ISD::PSHUFLW_LD";
11266   case X86ISD::SHUFPS:             return "X86ISD::SHUFPS";
11267   case X86ISD::SHUFPD:             return "X86ISD::SHUFPD";
11268   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
11269   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
11270   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
11271   case X86ISD::MOVHLPD:            return "X86ISD::MOVHLPD";
11272   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
11273   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
11274   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
11275   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
11276   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
11277   case X86ISD::MOVSHDUP_LD:        return "X86ISD::MOVSHDUP_LD";
11278   case X86ISD::MOVSLDUP_LD:        return "X86ISD::MOVSLDUP_LD";
11279   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
11280   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
11281   case X86ISD::UNPCKLPS:           return "X86ISD::UNPCKLPS";
11282   case X86ISD::UNPCKLPD:           return "X86ISD::UNPCKLPD";
11283   case X86ISD::VUNPCKLPSY:         return "X86ISD::VUNPCKLPSY";
11284   case X86ISD::VUNPCKLPDY:         return "X86ISD::VUNPCKLPDY";
11285   case X86ISD::UNPCKHPS:           return "X86ISD::UNPCKHPS";
11286   case X86ISD::UNPCKHPD:           return "X86ISD::UNPCKHPD";
11287   case X86ISD::PUNPCKLBW:          return "X86ISD::PUNPCKLBW";
11288   case X86ISD::PUNPCKLWD:          return "X86ISD::PUNPCKLWD";
11289   case X86ISD::PUNPCKLDQ:          return "X86ISD::PUNPCKLDQ";
11290   case X86ISD::PUNPCKLQDQ:         return "X86ISD::PUNPCKLQDQ";
11291   case X86ISD::PUNPCKHBW:          return "X86ISD::PUNPCKHBW";
11292   case X86ISD::PUNPCKHWD:          return "X86ISD::PUNPCKHWD";
11293   case X86ISD::PUNPCKHDQ:          return "X86ISD::PUNPCKHDQ";
11294   case X86ISD::PUNPCKHQDQ:         return "X86ISD::PUNPCKHQDQ";
11295   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
11296   case X86ISD::VPERMILPS:          return "X86ISD::VPERMILPS";
11297   case X86ISD::VPERMILPSY:         return "X86ISD::VPERMILPSY";
11298   case X86ISD::VPERMILPD:          return "X86ISD::VPERMILPD";
11299   case X86ISD::VPERMILPDY:         return "X86ISD::VPERMILPDY";
11300   case X86ISD::VPERM2F128:         return "X86ISD::VPERM2F128";
11301   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
11302   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
11303   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
11304   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
11305   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
11306   }
11307 }
11308
11309 // isLegalAddressingMode - Return true if the addressing mode represented
11310 // by AM is legal for this target, for a load/store of the specified type.
11311 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
11312                                               Type *Ty) const {
11313   // X86 supports extremely general addressing modes.
11314   CodeModel::Model M = getTargetMachine().getCodeModel();
11315   Reloc::Model R = getTargetMachine().getRelocationModel();
11316
11317   // X86 allows a sign-extended 32-bit immediate field as a displacement.
11318   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
11319     return false;
11320
11321   if (AM.BaseGV) {
11322     unsigned GVFlags =
11323       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
11324
11325     // If a reference to this global requires an extra load, we can't fold it.
11326     if (isGlobalStubReference(GVFlags))
11327       return false;
11328
11329     // If BaseGV requires a register for the PIC base, we cannot also have a
11330     // BaseReg specified.
11331     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
11332       return false;
11333
11334     // If lower 4G is not available, then we must use rip-relative addressing.
11335     if ((M != CodeModel::Small || R != Reloc::Static) &&
11336         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
11337       return false;
11338   }
11339
11340   switch (AM.Scale) {
11341   case 0:
11342   case 1:
11343   case 2:
11344   case 4:
11345   case 8:
11346     // These scales always work.
11347     break;
11348   case 3:
11349   case 5:
11350   case 9:
11351     // These scales are formed with basereg+scalereg.  Only accept if there is
11352     // no basereg yet.
11353     if (AM.HasBaseReg)
11354       return false;
11355     break;
11356   default:  // Other stuff never works.
11357     return false;
11358   }
11359
11360   return true;
11361 }
11362
11363
11364 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11365   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11366     return false;
11367   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11368   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11369   if (NumBits1 <= NumBits2)
11370     return false;
11371   return true;
11372 }
11373
11374 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11375   if (!VT1.isInteger() || !VT2.isInteger())
11376     return false;
11377   unsigned NumBits1 = VT1.getSizeInBits();
11378   unsigned NumBits2 = VT2.getSizeInBits();
11379   if (NumBits1 <= NumBits2)
11380     return false;
11381   return true;
11382 }
11383
11384 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
11385   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11386   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
11387 }
11388
11389 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
11390   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11391   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
11392 }
11393
11394 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
11395   // i16 instructions are longer (0x66 prefix) and potentially slower.
11396   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
11397 }
11398
11399 /// isShuffleMaskLegal - Targets can use this to indicate that they only
11400 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
11401 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
11402 /// are assumed to be legal.
11403 bool
11404 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
11405                                       EVT VT) const {
11406   // Very little shuffling can be done for 64-bit vectors right now.
11407   if (VT.getSizeInBits() == 64)
11408     return isPALIGNRMask(M, VT, Subtarget->hasSSSE3orAVX());
11409
11410   // FIXME: pshufb, blends, shifts.
11411   return (VT.getVectorNumElements() == 2 ||
11412           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
11413           isMOVLMask(M, VT) ||
11414           isSHUFPMask(M, VT) ||
11415           isPSHUFDMask(M, VT) ||
11416           isPSHUFHWMask(M, VT) ||
11417           isPSHUFLWMask(M, VT) ||
11418           isPALIGNRMask(M, VT, Subtarget->hasSSSE3orAVX()) ||
11419           isUNPCKLMask(M, VT, Subtarget->hasAVX2()) ||
11420           isUNPCKHMask(M, VT, Subtarget->hasAVX2()) ||
11421           isUNPCKL_v_undef_Mask(M, VT) ||
11422           isUNPCKH_v_undef_Mask(M, VT));
11423 }
11424
11425 bool
11426 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
11427                                           EVT VT) const {
11428   unsigned NumElts = VT.getVectorNumElements();
11429   // FIXME: This collection of masks seems suspect.
11430   if (NumElts == 2)
11431     return true;
11432   if (NumElts == 4 && VT.getSizeInBits() == 128) {
11433     return (isMOVLMask(Mask, VT)  ||
11434             isCommutedMOVLMask(Mask, VT, true) ||
11435             isSHUFPMask(Mask, VT) ||
11436             isCommutedSHUFPMask(Mask, VT));
11437   }
11438   return false;
11439 }
11440
11441 //===----------------------------------------------------------------------===//
11442 //                           X86 Scheduler Hooks
11443 //===----------------------------------------------------------------------===//
11444
11445 // private utility function
11446 MachineBasicBlock *
11447 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
11448                                                        MachineBasicBlock *MBB,
11449                                                        unsigned regOpc,
11450                                                        unsigned immOpc,
11451                                                        unsigned LoadOpc,
11452                                                        unsigned CXchgOpc,
11453                                                        unsigned notOpc,
11454                                                        unsigned EAXreg,
11455                                                        TargetRegisterClass *RC,
11456                                                        bool invSrc) const {
11457   // For the atomic bitwise operator, we generate
11458   //   thisMBB:
11459   //   newMBB:
11460   //     ld  t1 = [bitinstr.addr]
11461   //     op  t2 = t1, [bitinstr.val]
11462   //     mov EAX = t1
11463   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
11464   //     bz  newMBB
11465   //     fallthrough -->nextMBB
11466   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11467   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11468   MachineFunction::iterator MBBIter = MBB;
11469   ++MBBIter;
11470
11471   /// First build the CFG
11472   MachineFunction *F = MBB->getParent();
11473   MachineBasicBlock *thisMBB = MBB;
11474   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11475   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11476   F->insert(MBBIter, newMBB);
11477   F->insert(MBBIter, nextMBB);
11478
11479   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11480   nextMBB->splice(nextMBB->begin(), thisMBB,
11481                   llvm::next(MachineBasicBlock::iterator(bInstr)),
11482                   thisMBB->end());
11483   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11484
11485   // Update thisMBB to fall through to newMBB
11486   thisMBB->addSuccessor(newMBB);
11487
11488   // newMBB jumps to itself and fall through to nextMBB
11489   newMBB->addSuccessor(nextMBB);
11490   newMBB->addSuccessor(newMBB);
11491
11492   // Insert instructions into newMBB based on incoming instruction
11493   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11494          "unexpected number of operands");
11495   DebugLoc dl = bInstr->getDebugLoc();
11496   MachineOperand& destOper = bInstr->getOperand(0);
11497   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11498   int numArgs = bInstr->getNumOperands() - 1;
11499   for (int i=0; i < numArgs; ++i)
11500     argOpers[i] = &bInstr->getOperand(i+1);
11501
11502   // x86 address has 4 operands: base, index, scale, and displacement
11503   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11504   int valArgIndx = lastAddrIndx + 1;
11505
11506   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11507   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
11508   for (int i=0; i <= lastAddrIndx; ++i)
11509     (*MIB).addOperand(*argOpers[i]);
11510
11511   unsigned tt = F->getRegInfo().createVirtualRegister(RC);
11512   if (invSrc) {
11513     MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
11514   }
11515   else
11516     tt = t1;
11517
11518   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11519   assert((argOpers[valArgIndx]->isReg() ||
11520           argOpers[valArgIndx]->isImm()) &&
11521          "invalid operand");
11522   if (argOpers[valArgIndx]->isReg())
11523     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
11524   else
11525     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
11526   MIB.addReg(tt);
11527   (*MIB).addOperand(*argOpers[valArgIndx]);
11528
11529   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
11530   MIB.addReg(t1);
11531
11532   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
11533   for (int i=0; i <= lastAddrIndx; ++i)
11534     (*MIB).addOperand(*argOpers[i]);
11535   MIB.addReg(t2);
11536   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11537   (*MIB).setMemRefs(bInstr->memoperands_begin(),
11538                     bInstr->memoperands_end());
11539
11540   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11541   MIB.addReg(EAXreg);
11542
11543   // insert branch
11544   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11545
11546   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
11547   return nextMBB;
11548 }
11549
11550 // private utility function:  64 bit atomics on 32 bit host.
11551 MachineBasicBlock *
11552 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
11553                                                        MachineBasicBlock *MBB,
11554                                                        unsigned regOpcL,
11555                                                        unsigned regOpcH,
11556                                                        unsigned immOpcL,
11557                                                        unsigned immOpcH,
11558                                                        bool invSrc) const {
11559   // For the atomic bitwise operator, we generate
11560   //   thisMBB (instructions are in pairs, except cmpxchg8b)
11561   //     ld t1,t2 = [bitinstr.addr]
11562   //   newMBB:
11563   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
11564   //     op  t5, t6 <- out1, out2, [bitinstr.val]
11565   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
11566   //     mov ECX, EBX <- t5, t6
11567   //     mov EAX, EDX <- t1, t2
11568   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
11569   //     mov t3, t4 <- EAX, EDX
11570   //     bz  newMBB
11571   //     result in out1, out2
11572   //     fallthrough -->nextMBB
11573
11574   const TargetRegisterClass *RC = X86::GR32RegisterClass;
11575   const unsigned LoadOpc = X86::MOV32rm;
11576   const unsigned NotOpc = X86::NOT32r;
11577   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11578   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11579   MachineFunction::iterator MBBIter = MBB;
11580   ++MBBIter;
11581
11582   /// First build the CFG
11583   MachineFunction *F = MBB->getParent();
11584   MachineBasicBlock *thisMBB = MBB;
11585   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11586   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11587   F->insert(MBBIter, newMBB);
11588   F->insert(MBBIter, nextMBB);
11589
11590   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11591   nextMBB->splice(nextMBB->begin(), thisMBB,
11592                   llvm::next(MachineBasicBlock::iterator(bInstr)),
11593                   thisMBB->end());
11594   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11595
11596   // Update thisMBB to fall through to newMBB
11597   thisMBB->addSuccessor(newMBB);
11598
11599   // newMBB jumps to itself and fall through to nextMBB
11600   newMBB->addSuccessor(nextMBB);
11601   newMBB->addSuccessor(newMBB);
11602
11603   DebugLoc dl = bInstr->getDebugLoc();
11604   // Insert instructions into newMBB based on incoming instruction
11605   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
11606   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
11607          "unexpected number of operands");
11608   MachineOperand& dest1Oper = bInstr->getOperand(0);
11609   MachineOperand& dest2Oper = bInstr->getOperand(1);
11610   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11611   for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
11612     argOpers[i] = &bInstr->getOperand(i+2);
11613
11614     // We use some of the operands multiple times, so conservatively just
11615     // clear any kill flags that might be present.
11616     if (argOpers[i]->isReg() && argOpers[i]->isUse())
11617       argOpers[i]->setIsKill(false);
11618   }
11619
11620   // x86 address has 5 operands: base, index, scale, displacement, and segment.
11621   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11622
11623   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11624   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
11625   for (int i=0; i <= lastAddrIndx; ++i)
11626     (*MIB).addOperand(*argOpers[i]);
11627   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11628   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
11629   // add 4 to displacement.
11630   for (int i=0; i <= lastAddrIndx-2; ++i)
11631     (*MIB).addOperand(*argOpers[i]);
11632   MachineOperand newOp3 = *(argOpers[3]);
11633   if (newOp3.isImm())
11634     newOp3.setImm(newOp3.getImm()+4);
11635   else
11636     newOp3.setOffset(newOp3.getOffset()+4);
11637   (*MIB).addOperand(newOp3);
11638   (*MIB).addOperand(*argOpers[lastAddrIndx]);
11639
11640   // t3/4 are defined later, at the bottom of the loop
11641   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11642   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
11643   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
11644     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
11645   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
11646     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
11647
11648   // The subsequent operations should be using the destination registers of
11649   //the PHI instructions.
11650   if (invSrc) {
11651     t1 = F->getRegInfo().createVirtualRegister(RC);
11652     t2 = F->getRegInfo().createVirtualRegister(RC);
11653     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
11654     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
11655   } else {
11656     t1 = dest1Oper.getReg();
11657     t2 = dest2Oper.getReg();
11658   }
11659
11660   int valArgIndx = lastAddrIndx + 1;
11661   assert((argOpers[valArgIndx]->isReg() ||
11662           argOpers[valArgIndx]->isImm()) &&
11663          "invalid operand");
11664   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
11665   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
11666   if (argOpers[valArgIndx]->isReg())
11667     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
11668   else
11669     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
11670   if (regOpcL != X86::MOV32rr)
11671     MIB.addReg(t1);
11672   (*MIB).addOperand(*argOpers[valArgIndx]);
11673   assert(argOpers[valArgIndx + 1]->isReg() ==
11674          argOpers[valArgIndx]->isReg());
11675   assert(argOpers[valArgIndx + 1]->isImm() ==
11676          argOpers[valArgIndx]->isImm());
11677   if (argOpers[valArgIndx + 1]->isReg())
11678     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
11679   else
11680     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
11681   if (regOpcH != X86::MOV32rr)
11682     MIB.addReg(t2);
11683   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
11684
11685   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11686   MIB.addReg(t1);
11687   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
11688   MIB.addReg(t2);
11689
11690   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
11691   MIB.addReg(t5);
11692   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
11693   MIB.addReg(t6);
11694
11695   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
11696   for (int i=0; i <= lastAddrIndx; ++i)
11697     (*MIB).addOperand(*argOpers[i]);
11698
11699   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11700   (*MIB).setMemRefs(bInstr->memoperands_begin(),
11701                     bInstr->memoperands_end());
11702
11703   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
11704   MIB.addReg(X86::EAX);
11705   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
11706   MIB.addReg(X86::EDX);
11707
11708   // insert branch
11709   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11710
11711   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
11712   return nextMBB;
11713 }
11714
11715 // private utility function
11716 MachineBasicBlock *
11717 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
11718                                                       MachineBasicBlock *MBB,
11719                                                       unsigned cmovOpc) const {
11720   // For the atomic min/max operator, we generate
11721   //   thisMBB:
11722   //   newMBB:
11723   //     ld t1 = [min/max.addr]
11724   //     mov t2 = [min/max.val]
11725   //     cmp  t1, t2
11726   //     cmov[cond] t2 = t1
11727   //     mov EAX = t1
11728   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
11729   //     bz   newMBB
11730   //     fallthrough -->nextMBB
11731   //
11732   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11733   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11734   MachineFunction::iterator MBBIter = MBB;
11735   ++MBBIter;
11736
11737   /// First build the CFG
11738   MachineFunction *F = MBB->getParent();
11739   MachineBasicBlock *thisMBB = MBB;
11740   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11741   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11742   F->insert(MBBIter, newMBB);
11743   F->insert(MBBIter, nextMBB);
11744
11745   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11746   nextMBB->splice(nextMBB->begin(), thisMBB,
11747                   llvm::next(MachineBasicBlock::iterator(mInstr)),
11748                   thisMBB->end());
11749   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11750
11751   // Update thisMBB to fall through to newMBB
11752   thisMBB->addSuccessor(newMBB);
11753
11754   // newMBB jumps to newMBB and fall through to nextMBB
11755   newMBB->addSuccessor(nextMBB);
11756   newMBB->addSuccessor(newMBB);
11757
11758   DebugLoc dl = mInstr->getDebugLoc();
11759   // Insert instructions into newMBB based on incoming instruction
11760   assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11761          "unexpected number of operands");
11762   MachineOperand& destOper = mInstr->getOperand(0);
11763   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11764   int numArgs = mInstr->getNumOperands() - 1;
11765   for (int i=0; i < numArgs; ++i)
11766     argOpers[i] = &mInstr->getOperand(i+1);
11767
11768   // x86 address has 4 operands: base, index, scale, and displacement
11769   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11770   int valArgIndx = lastAddrIndx + 1;
11771
11772   unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11773   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
11774   for (int i=0; i <= lastAddrIndx; ++i)
11775     (*MIB).addOperand(*argOpers[i]);
11776
11777   // We only support register and immediate values
11778   assert((argOpers[valArgIndx]->isReg() ||
11779           argOpers[valArgIndx]->isImm()) &&
11780          "invalid operand");
11781
11782   unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11783   if (argOpers[valArgIndx]->isReg())
11784     MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
11785   else
11786     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
11787   (*MIB).addOperand(*argOpers[valArgIndx]);
11788
11789   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11790   MIB.addReg(t1);
11791
11792   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
11793   MIB.addReg(t1);
11794   MIB.addReg(t2);
11795
11796   // Generate movc
11797   unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11798   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
11799   MIB.addReg(t2);
11800   MIB.addReg(t1);
11801
11802   // Cmp and exchange if none has modified the memory location
11803   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
11804   for (int i=0; i <= lastAddrIndx; ++i)
11805     (*MIB).addOperand(*argOpers[i]);
11806   MIB.addReg(t3);
11807   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11808   (*MIB).setMemRefs(mInstr->memoperands_begin(),
11809                     mInstr->memoperands_end());
11810
11811   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11812   MIB.addReg(X86::EAX);
11813
11814   // insert branch
11815   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11816
11817   mInstr->eraseFromParent();   // The pseudo instruction is gone now.
11818   return nextMBB;
11819 }
11820
11821 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
11822 // or XMM0_V32I8 in AVX all of this code can be replaced with that
11823 // in the .td file.
11824 MachineBasicBlock *
11825 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
11826                             unsigned numArgs, bool memArg) const {
11827   assert(Subtarget->hasSSE42orAVX() &&
11828          "Target must have SSE4.2 or AVX features enabled");
11829
11830   DebugLoc dl = MI->getDebugLoc();
11831   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11832   unsigned Opc;
11833   if (!Subtarget->hasAVX()) {
11834     if (memArg)
11835       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
11836     else
11837       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
11838   } else {
11839     if (memArg)
11840       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
11841     else
11842       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
11843   }
11844
11845   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
11846   for (unsigned i = 0; i < numArgs; ++i) {
11847     MachineOperand &Op = MI->getOperand(i+1);
11848     if (!(Op.isReg() && Op.isImplicit()))
11849       MIB.addOperand(Op);
11850   }
11851   BuildMI(*BB, MI, dl,
11852     TII->get(Subtarget->hasAVX() ? X86::VMOVAPSrr : X86::MOVAPSrr),
11853              MI->getOperand(0).getReg())
11854     .addReg(X86::XMM0);
11855
11856   MI->eraseFromParent();
11857   return BB;
11858 }
11859
11860 MachineBasicBlock *
11861 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
11862   DebugLoc dl = MI->getDebugLoc();
11863   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11864
11865   // Address into RAX/EAX, other two args into ECX, EDX.
11866   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
11867   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11868   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
11869   for (int i = 0; i < X86::AddrNumOperands; ++i)
11870     MIB.addOperand(MI->getOperand(i));
11871
11872   unsigned ValOps = X86::AddrNumOperands;
11873   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11874     .addReg(MI->getOperand(ValOps).getReg());
11875   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
11876     .addReg(MI->getOperand(ValOps+1).getReg());
11877
11878   // The instruction doesn't actually take any operands though.
11879   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
11880
11881   MI->eraseFromParent(); // The pseudo is gone now.
11882   return BB;
11883 }
11884
11885 MachineBasicBlock *
11886 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
11887   DebugLoc dl = MI->getDebugLoc();
11888   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11889
11890   // First arg in ECX, the second in EAX.
11891   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11892     .addReg(MI->getOperand(0).getReg());
11893   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
11894     .addReg(MI->getOperand(1).getReg());
11895
11896   // The instruction doesn't actually take any operands though.
11897   BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
11898
11899   MI->eraseFromParent(); // The pseudo is gone now.
11900   return BB;
11901 }
11902
11903 MachineBasicBlock *
11904 X86TargetLowering::EmitVAARG64WithCustomInserter(
11905                    MachineInstr *MI,
11906                    MachineBasicBlock *MBB) const {
11907   // Emit va_arg instruction on X86-64.
11908
11909   // Operands to this pseudo-instruction:
11910   // 0  ) Output        : destination address (reg)
11911   // 1-5) Input         : va_list address (addr, i64mem)
11912   // 6  ) ArgSize       : Size (in bytes) of vararg type
11913   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
11914   // 8  ) Align         : Alignment of type
11915   // 9  ) EFLAGS (implicit-def)
11916
11917   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
11918   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
11919
11920   unsigned DestReg = MI->getOperand(0).getReg();
11921   MachineOperand &Base = MI->getOperand(1);
11922   MachineOperand &Scale = MI->getOperand(2);
11923   MachineOperand &Index = MI->getOperand(3);
11924   MachineOperand &Disp = MI->getOperand(4);
11925   MachineOperand &Segment = MI->getOperand(5);
11926   unsigned ArgSize = MI->getOperand(6).getImm();
11927   unsigned ArgMode = MI->getOperand(7).getImm();
11928   unsigned Align = MI->getOperand(8).getImm();
11929
11930   // Memory Reference
11931   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
11932   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
11933   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
11934
11935   // Machine Information
11936   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11937   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
11938   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
11939   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
11940   DebugLoc DL = MI->getDebugLoc();
11941
11942   // struct va_list {
11943   //   i32   gp_offset
11944   //   i32   fp_offset
11945   //   i64   overflow_area (address)
11946   //   i64   reg_save_area (address)
11947   // }
11948   // sizeof(va_list) = 24
11949   // alignment(va_list) = 8
11950
11951   unsigned TotalNumIntRegs = 6;
11952   unsigned TotalNumXMMRegs = 8;
11953   bool UseGPOffset = (ArgMode == 1);
11954   bool UseFPOffset = (ArgMode == 2);
11955   unsigned MaxOffset = TotalNumIntRegs * 8 +
11956                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
11957
11958   /* Align ArgSize to a multiple of 8 */
11959   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
11960   bool NeedsAlign = (Align > 8);
11961
11962   MachineBasicBlock *thisMBB = MBB;
11963   MachineBasicBlock *overflowMBB;
11964   MachineBasicBlock *offsetMBB;
11965   MachineBasicBlock *endMBB;
11966
11967   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
11968   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
11969   unsigned OffsetReg = 0;
11970
11971   if (!UseGPOffset && !UseFPOffset) {
11972     // If we only pull from the overflow region, we don't create a branch.
11973     // We don't need to alter control flow.
11974     OffsetDestReg = 0; // unused
11975     OverflowDestReg = DestReg;
11976
11977     offsetMBB = NULL;
11978     overflowMBB = thisMBB;
11979     endMBB = thisMBB;
11980   } else {
11981     // First emit code to check if gp_offset (or fp_offset) is below the bound.
11982     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
11983     // If not, pull from overflow_area. (branch to overflowMBB)
11984     //
11985     //       thisMBB
11986     //         |     .
11987     //         |        .
11988     //     offsetMBB   overflowMBB
11989     //         |        .
11990     //         |     .
11991     //        endMBB
11992
11993     // Registers for the PHI in endMBB
11994     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
11995     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
11996
11997     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11998     MachineFunction *MF = MBB->getParent();
11999     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12000     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12001     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12002
12003     MachineFunction::iterator MBBIter = MBB;
12004     ++MBBIter;
12005
12006     // Insert the new basic blocks
12007     MF->insert(MBBIter, offsetMBB);
12008     MF->insert(MBBIter, overflowMBB);
12009     MF->insert(MBBIter, endMBB);
12010
12011     // Transfer the remainder of MBB and its successor edges to endMBB.
12012     endMBB->splice(endMBB->begin(), thisMBB,
12013                     llvm::next(MachineBasicBlock::iterator(MI)),
12014                     thisMBB->end());
12015     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
12016
12017     // Make offsetMBB and overflowMBB successors of thisMBB
12018     thisMBB->addSuccessor(offsetMBB);
12019     thisMBB->addSuccessor(overflowMBB);
12020
12021     // endMBB is a successor of both offsetMBB and overflowMBB
12022     offsetMBB->addSuccessor(endMBB);
12023     overflowMBB->addSuccessor(endMBB);
12024
12025     // Load the offset value into a register
12026     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12027     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
12028       .addOperand(Base)
12029       .addOperand(Scale)
12030       .addOperand(Index)
12031       .addDisp(Disp, UseFPOffset ? 4 : 0)
12032       .addOperand(Segment)
12033       .setMemRefs(MMOBegin, MMOEnd);
12034
12035     // Check if there is enough room left to pull this argument.
12036     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
12037       .addReg(OffsetReg)
12038       .addImm(MaxOffset + 8 - ArgSizeA8);
12039
12040     // Branch to "overflowMBB" if offset >= max
12041     // Fall through to "offsetMBB" otherwise
12042     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
12043       .addMBB(overflowMBB);
12044   }
12045
12046   // In offsetMBB, emit code to use the reg_save_area.
12047   if (offsetMBB) {
12048     assert(OffsetReg != 0);
12049
12050     // Read the reg_save_area address.
12051     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
12052     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
12053       .addOperand(Base)
12054       .addOperand(Scale)
12055       .addOperand(Index)
12056       .addDisp(Disp, 16)
12057       .addOperand(Segment)
12058       .setMemRefs(MMOBegin, MMOEnd);
12059
12060     // Zero-extend the offset
12061     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
12062       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
12063         .addImm(0)
12064         .addReg(OffsetReg)
12065         .addImm(X86::sub_32bit);
12066
12067     // Add the offset to the reg_save_area to get the final address.
12068     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
12069       .addReg(OffsetReg64)
12070       .addReg(RegSaveReg);
12071
12072     // Compute the offset for the next argument
12073     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12074     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
12075       .addReg(OffsetReg)
12076       .addImm(UseFPOffset ? 16 : 8);
12077
12078     // Store it back into the va_list.
12079     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
12080       .addOperand(Base)
12081       .addOperand(Scale)
12082       .addOperand(Index)
12083       .addDisp(Disp, UseFPOffset ? 4 : 0)
12084       .addOperand(Segment)
12085       .addReg(NextOffsetReg)
12086       .setMemRefs(MMOBegin, MMOEnd);
12087
12088     // Jump to endMBB
12089     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
12090       .addMBB(endMBB);
12091   }
12092
12093   //
12094   // Emit code to use overflow area
12095   //
12096
12097   // Load the overflow_area address into a register.
12098   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
12099   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
12100     .addOperand(Base)
12101     .addOperand(Scale)
12102     .addOperand(Index)
12103     .addDisp(Disp, 8)
12104     .addOperand(Segment)
12105     .setMemRefs(MMOBegin, MMOEnd);
12106
12107   // If we need to align it, do so. Otherwise, just copy the address
12108   // to OverflowDestReg.
12109   if (NeedsAlign) {
12110     // Align the overflow address
12111     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
12112     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
12113
12114     // aligned_addr = (addr + (align-1)) & ~(align-1)
12115     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
12116       .addReg(OverflowAddrReg)
12117       .addImm(Align-1);
12118
12119     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
12120       .addReg(TmpReg)
12121       .addImm(~(uint64_t)(Align-1));
12122   } else {
12123     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
12124       .addReg(OverflowAddrReg);
12125   }
12126
12127   // Compute the next overflow address after this argument.
12128   // (the overflow address should be kept 8-byte aligned)
12129   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
12130   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
12131     .addReg(OverflowDestReg)
12132     .addImm(ArgSizeA8);
12133
12134   // Store the new overflow address.
12135   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
12136     .addOperand(Base)
12137     .addOperand(Scale)
12138     .addOperand(Index)
12139     .addDisp(Disp, 8)
12140     .addOperand(Segment)
12141     .addReg(NextAddrReg)
12142     .setMemRefs(MMOBegin, MMOEnd);
12143
12144   // If we branched, emit the PHI to the front of endMBB.
12145   if (offsetMBB) {
12146     BuildMI(*endMBB, endMBB->begin(), DL,
12147             TII->get(X86::PHI), DestReg)
12148       .addReg(OffsetDestReg).addMBB(offsetMBB)
12149       .addReg(OverflowDestReg).addMBB(overflowMBB);
12150   }
12151
12152   // Erase the pseudo instruction
12153   MI->eraseFromParent();
12154
12155   return endMBB;
12156 }
12157
12158 MachineBasicBlock *
12159 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
12160                                                  MachineInstr *MI,
12161                                                  MachineBasicBlock *MBB) const {
12162   // Emit code to save XMM registers to the stack. The ABI says that the
12163   // number of registers to save is given in %al, so it's theoretically
12164   // possible to do an indirect jump trick to avoid saving all of them,
12165   // however this code takes a simpler approach and just executes all
12166   // of the stores if %al is non-zero. It's less code, and it's probably
12167   // easier on the hardware branch predictor, and stores aren't all that
12168   // expensive anyway.
12169
12170   // Create the new basic blocks. One block contains all the XMM stores,
12171   // and one block is the final destination regardless of whether any
12172   // stores were performed.
12173   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12174   MachineFunction *F = MBB->getParent();
12175   MachineFunction::iterator MBBIter = MBB;
12176   ++MBBIter;
12177   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
12178   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
12179   F->insert(MBBIter, XMMSaveMBB);
12180   F->insert(MBBIter, EndMBB);
12181
12182   // Transfer the remainder of MBB and its successor edges to EndMBB.
12183   EndMBB->splice(EndMBB->begin(), MBB,
12184                  llvm::next(MachineBasicBlock::iterator(MI)),
12185                  MBB->end());
12186   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
12187
12188   // The original block will now fall through to the XMM save block.
12189   MBB->addSuccessor(XMMSaveMBB);
12190   // The XMMSaveMBB will fall through to the end block.
12191   XMMSaveMBB->addSuccessor(EndMBB);
12192
12193   // Now add the instructions.
12194   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12195   DebugLoc DL = MI->getDebugLoc();
12196
12197   unsigned CountReg = MI->getOperand(0).getReg();
12198   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
12199   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
12200
12201   if (!Subtarget->isTargetWin64()) {
12202     // If %al is 0, branch around the XMM save block.
12203     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
12204     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
12205     MBB->addSuccessor(EndMBB);
12206   }
12207
12208   unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
12209   // In the XMM save block, save all the XMM argument registers.
12210   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
12211     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
12212     MachineMemOperand *MMO =
12213       F->getMachineMemOperand(
12214           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
12215         MachineMemOperand::MOStore,
12216         /*Size=*/16, /*Align=*/16);
12217     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
12218       .addFrameIndex(RegSaveFrameIndex)
12219       .addImm(/*Scale=*/1)
12220       .addReg(/*IndexReg=*/0)
12221       .addImm(/*Disp=*/Offset)
12222       .addReg(/*Segment=*/0)
12223       .addReg(MI->getOperand(i).getReg())
12224       .addMemOperand(MMO);
12225   }
12226
12227   MI->eraseFromParent();   // The pseudo instruction is gone now.
12228
12229   return EndMBB;
12230 }
12231
12232 MachineBasicBlock *
12233 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
12234                                      MachineBasicBlock *BB) const {
12235   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12236   DebugLoc DL = MI->getDebugLoc();
12237
12238   // To "insert" a SELECT_CC instruction, we actually have to insert the
12239   // diamond control-flow pattern.  The incoming instruction knows the
12240   // destination vreg to set, the condition code register to branch on, the
12241   // true/false values to select between, and a branch opcode to use.
12242   const BasicBlock *LLVM_BB = BB->getBasicBlock();
12243   MachineFunction::iterator It = BB;
12244   ++It;
12245
12246   //  thisMBB:
12247   //  ...
12248   //   TrueVal = ...
12249   //   cmpTY ccX, r1, r2
12250   //   bCC copy1MBB
12251   //   fallthrough --> copy0MBB
12252   MachineBasicBlock *thisMBB = BB;
12253   MachineFunction *F = BB->getParent();
12254   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
12255   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12256   F->insert(It, copy0MBB);
12257   F->insert(It, sinkMBB);
12258
12259   // If the EFLAGS register isn't dead in the terminator, then claim that it's
12260   // live into the sink and copy blocks.
12261   if (!MI->killsRegister(X86::EFLAGS)) {
12262     copy0MBB->addLiveIn(X86::EFLAGS);
12263     sinkMBB->addLiveIn(X86::EFLAGS);
12264   }
12265
12266   // Transfer the remainder of BB and its successor edges to sinkMBB.
12267   sinkMBB->splice(sinkMBB->begin(), BB,
12268                   llvm::next(MachineBasicBlock::iterator(MI)),
12269                   BB->end());
12270   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12271
12272   // Add the true and fallthrough blocks as its successors.
12273   BB->addSuccessor(copy0MBB);
12274   BB->addSuccessor(sinkMBB);
12275
12276   // Create the conditional branch instruction.
12277   unsigned Opc =
12278     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
12279   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
12280
12281   //  copy0MBB:
12282   //   %FalseValue = ...
12283   //   # fallthrough to sinkMBB
12284   copy0MBB->addSuccessor(sinkMBB);
12285
12286   //  sinkMBB:
12287   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
12288   //  ...
12289   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12290           TII->get(X86::PHI), MI->getOperand(0).getReg())
12291     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
12292     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
12293
12294   MI->eraseFromParent();   // The pseudo instruction is gone now.
12295   return sinkMBB;
12296 }
12297
12298 MachineBasicBlock *
12299 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
12300                                         bool Is64Bit) const {
12301   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12302   DebugLoc DL = MI->getDebugLoc();
12303   MachineFunction *MF = BB->getParent();
12304   const BasicBlock *LLVM_BB = BB->getBasicBlock();
12305
12306   assert(EnableSegmentedStacks);
12307
12308   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
12309   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
12310
12311   // BB:
12312   //  ... [Till the alloca]
12313   // If stacklet is not large enough, jump to mallocMBB
12314   //
12315   // bumpMBB:
12316   //  Allocate by subtracting from RSP
12317   //  Jump to continueMBB
12318   //
12319   // mallocMBB:
12320   //  Allocate by call to runtime
12321   //
12322   // continueMBB:
12323   //  ...
12324   //  [rest of original BB]
12325   //
12326
12327   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12328   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12329   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12330
12331   MachineRegisterInfo &MRI = MF->getRegInfo();
12332   const TargetRegisterClass *AddrRegClass =
12333     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
12334
12335   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12336     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12337     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
12338     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
12339     sizeVReg = MI->getOperand(1).getReg(),
12340     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
12341
12342   MachineFunction::iterator MBBIter = BB;
12343   ++MBBIter;
12344
12345   MF->insert(MBBIter, bumpMBB);
12346   MF->insert(MBBIter, mallocMBB);
12347   MF->insert(MBBIter, continueMBB);
12348
12349   continueMBB->splice(continueMBB->begin(), BB, llvm::next
12350                       (MachineBasicBlock::iterator(MI)), BB->end());
12351   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
12352
12353   // Add code to the main basic block to check if the stack limit has been hit,
12354   // and if so, jump to mallocMBB otherwise to bumpMBB.
12355   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
12356   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
12357     .addReg(tmpSPVReg).addReg(sizeVReg);
12358   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
12359     .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg)
12360     .addReg(SPLimitVReg);
12361   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
12362
12363   // bumpMBB simply decreases the stack pointer, since we know the current
12364   // stacklet has enough space.
12365   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
12366     .addReg(SPLimitVReg);
12367   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
12368     .addReg(SPLimitVReg);
12369   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12370
12371   // Calls into a routine in libgcc to allocate more space from the heap.
12372   if (Is64Bit) {
12373     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
12374       .addReg(sizeVReg);
12375     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
12376     .addExternalSymbol("__morestack_allocate_stack_space").addReg(X86::RDI);
12377   } else {
12378     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
12379       .addImm(12);
12380     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
12381     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
12382       .addExternalSymbol("__morestack_allocate_stack_space");
12383   }
12384
12385   if (!Is64Bit)
12386     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
12387       .addImm(16);
12388
12389   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
12390     .addReg(Is64Bit ? X86::RAX : X86::EAX);
12391   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12392
12393   // Set up the CFG correctly.
12394   BB->addSuccessor(bumpMBB);
12395   BB->addSuccessor(mallocMBB);
12396   mallocMBB->addSuccessor(continueMBB);
12397   bumpMBB->addSuccessor(continueMBB);
12398
12399   // Take care of the PHI nodes.
12400   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
12401           MI->getOperand(0).getReg())
12402     .addReg(mallocPtrVReg).addMBB(mallocMBB)
12403     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
12404
12405   // Delete the original pseudo instruction.
12406   MI->eraseFromParent();
12407
12408   // And we're done.
12409   return continueMBB;
12410 }
12411
12412 MachineBasicBlock *
12413 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
12414                                           MachineBasicBlock *BB) const {
12415   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12416   DebugLoc DL = MI->getDebugLoc();
12417
12418   assert(!Subtarget->isTargetEnvMacho());
12419
12420   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
12421   // non-trivial part is impdef of ESP.
12422
12423   if (Subtarget->isTargetWin64()) {
12424     if (Subtarget->isTargetCygMing()) {
12425       // ___chkstk(Mingw64):
12426       // Clobbers R10, R11, RAX and EFLAGS.
12427       // Updates RSP.
12428       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12429         .addExternalSymbol("___chkstk")
12430         .addReg(X86::RAX, RegState::Implicit)
12431         .addReg(X86::RSP, RegState::Implicit)
12432         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
12433         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
12434         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12435     } else {
12436       // __chkstk(MSVCRT): does not update stack pointer.
12437       // Clobbers R10, R11 and EFLAGS.
12438       // FIXME: RAX(allocated size) might be reused and not killed.
12439       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12440         .addExternalSymbol("__chkstk")
12441         .addReg(X86::RAX, RegState::Implicit)
12442         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12443       // RAX has the offset to subtracted from RSP.
12444       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
12445         .addReg(X86::RSP)
12446         .addReg(X86::RAX);
12447     }
12448   } else {
12449     const char *StackProbeSymbol =
12450       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
12451
12452     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
12453       .addExternalSymbol(StackProbeSymbol)
12454       .addReg(X86::EAX, RegState::Implicit)
12455       .addReg(X86::ESP, RegState::Implicit)
12456       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
12457       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
12458       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12459   }
12460
12461   MI->eraseFromParent();   // The pseudo instruction is gone now.
12462   return BB;
12463 }
12464
12465 MachineBasicBlock *
12466 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
12467                                       MachineBasicBlock *BB) const {
12468   // This is pretty easy.  We're taking the value that we received from
12469   // our load from the relocation, sticking it in either RDI (x86-64)
12470   // or EAX and doing an indirect call.  The return value will then
12471   // be in the normal return register.
12472   const X86InstrInfo *TII
12473     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
12474   DebugLoc DL = MI->getDebugLoc();
12475   MachineFunction *F = BB->getParent();
12476
12477   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
12478   assert(MI->getOperand(3).isGlobal() && "This should be a global");
12479
12480   if (Subtarget->is64Bit()) {
12481     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12482                                       TII->get(X86::MOV64rm), X86::RDI)
12483     .addReg(X86::RIP)
12484     .addImm(0).addReg(0)
12485     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12486                       MI->getOperand(3).getTargetFlags())
12487     .addReg(0);
12488     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
12489     addDirectMem(MIB, X86::RDI);
12490   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
12491     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12492                                       TII->get(X86::MOV32rm), X86::EAX)
12493     .addReg(0)
12494     .addImm(0).addReg(0)
12495     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12496                       MI->getOperand(3).getTargetFlags())
12497     .addReg(0);
12498     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12499     addDirectMem(MIB, X86::EAX);
12500   } else {
12501     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12502                                       TII->get(X86::MOV32rm), X86::EAX)
12503     .addReg(TII->getGlobalBaseReg(F))
12504     .addImm(0).addReg(0)
12505     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12506                       MI->getOperand(3).getTargetFlags())
12507     .addReg(0);
12508     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12509     addDirectMem(MIB, X86::EAX);
12510   }
12511
12512   MI->eraseFromParent(); // The pseudo instruction is gone now.
12513   return BB;
12514 }
12515
12516 MachineBasicBlock *
12517 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
12518                                                MachineBasicBlock *BB) const {
12519   switch (MI->getOpcode()) {
12520   default: assert(0 && "Unexpected instr type to insert");
12521   case X86::TAILJMPd64:
12522   case X86::TAILJMPr64:
12523   case X86::TAILJMPm64:
12524     assert(0 && "TAILJMP64 would not be touched here.");
12525   case X86::TCRETURNdi64:
12526   case X86::TCRETURNri64:
12527   case X86::TCRETURNmi64:
12528     // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset.
12529     // On AMD64, additional defs should be added before register allocation.
12530     if (!Subtarget->isTargetWin64()) {
12531       MI->addRegisterDefined(X86::RSI);
12532       MI->addRegisterDefined(X86::RDI);
12533       MI->addRegisterDefined(X86::XMM6);
12534       MI->addRegisterDefined(X86::XMM7);
12535       MI->addRegisterDefined(X86::XMM8);
12536       MI->addRegisterDefined(X86::XMM9);
12537       MI->addRegisterDefined(X86::XMM10);
12538       MI->addRegisterDefined(X86::XMM11);
12539       MI->addRegisterDefined(X86::XMM12);
12540       MI->addRegisterDefined(X86::XMM13);
12541       MI->addRegisterDefined(X86::XMM14);
12542       MI->addRegisterDefined(X86::XMM15);
12543     }
12544     return BB;
12545   case X86::WIN_ALLOCA:
12546     return EmitLoweredWinAlloca(MI, BB);
12547   case X86::SEG_ALLOCA_32:
12548     return EmitLoweredSegAlloca(MI, BB, false);
12549   case X86::SEG_ALLOCA_64:
12550     return EmitLoweredSegAlloca(MI, BB, true);
12551   case X86::TLSCall_32:
12552   case X86::TLSCall_64:
12553     return EmitLoweredTLSCall(MI, BB);
12554   case X86::CMOV_GR8:
12555   case X86::CMOV_FR32:
12556   case X86::CMOV_FR64:
12557   case X86::CMOV_V4F32:
12558   case X86::CMOV_V2F64:
12559   case X86::CMOV_V2I64:
12560   case X86::CMOV_V8F32:
12561   case X86::CMOV_V4F64:
12562   case X86::CMOV_V4I64:
12563   case X86::CMOV_GR16:
12564   case X86::CMOV_GR32:
12565   case X86::CMOV_RFP32:
12566   case X86::CMOV_RFP64:
12567   case X86::CMOV_RFP80:
12568     return EmitLoweredSelect(MI, BB);
12569
12570   case X86::FP32_TO_INT16_IN_MEM:
12571   case X86::FP32_TO_INT32_IN_MEM:
12572   case X86::FP32_TO_INT64_IN_MEM:
12573   case X86::FP64_TO_INT16_IN_MEM:
12574   case X86::FP64_TO_INT32_IN_MEM:
12575   case X86::FP64_TO_INT64_IN_MEM:
12576   case X86::FP80_TO_INT16_IN_MEM:
12577   case X86::FP80_TO_INT32_IN_MEM:
12578   case X86::FP80_TO_INT64_IN_MEM: {
12579     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12580     DebugLoc DL = MI->getDebugLoc();
12581
12582     // Change the floating point control register to use "round towards zero"
12583     // mode when truncating to an integer value.
12584     MachineFunction *F = BB->getParent();
12585     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
12586     addFrameReference(BuildMI(*BB, MI, DL,
12587                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
12588
12589     // Load the old value of the high byte of the control word...
12590     unsigned OldCW =
12591       F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
12592     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
12593                       CWFrameIdx);
12594
12595     // Set the high part to be round to zero...
12596     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
12597       .addImm(0xC7F);
12598
12599     // Reload the modified control word now...
12600     addFrameReference(BuildMI(*BB, MI, DL,
12601                               TII->get(X86::FLDCW16m)), CWFrameIdx);
12602
12603     // Restore the memory image of control word to original value
12604     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
12605       .addReg(OldCW);
12606
12607     // Get the X86 opcode to use.
12608     unsigned Opc;
12609     switch (MI->getOpcode()) {
12610     default: llvm_unreachable("illegal opcode!");
12611     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
12612     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
12613     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
12614     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
12615     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
12616     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
12617     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
12618     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
12619     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
12620     }
12621
12622     X86AddressMode AM;
12623     MachineOperand &Op = MI->getOperand(0);
12624     if (Op.isReg()) {
12625       AM.BaseType = X86AddressMode::RegBase;
12626       AM.Base.Reg = Op.getReg();
12627     } else {
12628       AM.BaseType = X86AddressMode::FrameIndexBase;
12629       AM.Base.FrameIndex = Op.getIndex();
12630     }
12631     Op = MI->getOperand(1);
12632     if (Op.isImm())
12633       AM.Scale = Op.getImm();
12634     Op = MI->getOperand(2);
12635     if (Op.isImm())
12636       AM.IndexReg = Op.getImm();
12637     Op = MI->getOperand(3);
12638     if (Op.isGlobal()) {
12639       AM.GV = Op.getGlobal();
12640     } else {
12641       AM.Disp = Op.getImm();
12642     }
12643     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
12644                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
12645
12646     // Reload the original control word now.
12647     addFrameReference(BuildMI(*BB, MI, DL,
12648                               TII->get(X86::FLDCW16m)), CWFrameIdx);
12649
12650     MI->eraseFromParent();   // The pseudo instruction is gone now.
12651     return BB;
12652   }
12653     // String/text processing lowering.
12654   case X86::PCMPISTRM128REG:
12655   case X86::VPCMPISTRM128REG:
12656     return EmitPCMP(MI, BB, 3, false /* in-mem */);
12657   case X86::PCMPISTRM128MEM:
12658   case X86::VPCMPISTRM128MEM:
12659     return EmitPCMP(MI, BB, 3, true /* in-mem */);
12660   case X86::PCMPESTRM128REG:
12661   case X86::VPCMPESTRM128REG:
12662     return EmitPCMP(MI, BB, 5, false /* in mem */);
12663   case X86::PCMPESTRM128MEM:
12664   case X86::VPCMPESTRM128MEM:
12665     return EmitPCMP(MI, BB, 5, true /* in mem */);
12666
12667     // Thread synchronization.
12668   case X86::MONITOR:
12669     return EmitMonitor(MI, BB);
12670   case X86::MWAIT:
12671     return EmitMwait(MI, BB);
12672
12673     // Atomic Lowering.
12674   case X86::ATOMAND32:
12675     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12676                                                X86::AND32ri, X86::MOV32rm,
12677                                                X86::LCMPXCHG32,
12678                                                X86::NOT32r, X86::EAX,
12679                                                X86::GR32RegisterClass);
12680   case X86::ATOMOR32:
12681     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
12682                                                X86::OR32ri, X86::MOV32rm,
12683                                                X86::LCMPXCHG32,
12684                                                X86::NOT32r, X86::EAX,
12685                                                X86::GR32RegisterClass);
12686   case X86::ATOMXOR32:
12687     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
12688                                                X86::XOR32ri, X86::MOV32rm,
12689                                                X86::LCMPXCHG32,
12690                                                X86::NOT32r, X86::EAX,
12691                                                X86::GR32RegisterClass);
12692   case X86::ATOMNAND32:
12693     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12694                                                X86::AND32ri, X86::MOV32rm,
12695                                                X86::LCMPXCHG32,
12696                                                X86::NOT32r, X86::EAX,
12697                                                X86::GR32RegisterClass, true);
12698   case X86::ATOMMIN32:
12699     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
12700   case X86::ATOMMAX32:
12701     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
12702   case X86::ATOMUMIN32:
12703     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
12704   case X86::ATOMUMAX32:
12705     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
12706
12707   case X86::ATOMAND16:
12708     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12709                                                X86::AND16ri, X86::MOV16rm,
12710                                                X86::LCMPXCHG16,
12711                                                X86::NOT16r, X86::AX,
12712                                                X86::GR16RegisterClass);
12713   case X86::ATOMOR16:
12714     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
12715                                                X86::OR16ri, X86::MOV16rm,
12716                                                X86::LCMPXCHG16,
12717                                                X86::NOT16r, X86::AX,
12718                                                X86::GR16RegisterClass);
12719   case X86::ATOMXOR16:
12720     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
12721                                                X86::XOR16ri, X86::MOV16rm,
12722                                                X86::LCMPXCHG16,
12723                                                X86::NOT16r, X86::AX,
12724                                                X86::GR16RegisterClass);
12725   case X86::ATOMNAND16:
12726     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12727                                                X86::AND16ri, X86::MOV16rm,
12728                                                X86::LCMPXCHG16,
12729                                                X86::NOT16r, X86::AX,
12730                                                X86::GR16RegisterClass, true);
12731   case X86::ATOMMIN16:
12732     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
12733   case X86::ATOMMAX16:
12734     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
12735   case X86::ATOMUMIN16:
12736     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
12737   case X86::ATOMUMAX16:
12738     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
12739
12740   case X86::ATOMAND8:
12741     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12742                                                X86::AND8ri, X86::MOV8rm,
12743                                                X86::LCMPXCHG8,
12744                                                X86::NOT8r, X86::AL,
12745                                                X86::GR8RegisterClass);
12746   case X86::ATOMOR8:
12747     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
12748                                                X86::OR8ri, X86::MOV8rm,
12749                                                X86::LCMPXCHG8,
12750                                                X86::NOT8r, X86::AL,
12751                                                X86::GR8RegisterClass);
12752   case X86::ATOMXOR8:
12753     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
12754                                                X86::XOR8ri, X86::MOV8rm,
12755                                                X86::LCMPXCHG8,
12756                                                X86::NOT8r, X86::AL,
12757                                                X86::GR8RegisterClass);
12758   case X86::ATOMNAND8:
12759     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12760                                                X86::AND8ri, X86::MOV8rm,
12761                                                X86::LCMPXCHG8,
12762                                                X86::NOT8r, X86::AL,
12763                                                X86::GR8RegisterClass, true);
12764   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
12765   // This group is for 64-bit host.
12766   case X86::ATOMAND64:
12767     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12768                                                X86::AND64ri32, X86::MOV64rm,
12769                                                X86::LCMPXCHG64,
12770                                                X86::NOT64r, X86::RAX,
12771                                                X86::GR64RegisterClass);
12772   case X86::ATOMOR64:
12773     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
12774                                                X86::OR64ri32, X86::MOV64rm,
12775                                                X86::LCMPXCHG64,
12776                                                X86::NOT64r, X86::RAX,
12777                                                X86::GR64RegisterClass);
12778   case X86::ATOMXOR64:
12779     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
12780                                                X86::XOR64ri32, X86::MOV64rm,
12781                                                X86::LCMPXCHG64,
12782                                                X86::NOT64r, X86::RAX,
12783                                                X86::GR64RegisterClass);
12784   case X86::ATOMNAND64:
12785     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12786                                                X86::AND64ri32, X86::MOV64rm,
12787                                                X86::LCMPXCHG64,
12788                                                X86::NOT64r, X86::RAX,
12789                                                X86::GR64RegisterClass, true);
12790   case X86::ATOMMIN64:
12791     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
12792   case X86::ATOMMAX64:
12793     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
12794   case X86::ATOMUMIN64:
12795     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
12796   case X86::ATOMUMAX64:
12797     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
12798
12799   // This group does 64-bit operations on a 32-bit host.
12800   case X86::ATOMAND6432:
12801     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12802                                                X86::AND32rr, X86::AND32rr,
12803                                                X86::AND32ri, X86::AND32ri,
12804                                                false);
12805   case X86::ATOMOR6432:
12806     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12807                                                X86::OR32rr, X86::OR32rr,
12808                                                X86::OR32ri, X86::OR32ri,
12809                                                false);
12810   case X86::ATOMXOR6432:
12811     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12812                                                X86::XOR32rr, X86::XOR32rr,
12813                                                X86::XOR32ri, X86::XOR32ri,
12814                                                false);
12815   case X86::ATOMNAND6432:
12816     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12817                                                X86::AND32rr, X86::AND32rr,
12818                                                X86::AND32ri, X86::AND32ri,
12819                                                true);
12820   case X86::ATOMADD6432:
12821     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12822                                                X86::ADD32rr, X86::ADC32rr,
12823                                                X86::ADD32ri, X86::ADC32ri,
12824                                                false);
12825   case X86::ATOMSUB6432:
12826     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12827                                                X86::SUB32rr, X86::SBB32rr,
12828                                                X86::SUB32ri, X86::SBB32ri,
12829                                                false);
12830   case X86::ATOMSWAP6432:
12831     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12832                                                X86::MOV32rr, X86::MOV32rr,
12833                                                X86::MOV32ri, X86::MOV32ri,
12834                                                false);
12835   case X86::VASTART_SAVE_XMM_REGS:
12836     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
12837
12838   case X86::VAARG_64:
12839     return EmitVAARG64WithCustomInserter(MI, BB);
12840   }
12841 }
12842
12843 //===----------------------------------------------------------------------===//
12844 //                           X86 Optimization Hooks
12845 //===----------------------------------------------------------------------===//
12846
12847 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
12848                                                        const APInt &Mask,
12849                                                        APInt &KnownZero,
12850                                                        APInt &KnownOne,
12851                                                        const SelectionDAG &DAG,
12852                                                        unsigned Depth) const {
12853   unsigned Opc = Op.getOpcode();
12854   assert((Opc >= ISD::BUILTIN_OP_END ||
12855           Opc == ISD::INTRINSIC_WO_CHAIN ||
12856           Opc == ISD::INTRINSIC_W_CHAIN ||
12857           Opc == ISD::INTRINSIC_VOID) &&
12858          "Should use MaskedValueIsZero if you don't know whether Op"
12859          " is a target node!");
12860
12861   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
12862   switch (Opc) {
12863   default: break;
12864   case X86ISD::ADD:
12865   case X86ISD::SUB:
12866   case X86ISD::ADC:
12867   case X86ISD::SBB:
12868   case X86ISD::SMUL:
12869   case X86ISD::UMUL:
12870   case X86ISD::INC:
12871   case X86ISD::DEC:
12872   case X86ISD::OR:
12873   case X86ISD::XOR:
12874   case X86ISD::AND:
12875     // These nodes' second result is a boolean.
12876     if (Op.getResNo() == 0)
12877       break;
12878     // Fallthrough
12879   case X86ISD::SETCC:
12880     KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
12881                                        Mask.getBitWidth() - 1);
12882     break;
12883   case ISD::INTRINSIC_WO_CHAIN: {
12884     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12885     unsigned NumLoBits = 0;
12886     switch (IntId) {
12887     default: break;
12888     case Intrinsic::x86_sse_movmsk_ps:
12889     case Intrinsic::x86_avx_movmsk_ps_256:
12890     case Intrinsic::x86_sse2_movmsk_pd:
12891     case Intrinsic::x86_avx_movmsk_pd_256:
12892     case Intrinsic::x86_mmx_pmovmskb:
12893     case Intrinsic::x86_sse2_pmovmskb_128: {
12894       // High bits of movmskp{s|d}, pmovmskb are known zero.
12895       switch (IntId) {
12896         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
12897         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
12898         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
12899         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
12900         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
12901         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
12902       }
12903       KnownZero = APInt::getHighBitsSet(Mask.getBitWidth(),
12904                                         Mask.getBitWidth() - NumLoBits);
12905       break;
12906     }
12907     }
12908     break;
12909   }
12910   }
12911 }
12912
12913 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
12914                                                          unsigned Depth) const {
12915   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
12916   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
12917     return Op.getValueType().getScalarType().getSizeInBits();
12918
12919   // Fallback case.
12920   return 1;
12921 }
12922
12923 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
12924 /// node is a GlobalAddress + offset.
12925 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
12926                                        const GlobalValue* &GA,
12927                                        int64_t &Offset) const {
12928   if (N->getOpcode() == X86ISD::Wrapper) {
12929     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
12930       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
12931       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
12932       return true;
12933     }
12934   }
12935   return TargetLowering::isGAPlusOffset(N, GA, Offset);
12936 }
12937
12938 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
12939 /// same as extracting the high 128-bit part of 256-bit vector and then
12940 /// inserting the result into the low part of a new 256-bit vector
12941 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
12942   EVT VT = SVOp->getValueType(0);
12943   int NumElems = VT.getVectorNumElements();
12944
12945   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
12946   for (int i = 0, j = NumElems/2; i < NumElems/2; ++i, ++j)
12947     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12948         SVOp->getMaskElt(j) >= 0)
12949       return false;
12950
12951   return true;
12952 }
12953
12954 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
12955 /// same as extracting the low 128-bit part of 256-bit vector and then
12956 /// inserting the result into the high part of a new 256-bit vector
12957 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
12958   EVT VT = SVOp->getValueType(0);
12959   int NumElems = VT.getVectorNumElements();
12960
12961   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
12962   for (int i = NumElems/2, j = 0; i < NumElems; ++i, ++j)
12963     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12964         SVOp->getMaskElt(j) >= 0)
12965       return false;
12966
12967   return true;
12968 }
12969
12970 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
12971 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
12972                                         TargetLowering::DAGCombinerInfo &DCI) {
12973   DebugLoc dl = N->getDebugLoc();
12974   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
12975   SDValue V1 = SVOp->getOperand(0);
12976   SDValue V2 = SVOp->getOperand(1);
12977   EVT VT = SVOp->getValueType(0);
12978   int NumElems = VT.getVectorNumElements();
12979
12980   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
12981       V2.getOpcode() == ISD::CONCAT_VECTORS) {
12982     //
12983     //                   0,0,0,...
12984     //                      |
12985     //    V      UNDEF    BUILD_VECTOR    UNDEF
12986     //     \      /           \           /
12987     //  CONCAT_VECTOR         CONCAT_VECTOR
12988     //         \                  /
12989     //          \                /
12990     //          RESULT: V + zero extended
12991     //
12992     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
12993         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
12994         V1.getOperand(1).getOpcode() != ISD::UNDEF)
12995       return SDValue();
12996
12997     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
12998       return SDValue();
12999
13000     // To match the shuffle mask, the first half of the mask should
13001     // be exactly the first vector, and all the rest a splat with the
13002     // first element of the second one.
13003     for (int i = 0; i < NumElems/2; ++i)
13004       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
13005           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
13006         return SDValue();
13007
13008     // Emit a zeroed vector and insert the desired subvector on its
13009     // first half.
13010     SDValue Zeros = getZeroVector(VT, true /* HasXMMInt */, DAG, dl);
13011     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0),
13012                          DAG.getConstant(0, MVT::i32), DAG, dl);
13013     return DCI.CombineTo(N, InsV);
13014   }
13015
13016   //===--------------------------------------------------------------------===//
13017   // Combine some shuffles into subvector extracts and inserts:
13018   //
13019
13020   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13021   if (isShuffleHigh128VectorInsertLow(SVOp)) {
13022     SDValue V = Extract128BitVector(V1, DAG.getConstant(NumElems/2, MVT::i32),
13023                                     DAG, dl);
13024     SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT),
13025                                       V, DAG.getConstant(0, MVT::i32), DAG, dl);
13026     return DCI.CombineTo(N, InsV);
13027   }
13028
13029   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13030   if (isShuffleLow128VectorInsertHigh(SVOp)) {
13031     SDValue V = Extract128BitVector(V1, DAG.getConstant(0, MVT::i32), DAG, dl);
13032     SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT),
13033                              V, DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
13034     return DCI.CombineTo(N, InsV);
13035   }
13036
13037   return SDValue();
13038 }
13039
13040 /// PerformShuffleCombine - Performs several different shuffle combines.
13041 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
13042                                      TargetLowering::DAGCombinerInfo &DCI,
13043                                      const X86Subtarget *Subtarget) {
13044   DebugLoc dl = N->getDebugLoc();
13045   EVT VT = N->getValueType(0);
13046
13047   // Don't create instructions with illegal types after legalize types has run.
13048   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13049   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
13050     return SDValue();
13051
13052   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
13053   if (Subtarget->hasAVX() && VT.getSizeInBits() == 256 &&
13054       N->getOpcode() == ISD::VECTOR_SHUFFLE)
13055     return PerformShuffleCombine256(N, DAG, DCI);
13056
13057   // Only handle 128 wide vector from here on.
13058   if (VT.getSizeInBits() != 128)
13059     return SDValue();
13060
13061   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
13062   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
13063   // consecutive, non-overlapping, and in the right order.
13064   SmallVector<SDValue, 16> Elts;
13065   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
13066     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
13067
13068   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
13069 }
13070
13071 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
13072 /// generation and convert it from being a bunch of shuffles and extracts
13073 /// to a simple store and scalar loads to extract the elements.
13074 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
13075                                                 const TargetLowering &TLI) {
13076   SDValue InputVector = N->getOperand(0);
13077
13078   // Only operate on vectors of 4 elements, where the alternative shuffling
13079   // gets to be more expensive.
13080   if (InputVector.getValueType() != MVT::v4i32)
13081     return SDValue();
13082
13083   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
13084   // single use which is a sign-extend or zero-extend, and all elements are
13085   // used.
13086   SmallVector<SDNode *, 4> Uses;
13087   unsigned ExtractedElements = 0;
13088   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
13089        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
13090     if (UI.getUse().getResNo() != InputVector.getResNo())
13091       return SDValue();
13092
13093     SDNode *Extract = *UI;
13094     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13095       return SDValue();
13096
13097     if (Extract->getValueType(0) != MVT::i32)
13098       return SDValue();
13099     if (!Extract->hasOneUse())
13100       return SDValue();
13101     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
13102         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
13103       return SDValue();
13104     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
13105       return SDValue();
13106
13107     // Record which element was extracted.
13108     ExtractedElements |=
13109       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
13110
13111     Uses.push_back(Extract);
13112   }
13113
13114   // If not all the elements were used, this may not be worthwhile.
13115   if (ExtractedElements != 15)
13116     return SDValue();
13117
13118   // Ok, we've now decided to do the transformation.
13119   DebugLoc dl = InputVector.getDebugLoc();
13120
13121   // Store the value to a temporary stack slot.
13122   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
13123   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
13124                             MachinePointerInfo(), false, false, 0);
13125
13126   // Replace each use (extract) with a load of the appropriate element.
13127   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
13128        UE = Uses.end(); UI != UE; ++UI) {
13129     SDNode *Extract = *UI;
13130
13131     // cOMpute the element's address.
13132     SDValue Idx = Extract->getOperand(1);
13133     unsigned EltSize =
13134         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
13135     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
13136     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
13137
13138     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
13139                                      StackPtr, OffsetVal);
13140
13141     // Load the scalar.
13142     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
13143                                      ScalarAddr, MachinePointerInfo(),
13144                                      false, false, false, 0);
13145
13146     // Replace the exact with the load.
13147     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
13148   }
13149
13150   // The replacement was made in place; don't return anything.
13151   return SDValue();
13152 }
13153
13154 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
13155 /// nodes.
13156 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
13157                                     const X86Subtarget *Subtarget) {
13158   DebugLoc DL = N->getDebugLoc();
13159   SDValue Cond = N->getOperand(0);
13160   // Get the LHS/RHS of the select.
13161   SDValue LHS = N->getOperand(1);
13162   SDValue RHS = N->getOperand(2);
13163   EVT VT = LHS.getValueType();
13164
13165   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
13166   // instructions match the semantics of the common C idiom x<y?x:y but not
13167   // x<=y?x:y, because of how they handle negative zero (which can be
13168   // ignored in unsafe-math mode).
13169   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
13170       VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
13171       (Subtarget->hasXMMInt() ||
13172        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
13173     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
13174
13175     unsigned Opcode = 0;
13176     // Check for x CC y ? x : y.
13177     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
13178         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
13179       switch (CC) {
13180       default: break;
13181       case ISD::SETULT:
13182         // Converting this to a min would handle NaNs incorrectly, and swapping
13183         // the operands would cause it to handle comparisons between positive
13184         // and negative zero incorrectly.
13185         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13186           if (!UnsafeFPMath &&
13187               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13188             break;
13189           std::swap(LHS, RHS);
13190         }
13191         Opcode = X86ISD::FMIN;
13192         break;
13193       case ISD::SETOLE:
13194         // Converting this to a min would handle comparisons between positive
13195         // and negative zero incorrectly.
13196         if (!UnsafeFPMath &&
13197             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13198           break;
13199         Opcode = X86ISD::FMIN;
13200         break;
13201       case ISD::SETULE:
13202         // Converting this to a min would handle both negative zeros and NaNs
13203         // incorrectly, but we can swap the operands to fix both.
13204         std::swap(LHS, RHS);
13205       case ISD::SETOLT:
13206       case ISD::SETLT:
13207       case ISD::SETLE:
13208         Opcode = X86ISD::FMIN;
13209         break;
13210
13211       case ISD::SETOGE:
13212         // Converting this to a max would handle comparisons between positive
13213         // and negative zero incorrectly.
13214         if (!UnsafeFPMath &&
13215             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13216           break;
13217         Opcode = X86ISD::FMAX;
13218         break;
13219       case ISD::SETUGT:
13220         // Converting this to a max would handle NaNs incorrectly, and swapping
13221         // the operands would cause it to handle comparisons between positive
13222         // and negative zero incorrectly.
13223         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13224           if (!UnsafeFPMath &&
13225               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13226             break;
13227           std::swap(LHS, RHS);
13228         }
13229         Opcode = X86ISD::FMAX;
13230         break;
13231       case ISD::SETUGE:
13232         // Converting this to a max would handle both negative zeros and NaNs
13233         // incorrectly, but we can swap the operands to fix both.
13234         std::swap(LHS, RHS);
13235       case ISD::SETOGT:
13236       case ISD::SETGT:
13237       case ISD::SETGE:
13238         Opcode = X86ISD::FMAX;
13239         break;
13240       }
13241     // Check for x CC y ? y : x -- a min/max with reversed arms.
13242     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
13243                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
13244       switch (CC) {
13245       default: break;
13246       case ISD::SETOGE:
13247         // Converting this to a min would handle comparisons between positive
13248         // and negative zero incorrectly, and swapping the operands would
13249         // cause it to handle NaNs incorrectly.
13250         if (!UnsafeFPMath &&
13251             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
13252           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13253             break;
13254           std::swap(LHS, RHS);
13255         }
13256         Opcode = X86ISD::FMIN;
13257         break;
13258       case ISD::SETUGT:
13259         // Converting this to a min would handle NaNs incorrectly.
13260         if (!UnsafeFPMath &&
13261             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
13262           break;
13263         Opcode = X86ISD::FMIN;
13264         break;
13265       case ISD::SETUGE:
13266         // Converting this to a min would handle both negative zeros and NaNs
13267         // incorrectly, but we can swap the operands to fix both.
13268         std::swap(LHS, RHS);
13269       case ISD::SETOGT:
13270       case ISD::SETGT:
13271       case ISD::SETGE:
13272         Opcode = X86ISD::FMIN;
13273         break;
13274
13275       case ISD::SETULT:
13276         // Converting this to a max would handle NaNs incorrectly.
13277         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13278           break;
13279         Opcode = X86ISD::FMAX;
13280         break;
13281       case ISD::SETOLE:
13282         // Converting this to a max would handle comparisons between positive
13283         // and negative zero incorrectly, and swapping the operands would
13284         // cause it to handle NaNs incorrectly.
13285         if (!UnsafeFPMath &&
13286             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
13287           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13288             break;
13289           std::swap(LHS, RHS);
13290         }
13291         Opcode = X86ISD::FMAX;
13292         break;
13293       case ISD::SETULE:
13294         // Converting this to a max would handle both negative zeros and NaNs
13295         // incorrectly, but we can swap the operands to fix both.
13296         std::swap(LHS, RHS);
13297       case ISD::SETOLT:
13298       case ISD::SETLT:
13299       case ISD::SETLE:
13300         Opcode = X86ISD::FMAX;
13301         break;
13302       }
13303     }
13304
13305     if (Opcode)
13306       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
13307   }
13308
13309   // If this is a select between two integer constants, try to do some
13310   // optimizations.
13311   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
13312     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
13313       // Don't do this for crazy integer types.
13314       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
13315         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
13316         // so that TrueC (the true value) is larger than FalseC.
13317         bool NeedsCondInvert = false;
13318
13319         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
13320             // Efficiently invertible.
13321             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
13322              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
13323               isa<ConstantSDNode>(Cond.getOperand(1))))) {
13324           NeedsCondInvert = true;
13325           std::swap(TrueC, FalseC);
13326         }
13327
13328         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
13329         if (FalseC->getAPIntValue() == 0 &&
13330             TrueC->getAPIntValue().isPowerOf2()) {
13331           if (NeedsCondInvert) // Invert the condition if needed.
13332             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13333                                DAG.getConstant(1, Cond.getValueType()));
13334
13335           // Zero extend the condition if needed.
13336           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
13337
13338           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13339           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
13340                              DAG.getConstant(ShAmt, MVT::i8));
13341         }
13342
13343         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
13344         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13345           if (NeedsCondInvert) // Invert the condition if needed.
13346             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13347                                DAG.getConstant(1, Cond.getValueType()));
13348
13349           // Zero extend the condition if needed.
13350           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13351                              FalseC->getValueType(0), Cond);
13352           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13353                              SDValue(FalseC, 0));
13354         }
13355
13356         // Optimize cases that will turn into an LEA instruction.  This requires
13357         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13358         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13359           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13360           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13361
13362           bool isFastMultiplier = false;
13363           if (Diff < 10) {
13364             switch ((unsigned char)Diff) {
13365               default: break;
13366               case 1:  // result = add base, cond
13367               case 2:  // result = lea base(    , cond*2)
13368               case 3:  // result = lea base(cond, cond*2)
13369               case 4:  // result = lea base(    , cond*4)
13370               case 5:  // result = lea base(cond, cond*4)
13371               case 8:  // result = lea base(    , cond*8)
13372               case 9:  // result = lea base(cond, cond*8)
13373                 isFastMultiplier = true;
13374                 break;
13375             }
13376           }
13377
13378           if (isFastMultiplier) {
13379             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13380             if (NeedsCondInvert) // Invert the condition if needed.
13381               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13382                                  DAG.getConstant(1, Cond.getValueType()));
13383
13384             // Zero extend the condition if needed.
13385             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13386                                Cond);
13387             // Scale the condition by the difference.
13388             if (Diff != 1)
13389               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13390                                  DAG.getConstant(Diff, Cond.getValueType()));
13391
13392             // Add the base if non-zero.
13393             if (FalseC->getAPIntValue() != 0)
13394               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13395                                  SDValue(FalseC, 0));
13396             return Cond;
13397           }
13398         }
13399       }
13400   }
13401
13402   return SDValue();
13403 }
13404
13405 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
13406 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
13407                                   TargetLowering::DAGCombinerInfo &DCI) {
13408   DebugLoc DL = N->getDebugLoc();
13409
13410   // If the flag operand isn't dead, don't touch this CMOV.
13411   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
13412     return SDValue();
13413
13414   SDValue FalseOp = N->getOperand(0);
13415   SDValue TrueOp = N->getOperand(1);
13416   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
13417   SDValue Cond = N->getOperand(3);
13418   if (CC == X86::COND_E || CC == X86::COND_NE) {
13419     switch (Cond.getOpcode()) {
13420     default: break;
13421     case X86ISD::BSR:
13422     case X86ISD::BSF:
13423       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
13424       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
13425         return (CC == X86::COND_E) ? FalseOp : TrueOp;
13426     }
13427   }
13428
13429   // If this is a select between two integer constants, try to do some
13430   // optimizations.  Note that the operands are ordered the opposite of SELECT
13431   // operands.
13432   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
13433     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
13434       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
13435       // larger than FalseC (the false value).
13436       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
13437         CC = X86::GetOppositeBranchCondition(CC);
13438         std::swap(TrueC, FalseC);
13439       }
13440
13441       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
13442       // This is efficient for any integer data type (including i8/i16) and
13443       // shift amount.
13444       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
13445         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13446                            DAG.getConstant(CC, MVT::i8), Cond);
13447
13448         // Zero extend the condition if needed.
13449         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
13450
13451         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13452         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
13453                            DAG.getConstant(ShAmt, MVT::i8));
13454         if (N->getNumValues() == 2)  // Dead flag value?
13455           return DCI.CombineTo(N, Cond, SDValue());
13456         return Cond;
13457       }
13458
13459       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
13460       // for any integer data type, including i8/i16.
13461       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13462         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13463                            DAG.getConstant(CC, MVT::i8), Cond);
13464
13465         // Zero extend the condition if needed.
13466         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13467                            FalseC->getValueType(0), Cond);
13468         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13469                            SDValue(FalseC, 0));
13470
13471         if (N->getNumValues() == 2)  // Dead flag value?
13472           return DCI.CombineTo(N, Cond, SDValue());
13473         return Cond;
13474       }
13475
13476       // Optimize cases that will turn into an LEA instruction.  This requires
13477       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13478       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13479         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13480         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13481
13482         bool isFastMultiplier = false;
13483         if (Diff < 10) {
13484           switch ((unsigned char)Diff) {
13485           default: break;
13486           case 1:  // result = add base, cond
13487           case 2:  // result = lea base(    , cond*2)
13488           case 3:  // result = lea base(cond, cond*2)
13489           case 4:  // result = lea base(    , cond*4)
13490           case 5:  // result = lea base(cond, cond*4)
13491           case 8:  // result = lea base(    , cond*8)
13492           case 9:  // result = lea base(cond, cond*8)
13493             isFastMultiplier = true;
13494             break;
13495           }
13496         }
13497
13498         if (isFastMultiplier) {
13499           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13500           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13501                              DAG.getConstant(CC, MVT::i8), Cond);
13502           // Zero extend the condition if needed.
13503           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13504                              Cond);
13505           // Scale the condition by the difference.
13506           if (Diff != 1)
13507             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13508                                DAG.getConstant(Diff, Cond.getValueType()));
13509
13510           // Add the base if non-zero.
13511           if (FalseC->getAPIntValue() != 0)
13512             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13513                                SDValue(FalseC, 0));
13514           if (N->getNumValues() == 2)  // Dead flag value?
13515             return DCI.CombineTo(N, Cond, SDValue());
13516           return Cond;
13517         }
13518       }
13519     }
13520   }
13521   return SDValue();
13522 }
13523
13524
13525 /// PerformMulCombine - Optimize a single multiply with constant into two
13526 /// in order to implement it with two cheaper instructions, e.g.
13527 /// LEA + SHL, LEA + LEA.
13528 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
13529                                  TargetLowering::DAGCombinerInfo &DCI) {
13530   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
13531     return SDValue();
13532
13533   EVT VT = N->getValueType(0);
13534   if (VT != MVT::i64)
13535     return SDValue();
13536
13537   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
13538   if (!C)
13539     return SDValue();
13540   uint64_t MulAmt = C->getZExtValue();
13541   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
13542     return SDValue();
13543
13544   uint64_t MulAmt1 = 0;
13545   uint64_t MulAmt2 = 0;
13546   if ((MulAmt % 9) == 0) {
13547     MulAmt1 = 9;
13548     MulAmt2 = MulAmt / 9;
13549   } else if ((MulAmt % 5) == 0) {
13550     MulAmt1 = 5;
13551     MulAmt2 = MulAmt / 5;
13552   } else if ((MulAmt % 3) == 0) {
13553     MulAmt1 = 3;
13554     MulAmt2 = MulAmt / 3;
13555   }
13556   if (MulAmt2 &&
13557       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
13558     DebugLoc DL = N->getDebugLoc();
13559
13560     if (isPowerOf2_64(MulAmt2) &&
13561         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
13562       // If second multiplifer is pow2, issue it first. We want the multiply by
13563       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
13564       // is an add.
13565       std::swap(MulAmt1, MulAmt2);
13566
13567     SDValue NewMul;
13568     if (isPowerOf2_64(MulAmt1))
13569       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
13570                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
13571     else
13572       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
13573                            DAG.getConstant(MulAmt1, VT));
13574
13575     if (isPowerOf2_64(MulAmt2))
13576       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
13577                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
13578     else
13579       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
13580                            DAG.getConstant(MulAmt2, VT));
13581
13582     // Do not add new nodes to DAG combiner worklist.
13583     DCI.CombineTo(N, NewMul, false);
13584   }
13585   return SDValue();
13586 }
13587
13588 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
13589   SDValue N0 = N->getOperand(0);
13590   SDValue N1 = N->getOperand(1);
13591   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
13592   EVT VT = N0.getValueType();
13593
13594   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
13595   // since the result of setcc_c is all zero's or all ones.
13596   if (VT.isInteger() && !VT.isVector() &&
13597       N1C && N0.getOpcode() == ISD::AND &&
13598       N0.getOperand(1).getOpcode() == ISD::Constant) {
13599     SDValue N00 = N0.getOperand(0);
13600     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
13601         ((N00.getOpcode() == ISD::ANY_EXTEND ||
13602           N00.getOpcode() == ISD::ZERO_EXTEND) &&
13603          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
13604       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
13605       APInt ShAmt = N1C->getAPIntValue();
13606       Mask = Mask.shl(ShAmt);
13607       if (Mask != 0)
13608         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
13609                            N00, DAG.getConstant(Mask, VT));
13610     }
13611   }
13612
13613
13614   // Hardware support for vector shifts is sparse which makes us scalarize the
13615   // vector operations in many cases. Also, on sandybridge ADD is faster than
13616   // shl.
13617   // (shl V, 1) -> add V,V
13618   if (isSplatVector(N1.getNode())) {
13619     assert(N0.getValueType().isVector() && "Invalid vector shift type");
13620     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
13621     // We shift all of the values by one. In many cases we do not have
13622     // hardware support for this operation. This is better expressed as an ADD
13623     // of two values.
13624     if (N1C && (1 == N1C->getZExtValue())) {
13625       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
13626     }
13627   }
13628
13629   return SDValue();
13630 }
13631
13632 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
13633 ///                       when possible.
13634 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
13635                                    const X86Subtarget *Subtarget) {
13636   EVT VT = N->getValueType(0);
13637   if (N->getOpcode() == ISD::SHL) {
13638     SDValue V = PerformSHLCombine(N, DAG);
13639     if (V.getNode()) return V;
13640   }
13641
13642   // On X86 with SSE2 support, we can transform this to a vector shift if
13643   // all elements are shifted by the same amount.  We can't do this in legalize
13644   // because the a constant vector is typically transformed to a constant pool
13645   // so we have no knowledge of the shift amount.
13646   if (!Subtarget->hasXMMInt())
13647     return SDValue();
13648
13649   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
13650       (!Subtarget->hasAVX2() ||
13651        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
13652     return SDValue();
13653
13654   SDValue ShAmtOp = N->getOperand(1);
13655   EVT EltVT = VT.getVectorElementType();
13656   DebugLoc DL = N->getDebugLoc();
13657   SDValue BaseShAmt = SDValue();
13658   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
13659     unsigned NumElts = VT.getVectorNumElements();
13660     unsigned i = 0;
13661     for (; i != NumElts; ++i) {
13662       SDValue Arg = ShAmtOp.getOperand(i);
13663       if (Arg.getOpcode() == ISD::UNDEF) continue;
13664       BaseShAmt = Arg;
13665       break;
13666     }
13667     for (; i != NumElts; ++i) {
13668       SDValue Arg = ShAmtOp.getOperand(i);
13669       if (Arg.getOpcode() == ISD::UNDEF) continue;
13670       if (Arg != BaseShAmt) {
13671         return SDValue();
13672       }
13673     }
13674   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
13675              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
13676     SDValue InVec = ShAmtOp.getOperand(0);
13677     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13678       unsigned NumElts = InVec.getValueType().getVectorNumElements();
13679       unsigned i = 0;
13680       for (; i != NumElts; ++i) {
13681         SDValue Arg = InVec.getOperand(i);
13682         if (Arg.getOpcode() == ISD::UNDEF) continue;
13683         BaseShAmt = Arg;
13684         break;
13685       }
13686     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13687        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13688          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
13689          if (C->getZExtValue() == SplatIdx)
13690            BaseShAmt = InVec.getOperand(1);
13691        }
13692     }
13693     if (BaseShAmt.getNode() == 0)
13694       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
13695                               DAG.getIntPtrConstant(0));
13696   } else
13697     return SDValue();
13698
13699   // The shift amount is an i32.
13700   if (EltVT.bitsGT(MVT::i32))
13701     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
13702   else if (EltVT.bitsLT(MVT::i32))
13703     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
13704
13705   // The shift amount is identical so we can do a vector shift.
13706   SDValue  ValOp = N->getOperand(0);
13707   switch (N->getOpcode()) {
13708   default:
13709     llvm_unreachable("Unknown shift opcode!");
13710     break;
13711   case ISD::SHL:
13712     if (VT == MVT::v2i64)
13713       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13714                          DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
13715                          ValOp, BaseShAmt);
13716     if (VT == MVT::v4i32)
13717       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13718                          DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
13719                          ValOp, BaseShAmt);
13720     if (VT == MVT::v8i16)
13721       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13722                          DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
13723                          ValOp, BaseShAmt);
13724     if (VT == MVT::v4i64)
13725       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13726                          DAG.getConstant(Intrinsic::x86_avx2_pslli_q, MVT::i32),
13727                          ValOp, BaseShAmt);
13728     if (VT == MVT::v8i32)
13729       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13730                          DAG.getConstant(Intrinsic::x86_avx2_pslli_d, MVT::i32),
13731                          ValOp, BaseShAmt);
13732     if (VT == MVT::v16i16)
13733       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13734                          DAG.getConstant(Intrinsic::x86_avx2_pslli_w, MVT::i32),
13735                          ValOp, BaseShAmt);
13736     break;
13737   case ISD::SRA:
13738     if (VT == MVT::v4i32)
13739       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13740                          DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
13741                          ValOp, BaseShAmt);
13742     if (VT == MVT::v8i16)
13743       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13744                          DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
13745                          ValOp, BaseShAmt);
13746     if (VT == MVT::v8i32)
13747       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13748                          DAG.getConstant(Intrinsic::x86_avx2_psrai_d, MVT::i32),
13749                          ValOp, BaseShAmt);
13750     if (VT == MVT::v16i16)
13751       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13752                          DAG.getConstant(Intrinsic::x86_avx2_psrai_w, MVT::i32),
13753                          ValOp, BaseShAmt);
13754     break;
13755   case ISD::SRL:
13756     if (VT == MVT::v2i64)
13757       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13758                          DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
13759                          ValOp, BaseShAmt);
13760     if (VT == MVT::v4i32)
13761       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13762                          DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
13763                          ValOp, BaseShAmt);
13764     if (VT ==  MVT::v8i16)
13765       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13766                          DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
13767                          ValOp, BaseShAmt);
13768     if (VT == MVT::v4i64)
13769       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13770                          DAG.getConstant(Intrinsic::x86_avx2_psrli_q, MVT::i32),
13771                          ValOp, BaseShAmt);
13772     if (VT == MVT::v8i32)
13773       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13774                          DAG.getConstant(Intrinsic::x86_avx2_psrli_d, MVT::i32),
13775                          ValOp, BaseShAmt);
13776     if (VT ==  MVT::v16i16)
13777       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13778                          DAG.getConstant(Intrinsic::x86_avx2_psrli_w, MVT::i32),
13779                          ValOp, BaseShAmt);
13780     break;
13781   }
13782   return SDValue();
13783 }
13784
13785
13786 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
13787 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
13788 // and friends.  Likewise for OR -> CMPNEQSS.
13789 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
13790                             TargetLowering::DAGCombinerInfo &DCI,
13791                             const X86Subtarget *Subtarget) {
13792   unsigned opcode;
13793
13794   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
13795   // we're requiring SSE2 for both.
13796   if (Subtarget->hasXMMInt() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
13797     SDValue N0 = N->getOperand(0);
13798     SDValue N1 = N->getOperand(1);
13799     SDValue CMP0 = N0->getOperand(1);
13800     SDValue CMP1 = N1->getOperand(1);
13801     DebugLoc DL = N->getDebugLoc();
13802
13803     // The SETCCs should both refer to the same CMP.
13804     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
13805       return SDValue();
13806
13807     SDValue CMP00 = CMP0->getOperand(0);
13808     SDValue CMP01 = CMP0->getOperand(1);
13809     EVT     VT    = CMP00.getValueType();
13810
13811     if (VT == MVT::f32 || VT == MVT::f64) {
13812       bool ExpectingFlags = false;
13813       // Check for any users that want flags:
13814       for (SDNode::use_iterator UI = N->use_begin(),
13815              UE = N->use_end();
13816            !ExpectingFlags && UI != UE; ++UI)
13817         switch (UI->getOpcode()) {
13818         default:
13819         case ISD::BR_CC:
13820         case ISD::BRCOND:
13821         case ISD::SELECT:
13822           ExpectingFlags = true;
13823           break;
13824         case ISD::CopyToReg:
13825         case ISD::SIGN_EXTEND:
13826         case ISD::ZERO_EXTEND:
13827         case ISD::ANY_EXTEND:
13828           break;
13829         }
13830
13831       if (!ExpectingFlags) {
13832         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
13833         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
13834
13835         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
13836           X86::CondCode tmp = cc0;
13837           cc0 = cc1;
13838           cc1 = tmp;
13839         }
13840
13841         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
13842             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
13843           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
13844           X86ISD::NodeType NTOperator = is64BitFP ?
13845             X86ISD::FSETCCsd : X86ISD::FSETCCss;
13846           // FIXME: need symbolic constants for these magic numbers.
13847           // See X86ATTInstPrinter.cpp:printSSECC().
13848           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
13849           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
13850                                               DAG.getConstant(x86cc, MVT::i8));
13851           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
13852                                               OnesOrZeroesF);
13853           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
13854                                       DAG.getConstant(1, MVT::i32));
13855           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
13856           return OneBitOfTruth;
13857         }
13858       }
13859     }
13860   }
13861   return SDValue();
13862 }
13863
13864 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
13865 /// so it can be folded inside ANDNP.
13866 static bool CanFoldXORWithAllOnes(const SDNode *N) {
13867   EVT VT = N->getValueType(0);
13868
13869   // Match direct AllOnes for 128 and 256-bit vectors
13870   if (ISD::isBuildVectorAllOnes(N))
13871     return true;
13872
13873   // Look through a bit convert.
13874   if (N->getOpcode() == ISD::BITCAST)
13875     N = N->getOperand(0).getNode();
13876
13877   // Sometimes the operand may come from a insert_subvector building a 256-bit
13878   // allones vector
13879   if (VT.getSizeInBits() == 256 &&
13880       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
13881     SDValue V1 = N->getOperand(0);
13882     SDValue V2 = N->getOperand(1);
13883
13884     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
13885         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
13886         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
13887         ISD::isBuildVectorAllOnes(V2.getNode()))
13888       return true;
13889   }
13890
13891   return false;
13892 }
13893
13894 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
13895                                  TargetLowering::DAGCombinerInfo &DCI,
13896                                  const X86Subtarget *Subtarget) {
13897   if (DCI.isBeforeLegalizeOps())
13898     return SDValue();
13899
13900   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
13901   if (R.getNode())
13902     return R;
13903
13904   EVT VT = N->getValueType(0);
13905
13906   // Create ANDN, BLSI, and BLSR instructions
13907   // BLSI is X & (-X)
13908   // BLSR is X & (X-1)
13909   if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
13910     SDValue N0 = N->getOperand(0);
13911     SDValue N1 = N->getOperand(1);
13912     DebugLoc DL = N->getDebugLoc();
13913
13914     // Check LHS for not
13915     if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1)))
13916       return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1);
13917     // Check RHS for not
13918     if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1)))
13919       return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
13920
13921     // Check LHS for neg
13922     if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
13923         isZero(N0.getOperand(0)))
13924       return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
13925
13926     // Check RHS for neg
13927     if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
13928         isZero(N1.getOperand(0)))
13929       return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
13930
13931     // Check LHS for X-1
13932     if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
13933         isAllOnes(N0.getOperand(1)))
13934       return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
13935
13936     // Check RHS for X-1
13937     if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
13938         isAllOnes(N1.getOperand(1)))
13939       return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
13940
13941     return SDValue();
13942   }
13943
13944   // Want to form ANDNP nodes:
13945   // 1) In the hopes of then easily combining them with OR and AND nodes
13946   //    to form PBLEND/PSIGN.
13947   // 2) To match ANDN packed intrinsics
13948   if (VT != MVT::v2i64 && VT != MVT::v4i64)
13949     return SDValue();
13950
13951   SDValue N0 = N->getOperand(0);
13952   SDValue N1 = N->getOperand(1);
13953   DebugLoc DL = N->getDebugLoc();
13954
13955   // Check LHS for vnot
13956   if (N0.getOpcode() == ISD::XOR &&
13957       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
13958       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
13959     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
13960
13961   // Check RHS for vnot
13962   if (N1.getOpcode() == ISD::XOR &&
13963       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
13964       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
13965     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
13966
13967   return SDValue();
13968 }
13969
13970 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
13971                                 TargetLowering::DAGCombinerInfo &DCI,
13972                                 const X86Subtarget *Subtarget) {
13973   if (DCI.isBeforeLegalizeOps())
13974     return SDValue();
13975
13976   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
13977   if (R.getNode())
13978     return R;
13979
13980   EVT VT = N->getValueType(0);
13981
13982   SDValue N0 = N->getOperand(0);
13983   SDValue N1 = N->getOperand(1);
13984
13985   // look for psign/blend
13986   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
13987     if (!Subtarget->hasSSSE3orAVX() ||
13988         (VT == MVT::v4i64 && !Subtarget->hasAVX2()))
13989       return SDValue();
13990
13991     // Canonicalize pandn to RHS
13992     if (N0.getOpcode() == X86ISD::ANDNP)
13993       std::swap(N0, N1);
13994     // or (and (m, x), (pandn m, y))
13995     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
13996       SDValue Mask = N1.getOperand(0);
13997       SDValue X    = N1.getOperand(1);
13998       SDValue Y;
13999       if (N0.getOperand(0) == Mask)
14000         Y = N0.getOperand(1);
14001       if (N0.getOperand(1) == Mask)
14002         Y = N0.getOperand(0);
14003
14004       // Check to see if the mask appeared in both the AND and ANDNP and
14005       if (!Y.getNode())
14006         return SDValue();
14007
14008       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
14009       if (Mask.getOpcode() != ISD::BITCAST ||
14010           X.getOpcode() != ISD::BITCAST ||
14011           Y.getOpcode() != ISD::BITCAST)
14012         return SDValue();
14013
14014       // Look through mask bitcast.
14015       Mask = Mask.getOperand(0);
14016       EVT MaskVT = Mask.getValueType();
14017
14018       // Validate that the Mask operand is a vector sra node.  The sra node
14019       // will be an intrinsic.
14020       if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
14021         return SDValue();
14022
14023       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
14024       // there is no psrai.b
14025       switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
14026       case Intrinsic::x86_sse2_psrai_w:
14027       case Intrinsic::x86_sse2_psrai_d:
14028       case Intrinsic::x86_avx2_psrai_w:
14029       case Intrinsic::x86_avx2_psrai_d:
14030         break;
14031       default: return SDValue();
14032       }
14033
14034       // Check that the SRA is all signbits.
14035       SDValue SraC = Mask.getOperand(2);
14036       unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
14037       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
14038       if ((SraAmt + 1) != EltBits)
14039         return SDValue();
14040
14041       DebugLoc DL = N->getDebugLoc();
14042
14043       // Now we know we at least have a plendvb with the mask val.  See if
14044       // we can form a psignb/w/d.
14045       // psign = x.type == y.type == mask.type && y = sub(0, x);
14046       X = X.getOperand(0);
14047       Y = Y.getOperand(0);
14048       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
14049           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
14050           X.getValueType() == MaskVT && X.getValueType() == Y.getValueType() &&
14051           (EltBits == 8 || EltBits == 16 || EltBits == 32)) {
14052         SDValue Sign = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X,
14053                                    Mask.getOperand(1));
14054         return DAG.getNode(ISD::BITCAST, DL, VT, Sign);
14055       }
14056       // PBLENDVB only available on SSE 4.1
14057       if (!Subtarget->hasSSE41orAVX())
14058         return SDValue();
14059
14060       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
14061
14062       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
14063       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
14064       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
14065       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, X, Y);
14066       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
14067     }
14068   }
14069
14070   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
14071     return SDValue();
14072
14073   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
14074   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
14075     std::swap(N0, N1);
14076   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
14077     return SDValue();
14078   if (!N0.hasOneUse() || !N1.hasOneUse())
14079     return SDValue();
14080
14081   SDValue ShAmt0 = N0.getOperand(1);
14082   if (ShAmt0.getValueType() != MVT::i8)
14083     return SDValue();
14084   SDValue ShAmt1 = N1.getOperand(1);
14085   if (ShAmt1.getValueType() != MVT::i8)
14086     return SDValue();
14087   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
14088     ShAmt0 = ShAmt0.getOperand(0);
14089   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
14090     ShAmt1 = ShAmt1.getOperand(0);
14091
14092   DebugLoc DL = N->getDebugLoc();
14093   unsigned Opc = X86ISD::SHLD;
14094   SDValue Op0 = N0.getOperand(0);
14095   SDValue Op1 = N1.getOperand(0);
14096   if (ShAmt0.getOpcode() == ISD::SUB) {
14097     Opc = X86ISD::SHRD;
14098     std::swap(Op0, Op1);
14099     std::swap(ShAmt0, ShAmt1);
14100   }
14101
14102   unsigned Bits = VT.getSizeInBits();
14103   if (ShAmt1.getOpcode() == ISD::SUB) {
14104     SDValue Sum = ShAmt1.getOperand(0);
14105     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
14106       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
14107       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
14108         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
14109       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
14110         return DAG.getNode(Opc, DL, VT,
14111                            Op0, Op1,
14112                            DAG.getNode(ISD::TRUNCATE, DL,
14113                                        MVT::i8, ShAmt0));
14114     }
14115   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
14116     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
14117     if (ShAmt0C &&
14118         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
14119       return DAG.getNode(Opc, DL, VT,
14120                          N0.getOperand(0), N1.getOperand(0),
14121                          DAG.getNode(ISD::TRUNCATE, DL,
14122                                        MVT::i8, ShAmt0));
14123   }
14124
14125   return SDValue();
14126 }
14127
14128 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
14129                                  TargetLowering::DAGCombinerInfo &DCI,
14130                                  const X86Subtarget *Subtarget) {
14131   if (DCI.isBeforeLegalizeOps())
14132     return SDValue();
14133
14134   EVT VT = N->getValueType(0);
14135
14136   if (VT != MVT::i32 && VT != MVT::i64)
14137     return SDValue();
14138
14139   // Create BLSMSK instructions by finding X ^ (X-1)
14140   SDValue N0 = N->getOperand(0);
14141   SDValue N1 = N->getOperand(1);
14142   DebugLoc DL = N->getDebugLoc();
14143
14144   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
14145       isAllOnes(N0.getOperand(1)))
14146     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
14147
14148   if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
14149       isAllOnes(N1.getOperand(1)))
14150     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
14151
14152   return SDValue();
14153 }
14154
14155 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
14156 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
14157                                    const X86Subtarget *Subtarget) {
14158   LoadSDNode *Ld = cast<LoadSDNode>(N);
14159   EVT RegVT = Ld->getValueType(0);
14160   EVT MemVT = Ld->getMemoryVT();
14161   DebugLoc dl = Ld->getDebugLoc();
14162   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14163
14164   ISD::LoadExtType Ext = Ld->getExtensionType();
14165
14166   // If this is a vector EXT Load then attempt to optimize it using a
14167   // shuffle. We need SSE4 for the shuffles.
14168   // TODO: It is possible to support ZExt by zeroing the undef values
14169   // during the shuffle phase or after the shuffle.
14170   if (RegVT.isVector() && Ext == ISD::EXTLOAD && Subtarget->hasSSE41()) {
14171     assert(MemVT != RegVT && "Cannot extend to the same type");
14172     assert(MemVT.isVector() && "Must load a vector from memory");
14173
14174     unsigned NumElems = RegVT.getVectorNumElements();
14175     unsigned RegSz = RegVT.getSizeInBits();
14176     unsigned MemSz = MemVT.getSizeInBits();
14177     assert(RegSz > MemSz && "Register size must be greater than the mem size");
14178     // All sizes must be a power of two
14179     if (!isPowerOf2_32(RegSz * MemSz * NumElems)) return SDValue();
14180
14181     // Attempt to load the original value using a single load op.
14182     // Find a scalar type which is equal to the loaded word size.
14183     MVT SclrLoadTy = MVT::i8;
14184     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
14185          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
14186       MVT Tp = (MVT::SimpleValueType)tp;
14187       if (TLI.isTypeLegal(Tp) &&  Tp.getSizeInBits() == MemSz) {
14188         SclrLoadTy = Tp;
14189         break;
14190       }
14191     }
14192
14193     // Proceed if a load word is found.
14194     if (SclrLoadTy.getSizeInBits() != MemSz) return SDValue();
14195
14196     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
14197       RegSz/SclrLoadTy.getSizeInBits());
14198
14199     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14200                                   RegSz/MemVT.getScalarType().getSizeInBits());
14201     // Can't shuffle using an illegal type.
14202     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
14203
14204     // Perform a single load.
14205     SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
14206                                   Ld->getBasePtr(),
14207                                   Ld->getPointerInfo(), Ld->isVolatile(),
14208                                   Ld->isNonTemporal(), Ld->isInvariant(),
14209                                   Ld->getAlignment());
14210
14211     // Insert the word loaded into a vector.
14212     SDValue ScalarInVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
14213       LoadUnitVecVT, ScalarLoad);
14214
14215     // Bitcast the loaded value to a vector of the original element type, in
14216     // the size of the target vector type.
14217     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, ScalarInVector);
14218     unsigned SizeRatio = RegSz/MemSz;
14219
14220     // Redistribute the loaded elements into the different locations.
14221     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
14222     for (unsigned i = 0; i < NumElems; i++) ShuffleVec[i*SizeRatio] = i;
14223
14224     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14225                                 DAG.getUNDEF(SlicedVec.getValueType()),
14226                                 ShuffleVec.data());
14227
14228     // Bitcast to the requested type.
14229     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
14230     // Replace the original load with the new sequence
14231     // and return the new chain.
14232     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Shuff);
14233     return SDValue(ScalarLoad.getNode(), 1);
14234   }
14235
14236   return SDValue();
14237 }
14238
14239 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
14240 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
14241                                    const X86Subtarget *Subtarget) {
14242   StoreSDNode *St = cast<StoreSDNode>(N);
14243   EVT VT = St->getValue().getValueType();
14244   EVT StVT = St->getMemoryVT();
14245   DebugLoc dl = St->getDebugLoc();
14246   SDValue StoredVal = St->getOperand(1);
14247   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14248
14249   // If we are saving a concatination of two XMM registers, perform two stores.
14250   // This is better in Sandy Bridge cause one 256-bit mem op is done via two
14251   // 128-bit ones. If in the future the cost becomes only one memory access the
14252   // first version would be better.
14253   if (VT.getSizeInBits() == 256 &&
14254     StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
14255     StoredVal.getNumOperands() == 2) {
14256
14257     SDValue Value0 = StoredVal.getOperand(0);
14258     SDValue Value1 = StoredVal.getOperand(1);
14259
14260     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
14261     SDValue Ptr0 = St->getBasePtr();
14262     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
14263
14264     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
14265                                 St->getPointerInfo(), St->isVolatile(),
14266                                 St->isNonTemporal(), St->getAlignment());
14267     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
14268                                 St->getPointerInfo(), St->isVolatile(),
14269                                 St->isNonTemporal(), St->getAlignment());
14270     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
14271   }
14272
14273   // Optimize trunc store (of multiple scalars) to shuffle and store.
14274   // First, pack all of the elements in one place. Next, store to memory
14275   // in fewer chunks.
14276   if (St->isTruncatingStore() && VT.isVector()) {
14277     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14278     unsigned NumElems = VT.getVectorNumElements();
14279     assert(StVT != VT && "Cannot truncate to the same type");
14280     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
14281     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
14282
14283     // From, To sizes and ElemCount must be pow of two
14284     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
14285     // We are going to use the original vector elt for storing.
14286     // Accumulated smaller vector elements must be a multiple of the store size.
14287     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
14288
14289     unsigned SizeRatio  = FromSz / ToSz;
14290
14291     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
14292
14293     // Create a type on which we perform the shuffle
14294     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
14295             StVT.getScalarType(), NumElems*SizeRatio);
14296
14297     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
14298
14299     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
14300     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
14301     for (unsigned i = 0; i < NumElems; i++ ) ShuffleVec[i] = i * SizeRatio;
14302
14303     // Can't shuffle using an illegal type
14304     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
14305
14306     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
14307                                 DAG.getUNDEF(WideVec.getValueType()),
14308                                 ShuffleVec.data());
14309     // At this point all of the data is stored at the bottom of the
14310     // register. We now need to save it to mem.
14311
14312     // Find the largest store unit
14313     MVT StoreType = MVT::i8;
14314     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
14315          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
14316       MVT Tp = (MVT::SimpleValueType)tp;
14317       if (TLI.isTypeLegal(Tp) && StoreType.getSizeInBits() < NumElems * ToSz)
14318         StoreType = Tp;
14319     }
14320
14321     // Bitcast the original vector into a vector of store-size units
14322     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
14323             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
14324     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
14325     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
14326     SmallVector<SDValue, 8> Chains;
14327     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
14328                                         TLI.getPointerTy());
14329     SDValue Ptr = St->getBasePtr();
14330
14331     // Perform one or more big stores into memory.
14332     for (unsigned i = 0; i < (ToSz*NumElems)/StoreType.getSizeInBits() ; i++) {
14333       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
14334                                    StoreType, ShuffWide,
14335                                    DAG.getIntPtrConstant(i));
14336       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
14337                                 St->getPointerInfo(), St->isVolatile(),
14338                                 St->isNonTemporal(), St->getAlignment());
14339       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14340       Chains.push_back(Ch);
14341     }
14342
14343     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
14344                                Chains.size());
14345   }
14346
14347
14348   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
14349   // the FP state in cases where an emms may be missing.
14350   // A preferable solution to the general problem is to figure out the right
14351   // places to insert EMMS.  This qualifies as a quick hack.
14352
14353   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
14354   if (VT.getSizeInBits() != 64)
14355     return SDValue();
14356
14357   const Function *F = DAG.getMachineFunction().getFunction();
14358   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
14359   bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
14360                      && Subtarget->hasXMMInt();
14361   if ((VT.isVector() ||
14362        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
14363       isa<LoadSDNode>(St->getValue()) &&
14364       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
14365       St->getChain().hasOneUse() && !St->isVolatile()) {
14366     SDNode* LdVal = St->getValue().getNode();
14367     LoadSDNode *Ld = 0;
14368     int TokenFactorIndex = -1;
14369     SmallVector<SDValue, 8> Ops;
14370     SDNode* ChainVal = St->getChain().getNode();
14371     // Must be a store of a load.  We currently handle two cases:  the load
14372     // is a direct child, and it's under an intervening TokenFactor.  It is
14373     // possible to dig deeper under nested TokenFactors.
14374     if (ChainVal == LdVal)
14375       Ld = cast<LoadSDNode>(St->getChain());
14376     else if (St->getValue().hasOneUse() &&
14377              ChainVal->getOpcode() == ISD::TokenFactor) {
14378       for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
14379         if (ChainVal->getOperand(i).getNode() == LdVal) {
14380           TokenFactorIndex = i;
14381           Ld = cast<LoadSDNode>(St->getValue());
14382         } else
14383           Ops.push_back(ChainVal->getOperand(i));
14384       }
14385     }
14386
14387     if (!Ld || !ISD::isNormalLoad(Ld))
14388       return SDValue();
14389
14390     // If this is not the MMX case, i.e. we are just turning i64 load/store
14391     // into f64 load/store, avoid the transformation if there are multiple
14392     // uses of the loaded value.
14393     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
14394       return SDValue();
14395
14396     DebugLoc LdDL = Ld->getDebugLoc();
14397     DebugLoc StDL = N->getDebugLoc();
14398     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
14399     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
14400     // pair instead.
14401     if (Subtarget->is64Bit() || F64IsLegal) {
14402       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
14403       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
14404                                   Ld->getPointerInfo(), Ld->isVolatile(),
14405                                   Ld->isNonTemporal(), Ld->isInvariant(),
14406                                   Ld->getAlignment());
14407       SDValue NewChain = NewLd.getValue(1);
14408       if (TokenFactorIndex != -1) {
14409         Ops.push_back(NewChain);
14410         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14411                                Ops.size());
14412       }
14413       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
14414                           St->getPointerInfo(),
14415                           St->isVolatile(), St->isNonTemporal(),
14416                           St->getAlignment());
14417     }
14418
14419     // Otherwise, lower to two pairs of 32-bit loads / stores.
14420     SDValue LoAddr = Ld->getBasePtr();
14421     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
14422                                  DAG.getConstant(4, MVT::i32));
14423
14424     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
14425                                Ld->getPointerInfo(),
14426                                Ld->isVolatile(), Ld->isNonTemporal(),
14427                                Ld->isInvariant(), Ld->getAlignment());
14428     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
14429                                Ld->getPointerInfo().getWithOffset(4),
14430                                Ld->isVolatile(), Ld->isNonTemporal(),
14431                                Ld->isInvariant(),
14432                                MinAlign(Ld->getAlignment(), 4));
14433
14434     SDValue NewChain = LoLd.getValue(1);
14435     if (TokenFactorIndex != -1) {
14436       Ops.push_back(LoLd);
14437       Ops.push_back(HiLd);
14438       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14439                              Ops.size());
14440     }
14441
14442     LoAddr = St->getBasePtr();
14443     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
14444                          DAG.getConstant(4, MVT::i32));
14445
14446     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
14447                                 St->getPointerInfo(),
14448                                 St->isVolatile(), St->isNonTemporal(),
14449                                 St->getAlignment());
14450     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
14451                                 St->getPointerInfo().getWithOffset(4),
14452                                 St->isVolatile(),
14453                                 St->isNonTemporal(),
14454                                 MinAlign(St->getAlignment(), 4));
14455     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
14456   }
14457   return SDValue();
14458 }
14459
14460 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
14461 /// and return the operands for the horizontal operation in LHS and RHS.  A
14462 /// horizontal operation performs the binary operation on successive elements
14463 /// of its first operand, then on successive elements of its second operand,
14464 /// returning the resulting values in a vector.  For example, if
14465 ///   A = < float a0, float a1, float a2, float a3 >
14466 /// and
14467 ///   B = < float b0, float b1, float b2, float b3 >
14468 /// then the result of doing a horizontal operation on A and B is
14469 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
14470 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
14471 /// A horizontal-op B, for some already available A and B, and if so then LHS is
14472 /// set to A, RHS to B, and the routine returns 'true'.
14473 /// Note that the binary operation should have the property that if one of the
14474 /// operands is UNDEF then the result is UNDEF.
14475 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool isCommutative) {
14476   // Look for the following pattern: if
14477   //   A = < float a0, float a1, float a2, float a3 >
14478   //   B = < float b0, float b1, float b2, float b3 >
14479   // and
14480   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
14481   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
14482   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
14483   // which is A horizontal-op B.
14484
14485   // At least one of the operands should be a vector shuffle.
14486   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
14487       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
14488     return false;
14489
14490   EVT VT = LHS.getValueType();
14491   unsigned N = VT.getVectorNumElements();
14492
14493   // View LHS in the form
14494   //   LHS = VECTOR_SHUFFLE A, B, LMask
14495   // If LHS is not a shuffle then pretend it is the shuffle
14496   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
14497   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
14498   // type VT.
14499   SDValue A, B;
14500   SmallVector<int, 8> LMask(N);
14501   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
14502     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
14503       A = LHS.getOperand(0);
14504     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
14505       B = LHS.getOperand(1);
14506     cast<ShuffleVectorSDNode>(LHS.getNode())->getMask(LMask);
14507   } else {
14508     if (LHS.getOpcode() != ISD::UNDEF)
14509       A = LHS;
14510     for (unsigned i = 0; i != N; ++i)
14511       LMask[i] = i;
14512   }
14513
14514   // Likewise, view RHS in the form
14515   //   RHS = VECTOR_SHUFFLE C, D, RMask
14516   SDValue C, D;
14517   SmallVector<int, 8> RMask(N);
14518   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
14519     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
14520       C = RHS.getOperand(0);
14521     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
14522       D = RHS.getOperand(1);
14523     cast<ShuffleVectorSDNode>(RHS.getNode())->getMask(RMask);
14524   } else {
14525     if (RHS.getOpcode() != ISD::UNDEF)
14526       C = RHS;
14527     for (unsigned i = 0; i != N; ++i)
14528       RMask[i] = i;
14529   }
14530
14531   // Check that the shuffles are both shuffling the same vectors.
14532   if (!(A == C && B == D) && !(A == D && B == C))
14533     return false;
14534
14535   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
14536   if (!A.getNode() && !B.getNode())
14537     return false;
14538
14539   // If A and B occur in reverse order in RHS, then "swap" them (which means
14540   // rewriting the mask).
14541   if (A != C)
14542     for (unsigned i = 0; i != N; ++i) {
14543       unsigned Idx = RMask[i];
14544       if (Idx < N)
14545         RMask[i] += N;
14546       else if (Idx < 2*N)
14547         RMask[i] -= N;
14548     }
14549
14550   // At this point LHS and RHS are equivalent to
14551   //   LHS = VECTOR_SHUFFLE A, B, LMask
14552   //   RHS = VECTOR_SHUFFLE A, B, RMask
14553   // Check that the masks correspond to performing a horizontal operation.
14554   for (unsigned i = 0; i != N; ++i) {
14555     unsigned LIdx = LMask[i], RIdx = RMask[i];
14556
14557     // Ignore any UNDEF components.
14558     if (LIdx >= 2*N || RIdx >= 2*N || (!A.getNode() && (LIdx < N || RIdx < N))
14559         || (!B.getNode() && (LIdx >= N || RIdx >= N)))
14560       continue;
14561
14562     // Check that successive elements are being operated on.  If not, this is
14563     // not a horizontal operation.
14564     if (!(LIdx == 2*i && RIdx == 2*i + 1) &&
14565         !(isCommutative && LIdx == 2*i + 1 && RIdx == 2*i))
14566       return false;
14567   }
14568
14569   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
14570   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
14571   return true;
14572 }
14573
14574 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
14575 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
14576                                   const X86Subtarget *Subtarget) {
14577   EVT VT = N->getValueType(0);
14578   SDValue LHS = N->getOperand(0);
14579   SDValue RHS = N->getOperand(1);
14580
14581   // Try to synthesize horizontal adds from adds of shuffles.
14582   if (Subtarget->hasSSE3orAVX() && (VT == MVT::v4f32 || VT == MVT::v2f64) &&
14583       isHorizontalBinOp(LHS, RHS, true))
14584     return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
14585   return SDValue();
14586 }
14587
14588 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
14589 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
14590                                   const X86Subtarget *Subtarget) {
14591   EVT VT = N->getValueType(0);
14592   SDValue LHS = N->getOperand(0);
14593   SDValue RHS = N->getOperand(1);
14594
14595   // Try to synthesize horizontal subs from subs of shuffles.
14596   if (Subtarget->hasSSE3orAVX() && (VT == MVT::v4f32 || VT == MVT::v2f64) &&
14597       isHorizontalBinOp(LHS, RHS, false))
14598     return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
14599   return SDValue();
14600 }
14601
14602 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
14603 /// X86ISD::FXOR nodes.
14604 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
14605   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
14606   // F[X]OR(0.0, x) -> x
14607   // F[X]OR(x, 0.0) -> x
14608   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
14609     if (C->getValueAPF().isPosZero())
14610       return N->getOperand(1);
14611   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
14612     if (C->getValueAPF().isPosZero())
14613       return N->getOperand(0);
14614   return SDValue();
14615 }
14616
14617 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
14618 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
14619   // FAND(0.0, x) -> 0.0
14620   // FAND(x, 0.0) -> 0.0
14621   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
14622     if (C->getValueAPF().isPosZero())
14623       return N->getOperand(0);
14624   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
14625     if (C->getValueAPF().isPosZero())
14626       return N->getOperand(1);
14627   return SDValue();
14628 }
14629
14630 static SDValue PerformBTCombine(SDNode *N,
14631                                 SelectionDAG &DAG,
14632                                 TargetLowering::DAGCombinerInfo &DCI) {
14633   // BT ignores high bits in the bit index operand.
14634   SDValue Op1 = N->getOperand(1);
14635   if (Op1.hasOneUse()) {
14636     unsigned BitWidth = Op1.getValueSizeInBits();
14637     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
14638     APInt KnownZero, KnownOne;
14639     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
14640                                           !DCI.isBeforeLegalizeOps());
14641     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14642     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
14643         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
14644       DCI.CommitTargetLoweringOpt(TLO);
14645   }
14646   return SDValue();
14647 }
14648
14649 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
14650   SDValue Op = N->getOperand(0);
14651   if (Op.getOpcode() == ISD::BITCAST)
14652     Op = Op.getOperand(0);
14653   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
14654   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
14655       VT.getVectorElementType().getSizeInBits() ==
14656       OpVT.getVectorElementType().getSizeInBits()) {
14657     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
14658   }
14659   return SDValue();
14660 }
14661
14662 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
14663   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
14664   //           (and (i32 x86isd::setcc_carry), 1)
14665   // This eliminates the zext. This transformation is necessary because
14666   // ISD::SETCC is always legalized to i8.
14667   DebugLoc dl = N->getDebugLoc();
14668   SDValue N0 = N->getOperand(0);
14669   EVT VT = N->getValueType(0);
14670   if (N0.getOpcode() == ISD::AND &&
14671       N0.hasOneUse() &&
14672       N0.getOperand(0).hasOneUse()) {
14673     SDValue N00 = N0.getOperand(0);
14674     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
14675       return SDValue();
14676     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
14677     if (!C || C->getZExtValue() != 1)
14678       return SDValue();
14679     return DAG.getNode(ISD::AND, dl, VT,
14680                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
14681                                    N00.getOperand(0), N00.getOperand(1)),
14682                        DAG.getConstant(1, VT));
14683   }
14684
14685   return SDValue();
14686 }
14687
14688 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
14689 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
14690   unsigned X86CC = N->getConstantOperandVal(0);
14691   SDValue EFLAG = N->getOperand(1);
14692   DebugLoc DL = N->getDebugLoc();
14693
14694   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
14695   // a zext and produces an all-ones bit which is more useful than 0/1 in some
14696   // cases.
14697   if (X86CC == X86::COND_B)
14698     return DAG.getNode(ISD::AND, DL, MVT::i8,
14699                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
14700                                    DAG.getConstant(X86CC, MVT::i8), EFLAG),
14701                        DAG.getConstant(1, MVT::i8));
14702
14703   return SDValue();
14704 }
14705
14706 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
14707                                         const X86TargetLowering *XTLI) {
14708   SDValue Op0 = N->getOperand(0);
14709   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
14710   // a 32-bit target where SSE doesn't support i64->FP operations.
14711   if (Op0.getOpcode() == ISD::LOAD) {
14712     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
14713     EVT VT = Ld->getValueType(0);
14714     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
14715         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
14716         !XTLI->getSubtarget()->is64Bit() &&
14717         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14718       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
14719                                           Ld->getChain(), Op0, DAG);
14720       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
14721       return FILDChain;
14722     }
14723   }
14724   return SDValue();
14725 }
14726
14727 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
14728 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
14729                                  X86TargetLowering::DAGCombinerInfo &DCI) {
14730   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
14731   // the result is either zero or one (depending on the input carry bit).
14732   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
14733   if (X86::isZeroNode(N->getOperand(0)) &&
14734       X86::isZeroNode(N->getOperand(1)) &&
14735       // We don't have a good way to replace an EFLAGS use, so only do this when
14736       // dead right now.
14737       SDValue(N, 1).use_empty()) {
14738     DebugLoc DL = N->getDebugLoc();
14739     EVT VT = N->getValueType(0);
14740     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
14741     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
14742                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
14743                                            DAG.getConstant(X86::COND_B,MVT::i8),
14744                                            N->getOperand(2)),
14745                                DAG.getConstant(1, VT));
14746     return DCI.CombineTo(N, Res1, CarryOut);
14747   }
14748
14749   return SDValue();
14750 }
14751
14752 // fold (add Y, (sete  X, 0)) -> adc  0, Y
14753 //      (add Y, (setne X, 0)) -> sbb -1, Y
14754 //      (sub (sete  X, 0), Y) -> sbb  0, Y
14755 //      (sub (setne X, 0), Y) -> adc -1, Y
14756 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
14757   DebugLoc DL = N->getDebugLoc();
14758
14759   // Look through ZExts.
14760   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
14761   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
14762     return SDValue();
14763
14764   SDValue SetCC = Ext.getOperand(0);
14765   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
14766     return SDValue();
14767
14768   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
14769   if (CC != X86::COND_E && CC != X86::COND_NE)
14770     return SDValue();
14771
14772   SDValue Cmp = SetCC.getOperand(1);
14773   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
14774       !X86::isZeroNode(Cmp.getOperand(1)) ||
14775       !Cmp.getOperand(0).getValueType().isInteger())
14776     return SDValue();
14777
14778   SDValue CmpOp0 = Cmp.getOperand(0);
14779   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
14780                                DAG.getConstant(1, CmpOp0.getValueType()));
14781
14782   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
14783   if (CC == X86::COND_NE)
14784     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
14785                        DL, OtherVal.getValueType(), OtherVal,
14786                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
14787   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
14788                      DL, OtherVal.getValueType(), OtherVal,
14789                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
14790 }
14791
14792 /// PerformADDCombine - Do target-specific dag combines on integer adds.
14793 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
14794                                  const X86Subtarget *Subtarget) {
14795   EVT VT = N->getValueType(0);
14796   SDValue Op0 = N->getOperand(0);
14797   SDValue Op1 = N->getOperand(1);
14798
14799   // Try to synthesize horizontal adds from adds of shuffles.
14800   if ((Subtarget->hasSSSE3orAVX()) && (VT == MVT::v8i16 || VT == MVT::v4i32) &&
14801       isHorizontalBinOp(Op0, Op1, true))
14802     return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
14803
14804   return OptimizeConditionalInDecrement(N, DAG);
14805 }
14806
14807 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
14808                                  const X86Subtarget *Subtarget) {
14809   SDValue Op0 = N->getOperand(0);
14810   SDValue Op1 = N->getOperand(1);
14811
14812   // X86 can't encode an immediate LHS of a sub. See if we can push the
14813   // negation into a preceding instruction.
14814   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
14815     // If the RHS of the sub is a XOR with one use and a constant, invert the
14816     // immediate. Then add one to the LHS of the sub so we can turn
14817     // X-Y -> X+~Y+1, saving one register.
14818     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
14819         isa<ConstantSDNode>(Op1.getOperand(1))) {
14820       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
14821       EVT VT = Op0.getValueType();
14822       SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
14823                                    Op1.getOperand(0),
14824                                    DAG.getConstant(~XorC, VT));
14825       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
14826                          DAG.getConstant(C->getAPIntValue()+1, VT));
14827     }
14828   }
14829
14830   // Try to synthesize horizontal adds from adds of shuffles.
14831   EVT VT = N->getValueType(0);
14832   if ((Subtarget->hasSSSE3orAVX()) && (VT == MVT::v8i16 || VT == MVT::v4i32) &&
14833       isHorizontalBinOp(Op0, Op1, false))
14834     return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
14835
14836   return OptimizeConditionalInDecrement(N, DAG);
14837 }
14838
14839 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
14840                                              DAGCombinerInfo &DCI) const {
14841   SelectionDAG &DAG = DCI.DAG;
14842   switch (N->getOpcode()) {
14843   default: break;
14844   case ISD::EXTRACT_VECTOR_ELT:
14845     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
14846   case ISD::VSELECT:
14847   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
14848   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
14849   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
14850   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
14851   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
14852   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
14853   case ISD::SHL:
14854   case ISD::SRA:
14855   case ISD::SRL:            return PerformShiftCombine(N, DAG, Subtarget);
14856   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
14857   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
14858   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
14859   case ISD::LOAD:           return PerformLOADCombine(N, DAG, Subtarget);
14860   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
14861   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
14862   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
14863   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
14864   case X86ISD::FXOR:
14865   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
14866   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
14867   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
14868   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
14869   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG);
14870   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG);
14871   case X86ISD::SHUFPS:      // Handle all target specific shuffles
14872   case X86ISD::SHUFPD:
14873   case X86ISD::PALIGN:
14874   case X86ISD::PUNPCKHBW:
14875   case X86ISD::PUNPCKHWD:
14876   case X86ISD::PUNPCKHDQ:
14877   case X86ISD::PUNPCKHQDQ:
14878   case X86ISD::UNPCKHPS:
14879   case X86ISD::UNPCKHPD:
14880   case X86ISD::VUNPCKHPSY:
14881   case X86ISD::VUNPCKHPDY:
14882   case X86ISD::PUNPCKLBW:
14883   case X86ISD::PUNPCKLWD:
14884   case X86ISD::PUNPCKLDQ:
14885   case X86ISD::PUNPCKLQDQ:
14886   case X86ISD::UNPCKLPS:
14887   case X86ISD::UNPCKLPD:
14888   case X86ISD::VUNPCKLPSY:
14889   case X86ISD::VUNPCKLPDY:
14890   case X86ISD::MOVHLPS:
14891   case X86ISD::MOVLHPS:
14892   case X86ISD::PSHUFD:
14893   case X86ISD::PSHUFHW:
14894   case X86ISD::PSHUFLW:
14895   case X86ISD::MOVSS:
14896   case X86ISD::MOVSD:
14897   case X86ISD::VPERMILPS:
14898   case X86ISD::VPERMILPSY:
14899   case X86ISD::VPERMILPD:
14900   case X86ISD::VPERMILPDY:
14901   case X86ISD::VPERM2F128:
14902   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
14903   }
14904
14905   return SDValue();
14906 }
14907
14908 /// isTypeDesirableForOp - Return true if the target has native support for
14909 /// the specified value type and it is 'desirable' to use the type for the
14910 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
14911 /// instruction encodings are longer and some i16 instructions are slow.
14912 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
14913   if (!isTypeLegal(VT))
14914     return false;
14915   if (VT != MVT::i16)
14916     return true;
14917
14918   switch (Opc) {
14919   default:
14920     return true;
14921   case ISD::LOAD:
14922   case ISD::SIGN_EXTEND:
14923   case ISD::ZERO_EXTEND:
14924   case ISD::ANY_EXTEND:
14925   case ISD::SHL:
14926   case ISD::SRL:
14927   case ISD::SUB:
14928   case ISD::ADD:
14929   case ISD::MUL:
14930   case ISD::AND:
14931   case ISD::OR:
14932   case ISD::XOR:
14933     return false;
14934   }
14935 }
14936
14937 /// IsDesirableToPromoteOp - This method query the target whether it is
14938 /// beneficial for dag combiner to promote the specified node. If true, it
14939 /// should return the desired promotion type by reference.
14940 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
14941   EVT VT = Op.getValueType();
14942   if (VT != MVT::i16)
14943     return false;
14944
14945   bool Promote = false;
14946   bool Commute = false;
14947   switch (Op.getOpcode()) {
14948   default: break;
14949   case ISD::LOAD: {
14950     LoadSDNode *LD = cast<LoadSDNode>(Op);
14951     // If the non-extending load has a single use and it's not live out, then it
14952     // might be folded.
14953     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
14954                                                      Op.hasOneUse()*/) {
14955       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
14956              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
14957         // The only case where we'd want to promote LOAD (rather then it being
14958         // promoted as an operand is when it's only use is liveout.
14959         if (UI->getOpcode() != ISD::CopyToReg)
14960           return false;
14961       }
14962     }
14963     Promote = true;
14964     break;
14965   }
14966   case ISD::SIGN_EXTEND:
14967   case ISD::ZERO_EXTEND:
14968   case ISD::ANY_EXTEND:
14969     Promote = true;
14970     break;
14971   case ISD::SHL:
14972   case ISD::SRL: {
14973     SDValue N0 = Op.getOperand(0);
14974     // Look out for (store (shl (load), x)).
14975     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
14976       return false;
14977     Promote = true;
14978     break;
14979   }
14980   case ISD::ADD:
14981   case ISD::MUL:
14982   case ISD::AND:
14983   case ISD::OR:
14984   case ISD::XOR:
14985     Commute = true;
14986     // fallthrough
14987   case ISD::SUB: {
14988     SDValue N0 = Op.getOperand(0);
14989     SDValue N1 = Op.getOperand(1);
14990     if (!Commute && MayFoldLoad(N1))
14991       return false;
14992     // Avoid disabling potential load folding opportunities.
14993     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
14994       return false;
14995     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
14996       return false;
14997     Promote = true;
14998   }
14999   }
15000
15001   PVT = MVT::i32;
15002   return Promote;
15003 }
15004
15005 //===----------------------------------------------------------------------===//
15006 //                           X86 Inline Assembly Support
15007 //===----------------------------------------------------------------------===//
15008
15009 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
15010   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
15011
15012   std::string AsmStr = IA->getAsmString();
15013
15014   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
15015   SmallVector<StringRef, 4> AsmPieces;
15016   SplitString(AsmStr, AsmPieces, ";\n");
15017
15018   switch (AsmPieces.size()) {
15019   default: return false;
15020   case 1:
15021     AsmStr = AsmPieces[0];
15022     AsmPieces.clear();
15023     SplitString(AsmStr, AsmPieces, " \t");  // Split with whitespace.
15024
15025     // FIXME: this should verify that we are targeting a 486 or better.  If not,
15026     // we will turn this bswap into something that will be lowered to logical ops
15027     // instead of emitting the bswap asm.  For now, we don't support 486 or lower
15028     // so don't worry about this.
15029     // bswap $0
15030     if (AsmPieces.size() == 2 &&
15031         (AsmPieces[0] == "bswap" ||
15032          AsmPieces[0] == "bswapq" ||
15033          AsmPieces[0] == "bswapl") &&
15034         (AsmPieces[1] == "$0" ||
15035          AsmPieces[1] == "${0:q}")) {
15036       // No need to check constraints, nothing other than the equivalent of
15037       // "=r,0" would be valid here.
15038       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
15039       if (!Ty || Ty->getBitWidth() % 16 != 0)
15040         return false;
15041       return IntrinsicLowering::LowerToByteSwap(CI);
15042     }
15043     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
15044     if (CI->getType()->isIntegerTy(16) &&
15045         AsmPieces.size() == 3 &&
15046         (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
15047         AsmPieces[1] == "$$8," &&
15048         AsmPieces[2] == "${0:w}" &&
15049         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
15050       AsmPieces.clear();
15051       const std::string &ConstraintsStr = IA->getConstraintString();
15052       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
15053       std::sort(AsmPieces.begin(), AsmPieces.end());
15054       if (AsmPieces.size() == 4 &&
15055           AsmPieces[0] == "~{cc}" &&
15056           AsmPieces[1] == "~{dirflag}" &&
15057           AsmPieces[2] == "~{flags}" &&
15058           AsmPieces[3] == "~{fpsr}") {
15059         IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
15060         if (!Ty || Ty->getBitWidth() % 16 != 0)
15061           return false;
15062         return IntrinsicLowering::LowerToByteSwap(CI);
15063       }
15064     }
15065     break;
15066   case 3:
15067     if (CI->getType()->isIntegerTy(32) &&
15068         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
15069       SmallVector<StringRef, 4> Words;
15070       SplitString(AsmPieces[0], Words, " \t,");
15071       if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
15072           Words[2] == "${0:w}") {
15073         Words.clear();
15074         SplitString(AsmPieces[1], Words, " \t,");
15075         if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" &&
15076             Words[2] == "$0") {
15077           Words.clear();
15078           SplitString(AsmPieces[2], Words, " \t,");
15079           if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
15080               Words[2] == "${0:w}") {
15081             AsmPieces.clear();
15082             const std::string &ConstraintsStr = IA->getConstraintString();
15083             SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
15084             std::sort(AsmPieces.begin(), AsmPieces.end());
15085             if (AsmPieces.size() == 4 &&
15086                 AsmPieces[0] == "~{cc}" &&
15087                 AsmPieces[1] == "~{dirflag}" &&
15088                 AsmPieces[2] == "~{flags}" &&
15089                 AsmPieces[3] == "~{fpsr}") {
15090               IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
15091               if (!Ty || Ty->getBitWidth() % 16 != 0)
15092                 return false;
15093               return IntrinsicLowering::LowerToByteSwap(CI);
15094             }
15095           }
15096         }
15097       }
15098     }
15099
15100     if (CI->getType()->isIntegerTy(64)) {
15101       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
15102       if (Constraints.size() >= 2 &&
15103           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
15104           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
15105         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
15106         SmallVector<StringRef, 4> Words;
15107         SplitString(AsmPieces[0], Words, " \t");
15108         if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
15109           Words.clear();
15110           SplitString(AsmPieces[1], Words, " \t");
15111           if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
15112             Words.clear();
15113             SplitString(AsmPieces[2], Words, " \t,");
15114             if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
15115                 Words[2] == "%edx") {
15116               IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
15117               if (!Ty || Ty->getBitWidth() % 16 != 0)
15118                 return false;
15119               return IntrinsicLowering::LowerToByteSwap(CI);
15120             }
15121           }
15122         }
15123       }
15124     }
15125     break;
15126   }
15127   return false;
15128 }
15129
15130
15131
15132 /// getConstraintType - Given a constraint letter, return the type of
15133 /// constraint it is for this target.
15134 X86TargetLowering::ConstraintType
15135 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
15136   if (Constraint.size() == 1) {
15137     switch (Constraint[0]) {
15138     case 'R':
15139     case 'q':
15140     case 'Q':
15141     case 'f':
15142     case 't':
15143     case 'u':
15144     case 'y':
15145     case 'x':
15146     case 'Y':
15147     case 'l':
15148       return C_RegisterClass;
15149     case 'a':
15150     case 'b':
15151     case 'c':
15152     case 'd':
15153     case 'S':
15154     case 'D':
15155     case 'A':
15156       return C_Register;
15157     case 'I':
15158     case 'J':
15159     case 'K':
15160     case 'L':
15161     case 'M':
15162     case 'N':
15163     case 'G':
15164     case 'C':
15165     case 'e':
15166     case 'Z':
15167       return C_Other;
15168     default:
15169       break;
15170     }
15171   }
15172   return TargetLowering::getConstraintType(Constraint);
15173 }
15174
15175 /// Examine constraint type and operand type and determine a weight value.
15176 /// This object must already have been set up with the operand type
15177 /// and the current alternative constraint selected.
15178 TargetLowering::ConstraintWeight
15179   X86TargetLowering::getSingleConstraintMatchWeight(
15180     AsmOperandInfo &info, const char *constraint) const {
15181   ConstraintWeight weight = CW_Invalid;
15182   Value *CallOperandVal = info.CallOperandVal;
15183     // If we don't have a value, we can't do a match,
15184     // but allow it at the lowest weight.
15185   if (CallOperandVal == NULL)
15186     return CW_Default;
15187   Type *type = CallOperandVal->getType();
15188   // Look at the constraint type.
15189   switch (*constraint) {
15190   default:
15191     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
15192   case 'R':
15193   case 'q':
15194   case 'Q':
15195   case 'a':
15196   case 'b':
15197   case 'c':
15198   case 'd':
15199   case 'S':
15200   case 'D':
15201   case 'A':
15202     if (CallOperandVal->getType()->isIntegerTy())
15203       weight = CW_SpecificReg;
15204     break;
15205   case 'f':
15206   case 't':
15207   case 'u':
15208       if (type->isFloatingPointTy())
15209         weight = CW_SpecificReg;
15210       break;
15211   case 'y':
15212       if (type->isX86_MMXTy() && Subtarget->hasMMX())
15213         weight = CW_SpecificReg;
15214       break;
15215   case 'x':
15216   case 'Y':
15217     if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
15218       weight = CW_Register;
15219     break;
15220   case 'I':
15221     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
15222       if (C->getZExtValue() <= 31)
15223         weight = CW_Constant;
15224     }
15225     break;
15226   case 'J':
15227     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15228       if (C->getZExtValue() <= 63)
15229         weight = CW_Constant;
15230     }
15231     break;
15232   case 'K':
15233     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15234       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
15235         weight = CW_Constant;
15236     }
15237     break;
15238   case 'L':
15239     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15240       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
15241         weight = CW_Constant;
15242     }
15243     break;
15244   case 'M':
15245     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15246       if (C->getZExtValue() <= 3)
15247         weight = CW_Constant;
15248     }
15249     break;
15250   case 'N':
15251     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15252       if (C->getZExtValue() <= 0xff)
15253         weight = CW_Constant;
15254     }
15255     break;
15256   case 'G':
15257   case 'C':
15258     if (dyn_cast<ConstantFP>(CallOperandVal)) {
15259       weight = CW_Constant;
15260     }
15261     break;
15262   case 'e':
15263     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15264       if ((C->getSExtValue() >= -0x80000000LL) &&
15265           (C->getSExtValue() <= 0x7fffffffLL))
15266         weight = CW_Constant;
15267     }
15268     break;
15269   case 'Z':
15270     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15271       if (C->getZExtValue() <= 0xffffffff)
15272         weight = CW_Constant;
15273     }
15274     break;
15275   }
15276   return weight;
15277 }
15278
15279 /// LowerXConstraint - try to replace an X constraint, which matches anything,
15280 /// with another that has more specific requirements based on the type of the
15281 /// corresponding operand.
15282 const char *X86TargetLowering::
15283 LowerXConstraint(EVT ConstraintVT) const {
15284   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
15285   // 'f' like normal targets.
15286   if (ConstraintVT.isFloatingPoint()) {
15287     if (Subtarget->hasXMMInt())
15288       return "Y";
15289     if (Subtarget->hasXMM())
15290       return "x";
15291   }
15292
15293   return TargetLowering::LowerXConstraint(ConstraintVT);
15294 }
15295
15296 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
15297 /// vector.  If it is invalid, don't add anything to Ops.
15298 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
15299                                                      std::string &Constraint,
15300                                                      std::vector<SDValue>&Ops,
15301                                                      SelectionDAG &DAG) const {
15302   SDValue Result(0, 0);
15303
15304   // Only support length 1 constraints for now.
15305   if (Constraint.length() > 1) return;
15306
15307   char ConstraintLetter = Constraint[0];
15308   switch (ConstraintLetter) {
15309   default: break;
15310   case 'I':
15311     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15312       if (C->getZExtValue() <= 31) {
15313         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15314         break;
15315       }
15316     }
15317     return;
15318   case 'J':
15319     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15320       if (C->getZExtValue() <= 63) {
15321         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15322         break;
15323       }
15324     }
15325     return;
15326   case 'K':
15327     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15328       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
15329         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15330         break;
15331       }
15332     }
15333     return;
15334   case 'N':
15335     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15336       if (C->getZExtValue() <= 255) {
15337         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15338         break;
15339       }
15340     }
15341     return;
15342   case 'e': {
15343     // 32-bit signed value
15344     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15345       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
15346                                            C->getSExtValue())) {
15347         // Widen to 64 bits here to get it sign extended.
15348         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
15349         break;
15350       }
15351     // FIXME gcc accepts some relocatable values here too, but only in certain
15352     // memory models; it's complicated.
15353     }
15354     return;
15355   }
15356   case 'Z': {
15357     // 32-bit unsigned value
15358     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15359       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
15360                                            C->getZExtValue())) {
15361         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15362         break;
15363       }
15364     }
15365     // FIXME gcc accepts some relocatable values here too, but only in certain
15366     // memory models; it's complicated.
15367     return;
15368   }
15369   case 'i': {
15370     // Literal immediates are always ok.
15371     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
15372       // Widen to 64 bits here to get it sign extended.
15373       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
15374       break;
15375     }
15376
15377     // In any sort of PIC mode addresses need to be computed at runtime by
15378     // adding in a register or some sort of table lookup.  These can't
15379     // be used as immediates.
15380     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
15381       return;
15382
15383     // If we are in non-pic codegen mode, we allow the address of a global (with
15384     // an optional displacement) to be used with 'i'.
15385     GlobalAddressSDNode *GA = 0;
15386     int64_t Offset = 0;
15387
15388     // Match either (GA), (GA+C), (GA+C1+C2), etc.
15389     while (1) {
15390       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
15391         Offset += GA->getOffset();
15392         break;
15393       } else if (Op.getOpcode() == ISD::ADD) {
15394         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
15395           Offset += C->getZExtValue();
15396           Op = Op.getOperand(0);
15397           continue;
15398         }
15399       } else if (Op.getOpcode() == ISD::SUB) {
15400         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
15401           Offset += -C->getZExtValue();
15402           Op = Op.getOperand(0);
15403           continue;
15404         }
15405       }
15406
15407       // Otherwise, this isn't something we can handle, reject it.
15408       return;
15409     }
15410
15411     const GlobalValue *GV = GA->getGlobal();
15412     // If we require an extra load to get this address, as in PIC mode, we
15413     // can't accept it.
15414     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
15415                                                         getTargetMachine())))
15416       return;
15417
15418     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
15419                                         GA->getValueType(0), Offset);
15420     break;
15421   }
15422   }
15423
15424   if (Result.getNode()) {
15425     Ops.push_back(Result);
15426     return;
15427   }
15428   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
15429 }
15430
15431 std::pair<unsigned, const TargetRegisterClass*>
15432 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
15433                                                 EVT VT) const {
15434   // First, see if this is a constraint that directly corresponds to an LLVM
15435   // register class.
15436   if (Constraint.size() == 1) {
15437     // GCC Constraint Letters
15438     switch (Constraint[0]) {
15439     default: break;
15440       // TODO: Slight differences here in allocation order and leaving
15441       // RIP in the class. Do they matter any more here than they do
15442       // in the normal allocation?
15443     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
15444       if (Subtarget->is64Bit()) {
15445         if (VT == MVT::i32 || VT == MVT::f32)
15446           return std::make_pair(0U, X86::GR32RegisterClass);
15447         else if (VT == MVT::i16)
15448           return std::make_pair(0U, X86::GR16RegisterClass);
15449         else if (VT == MVT::i8 || VT == MVT::i1)
15450           return std::make_pair(0U, X86::GR8RegisterClass);
15451         else if (VT == MVT::i64 || VT == MVT::f64)
15452           return std::make_pair(0U, X86::GR64RegisterClass);
15453         break;
15454       }
15455       // 32-bit fallthrough
15456     case 'Q':   // Q_REGS
15457       if (VT == MVT::i32 || VT == MVT::f32)
15458         return std::make_pair(0U, X86::GR32_ABCDRegisterClass);
15459       else if (VT == MVT::i16)
15460         return std::make_pair(0U, X86::GR16_ABCDRegisterClass);
15461       else if (VT == MVT::i8 || VT == MVT::i1)
15462         return std::make_pair(0U, X86::GR8_ABCD_LRegisterClass);
15463       else if (VT == MVT::i64)
15464         return std::make_pair(0U, X86::GR64_ABCDRegisterClass);
15465       break;
15466     case 'r':   // GENERAL_REGS
15467     case 'l':   // INDEX_REGS
15468       if (VT == MVT::i8 || VT == MVT::i1)
15469         return std::make_pair(0U, X86::GR8RegisterClass);
15470       if (VT == MVT::i16)
15471         return std::make_pair(0U, X86::GR16RegisterClass);
15472       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
15473         return std::make_pair(0U, X86::GR32RegisterClass);
15474       return std::make_pair(0U, X86::GR64RegisterClass);
15475     case 'R':   // LEGACY_REGS
15476       if (VT == MVT::i8 || VT == MVT::i1)
15477         return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
15478       if (VT == MVT::i16)
15479         return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
15480       if (VT == MVT::i32 || !Subtarget->is64Bit())
15481         return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
15482       return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
15483     case 'f':  // FP Stack registers.
15484       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
15485       // value to the correct fpstack register class.
15486       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
15487         return std::make_pair(0U, X86::RFP32RegisterClass);
15488       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
15489         return std::make_pair(0U, X86::RFP64RegisterClass);
15490       return std::make_pair(0U, X86::RFP80RegisterClass);
15491     case 'y':   // MMX_REGS if MMX allowed.
15492       if (!Subtarget->hasMMX()) break;
15493       return std::make_pair(0U, X86::VR64RegisterClass);
15494     case 'Y':   // SSE_REGS if SSE2 allowed
15495       if (!Subtarget->hasXMMInt()) break;
15496       // FALL THROUGH.
15497     case 'x':   // SSE_REGS if SSE1 allowed
15498       if (!Subtarget->hasXMM()) break;
15499
15500       switch (VT.getSimpleVT().SimpleTy) {
15501       default: break;
15502       // Scalar SSE types.
15503       case MVT::f32:
15504       case MVT::i32:
15505         return std::make_pair(0U, X86::FR32RegisterClass);
15506       case MVT::f64:
15507       case MVT::i64:
15508         return std::make_pair(0U, X86::FR64RegisterClass);
15509       // Vector types.
15510       case MVT::v16i8:
15511       case MVT::v8i16:
15512       case MVT::v4i32:
15513       case MVT::v2i64:
15514       case MVT::v4f32:
15515       case MVT::v2f64:
15516         return std::make_pair(0U, X86::VR128RegisterClass);
15517       }
15518       break;
15519     }
15520   }
15521
15522   // Use the default implementation in TargetLowering to convert the register
15523   // constraint into a member of a register class.
15524   std::pair<unsigned, const TargetRegisterClass*> Res;
15525   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
15526
15527   // Not found as a standard register?
15528   if (Res.second == 0) {
15529     // Map st(0) -> st(7) -> ST0
15530     if (Constraint.size() == 7 && Constraint[0] == '{' &&
15531         tolower(Constraint[1]) == 's' &&
15532         tolower(Constraint[2]) == 't' &&
15533         Constraint[3] == '(' &&
15534         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
15535         Constraint[5] == ')' &&
15536         Constraint[6] == '}') {
15537
15538       Res.first = X86::ST0+Constraint[4]-'0';
15539       Res.second = X86::RFP80RegisterClass;
15540       return Res;
15541     }
15542
15543     // GCC allows "st(0)" to be called just plain "st".
15544     if (StringRef("{st}").equals_lower(Constraint)) {
15545       Res.first = X86::ST0;
15546       Res.second = X86::RFP80RegisterClass;
15547       return Res;
15548     }
15549
15550     // flags -> EFLAGS
15551     if (StringRef("{flags}").equals_lower(Constraint)) {
15552       Res.first = X86::EFLAGS;
15553       Res.second = X86::CCRRegisterClass;
15554       return Res;
15555     }
15556
15557     // 'A' means EAX + EDX.
15558     if (Constraint == "A") {
15559       Res.first = X86::EAX;
15560       Res.second = X86::GR32_ADRegisterClass;
15561       return Res;
15562     }
15563     return Res;
15564   }
15565
15566   // Otherwise, check to see if this is a register class of the wrong value
15567   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
15568   // turn into {ax},{dx}.
15569   if (Res.second->hasType(VT))
15570     return Res;   // Correct type already, nothing to do.
15571
15572   // All of the single-register GCC register classes map their values onto
15573   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
15574   // really want an 8-bit or 32-bit register, map to the appropriate register
15575   // class and return the appropriate register.
15576   if (Res.second == X86::GR16RegisterClass) {
15577     if (VT == MVT::i8) {
15578       unsigned DestReg = 0;
15579       switch (Res.first) {
15580       default: break;
15581       case X86::AX: DestReg = X86::AL; break;
15582       case X86::DX: DestReg = X86::DL; break;
15583       case X86::CX: DestReg = X86::CL; break;
15584       case X86::BX: DestReg = X86::BL; break;
15585       }
15586       if (DestReg) {
15587         Res.first = DestReg;
15588         Res.second = X86::GR8RegisterClass;
15589       }
15590     } else if (VT == MVT::i32) {
15591       unsigned DestReg = 0;
15592       switch (Res.first) {
15593       default: break;
15594       case X86::AX: DestReg = X86::EAX; break;
15595       case X86::DX: DestReg = X86::EDX; break;
15596       case X86::CX: DestReg = X86::ECX; break;
15597       case X86::BX: DestReg = X86::EBX; break;
15598       case X86::SI: DestReg = X86::ESI; break;
15599       case X86::DI: DestReg = X86::EDI; break;
15600       case X86::BP: DestReg = X86::EBP; break;
15601       case X86::SP: DestReg = X86::ESP; break;
15602       }
15603       if (DestReg) {
15604         Res.first = DestReg;
15605         Res.second = X86::GR32RegisterClass;
15606       }
15607     } else if (VT == MVT::i64) {
15608       unsigned DestReg = 0;
15609       switch (Res.first) {
15610       default: break;
15611       case X86::AX: DestReg = X86::RAX; break;
15612       case X86::DX: DestReg = X86::RDX; break;
15613       case X86::CX: DestReg = X86::RCX; break;
15614       case X86::BX: DestReg = X86::RBX; break;
15615       case X86::SI: DestReg = X86::RSI; break;
15616       case X86::DI: DestReg = X86::RDI; break;
15617       case X86::BP: DestReg = X86::RBP; break;
15618       case X86::SP: DestReg = X86::RSP; break;
15619       }
15620       if (DestReg) {
15621         Res.first = DestReg;
15622         Res.second = X86::GR64RegisterClass;
15623       }
15624     }
15625   } else if (Res.second == X86::FR32RegisterClass ||
15626              Res.second == X86::FR64RegisterClass ||
15627              Res.second == X86::VR128RegisterClass) {
15628     // Handle references to XMM physical registers that got mapped into the
15629     // wrong class.  This can happen with constraints like {xmm0} where the
15630     // target independent register mapper will just pick the first match it can
15631     // find, ignoring the required type.
15632     if (VT == MVT::f32)
15633       Res.second = X86::FR32RegisterClass;
15634     else if (VT == MVT::f64)
15635       Res.second = X86::FR64RegisterClass;
15636     else if (X86::VR128RegisterClass->hasType(VT))
15637       Res.second = X86::VR128RegisterClass;
15638   }
15639
15640   return Res;
15641 }