]> CyberLeo.Net >> Repos - FreeBSD/releng/9.2.git/blob - contrib/llvm/lib/Target/X86/X86ISelLowering.cpp
- Copy stable/9 to releng/9.2 as part of the 9.2-RELEASE cycle.
[FreeBSD/releng/9.2.git] / contrib / llvm / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "x86-isel"
16 #include "X86ISelLowering.h"
17 #include "Utils/X86ShuffleDecode.h"
18 #include "X86.h"
19 #include "X86InstrBuilder.h"
20 #include "X86TargetMachine.h"
21 #include "X86TargetObjectFile.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/VariadicFunction.h"
26 #include "llvm/CodeGen/IntrinsicLowering.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/CodeGen/MachineJumpTableInfo.h"
31 #include "llvm/CodeGen/MachineModuleInfo.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/IR/CallingConv.h"
34 #include "llvm/IR/Constants.h"
35 #include "llvm/IR/DerivedTypes.h"
36 #include "llvm/IR/Function.h"
37 #include "llvm/IR/GlobalAlias.h"
38 #include "llvm/IR/GlobalVariable.h"
39 #include "llvm/IR/Instructions.h"
40 #include "llvm/IR/Intrinsics.h"
41 #include "llvm/IR/LLVMContext.h"
42 #include "llvm/MC/MCAsmInfo.h"
43 #include "llvm/MC/MCContext.h"
44 #include "llvm/MC/MCExpr.h"
45 #include "llvm/MC/MCSymbol.h"
46 #include "llvm/Support/CallSite.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Target/TargetOptions.h"
51 #include <bitset>
52 #include <cctype>
53 using namespace llvm;
54
55 STATISTIC(NumTailCalls, "Number of tail calls");
56
57 // Forward declarations.
58 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
59                        SDValue V2);
60
61 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
62 /// sets things up to match to an AVX VEXTRACTF128 instruction or a
63 /// simple subregister reference.  Idx is an index in the 128 bits we
64 /// want.  It need not be aligned to a 128-bit bounday.  That makes
65 /// lowering EXTRACT_VECTOR_ELT operations easier.
66 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
67                                    SelectionDAG &DAG, DebugLoc dl) {
68   EVT VT = Vec.getValueType();
69   assert(VT.is256BitVector() && "Unexpected vector size!");
70   EVT ElVT = VT.getVectorElementType();
71   unsigned Factor = VT.getSizeInBits()/128;
72   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
73                                   VT.getVectorNumElements()/Factor);
74
75   // Extract from UNDEF is UNDEF.
76   if (Vec.getOpcode() == ISD::UNDEF)
77     return DAG.getUNDEF(ResultVT);
78
79   // Extract the relevant 128 bits.  Generate an EXTRACT_SUBVECTOR
80   // we can match to VEXTRACTF128.
81   unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
82
83   // This is the index of the first element of the 128-bit chunk
84   // we want.
85   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
86                                * ElemsPerChunk);
87
88   // If the input is a buildvector just emit a smaller one.
89   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
90     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
91                        Vec->op_begin()+NormalizedIdxVal, ElemsPerChunk);
92
93   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
94   SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
95                                VecIdx);
96
97   return Result;
98 }
99
100 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
101 /// sets things up to match to an AVX VINSERTF128 instruction or a
102 /// simple superregister reference.  Idx is an index in the 128 bits
103 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
104 /// lowering INSERT_VECTOR_ELT operations easier.
105 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
106                                   unsigned IdxVal, SelectionDAG &DAG,
107                                   DebugLoc dl) {
108   // Inserting UNDEF is Result
109   if (Vec.getOpcode() == ISD::UNDEF)
110     return Result;
111
112   EVT VT = Vec.getValueType();
113   assert(VT.is128BitVector() && "Unexpected vector size!");
114
115   EVT ElVT = VT.getVectorElementType();
116   EVT ResultVT = Result.getValueType();
117
118   // Insert the relevant 128 bits.
119   unsigned ElemsPerChunk = 128/ElVT.getSizeInBits();
120
121   // This is the index of the first element of the 128-bit chunk
122   // we want.
123   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/128)
124                                * ElemsPerChunk);
125
126   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
127   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
128                      VecIdx);
129 }
130
131 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
132 /// instructions. This is used because creating CONCAT_VECTOR nodes of
133 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
134 /// large BUILD_VECTORS.
135 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
136                                    unsigned NumElems, SelectionDAG &DAG,
137                                    DebugLoc dl) {
138   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
139   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
140 }
141
142 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
143   const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
144   bool is64Bit = Subtarget->is64Bit();
145
146   if (Subtarget->isTargetEnvMacho()) {
147     if (is64Bit)
148       return new X86_64MachoTargetObjectFile();
149     return new TargetLoweringObjectFileMachO();
150   }
151
152   if (Subtarget->isTargetLinux())
153     return new X86LinuxTargetObjectFile();
154   if (Subtarget->isTargetELF())
155     return new TargetLoweringObjectFileELF();
156   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
157     return new TargetLoweringObjectFileCOFF();
158   llvm_unreachable("unknown subtarget type");
159 }
160
161 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
162   : TargetLowering(TM, createTLOF(TM)) {
163   Subtarget = &TM.getSubtarget<X86Subtarget>();
164   X86ScalarSSEf64 = Subtarget->hasSSE2();
165   X86ScalarSSEf32 = Subtarget->hasSSE1();
166   RegInfo = TM.getRegisterInfo();
167   TD = getDataLayout();
168
169   resetOperationActions();
170 }
171
172 void X86TargetLowering::resetOperationActions() {
173   const TargetMachine &TM = getTargetMachine();
174   static bool FirstTimeThrough = true;
175
176   // If none of the target options have changed, then we don't need to reset the
177   // operation actions.
178   if (!FirstTimeThrough && TO == TM.Options) return;
179
180   if (!FirstTimeThrough) {
181     // Reinitialize the actions.
182     initActions();
183     FirstTimeThrough = false;
184   }
185
186   TO = TM.Options;
187
188   // Set up the TargetLowering object.
189   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
190
191   // X86 is weird, it always uses i8 for shift amounts and setcc results.
192   setBooleanContents(ZeroOrOneBooleanContent);
193   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
194   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
195
196   // For 64-bit since we have so many registers use the ILP scheduler, for
197   // 32-bit code use the register pressure specific scheduling.
198   // For Atom, always use ILP scheduling.
199   if (Subtarget->isAtom())
200     setSchedulingPreference(Sched::ILP);
201   else if (Subtarget->is64Bit())
202     setSchedulingPreference(Sched::ILP);
203   else
204     setSchedulingPreference(Sched::RegPressure);
205   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
206
207   // Bypass expensive divides on Atom when compiling with O2
208   if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
209     addBypassSlowDiv(32, 8);
210     if (Subtarget->is64Bit())
211       addBypassSlowDiv(64, 16);
212   }
213
214   if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
215     // Setup Windows compiler runtime calls.
216     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
217     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
218     setLibcallName(RTLIB::SREM_I64, "_allrem");
219     setLibcallName(RTLIB::UREM_I64, "_aullrem");
220     setLibcallName(RTLIB::MUL_I64, "_allmul");
221     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
222     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
223     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
224     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
225     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
226
227     // The _ftol2 runtime function has an unusual calling conv, which
228     // is modeled by a special pseudo-instruction.
229     setLibcallName(RTLIB::FPTOUINT_F64_I64, 0);
230     setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
231     setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
232     setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
233   }
234
235   if (Subtarget->isTargetDarwin()) {
236     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
237     setUseUnderscoreSetJmp(false);
238     setUseUnderscoreLongJmp(false);
239   } else if (Subtarget->isTargetMingw()) {
240     // MS runtime is weird: it exports _setjmp, but longjmp!
241     setUseUnderscoreSetJmp(true);
242     setUseUnderscoreLongJmp(false);
243   } else {
244     setUseUnderscoreSetJmp(true);
245     setUseUnderscoreLongJmp(true);
246   }
247
248   // Set up the register classes.
249   addRegisterClass(MVT::i8, &X86::GR8RegClass);
250   addRegisterClass(MVT::i16, &X86::GR16RegClass);
251   addRegisterClass(MVT::i32, &X86::GR32RegClass);
252   if (Subtarget->is64Bit())
253     addRegisterClass(MVT::i64, &X86::GR64RegClass);
254
255   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
256
257   // We don't accept any truncstore of integer registers.
258   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
259   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
260   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
261   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
262   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
263   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
264
265   // SETOEQ and SETUNE require checking two conditions.
266   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
267   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
268   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
269   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
270   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
271   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
272
273   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
274   // operation.
275   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
276   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
277   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
278
279   if (Subtarget->is64Bit()) {
280     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
281     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
282   } else if (!TM.Options.UseSoftFloat) {
283     // We have an algorithm for SSE2->double, and we turn this into a
284     // 64-bit FILD followed by conditional FADD for other targets.
285     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
286     // We have an algorithm for SSE2, and we turn this into a 64-bit
287     // FILD for other targets.
288     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
289   }
290
291   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
292   // this operation.
293   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
294   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
295
296   if (!TM.Options.UseSoftFloat) {
297     // SSE has no i16 to fp conversion, only i32
298     if (X86ScalarSSEf32) {
299       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
300       // f32 and f64 cases are Legal, f80 case is not
301       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
302     } else {
303       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
304       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
305     }
306   } else {
307     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
308     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
309   }
310
311   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
312   // are Legal, f80 is custom lowered.
313   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
314   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
315
316   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
317   // this operation.
318   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
319   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
320
321   if (X86ScalarSSEf32) {
322     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
323     // f32 and f64 cases are Legal, f80 case is not
324     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
325   } else {
326     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
327     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
328   }
329
330   // Handle FP_TO_UINT by promoting the destination to a larger signed
331   // conversion.
332   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
333   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
334   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
335
336   if (Subtarget->is64Bit()) {
337     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
338     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
339   } else if (!TM.Options.UseSoftFloat) {
340     // Since AVX is a superset of SSE3, only check for SSE here.
341     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
342       // Expand FP_TO_UINT into a select.
343       // FIXME: We would like to use a Custom expander here eventually to do
344       // the optimal thing for SSE vs. the default expansion in the legalizer.
345       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
346     else
347       // With SSE3 we can use fisttpll to convert to a signed i64; without
348       // SSE, we're stuck with a fistpll.
349       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
350   }
351
352   if (isTargetFTOL()) {
353     // Use the _ftol2 runtime function, which has a pseudo-instruction
354     // to handle its weird calling convention.
355     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
356   }
357
358   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
359   if (!X86ScalarSSEf64) {
360     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
361     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
362     if (Subtarget->is64Bit()) {
363       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
364       // Without SSE, i64->f64 goes through memory.
365       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
366     }
367   }
368
369   // Scalar integer divide and remainder are lowered to use operations that
370   // produce two results, to match the available instructions. This exposes
371   // the two-result form to trivial CSE, which is able to combine x/y and x%y
372   // into a single instruction.
373   //
374   // Scalar integer multiply-high is also lowered to use two-result
375   // operations, to match the available instructions. However, plain multiply
376   // (low) operations are left as Legal, as there are single-result
377   // instructions for this in x86. Using the two-result multiply instructions
378   // when both high and low results are needed must be arranged by dagcombine.
379   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
380     MVT VT = IntVTs[i];
381     setOperationAction(ISD::MULHS, VT, Expand);
382     setOperationAction(ISD::MULHU, VT, Expand);
383     setOperationAction(ISD::SDIV, VT, Expand);
384     setOperationAction(ISD::UDIV, VT, Expand);
385     setOperationAction(ISD::SREM, VT, Expand);
386     setOperationAction(ISD::UREM, VT, Expand);
387
388     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
389     setOperationAction(ISD::ADDC, VT, Custom);
390     setOperationAction(ISD::ADDE, VT, Custom);
391     setOperationAction(ISD::SUBC, VT, Custom);
392     setOperationAction(ISD::SUBE, VT, Custom);
393   }
394
395   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
396   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
397   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
398   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
399   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
400   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
401   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
402   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
403   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
404   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
405   if (Subtarget->is64Bit())
406     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
407   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
408   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
409   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
410   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
411   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
412   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
413   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
414   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
415
416   // Promote the i8 variants and force them on up to i32 which has a shorter
417   // encoding.
418   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
419   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
420   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
421   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
422   if (Subtarget->hasBMI()) {
423     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
424     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
425     if (Subtarget->is64Bit())
426       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
427   } else {
428     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
429     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
430     if (Subtarget->is64Bit())
431       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
432   }
433
434   if (Subtarget->hasLZCNT()) {
435     // When promoting the i8 variants, force them to i32 for a shorter
436     // encoding.
437     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
438     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
439     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
440     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
441     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
442     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
443     if (Subtarget->is64Bit())
444       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
445   } else {
446     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
447     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
448     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
449     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
450     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
451     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
452     if (Subtarget->is64Bit()) {
453       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
454       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
455     }
456   }
457
458   if (Subtarget->hasPOPCNT()) {
459     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
460   } else {
461     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
462     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
463     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
464     if (Subtarget->is64Bit())
465       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
466   }
467
468   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
469   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
470
471   // These should be promoted to a larger select which is supported.
472   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
473   // X86 wants to expand cmov itself.
474   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
475   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
476   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
477   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
478   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
479   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
480   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
481   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
482   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
483   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
484   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
485   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
486   if (Subtarget->is64Bit()) {
487     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
488     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
489   }
490   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
491   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
492   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
493   // support continuation, user-level threading, and etc.. As a result, no
494   // other SjLj exception interfaces are implemented and please don't build
495   // your own exception handling based on them.
496   // LLVM/Clang supports zero-cost DWARF exception handling.
497   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
498   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
499
500   // Darwin ABI issue.
501   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
502   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
503   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
504   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
505   if (Subtarget->is64Bit())
506     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
507   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
508   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
509   if (Subtarget->is64Bit()) {
510     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
511     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
512     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
513     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
514     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
515   }
516   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
517   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
518   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
519   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
520   if (Subtarget->is64Bit()) {
521     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
522     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
523     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
524   }
525
526   if (Subtarget->hasSSE1())
527     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
528
529   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
530
531   // Expand certain atomics
532   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
533     MVT VT = IntVTs[i];
534     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
535     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
536     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
537   }
538
539   if (!Subtarget->is64Bit()) {
540     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
541     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
542     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
543     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
544     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
545     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
546     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
547     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
548     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
549     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
550     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
551     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
552   }
553
554   if (Subtarget->hasCmpxchg16b()) {
555     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
556   }
557
558   // FIXME - use subtarget debug flags
559   if (!Subtarget->isTargetDarwin() &&
560       !Subtarget->isTargetELF() &&
561       !Subtarget->isTargetCygMing()) {
562     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
563   }
564
565   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
566   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
567   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
568   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
569   if (Subtarget->is64Bit()) {
570     setExceptionPointerRegister(X86::RAX);
571     setExceptionSelectorRegister(X86::RDX);
572   } else {
573     setExceptionPointerRegister(X86::EAX);
574     setExceptionSelectorRegister(X86::EDX);
575   }
576   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
577   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
578
579   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
580   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
581
582   setOperationAction(ISD::TRAP, MVT::Other, Legal);
583   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
584
585   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
586   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
587   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
588   if (Subtarget->is64Bit()) {
589     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
590     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
591   } else {
592     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
593     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
594   }
595
596   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
597   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
598
599   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
600     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
601                        MVT::i64 : MVT::i32, Custom);
602   else if (TM.Options.EnableSegmentedStacks)
603     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
604                        MVT::i64 : MVT::i32, Custom);
605   else
606     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
607                        MVT::i64 : MVT::i32, Expand);
608
609   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
610     // f32 and f64 use SSE.
611     // Set up the FP register classes.
612     addRegisterClass(MVT::f32, &X86::FR32RegClass);
613     addRegisterClass(MVT::f64, &X86::FR64RegClass);
614
615     // Use ANDPD to simulate FABS.
616     setOperationAction(ISD::FABS , MVT::f64, Custom);
617     setOperationAction(ISD::FABS , MVT::f32, Custom);
618
619     // Use XORP to simulate FNEG.
620     setOperationAction(ISD::FNEG , MVT::f64, Custom);
621     setOperationAction(ISD::FNEG , MVT::f32, Custom);
622
623     // Use ANDPD and ORPD to simulate FCOPYSIGN.
624     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
625     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
626
627     // Lower this to FGETSIGNx86 plus an AND.
628     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
629     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
630
631     // We don't support sin/cos/fmod
632     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
633     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
634     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
635     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
636     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
637     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
638
639     // Expand FP immediates into loads from the stack, except for the special
640     // cases we handle.
641     addLegalFPImmediate(APFloat(+0.0)); // xorpd
642     addLegalFPImmediate(APFloat(+0.0f)); // xorps
643   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
644     // Use SSE for f32, x87 for f64.
645     // Set up the FP register classes.
646     addRegisterClass(MVT::f32, &X86::FR32RegClass);
647     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
648
649     // Use ANDPS to simulate FABS.
650     setOperationAction(ISD::FABS , MVT::f32, Custom);
651
652     // Use XORP to simulate FNEG.
653     setOperationAction(ISD::FNEG , MVT::f32, Custom);
654
655     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
656
657     // Use ANDPS and ORPS to simulate FCOPYSIGN.
658     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
659     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
660
661     // We don't support sin/cos/fmod
662     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
663     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
664     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
665
666     // Special cases we handle for FP constants.
667     addLegalFPImmediate(APFloat(+0.0f)); // xorps
668     addLegalFPImmediate(APFloat(+0.0)); // FLD0
669     addLegalFPImmediate(APFloat(+1.0)); // FLD1
670     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
671     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
672
673     if (!TM.Options.UnsafeFPMath) {
674       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
675       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
676       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
677     }
678   } else if (!TM.Options.UseSoftFloat) {
679     // f32 and f64 in x87.
680     // Set up the FP register classes.
681     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
682     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
683
684     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
685     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
686     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
687     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
688
689     if (!TM.Options.UnsafeFPMath) {
690       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
691       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
692       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
693       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
694       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
695       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
696     }
697     addLegalFPImmediate(APFloat(+0.0)); // FLD0
698     addLegalFPImmediate(APFloat(+1.0)); // FLD1
699     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
700     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
701     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
702     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
703     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
704     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
705   }
706
707   // We don't support FMA.
708   setOperationAction(ISD::FMA, MVT::f64, Expand);
709   setOperationAction(ISD::FMA, MVT::f32, Expand);
710
711   // Long double always uses X87.
712   if (!TM.Options.UseSoftFloat) {
713     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
714     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
715     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
716     {
717       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
718       addLegalFPImmediate(TmpFlt);  // FLD0
719       TmpFlt.changeSign();
720       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
721
722       bool ignored;
723       APFloat TmpFlt2(+1.0);
724       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
725                       &ignored);
726       addLegalFPImmediate(TmpFlt2);  // FLD1
727       TmpFlt2.changeSign();
728       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
729     }
730
731     if (!TM.Options.UnsafeFPMath) {
732       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
733       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
734       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
735     }
736
737     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
738     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
739     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
740     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
741     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
742     setOperationAction(ISD::FMA, MVT::f80, Expand);
743   }
744
745   // Always use a library call for pow.
746   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
747   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
748   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
749
750   setOperationAction(ISD::FLOG, MVT::f80, Expand);
751   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
752   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
753   setOperationAction(ISD::FEXP, MVT::f80, Expand);
754   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
755
756   // First set operation action for all vector types to either promote
757   // (for widening) or expand (for scalarization). Then we will selectively
758   // turn on ones that can be effectively codegen'd.
759   for (int i = MVT::FIRST_VECTOR_VALUETYPE;
760            i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
761     MVT VT = (MVT::SimpleValueType)i;
762     setOperationAction(ISD::ADD , VT, Expand);
763     setOperationAction(ISD::SUB , VT, Expand);
764     setOperationAction(ISD::FADD, VT, Expand);
765     setOperationAction(ISD::FNEG, VT, Expand);
766     setOperationAction(ISD::FSUB, VT, Expand);
767     setOperationAction(ISD::MUL , VT, Expand);
768     setOperationAction(ISD::FMUL, VT, Expand);
769     setOperationAction(ISD::SDIV, VT, Expand);
770     setOperationAction(ISD::UDIV, VT, Expand);
771     setOperationAction(ISD::FDIV, VT, Expand);
772     setOperationAction(ISD::SREM, VT, Expand);
773     setOperationAction(ISD::UREM, VT, Expand);
774     setOperationAction(ISD::LOAD, VT, Expand);
775     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
776     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
777     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
778     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
779     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
780     setOperationAction(ISD::FABS, VT, Expand);
781     setOperationAction(ISD::FSIN, VT, Expand);
782     setOperationAction(ISD::FSINCOS, VT, Expand);
783     setOperationAction(ISD::FCOS, VT, Expand);
784     setOperationAction(ISD::FSINCOS, VT, Expand);
785     setOperationAction(ISD::FREM, VT, Expand);
786     setOperationAction(ISD::FMA,  VT, Expand);
787     setOperationAction(ISD::FPOWI, VT, Expand);
788     setOperationAction(ISD::FSQRT, VT, Expand);
789     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
790     setOperationAction(ISD::FFLOOR, VT, Expand);
791     setOperationAction(ISD::FCEIL, VT, Expand);
792     setOperationAction(ISD::FTRUNC, VT, Expand);
793     setOperationAction(ISD::FRINT, VT, Expand);
794     setOperationAction(ISD::FNEARBYINT, VT, Expand);
795     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
796     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
797     setOperationAction(ISD::SDIVREM, VT, Expand);
798     setOperationAction(ISD::UDIVREM, VT, Expand);
799     setOperationAction(ISD::FPOW, VT, Expand);
800     setOperationAction(ISD::CTPOP, VT, Expand);
801     setOperationAction(ISD::CTTZ, VT, Expand);
802     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
803     setOperationAction(ISD::CTLZ, VT, Expand);
804     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
805     setOperationAction(ISD::SHL, VT, Expand);
806     setOperationAction(ISD::SRA, VT, Expand);
807     setOperationAction(ISD::SRL, VT, Expand);
808     setOperationAction(ISD::ROTL, VT, Expand);
809     setOperationAction(ISD::ROTR, VT, Expand);
810     setOperationAction(ISD::BSWAP, VT, Expand);
811     setOperationAction(ISD::SETCC, VT, Expand);
812     setOperationAction(ISD::FLOG, VT, Expand);
813     setOperationAction(ISD::FLOG2, VT, Expand);
814     setOperationAction(ISD::FLOG10, VT, Expand);
815     setOperationAction(ISD::FEXP, VT, Expand);
816     setOperationAction(ISD::FEXP2, VT, Expand);
817     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
818     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
819     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
820     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
821     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
822     setOperationAction(ISD::TRUNCATE, VT, Expand);
823     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
824     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
825     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
826     setOperationAction(ISD::VSELECT, VT, Expand);
827     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
828              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
829       setTruncStoreAction(VT,
830                           (MVT::SimpleValueType)InnerVT, Expand);
831     setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
832     setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
833     setLoadExtAction(ISD::EXTLOAD, VT, Expand);
834   }
835
836   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
837   // with -msoft-float, disable use of MMX as well.
838   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
839     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
840     // No operations on x86mmx supported, everything uses intrinsics.
841   }
842
843   // MMX-sized vectors (other than x86mmx) are expected to be expanded
844   // into smaller operations.
845   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
846   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
847   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
848   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
849   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
850   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
851   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
852   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
853   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
854   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
855   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
856   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
857   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
858   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
859   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
860   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
861   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
862   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
863   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
864   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
865   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
866   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
867   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
868   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
869   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
870   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
871   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
872   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
873   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
874
875   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
876     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
877
878     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
879     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
880     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
881     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
882     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
883     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
884     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
885     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
886     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
887     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
888     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
889     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
890   }
891
892   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
893     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
894
895     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
896     // registers cannot be used even for integer operations.
897     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
898     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
899     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
900     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
901
902     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
903     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
904     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
905     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
906     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
907     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
908     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
909     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
910     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
911     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
912     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
913     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
914     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
915     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
916     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
917     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
918     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
919     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
920
921     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
922     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
923     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
924     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
925
926     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
927     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
928     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
929     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
930     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
931
932     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
933     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
934       MVT VT = (MVT::SimpleValueType)i;
935       // Do not attempt to custom lower non-power-of-2 vectors
936       if (!isPowerOf2_32(VT.getVectorNumElements()))
937         continue;
938       // Do not attempt to custom lower non-128-bit vectors
939       if (!VT.is128BitVector())
940         continue;
941       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
942       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
943       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
944     }
945
946     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
947     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
948     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
949     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
950     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
951     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
952
953     if (Subtarget->is64Bit()) {
954       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
955       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
956     }
957
958     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
959     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
960       MVT VT = (MVT::SimpleValueType)i;
961
962       // Do not attempt to promote non-128-bit vectors
963       if (!VT.is128BitVector())
964         continue;
965
966       setOperationAction(ISD::AND,    VT, Promote);
967       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
968       setOperationAction(ISD::OR,     VT, Promote);
969       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
970       setOperationAction(ISD::XOR,    VT, Promote);
971       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
972       setOperationAction(ISD::LOAD,   VT, Promote);
973       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
974       setOperationAction(ISD::SELECT, VT, Promote);
975       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
976     }
977
978     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
979
980     // Custom lower v2i64 and v2f64 selects.
981     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
982     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
983     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
984     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
985
986     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
987     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
988
989     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
990     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
991     // As there is no 64-bit GPR available, we need build a special custom
992     // sequence to convert from v2i32 to v2f32.
993     if (!Subtarget->is64Bit())
994       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
995
996     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
997     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
998
999     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
1000   }
1001
1002   if (Subtarget->hasSSE41()) {
1003     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1004     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1005     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1006     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1007     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1008     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1009     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1010     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1011     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1012     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1013
1014     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1015     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1016     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1017     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1018     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1019     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1020     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1021     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1022     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1023     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1024
1025     // FIXME: Do we need to handle scalar-to-vector here?
1026     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1027
1028     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
1029     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
1030     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1031     setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
1032     setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
1033
1034     // i8 and i16 vectors are custom , because the source register and source
1035     // source memory operand types are not the same width.  f32 vectors are
1036     // custom since the immediate controlling the insert encodes additional
1037     // information.
1038     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1039     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1040     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1041     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1042
1043     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1044     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1045     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1046     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1047
1048     // FIXME: these should be Legal but thats only for the case where
1049     // the index is constant.  For now custom expand to deal with that.
1050     if (Subtarget->is64Bit()) {
1051       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1052       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1053     }
1054   }
1055
1056   if (Subtarget->hasSSE2()) {
1057     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1058     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1059
1060     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1061     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1062
1063     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1064     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1065
1066     // In the customized shift lowering, the legal cases in AVX2 will be
1067     // recognized.
1068     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1069     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1070
1071     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1072     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1073
1074     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1075
1076     setOperationAction(ISD::SDIV,              MVT::v8i16, Custom);
1077     setOperationAction(ISD::SDIV,              MVT::v4i32, Custom);
1078   }
1079
1080   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1081     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1082     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1083     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1084     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1085     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1086     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1087
1088     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1089     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1090     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1091
1092     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1093     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1094     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1095     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1096     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1097     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1098     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1099     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1100     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1101     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1102     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1103     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1104
1105     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1106     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1107     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1108     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1109     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1110     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1111     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1112     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1113     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1114     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1115     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1116     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1117
1118     setOperationAction(ISD::TRUNCATE,           MVT::v8i16, Custom);
1119     setOperationAction(ISD::TRUNCATE,           MVT::v4i32, Custom);
1120
1121     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Custom);
1122
1123     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1124     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1125     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1126     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1127
1128     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i32, Custom);
1129     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1130     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1131
1132     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1133
1134     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1135     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1136
1137     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1138     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1139
1140     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1141     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1142
1143     setOperationAction(ISD::SDIV,              MVT::v16i16, Custom);
1144
1145     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1146     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1147     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1148     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1149
1150     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1151     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1152     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1153
1154     setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1155     setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1156     setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1157     setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1158
1159     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1160     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1161     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1162     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1163     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1164     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1165
1166     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1167       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1168       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1169       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1170       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1171       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1172       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1173     }
1174
1175     if (Subtarget->hasInt256()) {
1176       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1177       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1178       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1179       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1180
1181       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1182       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1183       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1184       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1185
1186       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1187       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1188       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1189       // Don't lower v32i8 because there is no 128-bit byte mul
1190
1191       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1192
1193       setOperationAction(ISD::SDIV,            MVT::v8i32, Custom);
1194     } else {
1195       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1196       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1197       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1198       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1199
1200       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1201       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1202       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1203       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1204
1205       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1206       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1207       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1208       // Don't lower v32i8 because there is no 128-bit byte mul
1209     }
1210
1211     // In the customized shift lowering, the legal cases in AVX2 will be
1212     // recognized.
1213     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1214     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1215
1216     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1217     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1218
1219     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1220
1221     // Custom lower several nodes for 256-bit types.
1222     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1223              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1224       MVT VT = (MVT::SimpleValueType)i;
1225
1226       // Extract subvector is special because the value type
1227       // (result) is 128-bit but the source is 256-bit wide.
1228       if (VT.is128BitVector())
1229         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1230
1231       // Do not attempt to custom lower other non-256-bit vectors
1232       if (!VT.is256BitVector())
1233         continue;
1234
1235       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1236       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1237       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1238       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1239       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1240       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1241       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1242     }
1243
1244     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1245     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1246       MVT VT = (MVT::SimpleValueType)i;
1247
1248       // Do not attempt to promote non-256-bit vectors
1249       if (!VT.is256BitVector())
1250         continue;
1251
1252       setOperationAction(ISD::AND,    VT, Promote);
1253       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1254       setOperationAction(ISD::OR,     VT, Promote);
1255       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1256       setOperationAction(ISD::XOR,    VT, Promote);
1257       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1258       setOperationAction(ISD::LOAD,   VT, Promote);
1259       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1260       setOperationAction(ISD::SELECT, VT, Promote);
1261       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1262     }
1263   }
1264
1265   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1266   // of this type with custom code.
1267   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1268            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1269     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1270                        Custom);
1271   }
1272
1273   // We want to custom lower some of our intrinsics.
1274   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1275   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1276
1277   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1278   // handle type legalization for these operations here.
1279   //
1280   // FIXME: We really should do custom legalization for addition and
1281   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1282   // than generic legalization for 64-bit multiplication-with-overflow, though.
1283   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1284     // Add/Sub/Mul with overflow operations are custom lowered.
1285     MVT VT = IntVTs[i];
1286     setOperationAction(ISD::SADDO, VT, Custom);
1287     setOperationAction(ISD::UADDO, VT, Custom);
1288     setOperationAction(ISD::SSUBO, VT, Custom);
1289     setOperationAction(ISD::USUBO, VT, Custom);
1290     setOperationAction(ISD::SMULO, VT, Custom);
1291     setOperationAction(ISD::UMULO, VT, Custom);
1292   }
1293
1294   // There are no 8-bit 3-address imul/mul instructions
1295   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1296   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1297
1298   if (!Subtarget->is64Bit()) {
1299     // These libcalls are not available in 32-bit.
1300     setLibcallName(RTLIB::SHL_I128, 0);
1301     setLibcallName(RTLIB::SRL_I128, 0);
1302     setLibcallName(RTLIB::SRA_I128, 0);
1303   }
1304
1305   // Combine sin / cos into one node or libcall if possible.
1306   if (Subtarget->hasSinCos()) {
1307     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1308     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1309     if (Subtarget->isTargetDarwin()) {
1310       // For MacOSX, we don't want to the normal expansion of a libcall to
1311       // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1312       // traffic.
1313       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1314       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1315     }
1316   }
1317
1318   // We have target-specific dag combine patterns for the following nodes:
1319   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1320   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1321   setTargetDAGCombine(ISD::VSELECT);
1322   setTargetDAGCombine(ISD::SELECT);
1323   setTargetDAGCombine(ISD::SHL);
1324   setTargetDAGCombine(ISD::SRA);
1325   setTargetDAGCombine(ISD::SRL);
1326   setTargetDAGCombine(ISD::OR);
1327   setTargetDAGCombine(ISD::AND);
1328   setTargetDAGCombine(ISD::ADD);
1329   setTargetDAGCombine(ISD::FADD);
1330   setTargetDAGCombine(ISD::FSUB);
1331   setTargetDAGCombine(ISD::FMA);
1332   setTargetDAGCombine(ISD::SUB);
1333   setTargetDAGCombine(ISD::LOAD);
1334   setTargetDAGCombine(ISD::STORE);
1335   setTargetDAGCombine(ISD::ZERO_EXTEND);
1336   setTargetDAGCombine(ISD::ANY_EXTEND);
1337   setTargetDAGCombine(ISD::SIGN_EXTEND);
1338   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1339   setTargetDAGCombine(ISD::TRUNCATE);
1340   setTargetDAGCombine(ISD::SINT_TO_FP);
1341   setTargetDAGCombine(ISD::SETCC);
1342   if (Subtarget->is64Bit())
1343     setTargetDAGCombine(ISD::MUL);
1344   setTargetDAGCombine(ISD::XOR);
1345
1346   computeRegisterProperties();
1347
1348   // On Darwin, -Os means optimize for size without hurting performance,
1349   // do not reduce the limit.
1350   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1351   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1352   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1353   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1354   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1355   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1356   setPrefLoopAlignment(4); // 2^4 bytes.
1357
1358   // Predictable cmov don't hurt on atom because it's in-order.
1359   PredictableSelectIsExpensive = !Subtarget->isAtom();
1360
1361   setPrefFunctionAlignment(4); // 2^4 bytes.
1362 }
1363
1364 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1365   if (!VT.isVector()) return MVT::i8;
1366   return VT.changeVectorElementTypeToInteger();
1367 }
1368
1369 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1370 /// the desired ByVal argument alignment.
1371 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1372   if (MaxAlign == 16)
1373     return;
1374   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1375     if (VTy->getBitWidth() == 128)
1376       MaxAlign = 16;
1377   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1378     unsigned EltAlign = 0;
1379     getMaxByValAlign(ATy->getElementType(), EltAlign);
1380     if (EltAlign > MaxAlign)
1381       MaxAlign = EltAlign;
1382   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1383     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1384       unsigned EltAlign = 0;
1385       getMaxByValAlign(STy->getElementType(i), EltAlign);
1386       if (EltAlign > MaxAlign)
1387         MaxAlign = EltAlign;
1388       if (MaxAlign == 16)
1389         break;
1390     }
1391   }
1392 }
1393
1394 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1395 /// function arguments in the caller parameter area. For X86, aggregates
1396 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1397 /// are at 4-byte boundaries.
1398 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1399   if (Subtarget->is64Bit()) {
1400     // Max of 8 and alignment of type.
1401     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1402     if (TyAlign > 8)
1403       return TyAlign;
1404     return 8;
1405   }
1406
1407   unsigned Align = 4;
1408   if (Subtarget->hasSSE1())
1409     getMaxByValAlign(Ty, Align);
1410   return Align;
1411 }
1412
1413 /// getOptimalMemOpType - Returns the target specific optimal type for load
1414 /// and store operations as a result of memset, memcpy, and memmove
1415 /// lowering. If DstAlign is zero that means it's safe to destination
1416 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1417 /// means there isn't a need to check it against alignment requirement,
1418 /// probably because the source does not need to be loaded. If 'IsMemset' is
1419 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1420 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1421 /// source is constant so it does not need to be loaded.
1422 /// It returns EVT::Other if the type should be determined using generic
1423 /// target-independent logic.
1424 EVT
1425 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1426                                        unsigned DstAlign, unsigned SrcAlign,
1427                                        bool IsMemset, bool ZeroMemset,
1428                                        bool MemcpyStrSrc,
1429                                        MachineFunction &MF) const {
1430   const Function *F = MF.getFunction();
1431   if ((!IsMemset || ZeroMemset) &&
1432       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1433                                        Attribute::NoImplicitFloat)) {
1434     if (Size >= 16 &&
1435         (Subtarget->isUnalignedMemAccessFast() ||
1436          ((DstAlign == 0 || DstAlign >= 16) &&
1437           (SrcAlign == 0 || SrcAlign >= 16)))) {
1438       if (Size >= 32) {
1439         if (Subtarget->hasInt256())
1440           return MVT::v8i32;
1441         if (Subtarget->hasFp256())
1442           return MVT::v8f32;
1443       }
1444       if (Subtarget->hasSSE2())
1445         return MVT::v4i32;
1446       if (Subtarget->hasSSE1())
1447         return MVT::v4f32;
1448     } else if (!MemcpyStrSrc && Size >= 8 &&
1449                !Subtarget->is64Bit() &&
1450                Subtarget->hasSSE2()) {
1451       // Do not use f64 to lower memcpy if source is string constant. It's
1452       // better to use i32 to avoid the loads.
1453       return MVT::f64;
1454     }
1455   }
1456   if (Subtarget->is64Bit() && Size >= 8)
1457     return MVT::i64;
1458   return MVT::i32;
1459 }
1460
1461 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1462   if (VT == MVT::f32)
1463     return X86ScalarSSEf32;
1464   else if (VT == MVT::f64)
1465     return X86ScalarSSEf64;
1466   return true;
1467 }
1468
1469 bool
1470 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
1471   if (Fast)
1472     *Fast = Subtarget->isUnalignedMemAccessFast();
1473   return true;
1474 }
1475
1476 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1477 /// current function.  The returned value is a member of the
1478 /// MachineJumpTableInfo::JTEntryKind enum.
1479 unsigned X86TargetLowering::getJumpTableEncoding() const {
1480   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1481   // symbol.
1482   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1483       Subtarget->isPICStyleGOT())
1484     return MachineJumpTableInfo::EK_Custom32;
1485
1486   // Otherwise, use the normal jump table encoding heuristics.
1487   return TargetLowering::getJumpTableEncoding();
1488 }
1489
1490 const MCExpr *
1491 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1492                                              const MachineBasicBlock *MBB,
1493                                              unsigned uid,MCContext &Ctx) const{
1494   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1495          Subtarget->isPICStyleGOT());
1496   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1497   // entries.
1498   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1499                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1500 }
1501
1502 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1503 /// jumptable.
1504 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1505                                                     SelectionDAG &DAG) const {
1506   if (!Subtarget->is64Bit())
1507     // This doesn't have DebugLoc associated with it, but is not really the
1508     // same as a Register.
1509     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1510   return Table;
1511 }
1512
1513 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1514 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1515 /// MCExpr.
1516 const MCExpr *X86TargetLowering::
1517 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1518                              MCContext &Ctx) const {
1519   // X86-64 uses RIP relative addressing based on the jump table label.
1520   if (Subtarget->isPICStyleRIPRel())
1521     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1522
1523   // Otherwise, the reference is relative to the PIC base.
1524   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1525 }
1526
1527 // FIXME: Why this routine is here? Move to RegInfo!
1528 std::pair<const TargetRegisterClass*, uint8_t>
1529 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1530   const TargetRegisterClass *RRC = 0;
1531   uint8_t Cost = 1;
1532   switch (VT.SimpleTy) {
1533   default:
1534     return TargetLowering::findRepresentativeClass(VT);
1535   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1536     RRC = Subtarget->is64Bit() ?
1537       (const TargetRegisterClass*)&X86::GR64RegClass :
1538       (const TargetRegisterClass*)&X86::GR32RegClass;
1539     break;
1540   case MVT::x86mmx:
1541     RRC = &X86::VR64RegClass;
1542     break;
1543   case MVT::f32: case MVT::f64:
1544   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1545   case MVT::v4f32: case MVT::v2f64:
1546   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1547   case MVT::v4f64:
1548     RRC = &X86::VR128RegClass;
1549     break;
1550   }
1551   return std::make_pair(RRC, Cost);
1552 }
1553
1554 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1555                                                unsigned &Offset) const {
1556   if (!Subtarget->isTargetLinux())
1557     return false;
1558
1559   if (Subtarget->is64Bit()) {
1560     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1561     Offset = 0x28;
1562     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1563       AddressSpace = 256;
1564     else
1565       AddressSpace = 257;
1566   } else {
1567     // %gs:0x14 on i386
1568     Offset = 0x14;
1569     AddressSpace = 256;
1570   }
1571   return true;
1572 }
1573
1574 //===----------------------------------------------------------------------===//
1575 //               Return Value Calling Convention Implementation
1576 //===----------------------------------------------------------------------===//
1577
1578 #include "X86GenCallingConv.inc"
1579
1580 bool
1581 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1582                                   MachineFunction &MF, bool isVarArg,
1583                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1584                         LLVMContext &Context) const {
1585   SmallVector<CCValAssign, 16> RVLocs;
1586   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1587                  RVLocs, Context);
1588   return CCInfo.CheckReturn(Outs, RetCC_X86);
1589 }
1590
1591 SDValue
1592 X86TargetLowering::LowerReturn(SDValue Chain,
1593                                CallingConv::ID CallConv, bool isVarArg,
1594                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1595                                const SmallVectorImpl<SDValue> &OutVals,
1596                                DebugLoc dl, SelectionDAG &DAG) const {
1597   MachineFunction &MF = DAG.getMachineFunction();
1598   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1599
1600   SmallVector<CCValAssign, 16> RVLocs;
1601   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1602                  RVLocs, *DAG.getContext());
1603   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1604
1605   SDValue Flag;
1606   SmallVector<SDValue, 6> RetOps;
1607   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1608   // Operand #1 = Bytes To Pop
1609   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1610                    MVT::i16));
1611
1612   // Copy the result values into the output registers.
1613   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1614     CCValAssign &VA = RVLocs[i];
1615     assert(VA.isRegLoc() && "Can only return in registers!");
1616     SDValue ValToCopy = OutVals[i];
1617     EVT ValVT = ValToCopy.getValueType();
1618
1619     // Promote values to the appropriate types
1620     if (VA.getLocInfo() == CCValAssign::SExt)
1621       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1622     else if (VA.getLocInfo() == CCValAssign::ZExt)
1623       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1624     else if (VA.getLocInfo() == CCValAssign::AExt)
1625       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1626     else if (VA.getLocInfo() == CCValAssign::BCvt)
1627       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1628
1629     // If this is x86-64, and we disabled SSE, we can't return FP values,
1630     // or SSE or MMX vectors.
1631     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1632          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1633           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1634       report_fatal_error("SSE register return with SSE disabled");
1635     }
1636     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1637     // llvm-gcc has never done it right and no one has noticed, so this
1638     // should be OK for now.
1639     if (ValVT == MVT::f64 &&
1640         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1641       report_fatal_error("SSE2 register return with SSE2 disabled");
1642
1643     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1644     // the RET instruction and handled by the FP Stackifier.
1645     if (VA.getLocReg() == X86::ST0 ||
1646         VA.getLocReg() == X86::ST1) {
1647       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1648       // change the value to the FP stack register class.
1649       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1650         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1651       RetOps.push_back(ValToCopy);
1652       // Don't emit a copytoreg.
1653       continue;
1654     }
1655
1656     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1657     // which is returned in RAX / RDX.
1658     if (Subtarget->is64Bit()) {
1659       if (ValVT == MVT::x86mmx) {
1660         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1661           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1662           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1663                                   ValToCopy);
1664           // If we don't have SSE2 available, convert to v4f32 so the generated
1665           // register is legal.
1666           if (!Subtarget->hasSSE2())
1667             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1668         }
1669       }
1670     }
1671
1672     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1673     Flag = Chain.getValue(1);
1674     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1675   }
1676
1677   // The x86-64 ABIs require that for returning structs by value we copy
1678   // the sret argument into %rax/%eax (depending on ABI) for the return.
1679   // Win32 requires us to put the sret argument to %eax as well.
1680   // We saved the argument into a virtual register in the entry block,
1681   // so now we copy the value out and into %rax/%eax.
1682   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1683       (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
1684     MachineFunction &MF = DAG.getMachineFunction();
1685     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1686     unsigned Reg = FuncInfo->getSRetReturnReg();
1687     assert(Reg &&
1688            "SRetReturnReg should have been set in LowerFormalArguments().");
1689     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1690
1691     unsigned RetValReg
1692         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1693           X86::RAX : X86::EAX;
1694     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1695     Flag = Chain.getValue(1);
1696
1697     // RAX/EAX now acts like a return value.
1698     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1699   }
1700
1701   RetOps[0] = Chain;  // Update chain.
1702
1703   // Add the flag if we have it.
1704   if (Flag.getNode())
1705     RetOps.push_back(Flag);
1706
1707   return DAG.getNode(X86ISD::RET_FLAG, dl,
1708                      MVT::Other, &RetOps[0], RetOps.size());
1709 }
1710
1711 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1712   if (N->getNumValues() != 1)
1713     return false;
1714   if (!N->hasNUsesOfValue(1, 0))
1715     return false;
1716
1717   SDValue TCChain = Chain;
1718   SDNode *Copy = *N->use_begin();
1719   if (Copy->getOpcode() == ISD::CopyToReg) {
1720     // If the copy has a glue operand, we conservatively assume it isn't safe to
1721     // perform a tail call.
1722     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1723       return false;
1724     TCChain = Copy->getOperand(0);
1725   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1726     return false;
1727
1728   bool HasRet = false;
1729   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1730        UI != UE; ++UI) {
1731     if (UI->getOpcode() != X86ISD::RET_FLAG)
1732       return false;
1733     HasRet = true;
1734   }
1735
1736   if (!HasRet)
1737     return false;
1738
1739   Chain = TCChain;
1740   return true;
1741 }
1742
1743 MVT
1744 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1745                                             ISD::NodeType ExtendKind) const {
1746   MVT ReturnMVT;
1747   // TODO: Is this also valid on 32-bit?
1748   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1749     ReturnMVT = MVT::i8;
1750   else
1751     ReturnMVT = MVT::i32;
1752
1753   MVT MinVT = getRegisterType(ReturnMVT);
1754   return VT.bitsLT(MinVT) ? MinVT : VT;
1755 }
1756
1757 /// LowerCallResult - Lower the result values of a call into the
1758 /// appropriate copies out of appropriate physical registers.
1759 ///
1760 SDValue
1761 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1762                                    CallingConv::ID CallConv, bool isVarArg,
1763                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1764                                    DebugLoc dl, SelectionDAG &DAG,
1765                                    SmallVectorImpl<SDValue> &InVals) const {
1766
1767   // Assign locations to each value returned by this call.
1768   SmallVector<CCValAssign, 16> RVLocs;
1769   bool Is64Bit = Subtarget->is64Bit();
1770   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1771                  getTargetMachine(), RVLocs, *DAG.getContext());
1772   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1773
1774   // Copy all of the result registers out of their specified physreg.
1775   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1776     CCValAssign &VA = RVLocs[i];
1777     EVT CopyVT = VA.getValVT();
1778
1779     // If this is x86-64, and we disabled SSE, we can't return FP values
1780     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1781         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1782       report_fatal_error("SSE register return with SSE disabled");
1783     }
1784
1785     SDValue Val;
1786
1787     // If this is a call to a function that returns an fp value on the floating
1788     // point stack, we must guarantee the value is popped from the stack, so
1789     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1790     // if the return value is not used. We use the FpPOP_RETVAL instruction
1791     // instead.
1792     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1793       // If we prefer to use the value in xmm registers, copy it out as f80 and
1794       // use a truncate to move it from fp stack reg to xmm reg.
1795       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1796       SDValue Ops[] = { Chain, InFlag };
1797       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1798                                          MVT::Other, MVT::Glue, Ops), 1);
1799       Val = Chain.getValue(0);
1800
1801       // Round the f80 to the right size, which also moves it to the appropriate
1802       // xmm register.
1803       if (CopyVT != VA.getValVT())
1804         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1805                           // This truncation won't change the value.
1806                           DAG.getIntPtrConstant(1));
1807     } else {
1808       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1809                                  CopyVT, InFlag).getValue(1);
1810       Val = Chain.getValue(0);
1811     }
1812     InFlag = Chain.getValue(2);
1813     InVals.push_back(Val);
1814   }
1815
1816   return Chain;
1817 }
1818
1819 //===----------------------------------------------------------------------===//
1820 //                C & StdCall & Fast Calling Convention implementation
1821 //===----------------------------------------------------------------------===//
1822 //  StdCall calling convention seems to be standard for many Windows' API
1823 //  routines and around. It differs from C calling convention just a little:
1824 //  callee should clean up the stack, not caller. Symbols should be also
1825 //  decorated in some fancy way :) It doesn't support any vector arguments.
1826 //  For info on fast calling convention see Fast Calling Convention (tail call)
1827 //  implementation LowerX86_32FastCCCallTo.
1828
1829 /// CallIsStructReturn - Determines whether a call uses struct return
1830 /// semantics.
1831 enum StructReturnType {
1832   NotStructReturn,
1833   RegStructReturn,
1834   StackStructReturn
1835 };
1836 static StructReturnType
1837 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1838   if (Outs.empty())
1839     return NotStructReturn;
1840
1841   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
1842   if (!Flags.isSRet())
1843     return NotStructReturn;
1844   if (Flags.isInReg())
1845     return RegStructReturn;
1846   return StackStructReturn;
1847 }
1848
1849 /// ArgsAreStructReturn - Determines whether a function uses struct
1850 /// return semantics.
1851 static StructReturnType
1852 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1853   if (Ins.empty())
1854     return NotStructReturn;
1855
1856   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
1857   if (!Flags.isSRet())
1858     return NotStructReturn;
1859   if (Flags.isInReg())
1860     return RegStructReturn;
1861   return StackStructReturn;
1862 }
1863
1864 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1865 /// by "Src" to address "Dst" with size and alignment information specified by
1866 /// the specific parameter attribute. The copy will be passed as a byval
1867 /// function parameter.
1868 static SDValue
1869 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1870                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1871                           DebugLoc dl) {
1872   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1873
1874   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1875                        /*isVolatile*/false, /*AlwaysInline=*/true,
1876                        MachinePointerInfo(), MachinePointerInfo());
1877 }
1878
1879 /// IsTailCallConvention - Return true if the calling convention is one that
1880 /// supports tail call optimization.
1881 static bool IsTailCallConvention(CallingConv::ID CC) {
1882   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
1883           CC == CallingConv::HiPE);
1884 }
1885
1886 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1887   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1888     return false;
1889
1890   CallSite CS(CI);
1891   CallingConv::ID CalleeCC = CS.getCallingConv();
1892   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1893     return false;
1894
1895   return true;
1896 }
1897
1898 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1899 /// a tailcall target by changing its ABI.
1900 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1901                                    bool GuaranteedTailCallOpt) {
1902   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1903 }
1904
1905 SDValue
1906 X86TargetLowering::LowerMemArgument(SDValue Chain,
1907                                     CallingConv::ID CallConv,
1908                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1909                                     DebugLoc dl, SelectionDAG &DAG,
1910                                     const CCValAssign &VA,
1911                                     MachineFrameInfo *MFI,
1912                                     unsigned i) const {
1913   // Create the nodes corresponding to a load from this parameter slot.
1914   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1915   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1916                               getTargetMachine().Options.GuaranteedTailCallOpt);
1917   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1918   EVT ValVT;
1919
1920   // If value is passed by pointer we have address passed instead of the value
1921   // itself.
1922   if (VA.getLocInfo() == CCValAssign::Indirect)
1923     ValVT = VA.getLocVT();
1924   else
1925     ValVT = VA.getValVT();
1926
1927   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1928   // changed with more analysis.
1929   // In case of tail call optimization mark all arguments mutable. Since they
1930   // could be overwritten by lowering of arguments in case of a tail call.
1931   if (Flags.isByVal()) {
1932     unsigned Bytes = Flags.getByValSize();
1933     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1934     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1935     return DAG.getFrameIndex(FI, getPointerTy());
1936   } else {
1937     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1938                                     VA.getLocMemOffset(), isImmutable);
1939     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1940     return DAG.getLoad(ValVT, dl, Chain, FIN,
1941                        MachinePointerInfo::getFixedStack(FI),
1942                        false, false, false, 0);
1943   }
1944 }
1945
1946 SDValue
1947 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1948                                         CallingConv::ID CallConv,
1949                                         bool isVarArg,
1950                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1951                                         DebugLoc dl,
1952                                         SelectionDAG &DAG,
1953                                         SmallVectorImpl<SDValue> &InVals)
1954                                           const {
1955   MachineFunction &MF = DAG.getMachineFunction();
1956   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1957
1958   const Function* Fn = MF.getFunction();
1959   if (Fn->hasExternalLinkage() &&
1960       Subtarget->isTargetCygMing() &&
1961       Fn->getName() == "main")
1962     FuncInfo->setForceFramePointer(true);
1963
1964   MachineFrameInfo *MFI = MF.getFrameInfo();
1965   bool Is64Bit = Subtarget->is64Bit();
1966   bool IsWindows = Subtarget->isTargetWindows();
1967   bool IsWin64 = Subtarget->isTargetWin64();
1968
1969   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1970          "Var args not supported with calling convention fastcc, ghc or hipe");
1971
1972   // Assign locations to all of the incoming arguments.
1973   SmallVector<CCValAssign, 16> ArgLocs;
1974   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1975                  ArgLocs, *DAG.getContext());
1976
1977   // Allocate shadow area for Win64
1978   if (IsWin64) {
1979     CCInfo.AllocateStack(32, 8);
1980   }
1981
1982   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1983
1984   unsigned LastVal = ~0U;
1985   SDValue ArgValue;
1986   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1987     CCValAssign &VA = ArgLocs[i];
1988     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1989     // places.
1990     assert(VA.getValNo() != LastVal &&
1991            "Don't support value assigned to multiple locs yet");
1992     (void)LastVal;
1993     LastVal = VA.getValNo();
1994
1995     if (VA.isRegLoc()) {
1996       EVT RegVT = VA.getLocVT();
1997       const TargetRegisterClass *RC;
1998       if (RegVT == MVT::i32)
1999         RC = &X86::GR32RegClass;
2000       else if (Is64Bit && RegVT == MVT::i64)
2001         RC = &X86::GR64RegClass;
2002       else if (RegVT == MVT::f32)
2003         RC = &X86::FR32RegClass;
2004       else if (RegVT == MVT::f64)
2005         RC = &X86::FR64RegClass;
2006       else if (RegVT.is256BitVector())
2007         RC = &X86::VR256RegClass;
2008       else if (RegVT.is128BitVector())
2009         RC = &X86::VR128RegClass;
2010       else if (RegVT == MVT::x86mmx)
2011         RC = &X86::VR64RegClass;
2012       else
2013         llvm_unreachable("Unknown argument type!");
2014
2015       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2016       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2017
2018       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2019       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2020       // right size.
2021       if (VA.getLocInfo() == CCValAssign::SExt)
2022         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2023                                DAG.getValueType(VA.getValVT()));
2024       else if (VA.getLocInfo() == CCValAssign::ZExt)
2025         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2026                                DAG.getValueType(VA.getValVT()));
2027       else if (VA.getLocInfo() == CCValAssign::BCvt)
2028         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2029
2030       if (VA.isExtInLoc()) {
2031         // Handle MMX values passed in XMM regs.
2032         if (RegVT.isVector())
2033           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2034         else
2035           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2036       }
2037     } else {
2038       assert(VA.isMemLoc());
2039       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2040     }
2041
2042     // If value is passed via pointer - do a load.
2043     if (VA.getLocInfo() == CCValAssign::Indirect)
2044       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2045                              MachinePointerInfo(), false, false, false, 0);
2046
2047     InVals.push_back(ArgValue);
2048   }
2049
2050   // The x86-64 ABIs require that for returning structs by value we copy
2051   // the sret argument into %rax/%eax (depending on ABI) for the return.
2052   // Win32 requires us to put the sret argument to %eax as well.
2053   // Save the argument into a virtual register so that we can access it
2054   // from the return points.
2055   if (MF.getFunction()->hasStructRetAttr() &&
2056       (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
2057     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2058     unsigned Reg = FuncInfo->getSRetReturnReg();
2059     if (!Reg) {
2060       MVT PtrTy = getPointerTy();
2061       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2062       FuncInfo->setSRetReturnReg(Reg);
2063     }
2064     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2065     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2066   }
2067
2068   unsigned StackSize = CCInfo.getNextStackOffset();
2069   // Align stack specially for tail calls.
2070   if (FuncIsMadeTailCallSafe(CallConv,
2071                              MF.getTarget().Options.GuaranteedTailCallOpt))
2072     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2073
2074   // If the function takes variable number of arguments, make a frame index for
2075   // the start of the first vararg value... for expansion of llvm.va_start.
2076   if (isVarArg) {
2077     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2078                     CallConv != CallingConv::X86_ThisCall)) {
2079       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2080     }
2081     if (Is64Bit) {
2082       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2083
2084       // FIXME: We should really autogenerate these arrays
2085       static const uint16_t GPR64ArgRegsWin64[] = {
2086         X86::RCX, X86::RDX, X86::R8,  X86::R9
2087       };
2088       static const uint16_t GPR64ArgRegs64Bit[] = {
2089         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2090       };
2091       static const uint16_t XMMArgRegs64Bit[] = {
2092         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2093         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2094       };
2095       const uint16_t *GPR64ArgRegs;
2096       unsigned NumXMMRegs = 0;
2097
2098       if (IsWin64) {
2099         // The XMM registers which might contain var arg parameters are shadowed
2100         // in their paired GPR.  So we only need to save the GPR to their home
2101         // slots.
2102         TotalNumIntRegs = 4;
2103         GPR64ArgRegs = GPR64ArgRegsWin64;
2104       } else {
2105         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2106         GPR64ArgRegs = GPR64ArgRegs64Bit;
2107
2108         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2109                                                 TotalNumXMMRegs);
2110       }
2111       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2112                                                        TotalNumIntRegs);
2113
2114       bool NoImplicitFloatOps = Fn->getAttributes().
2115         hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2116       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2117              "SSE register cannot be used when SSE is disabled!");
2118       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2119                NoImplicitFloatOps) &&
2120              "SSE register cannot be used when SSE is disabled!");
2121       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2122           !Subtarget->hasSSE1())
2123         // Kernel mode asks for SSE to be disabled, so don't push them
2124         // on the stack.
2125         TotalNumXMMRegs = 0;
2126
2127       if (IsWin64) {
2128         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2129         // Get to the caller-allocated home save location.  Add 8 to account
2130         // for the return address.
2131         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2132         FuncInfo->setRegSaveFrameIndex(
2133           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2134         // Fixup to set vararg frame on shadow area (4 x i64).
2135         if (NumIntRegs < 4)
2136           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2137       } else {
2138         // For X86-64, if there are vararg parameters that are passed via
2139         // registers, then we must store them to their spots on the stack so
2140         // they may be loaded by deferencing the result of va_next.
2141         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2142         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2143         FuncInfo->setRegSaveFrameIndex(
2144           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2145                                false));
2146       }
2147
2148       // Store the integer parameter registers.
2149       SmallVector<SDValue, 8> MemOps;
2150       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2151                                         getPointerTy());
2152       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2153       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2154         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2155                                   DAG.getIntPtrConstant(Offset));
2156         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2157                                      &X86::GR64RegClass);
2158         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2159         SDValue Store =
2160           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2161                        MachinePointerInfo::getFixedStack(
2162                          FuncInfo->getRegSaveFrameIndex(), Offset),
2163                        false, false, 0);
2164         MemOps.push_back(Store);
2165         Offset += 8;
2166       }
2167
2168       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2169         // Now store the XMM (fp + vector) parameter registers.
2170         SmallVector<SDValue, 11> SaveXMMOps;
2171         SaveXMMOps.push_back(Chain);
2172
2173         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2174         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2175         SaveXMMOps.push_back(ALVal);
2176
2177         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2178                                FuncInfo->getRegSaveFrameIndex()));
2179         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2180                                FuncInfo->getVarArgsFPOffset()));
2181
2182         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2183           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2184                                        &X86::VR128RegClass);
2185           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2186           SaveXMMOps.push_back(Val);
2187         }
2188         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2189                                      MVT::Other,
2190                                      &SaveXMMOps[0], SaveXMMOps.size()));
2191       }
2192
2193       if (!MemOps.empty())
2194         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2195                             &MemOps[0], MemOps.size());
2196     }
2197   }
2198
2199   // Some CCs need callee pop.
2200   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2201                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2202     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2203   } else {
2204     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2205     // If this is an sret function, the return should pop the hidden pointer.
2206     if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2207         argsAreStructReturn(Ins) == StackStructReturn)
2208       FuncInfo->setBytesToPopOnReturn(4);
2209   }
2210
2211   if (!Is64Bit) {
2212     // RegSaveFrameIndex is X86-64 only.
2213     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2214     if (CallConv == CallingConv::X86_FastCall ||
2215         CallConv == CallingConv::X86_ThisCall)
2216       // fastcc functions can't have varargs.
2217       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2218   }
2219
2220   FuncInfo->setArgumentStackSize(StackSize);
2221
2222   return Chain;
2223 }
2224
2225 SDValue
2226 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2227                                     SDValue StackPtr, SDValue Arg,
2228                                     DebugLoc dl, SelectionDAG &DAG,
2229                                     const CCValAssign &VA,
2230                                     ISD::ArgFlagsTy Flags) const {
2231   unsigned LocMemOffset = VA.getLocMemOffset();
2232   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2233   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2234   if (Flags.isByVal())
2235     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2236
2237   return DAG.getStore(Chain, dl, Arg, PtrOff,
2238                       MachinePointerInfo::getStack(LocMemOffset),
2239                       false, false, 0);
2240 }
2241
2242 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2243 /// optimization is performed and it is required.
2244 SDValue
2245 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2246                                            SDValue &OutRetAddr, SDValue Chain,
2247                                            bool IsTailCall, bool Is64Bit,
2248                                            int FPDiff, DebugLoc dl) const {
2249   // Adjust the Return address stack slot.
2250   EVT VT = getPointerTy();
2251   OutRetAddr = getReturnAddressFrameIndex(DAG);
2252
2253   // Load the "old" Return address.
2254   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2255                            false, false, false, 0);
2256   return SDValue(OutRetAddr.getNode(), 1);
2257 }
2258
2259 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2260 /// optimization is performed and it is required (FPDiff!=0).
2261 static SDValue
2262 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2263                          SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2264                          unsigned SlotSize, int FPDiff, DebugLoc dl) {
2265   // Store the return address to the appropriate stack slot.
2266   if (!FPDiff) return Chain;
2267   // Calculate the new stack slot for the return address.
2268   int NewReturnAddrFI =
2269     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2270   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2271   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2272                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2273                        false, false, 0);
2274   return Chain;
2275 }
2276
2277 SDValue
2278 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2279                              SmallVectorImpl<SDValue> &InVals) const {
2280   SelectionDAG &DAG                     = CLI.DAG;
2281   DebugLoc &dl                          = CLI.DL;
2282   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2283   SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
2284   SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
2285   SDValue Chain                         = CLI.Chain;
2286   SDValue Callee                        = CLI.Callee;
2287   CallingConv::ID CallConv              = CLI.CallConv;
2288   bool &isTailCall                      = CLI.IsTailCall;
2289   bool isVarArg                         = CLI.IsVarArg;
2290
2291   MachineFunction &MF = DAG.getMachineFunction();
2292   bool Is64Bit        = Subtarget->is64Bit();
2293   bool IsWin64        = Subtarget->isTargetWin64();
2294   bool IsWindows      = Subtarget->isTargetWindows();
2295   StructReturnType SR = callIsStructReturn(Outs);
2296   bool IsSibcall      = false;
2297
2298   if (MF.getTarget().Options.DisableTailCalls)
2299     isTailCall = false;
2300
2301   if (isTailCall) {
2302     // Check if it's really possible to do a tail call.
2303     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2304                     isVarArg, SR != NotStructReturn,
2305                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2306                     Outs, OutVals, Ins, DAG);
2307
2308     // Sibcalls are automatically detected tailcalls which do not require
2309     // ABI changes.
2310     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2311       IsSibcall = true;
2312
2313     if (isTailCall)
2314       ++NumTailCalls;
2315   }
2316
2317   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2318          "Var args not supported with calling convention fastcc, ghc or hipe");
2319
2320   // Analyze operands of the call, assigning locations to each operand.
2321   SmallVector<CCValAssign, 16> ArgLocs;
2322   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2323                  ArgLocs, *DAG.getContext());
2324
2325   // Allocate shadow area for Win64
2326   if (IsWin64) {
2327     CCInfo.AllocateStack(32, 8);
2328   }
2329
2330   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2331
2332   // Get a count of how many bytes are to be pushed on the stack.
2333   unsigned NumBytes = CCInfo.getNextStackOffset();
2334   if (IsSibcall)
2335     // This is a sibcall. The memory operands are available in caller's
2336     // own caller's stack.
2337     NumBytes = 0;
2338   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2339            IsTailCallConvention(CallConv))
2340     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2341
2342   int FPDiff = 0;
2343   if (isTailCall && !IsSibcall) {
2344     // Lower arguments at fp - stackoffset + fpdiff.
2345     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2346     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2347
2348     FPDiff = NumBytesCallerPushed - NumBytes;
2349
2350     // Set the delta of movement of the returnaddr stackslot.
2351     // But only set if delta is greater than previous delta.
2352     if (FPDiff < X86Info->getTCReturnAddrDelta())
2353       X86Info->setTCReturnAddrDelta(FPDiff);
2354   }
2355
2356   if (!IsSibcall)
2357     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2358
2359   SDValue RetAddrFrIdx;
2360   // Load return address for tail calls.
2361   if (isTailCall && FPDiff)
2362     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2363                                     Is64Bit, FPDiff, dl);
2364
2365   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2366   SmallVector<SDValue, 8> MemOpChains;
2367   SDValue StackPtr;
2368
2369   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2370   // of tail call optimization arguments are handle later.
2371   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2372     CCValAssign &VA = ArgLocs[i];
2373     EVT RegVT = VA.getLocVT();
2374     SDValue Arg = OutVals[i];
2375     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2376     bool isByVal = Flags.isByVal();
2377
2378     // Promote the value if needed.
2379     switch (VA.getLocInfo()) {
2380     default: llvm_unreachable("Unknown loc info!");
2381     case CCValAssign::Full: break;
2382     case CCValAssign::SExt:
2383       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2384       break;
2385     case CCValAssign::ZExt:
2386       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2387       break;
2388     case CCValAssign::AExt:
2389       if (RegVT.is128BitVector()) {
2390         // Special case: passing MMX values in XMM registers.
2391         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2392         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2393         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2394       } else
2395         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2396       break;
2397     case CCValAssign::BCvt:
2398       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2399       break;
2400     case CCValAssign::Indirect: {
2401       // Store the argument.
2402       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2403       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2404       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2405                            MachinePointerInfo::getFixedStack(FI),
2406                            false, false, 0);
2407       Arg = SpillSlot;
2408       break;
2409     }
2410     }
2411
2412     if (VA.isRegLoc()) {
2413       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2414       if (isVarArg && IsWin64) {
2415         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2416         // shadow reg if callee is a varargs function.
2417         unsigned ShadowReg = 0;
2418         switch (VA.getLocReg()) {
2419         case X86::XMM0: ShadowReg = X86::RCX; break;
2420         case X86::XMM1: ShadowReg = X86::RDX; break;
2421         case X86::XMM2: ShadowReg = X86::R8; break;
2422         case X86::XMM3: ShadowReg = X86::R9; break;
2423         }
2424         if (ShadowReg)
2425           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2426       }
2427     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2428       assert(VA.isMemLoc());
2429       if (StackPtr.getNode() == 0)
2430         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2431                                       getPointerTy());
2432       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2433                                              dl, DAG, VA, Flags));
2434     }
2435   }
2436
2437   if (!MemOpChains.empty())
2438     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2439                         &MemOpChains[0], MemOpChains.size());
2440
2441   if (Subtarget->isPICStyleGOT()) {
2442     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2443     // GOT pointer.
2444     if (!isTailCall) {
2445       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2446                DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy())));
2447     } else {
2448       // If we are tail calling and generating PIC/GOT style code load the
2449       // address of the callee into ECX. The value in ecx is used as target of
2450       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2451       // for tail calls on PIC/GOT architectures. Normally we would just put the
2452       // address of GOT into ebx and then call target@PLT. But for tail calls
2453       // ebx would be restored (since ebx is callee saved) before jumping to the
2454       // target@PLT.
2455
2456       // Note: The actual moving to ECX is done further down.
2457       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2458       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2459           !G->getGlobal()->hasProtectedVisibility())
2460         Callee = LowerGlobalAddress(Callee, DAG);
2461       else if (isa<ExternalSymbolSDNode>(Callee))
2462         Callee = LowerExternalSymbol(Callee, DAG);
2463     }
2464   }
2465
2466   if (Is64Bit && isVarArg && !IsWin64) {
2467     // From AMD64 ABI document:
2468     // For calls that may call functions that use varargs or stdargs
2469     // (prototype-less calls or calls to functions containing ellipsis (...) in
2470     // the declaration) %al is used as hidden argument to specify the number
2471     // of SSE registers used. The contents of %al do not need to match exactly
2472     // the number of registers, but must be an ubound on the number of SSE
2473     // registers used and is in the range 0 - 8 inclusive.
2474
2475     // Count the number of XMM registers allocated.
2476     static const uint16_t XMMArgRegs[] = {
2477       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2478       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2479     };
2480     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2481     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2482            && "SSE registers cannot be used when SSE is disabled");
2483
2484     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2485                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2486   }
2487
2488   // For tail calls lower the arguments to the 'real' stack slot.
2489   if (isTailCall) {
2490     // Force all the incoming stack arguments to be loaded from the stack
2491     // before any new outgoing arguments are stored to the stack, because the
2492     // outgoing stack slots may alias the incoming argument stack slots, and
2493     // the alias isn't otherwise explicit. This is slightly more conservative
2494     // than necessary, because it means that each store effectively depends
2495     // on every argument instead of just those arguments it would clobber.
2496     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2497
2498     SmallVector<SDValue, 8> MemOpChains2;
2499     SDValue FIN;
2500     int FI = 0;
2501     if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2502       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2503         CCValAssign &VA = ArgLocs[i];
2504         if (VA.isRegLoc())
2505           continue;
2506         assert(VA.isMemLoc());
2507         SDValue Arg = OutVals[i];
2508         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2509         // Create frame index.
2510         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2511         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2512         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2513         FIN = DAG.getFrameIndex(FI, getPointerTy());
2514
2515         if (Flags.isByVal()) {
2516           // Copy relative to framepointer.
2517           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2518           if (StackPtr.getNode() == 0)
2519             StackPtr = DAG.getCopyFromReg(Chain, dl,
2520                                           RegInfo->getStackRegister(),
2521                                           getPointerTy());
2522           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2523
2524           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2525                                                            ArgChain,
2526                                                            Flags, DAG, dl));
2527         } else {
2528           // Store relative to framepointer.
2529           MemOpChains2.push_back(
2530             DAG.getStore(ArgChain, dl, Arg, FIN,
2531                          MachinePointerInfo::getFixedStack(FI),
2532                          false, false, 0));
2533         }
2534       }
2535     }
2536
2537     if (!MemOpChains2.empty())
2538       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2539                           &MemOpChains2[0], MemOpChains2.size());
2540
2541     // Store the return address to the appropriate stack slot.
2542     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2543                                      getPointerTy(), RegInfo->getSlotSize(),
2544                                      FPDiff, dl);
2545   }
2546
2547   // Build a sequence of copy-to-reg nodes chained together with token chain
2548   // and flag operands which copy the outgoing args into registers.
2549   SDValue InFlag;
2550   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2551     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2552                              RegsToPass[i].second, InFlag);
2553     InFlag = Chain.getValue(1);
2554   }
2555
2556   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2557     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2558     // In the 64-bit large code model, we have to make all calls
2559     // through a register, since the call instruction's 32-bit
2560     // pc-relative offset may not be large enough to hold the whole
2561     // address.
2562   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2563     // If the callee is a GlobalAddress node (quite common, every direct call
2564     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2565     // it.
2566
2567     // We should use extra load for direct calls to dllimported functions in
2568     // non-JIT mode.
2569     const GlobalValue *GV = G->getGlobal();
2570     if (!GV->hasDLLImportLinkage()) {
2571       unsigned char OpFlags = 0;
2572       bool ExtraLoad = false;
2573       unsigned WrapperKind = ISD::DELETED_NODE;
2574
2575       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2576       // external symbols most go through the PLT in PIC mode.  If the symbol
2577       // has hidden or protected visibility, or if it is static or local, then
2578       // we don't need to use the PLT - we can directly call it.
2579       if (Subtarget->isTargetELF() &&
2580           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2581           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2582         OpFlags = X86II::MO_PLT;
2583       } else if (Subtarget->isPICStyleStubAny() &&
2584                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2585                  (!Subtarget->getTargetTriple().isMacOSX() ||
2586                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2587         // PC-relative references to external symbols should go through $stub,
2588         // unless we're building with the leopard linker or later, which
2589         // automatically synthesizes these stubs.
2590         OpFlags = X86II::MO_DARWIN_STUB;
2591       } else if (Subtarget->isPICStyleRIPRel() &&
2592                  isa<Function>(GV) &&
2593                  cast<Function>(GV)->getAttributes().
2594                    hasAttribute(AttributeSet::FunctionIndex,
2595                                 Attribute::NonLazyBind)) {
2596         // If the function is marked as non-lazy, generate an indirect call
2597         // which loads from the GOT directly. This avoids runtime overhead
2598         // at the cost of eager binding (and one extra byte of encoding).
2599         OpFlags = X86II::MO_GOTPCREL;
2600         WrapperKind = X86ISD::WrapperRIP;
2601         ExtraLoad = true;
2602       }
2603
2604       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2605                                           G->getOffset(), OpFlags);
2606
2607       // Add a wrapper if needed.
2608       if (WrapperKind != ISD::DELETED_NODE)
2609         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2610       // Add extra indirection if needed.
2611       if (ExtraLoad)
2612         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2613                              MachinePointerInfo::getGOT(),
2614                              false, false, false, 0);
2615     }
2616   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2617     unsigned char OpFlags = 0;
2618
2619     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2620     // external symbols should go through the PLT.
2621     if (Subtarget->isTargetELF() &&
2622         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2623       OpFlags = X86II::MO_PLT;
2624     } else if (Subtarget->isPICStyleStubAny() &&
2625                (!Subtarget->getTargetTriple().isMacOSX() ||
2626                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2627       // PC-relative references to external symbols should go through $stub,
2628       // unless we're building with the leopard linker or later, which
2629       // automatically synthesizes these stubs.
2630       OpFlags = X86II::MO_DARWIN_STUB;
2631     }
2632
2633     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2634                                          OpFlags);
2635   }
2636
2637   // Returns a chain & a flag for retval copy to use.
2638   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2639   SmallVector<SDValue, 8> Ops;
2640
2641   if (!IsSibcall && isTailCall) {
2642     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2643                            DAG.getIntPtrConstant(0, true), InFlag);
2644     InFlag = Chain.getValue(1);
2645   }
2646
2647   Ops.push_back(Chain);
2648   Ops.push_back(Callee);
2649
2650   if (isTailCall)
2651     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2652
2653   // Add argument registers to the end of the list so that they are known live
2654   // into the call.
2655   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2656     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2657                                   RegsToPass[i].second.getValueType()));
2658
2659   // Add a register mask operand representing the call-preserved registers.
2660   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2661   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2662   assert(Mask && "Missing call preserved mask for calling convention");
2663   Ops.push_back(DAG.getRegisterMask(Mask));
2664
2665   if (InFlag.getNode())
2666     Ops.push_back(InFlag);
2667
2668   if (isTailCall) {
2669     // We used to do:
2670     //// If this is the first return lowered for this function, add the regs
2671     //// to the liveout set for the function.
2672     // This isn't right, although it's probably harmless on x86; liveouts
2673     // should be computed from returns not tail calls.  Consider a void
2674     // function making a tail call to a function returning int.
2675     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
2676   }
2677
2678   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2679   InFlag = Chain.getValue(1);
2680
2681   // Create the CALLSEQ_END node.
2682   unsigned NumBytesForCalleeToPush;
2683   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2684                        getTargetMachine().Options.GuaranteedTailCallOpt))
2685     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2686   else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2687            SR == StackStructReturn)
2688     // If this is a call to a struct-return function, the callee
2689     // pops the hidden struct pointer, so we have to push it back.
2690     // This is common for Darwin/X86, Linux & Mingw32 targets.
2691     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2692     NumBytesForCalleeToPush = 4;
2693   else
2694     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2695
2696   // Returns a flag for retval copy to use.
2697   if (!IsSibcall) {
2698     Chain = DAG.getCALLSEQ_END(Chain,
2699                                DAG.getIntPtrConstant(NumBytes, true),
2700                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2701                                                      true),
2702                                InFlag);
2703     InFlag = Chain.getValue(1);
2704   }
2705
2706   // Handle result values, copying them out of physregs into vregs that we
2707   // return.
2708   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2709                          Ins, dl, DAG, InVals);
2710 }
2711
2712 //===----------------------------------------------------------------------===//
2713 //                Fast Calling Convention (tail call) implementation
2714 //===----------------------------------------------------------------------===//
2715
2716 //  Like std call, callee cleans arguments, convention except that ECX is
2717 //  reserved for storing the tail called function address. Only 2 registers are
2718 //  free for argument passing (inreg). Tail call optimization is performed
2719 //  provided:
2720 //                * tailcallopt is enabled
2721 //                * caller/callee are fastcc
2722 //  On X86_64 architecture with GOT-style position independent code only local
2723 //  (within module) calls are supported at the moment.
2724 //  To keep the stack aligned according to platform abi the function
2725 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2726 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2727 //  If a tail called function callee has more arguments than the caller the
2728 //  caller needs to make sure that there is room to move the RETADDR to. This is
2729 //  achieved by reserving an area the size of the argument delta right after the
2730 //  original REtADDR, but before the saved framepointer or the spilled registers
2731 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2732 //  stack layout:
2733 //    arg1
2734 //    arg2
2735 //    RETADDR
2736 //    [ new RETADDR
2737 //      move area ]
2738 //    (possible EBP)
2739 //    ESI
2740 //    EDI
2741 //    local1 ..
2742
2743 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2744 /// for a 16 byte align requirement.
2745 unsigned
2746 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2747                                                SelectionDAG& DAG) const {
2748   MachineFunction &MF = DAG.getMachineFunction();
2749   const TargetMachine &TM = MF.getTarget();
2750   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2751   unsigned StackAlignment = TFI.getStackAlignment();
2752   uint64_t AlignMask = StackAlignment - 1;
2753   int64_t Offset = StackSize;
2754   unsigned SlotSize = RegInfo->getSlotSize();
2755   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2756     // Number smaller than 12 so just add the difference.
2757     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2758   } else {
2759     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2760     Offset = ((~AlignMask) & Offset) + StackAlignment +
2761       (StackAlignment-SlotSize);
2762   }
2763   return Offset;
2764 }
2765
2766 /// MatchingStackOffset - Return true if the given stack call argument is
2767 /// already available in the same position (relatively) of the caller's
2768 /// incoming argument stack.
2769 static
2770 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2771                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2772                          const X86InstrInfo *TII) {
2773   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2774   int FI = INT_MAX;
2775   if (Arg.getOpcode() == ISD::CopyFromReg) {
2776     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2777     if (!TargetRegisterInfo::isVirtualRegister(VR))
2778       return false;
2779     MachineInstr *Def = MRI->getVRegDef(VR);
2780     if (!Def)
2781       return false;
2782     if (!Flags.isByVal()) {
2783       if (!TII->isLoadFromStackSlot(Def, FI))
2784         return false;
2785     } else {
2786       unsigned Opcode = Def->getOpcode();
2787       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2788           Def->getOperand(1).isFI()) {
2789         FI = Def->getOperand(1).getIndex();
2790         Bytes = Flags.getByValSize();
2791       } else
2792         return false;
2793     }
2794   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2795     if (Flags.isByVal())
2796       // ByVal argument is passed in as a pointer but it's now being
2797       // dereferenced. e.g.
2798       // define @foo(%struct.X* %A) {
2799       //   tail call @bar(%struct.X* byval %A)
2800       // }
2801       return false;
2802     SDValue Ptr = Ld->getBasePtr();
2803     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2804     if (!FINode)
2805       return false;
2806     FI = FINode->getIndex();
2807   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2808     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2809     FI = FINode->getIndex();
2810     Bytes = Flags.getByValSize();
2811   } else
2812     return false;
2813
2814   assert(FI != INT_MAX);
2815   if (!MFI->isFixedObjectIndex(FI))
2816     return false;
2817   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2818 }
2819
2820 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2821 /// for tail call optimization. Targets which want to do tail call
2822 /// optimization should implement this function.
2823 bool
2824 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2825                                                      CallingConv::ID CalleeCC,
2826                                                      bool isVarArg,
2827                                                      bool isCalleeStructRet,
2828                                                      bool isCallerStructRet,
2829                                                      Type *RetTy,
2830                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2831                                     const SmallVectorImpl<SDValue> &OutVals,
2832                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2833                                                      SelectionDAG &DAG) const {
2834   if (!IsTailCallConvention(CalleeCC) &&
2835       CalleeCC != CallingConv::C)
2836     return false;
2837
2838   // If -tailcallopt is specified, make fastcc functions tail-callable.
2839   const MachineFunction &MF = DAG.getMachineFunction();
2840   const Function *CallerF = DAG.getMachineFunction().getFunction();
2841
2842   // If the function return type is x86_fp80 and the callee return type is not,
2843   // then the FP_EXTEND of the call result is not a nop. It's not safe to
2844   // perform a tailcall optimization here.
2845   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
2846     return false;
2847
2848   CallingConv::ID CallerCC = CallerF->getCallingConv();
2849   bool CCMatch = CallerCC == CalleeCC;
2850
2851   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2852     if (IsTailCallConvention(CalleeCC) && CCMatch)
2853       return true;
2854     return false;
2855   }
2856
2857   // Look for obvious safe cases to perform tail call optimization that do not
2858   // require ABI changes. This is what gcc calls sibcall.
2859
2860   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2861   // emit a special epilogue.
2862   if (RegInfo->needsStackRealignment(MF))
2863     return false;
2864
2865   // Also avoid sibcall optimization if either caller or callee uses struct
2866   // return semantics.
2867   if (isCalleeStructRet || isCallerStructRet)
2868     return false;
2869
2870   // An stdcall caller is expected to clean up its arguments; the callee
2871   // isn't going to do that.
2872   if (!CCMatch && CallerCC == CallingConv::X86_StdCall)
2873     return false;
2874
2875   // Do not sibcall optimize vararg calls unless all arguments are passed via
2876   // registers.
2877   if (isVarArg && !Outs.empty()) {
2878
2879     // Optimizing for varargs on Win64 is unlikely to be safe without
2880     // additional testing.
2881     if (Subtarget->isTargetWin64())
2882       return false;
2883
2884     SmallVector<CCValAssign, 16> ArgLocs;
2885     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2886                    getTargetMachine(), ArgLocs, *DAG.getContext());
2887
2888     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2889     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2890       if (!ArgLocs[i].isRegLoc())
2891         return false;
2892   }
2893
2894   // If the call result is in ST0 / ST1, it needs to be popped off the x87
2895   // stack.  Therefore, if it's not used by the call it is not safe to optimize
2896   // this into a sibcall.
2897   bool Unused = false;
2898   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2899     if (!Ins[i].Used) {
2900       Unused = true;
2901       break;
2902     }
2903   }
2904   if (Unused) {
2905     SmallVector<CCValAssign, 16> RVLocs;
2906     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2907                    getTargetMachine(), RVLocs, *DAG.getContext());
2908     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2909     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2910       CCValAssign &VA = RVLocs[i];
2911       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2912         return false;
2913     }
2914   }
2915
2916   // If the calling conventions do not match, then we'd better make sure the
2917   // results are returned in the same way as what the caller expects.
2918   if (!CCMatch) {
2919     SmallVector<CCValAssign, 16> RVLocs1;
2920     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2921                     getTargetMachine(), RVLocs1, *DAG.getContext());
2922     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2923
2924     SmallVector<CCValAssign, 16> RVLocs2;
2925     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2926                     getTargetMachine(), RVLocs2, *DAG.getContext());
2927     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2928
2929     if (RVLocs1.size() != RVLocs2.size())
2930       return false;
2931     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2932       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2933         return false;
2934       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2935         return false;
2936       if (RVLocs1[i].isRegLoc()) {
2937         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2938           return false;
2939       } else {
2940         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2941           return false;
2942       }
2943     }
2944   }
2945
2946   // If the callee takes no arguments then go on to check the results of the
2947   // call.
2948   if (!Outs.empty()) {
2949     // Check if stack adjustment is needed. For now, do not do this if any
2950     // argument is passed on the stack.
2951     SmallVector<CCValAssign, 16> ArgLocs;
2952     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2953                    getTargetMachine(), ArgLocs, *DAG.getContext());
2954
2955     // Allocate shadow area for Win64
2956     if (Subtarget->isTargetWin64()) {
2957       CCInfo.AllocateStack(32, 8);
2958     }
2959
2960     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2961     if (CCInfo.getNextStackOffset()) {
2962       MachineFunction &MF = DAG.getMachineFunction();
2963       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2964         return false;
2965
2966       // Check if the arguments are already laid out in the right way as
2967       // the caller's fixed stack objects.
2968       MachineFrameInfo *MFI = MF.getFrameInfo();
2969       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2970       const X86InstrInfo *TII =
2971         ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
2972       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2973         CCValAssign &VA = ArgLocs[i];
2974         SDValue Arg = OutVals[i];
2975         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2976         if (VA.getLocInfo() == CCValAssign::Indirect)
2977           return false;
2978         if (!VA.isRegLoc()) {
2979           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2980                                    MFI, MRI, TII))
2981             return false;
2982         }
2983       }
2984     }
2985
2986     // If the tailcall address may be in a register, then make sure it's
2987     // possible to register allocate for it. In 32-bit, the call address can
2988     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2989     // callee-saved registers are restored. These happen to be the same
2990     // registers used to pass 'inreg' arguments so watch out for those.
2991     if (!Subtarget->is64Bit() &&
2992         ((!isa<GlobalAddressSDNode>(Callee) &&
2993           !isa<ExternalSymbolSDNode>(Callee)) ||
2994          getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
2995       unsigned NumInRegs = 0;
2996       // In PIC we need an extra register to formulate the address computation
2997       // for the callee.
2998       unsigned MaxInRegs =
2999           (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3000
3001       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3002         CCValAssign &VA = ArgLocs[i];
3003         if (!VA.isRegLoc())
3004           continue;
3005         unsigned Reg = VA.getLocReg();
3006         switch (Reg) {
3007         default: break;
3008         case X86::EAX: case X86::EDX: case X86::ECX:
3009           if (++NumInRegs == MaxInRegs)
3010             return false;
3011           break;
3012         }
3013       }
3014     }
3015   }
3016
3017   return true;
3018 }
3019
3020 FastISel *
3021 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3022                                   const TargetLibraryInfo *libInfo) const {
3023   return X86::createFastISel(funcInfo, libInfo);
3024 }
3025
3026 //===----------------------------------------------------------------------===//
3027 //                           Other Lowering Hooks
3028 //===----------------------------------------------------------------------===//
3029
3030 static bool MayFoldLoad(SDValue Op) {
3031   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3032 }
3033
3034 static bool MayFoldIntoStore(SDValue Op) {
3035   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3036 }
3037
3038 static bool isTargetShuffle(unsigned Opcode) {
3039   switch(Opcode) {
3040   default: return false;
3041   case X86ISD::PSHUFD:
3042   case X86ISD::PSHUFHW:
3043   case X86ISD::PSHUFLW:
3044   case X86ISD::SHUFP:
3045   case X86ISD::PALIGNR:
3046   case X86ISD::MOVLHPS:
3047   case X86ISD::MOVLHPD:
3048   case X86ISD::MOVHLPS:
3049   case X86ISD::MOVLPS:
3050   case X86ISD::MOVLPD:
3051   case X86ISD::MOVSHDUP:
3052   case X86ISD::MOVSLDUP:
3053   case X86ISD::MOVDDUP:
3054   case X86ISD::MOVSS:
3055   case X86ISD::MOVSD:
3056   case X86ISD::UNPCKL:
3057   case X86ISD::UNPCKH:
3058   case X86ISD::VPERMILP:
3059   case X86ISD::VPERM2X128:
3060   case X86ISD::VPERMI:
3061     return true;
3062   }
3063 }
3064
3065 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3066                                     SDValue V1, SelectionDAG &DAG) {
3067   switch(Opc) {
3068   default: llvm_unreachable("Unknown x86 shuffle node");
3069   case X86ISD::MOVSHDUP:
3070   case X86ISD::MOVSLDUP:
3071   case X86ISD::MOVDDUP:
3072     return DAG.getNode(Opc, dl, VT, V1);
3073   }
3074 }
3075
3076 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3077                                     SDValue V1, unsigned TargetMask,
3078                                     SelectionDAG &DAG) {
3079   switch(Opc) {
3080   default: llvm_unreachable("Unknown x86 shuffle node");
3081   case X86ISD::PSHUFD:
3082   case X86ISD::PSHUFHW:
3083   case X86ISD::PSHUFLW:
3084   case X86ISD::VPERMILP:
3085   case X86ISD::VPERMI:
3086     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3087   }
3088 }
3089
3090 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3091                                     SDValue V1, SDValue V2, unsigned TargetMask,
3092                                     SelectionDAG &DAG) {
3093   switch(Opc) {
3094   default: llvm_unreachable("Unknown x86 shuffle node");
3095   case X86ISD::PALIGNR:
3096   case X86ISD::SHUFP:
3097   case X86ISD::VPERM2X128:
3098     return DAG.getNode(Opc, dl, VT, V1, V2,
3099                        DAG.getConstant(TargetMask, MVT::i8));
3100   }
3101 }
3102
3103 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3104                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3105   switch(Opc) {
3106   default: llvm_unreachable("Unknown x86 shuffle node");
3107   case X86ISD::MOVLHPS:
3108   case X86ISD::MOVLHPD:
3109   case X86ISD::MOVHLPS:
3110   case X86ISD::MOVLPS:
3111   case X86ISD::MOVLPD:
3112   case X86ISD::MOVSS:
3113   case X86ISD::MOVSD:
3114   case X86ISD::UNPCKL:
3115   case X86ISD::UNPCKH:
3116     return DAG.getNode(Opc, dl, VT, V1, V2);
3117   }
3118 }
3119
3120 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3121   MachineFunction &MF = DAG.getMachineFunction();
3122   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3123   int ReturnAddrIndex = FuncInfo->getRAIndex();
3124
3125   if (ReturnAddrIndex == 0) {
3126     // Set up a frame object for the return address.
3127     unsigned SlotSize = RegInfo->getSlotSize();
3128     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
3129                                                            false);
3130     FuncInfo->setRAIndex(ReturnAddrIndex);
3131   }
3132
3133   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3134 }
3135
3136 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3137                                        bool hasSymbolicDisplacement) {
3138   // Offset should fit into 32 bit immediate field.
3139   if (!isInt<32>(Offset))
3140     return false;
3141
3142   // If we don't have a symbolic displacement - we don't have any extra
3143   // restrictions.
3144   if (!hasSymbolicDisplacement)
3145     return true;
3146
3147   // FIXME: Some tweaks might be needed for medium code model.
3148   if (M != CodeModel::Small && M != CodeModel::Kernel)
3149     return false;
3150
3151   // For small code model we assume that latest object is 16MB before end of 31
3152   // bits boundary. We may also accept pretty large negative constants knowing
3153   // that all objects are in the positive half of address space.
3154   if (M == CodeModel::Small && Offset < 16*1024*1024)
3155     return true;
3156
3157   // For kernel code model we know that all object resist in the negative half
3158   // of 32bits address space. We may not accept negative offsets, since they may
3159   // be just off and we may accept pretty large positive ones.
3160   if (M == CodeModel::Kernel && Offset > 0)
3161     return true;
3162
3163   return false;
3164 }
3165
3166 /// isCalleePop - Determines whether the callee is required to pop its
3167 /// own arguments. Callee pop is necessary to support tail calls.
3168 bool X86::isCalleePop(CallingConv::ID CallingConv,
3169                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3170   if (IsVarArg)
3171     return false;
3172
3173   switch (CallingConv) {
3174   default:
3175     return false;
3176   case CallingConv::X86_StdCall:
3177     return !is64Bit;
3178   case CallingConv::X86_FastCall:
3179     return !is64Bit;
3180   case CallingConv::X86_ThisCall:
3181     return !is64Bit;
3182   case CallingConv::Fast:
3183     return TailCallOpt;
3184   case CallingConv::GHC:
3185     return TailCallOpt;
3186   case CallingConv::HiPE:
3187     return TailCallOpt;
3188   }
3189 }
3190
3191 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3192 /// specific condition code, returning the condition code and the LHS/RHS of the
3193 /// comparison to make.
3194 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3195                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3196   if (!isFP) {
3197     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3198       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3199         // X > -1   -> X == 0, jump !sign.
3200         RHS = DAG.getConstant(0, RHS.getValueType());
3201         return X86::COND_NS;
3202       }
3203       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3204         // X < 0   -> X == 0, jump on sign.
3205         return X86::COND_S;
3206       }
3207       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3208         // X < 1   -> X <= 0
3209         RHS = DAG.getConstant(0, RHS.getValueType());
3210         return X86::COND_LE;
3211       }
3212     }
3213
3214     switch (SetCCOpcode) {
3215     default: llvm_unreachable("Invalid integer condition!");
3216     case ISD::SETEQ:  return X86::COND_E;
3217     case ISD::SETGT:  return X86::COND_G;
3218     case ISD::SETGE:  return X86::COND_GE;
3219     case ISD::SETLT:  return X86::COND_L;
3220     case ISD::SETLE:  return X86::COND_LE;
3221     case ISD::SETNE:  return X86::COND_NE;
3222     case ISD::SETULT: return X86::COND_B;
3223     case ISD::SETUGT: return X86::COND_A;
3224     case ISD::SETULE: return X86::COND_BE;
3225     case ISD::SETUGE: return X86::COND_AE;
3226     }
3227   }
3228
3229   // First determine if it is required or is profitable to flip the operands.
3230
3231   // If LHS is a foldable load, but RHS is not, flip the condition.
3232   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3233       !ISD::isNON_EXTLoad(RHS.getNode())) {
3234     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3235     std::swap(LHS, RHS);
3236   }
3237
3238   switch (SetCCOpcode) {
3239   default: break;
3240   case ISD::SETOLT:
3241   case ISD::SETOLE:
3242   case ISD::SETUGT:
3243   case ISD::SETUGE:
3244     std::swap(LHS, RHS);
3245     break;
3246   }
3247
3248   // On a floating point condition, the flags are set as follows:
3249   // ZF  PF  CF   op
3250   //  0 | 0 | 0 | X > Y
3251   //  0 | 0 | 1 | X < Y
3252   //  1 | 0 | 0 | X == Y
3253   //  1 | 1 | 1 | unordered
3254   switch (SetCCOpcode) {
3255   default: llvm_unreachable("Condcode should be pre-legalized away");
3256   case ISD::SETUEQ:
3257   case ISD::SETEQ:   return X86::COND_E;
3258   case ISD::SETOLT:              // flipped
3259   case ISD::SETOGT:
3260   case ISD::SETGT:   return X86::COND_A;
3261   case ISD::SETOLE:              // flipped
3262   case ISD::SETOGE:
3263   case ISD::SETGE:   return X86::COND_AE;
3264   case ISD::SETUGT:              // flipped
3265   case ISD::SETULT:
3266   case ISD::SETLT:   return X86::COND_B;
3267   case ISD::SETUGE:              // flipped
3268   case ISD::SETULE:
3269   case ISD::SETLE:   return X86::COND_BE;
3270   case ISD::SETONE:
3271   case ISD::SETNE:   return X86::COND_NE;
3272   case ISD::SETUO:   return X86::COND_P;
3273   case ISD::SETO:    return X86::COND_NP;
3274   case ISD::SETOEQ:
3275   case ISD::SETUNE:  return X86::COND_INVALID;
3276   }
3277 }
3278
3279 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3280 /// code. Current x86 isa includes the following FP cmov instructions:
3281 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3282 static bool hasFPCMov(unsigned X86CC) {
3283   switch (X86CC) {
3284   default:
3285     return false;
3286   case X86::COND_B:
3287   case X86::COND_BE:
3288   case X86::COND_E:
3289   case X86::COND_P:
3290   case X86::COND_A:
3291   case X86::COND_AE:
3292   case X86::COND_NE:
3293   case X86::COND_NP:
3294     return true;
3295   }
3296 }
3297
3298 /// isFPImmLegal - Returns true if the target can instruction select the
3299 /// specified FP immediate natively. If false, the legalizer will
3300 /// materialize the FP immediate as a load from a constant pool.
3301 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3302   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3303     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3304       return true;
3305   }
3306   return false;
3307 }
3308
3309 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3310 /// the specified range (L, H].
3311 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3312   return (Val < 0) || (Val >= Low && Val < Hi);
3313 }
3314
3315 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3316 /// specified value.
3317 static bool isUndefOrEqual(int Val, int CmpVal) {
3318   return (Val < 0 || Val == CmpVal);
3319 }
3320
3321 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3322 /// from position Pos and ending in Pos+Size, falls within the specified
3323 /// sequential range (L, L+Pos]. or is undef.
3324 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3325                                        unsigned Pos, unsigned Size, int Low) {
3326   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3327     if (!isUndefOrEqual(Mask[i], Low))
3328       return false;
3329   return true;
3330 }
3331
3332 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3333 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3334 /// the second operand.
3335 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3336   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3337     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3338   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3339     return (Mask[0] < 2 && Mask[1] < 2);
3340   return false;
3341 }
3342
3343 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3344 /// is suitable for input to PSHUFHW.
3345 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3346   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3347     return false;
3348
3349   // Lower quadword copied in order or undef.
3350   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3351     return false;
3352
3353   // Upper quadword shuffled.
3354   for (unsigned i = 4; i != 8; ++i)
3355     if (!isUndefOrInRange(Mask[i], 4, 8))
3356       return false;
3357
3358   if (VT == MVT::v16i16) {
3359     // Lower quadword copied in order or undef.
3360     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3361       return false;
3362
3363     // Upper quadword shuffled.
3364     for (unsigned i = 12; i != 16; ++i)
3365       if (!isUndefOrInRange(Mask[i], 12, 16))
3366         return false;
3367   }
3368
3369   return true;
3370 }
3371
3372 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3373 /// is suitable for input to PSHUFLW.
3374 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3375   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3376     return false;
3377
3378   // Upper quadword copied in order.
3379   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3380     return false;
3381
3382   // Lower quadword shuffled.
3383   for (unsigned i = 0; i != 4; ++i)
3384     if (!isUndefOrInRange(Mask[i], 0, 4))
3385       return false;
3386
3387   if (VT == MVT::v16i16) {
3388     // Upper quadword copied in order.
3389     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3390       return false;
3391
3392     // Lower quadword shuffled.
3393     for (unsigned i = 8; i != 12; ++i)
3394       if (!isUndefOrInRange(Mask[i], 8, 12))
3395         return false;
3396   }
3397
3398   return true;
3399 }
3400
3401 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3402 /// is suitable for input to PALIGNR.
3403 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3404                           const X86Subtarget *Subtarget) {
3405   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3406       (VT.is256BitVector() && !Subtarget->hasInt256()))
3407     return false;
3408
3409   unsigned NumElts = VT.getVectorNumElements();
3410   unsigned NumLanes = VT.getSizeInBits()/128;
3411   unsigned NumLaneElts = NumElts/NumLanes;
3412
3413   // Do not handle 64-bit element shuffles with palignr.
3414   if (NumLaneElts == 2)
3415     return false;
3416
3417   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3418     unsigned i;
3419     for (i = 0; i != NumLaneElts; ++i) {
3420       if (Mask[i+l] >= 0)
3421         break;
3422     }
3423
3424     // Lane is all undef, go to next lane
3425     if (i == NumLaneElts)
3426       continue;
3427
3428     int Start = Mask[i+l];
3429
3430     // Make sure its in this lane in one of the sources
3431     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3432         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3433       return false;
3434
3435     // If not lane 0, then we must match lane 0
3436     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3437       return false;
3438
3439     // Correct second source to be contiguous with first source
3440     if (Start >= (int)NumElts)
3441       Start -= NumElts - NumLaneElts;
3442
3443     // Make sure we're shifting in the right direction.
3444     if (Start <= (int)(i+l))
3445       return false;
3446
3447     Start -= i;
3448
3449     // Check the rest of the elements to see if they are consecutive.
3450     for (++i; i != NumLaneElts; ++i) {
3451       int Idx = Mask[i+l];
3452
3453       // Make sure its in this lane
3454       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3455           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3456         return false;
3457
3458       // If not lane 0, then we must match lane 0
3459       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3460         return false;
3461
3462       if (Idx >= (int)NumElts)
3463         Idx -= NumElts - NumLaneElts;
3464
3465       if (!isUndefOrEqual(Idx, Start+i))
3466         return false;
3467
3468     }
3469   }
3470
3471   return true;
3472 }
3473
3474 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3475 /// the two vector operands have swapped position.
3476 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3477                                      unsigned NumElems) {
3478   for (unsigned i = 0; i != NumElems; ++i) {
3479     int idx = Mask[i];
3480     if (idx < 0)
3481       continue;
3482     else if (idx < (int)NumElems)
3483       Mask[i] = idx + NumElems;
3484     else
3485       Mask[i] = idx - NumElems;
3486   }
3487 }
3488
3489 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3490 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3491 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3492 /// reverse of what x86 shuffles want.
3493 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256,
3494                         bool Commuted = false) {
3495   if (!HasFp256 && VT.is256BitVector())
3496     return false;
3497
3498   unsigned NumElems = VT.getVectorNumElements();
3499   unsigned NumLanes = VT.getSizeInBits()/128;
3500   unsigned NumLaneElems = NumElems/NumLanes;
3501
3502   if (NumLaneElems != 2 && NumLaneElems != 4)
3503     return false;
3504
3505   // VSHUFPSY divides the resulting vector into 4 chunks.
3506   // The sources are also splitted into 4 chunks, and each destination
3507   // chunk must come from a different source chunk.
3508   //
3509   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3510   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3511   //
3512   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3513   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3514   //
3515   // VSHUFPDY divides the resulting vector into 4 chunks.
3516   // The sources are also splitted into 4 chunks, and each destination
3517   // chunk must come from a different source chunk.
3518   //
3519   //  SRC1 =>      X3       X2       X1       X0
3520   //  SRC2 =>      Y3       Y2       Y1       Y0
3521   //
3522   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3523   //
3524   unsigned HalfLaneElems = NumLaneElems/2;
3525   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3526     for (unsigned i = 0; i != NumLaneElems; ++i) {
3527       int Idx = Mask[i+l];
3528       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3529       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3530         return false;
3531       // For VSHUFPSY, the mask of the second half must be the same as the
3532       // first but with the appropriate offsets. This works in the same way as
3533       // VPERMILPS works with masks.
3534       if (NumElems != 8 || l == 0 || Mask[i] < 0)
3535         continue;
3536       if (!isUndefOrEqual(Idx, Mask[i]+l))
3537         return false;
3538     }
3539   }
3540
3541   return true;
3542 }
3543
3544 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3545 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3546 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3547   if (!VT.is128BitVector())
3548     return false;
3549
3550   unsigned NumElems = VT.getVectorNumElements();
3551
3552   if (NumElems != 4)
3553     return false;
3554
3555   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3556   return isUndefOrEqual(Mask[0], 6) &&
3557          isUndefOrEqual(Mask[1], 7) &&
3558          isUndefOrEqual(Mask[2], 2) &&
3559          isUndefOrEqual(Mask[3], 3);
3560 }
3561
3562 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3563 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3564 /// <2, 3, 2, 3>
3565 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3566   if (!VT.is128BitVector())
3567     return false;
3568
3569   unsigned NumElems = VT.getVectorNumElements();
3570
3571   if (NumElems != 4)
3572     return false;
3573
3574   return isUndefOrEqual(Mask[0], 2) &&
3575          isUndefOrEqual(Mask[1], 3) &&
3576          isUndefOrEqual(Mask[2], 2) &&
3577          isUndefOrEqual(Mask[3], 3);
3578 }
3579
3580 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3581 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3582 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3583   if (!VT.is128BitVector())
3584     return false;
3585
3586   unsigned NumElems = VT.getVectorNumElements();
3587
3588   if (NumElems != 2 && NumElems != 4)
3589     return false;
3590
3591   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3592     if (!isUndefOrEqual(Mask[i], i + NumElems))
3593       return false;
3594
3595   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3596     if (!isUndefOrEqual(Mask[i], i))
3597       return false;
3598
3599   return true;
3600 }
3601
3602 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3603 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3604 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3605   if (!VT.is128BitVector())
3606     return false;
3607
3608   unsigned NumElems = VT.getVectorNumElements();
3609
3610   if (NumElems != 2 && NumElems != 4)
3611     return false;
3612
3613   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3614     if (!isUndefOrEqual(Mask[i], i))
3615       return false;
3616
3617   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3618     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3619       return false;
3620
3621   return true;
3622 }
3623
3624 //
3625 // Some special combinations that can be optimized.
3626 //
3627 static
3628 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3629                                SelectionDAG &DAG) {
3630   MVT VT = SVOp->getValueType(0).getSimpleVT();
3631   DebugLoc dl = SVOp->getDebugLoc();
3632
3633   if (VT != MVT::v8i32 && VT != MVT::v8f32)
3634     return SDValue();
3635
3636   ArrayRef<int> Mask = SVOp->getMask();
3637
3638   // These are the special masks that may be optimized.
3639   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3640   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
3641   bool MatchEvenMask = true;
3642   bool MatchOddMask  = true;
3643   for (int i=0; i<8; ++i) {
3644     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3645       MatchEvenMask = false;
3646     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3647       MatchOddMask = false;
3648   }
3649
3650   if (!MatchEvenMask && !MatchOddMask)
3651     return SDValue();
3652
3653   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3654
3655   SDValue Op0 = SVOp->getOperand(0);
3656   SDValue Op1 = SVOp->getOperand(1);
3657
3658   if (MatchEvenMask) {
3659     // Shift the second operand right to 32 bits.
3660     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3661     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3662   } else {
3663     // Shift the first operand left to 32 bits.
3664     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3665     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3666   }
3667   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3668   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3669 }
3670
3671 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3672 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3673 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3674                          bool HasInt256, bool V2IsSplat = false) {
3675   unsigned NumElts = VT.getVectorNumElements();
3676
3677   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3678          "Unsupported vector type for unpckh");
3679
3680   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3681       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3682     return false;
3683
3684   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3685   // independently on 128-bit lanes.
3686   unsigned NumLanes = VT.getSizeInBits()/128;
3687   unsigned NumLaneElts = NumElts/NumLanes;
3688
3689   for (unsigned l = 0; l != NumLanes; ++l) {
3690     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3691          i != (l+1)*NumLaneElts;
3692          i += 2, ++j) {
3693       int BitI  = Mask[i];
3694       int BitI1 = Mask[i+1];
3695       if (!isUndefOrEqual(BitI, j))
3696         return false;
3697       if (V2IsSplat) {
3698         if (!isUndefOrEqual(BitI1, NumElts))
3699           return false;
3700       } else {
3701         if (!isUndefOrEqual(BitI1, j + NumElts))
3702           return false;
3703       }
3704     }
3705   }
3706
3707   return true;
3708 }
3709
3710 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3711 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3712 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3713                          bool HasInt256, bool V2IsSplat = false) {
3714   unsigned NumElts = VT.getVectorNumElements();
3715
3716   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3717          "Unsupported vector type for unpckh");
3718
3719   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3720       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3721     return false;
3722
3723   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3724   // independently on 128-bit lanes.
3725   unsigned NumLanes = VT.getSizeInBits()/128;
3726   unsigned NumLaneElts = NumElts/NumLanes;
3727
3728   for (unsigned l = 0; l != NumLanes; ++l) {
3729     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3730          i != (l+1)*NumLaneElts; i += 2, ++j) {
3731       int BitI  = Mask[i];
3732       int BitI1 = Mask[i+1];
3733       if (!isUndefOrEqual(BitI, j))
3734         return false;
3735       if (V2IsSplat) {
3736         if (isUndefOrEqual(BitI1, NumElts))
3737           return false;
3738       } else {
3739         if (!isUndefOrEqual(BitI1, j+NumElts))
3740           return false;
3741       }
3742     }
3743   }
3744   return true;
3745 }
3746
3747 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3748 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3749 /// <0, 0, 1, 1>
3750 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3751   unsigned NumElts = VT.getVectorNumElements();
3752   bool Is256BitVec = VT.is256BitVector();
3753
3754   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3755          "Unsupported vector type for unpckh");
3756
3757   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
3758       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3759     return false;
3760
3761   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3762   // FIXME: Need a better way to get rid of this, there's no latency difference
3763   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3764   // the former later. We should also remove the "_undef" special mask.
3765   if (NumElts == 4 && Is256BitVec)
3766     return false;
3767
3768   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3769   // independently on 128-bit lanes.
3770   unsigned NumLanes = VT.getSizeInBits()/128;
3771   unsigned NumLaneElts = NumElts/NumLanes;
3772
3773   for (unsigned l = 0; l != NumLanes; ++l) {
3774     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3775          i != (l+1)*NumLaneElts;
3776          i += 2, ++j) {
3777       int BitI  = Mask[i];
3778       int BitI1 = Mask[i+1];
3779
3780       if (!isUndefOrEqual(BitI, j))
3781         return false;
3782       if (!isUndefOrEqual(BitI1, j))
3783         return false;
3784     }
3785   }
3786
3787   return true;
3788 }
3789
3790 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3791 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3792 /// <2, 2, 3, 3>
3793 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3794   unsigned NumElts = VT.getVectorNumElements();
3795
3796   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3797          "Unsupported vector type for unpckh");
3798
3799   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3800       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3801     return false;
3802
3803   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3804   // independently on 128-bit lanes.
3805   unsigned NumLanes = VT.getSizeInBits()/128;
3806   unsigned NumLaneElts = NumElts/NumLanes;
3807
3808   for (unsigned l = 0; l != NumLanes; ++l) {
3809     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3810          i != (l+1)*NumLaneElts; i += 2, ++j) {
3811       int BitI  = Mask[i];
3812       int BitI1 = Mask[i+1];
3813       if (!isUndefOrEqual(BitI, j))
3814         return false;
3815       if (!isUndefOrEqual(BitI1, j))
3816         return false;
3817     }
3818   }
3819   return true;
3820 }
3821
3822 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3823 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3824 /// MOVSD, and MOVD, i.e. setting the lowest element.
3825 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3826   if (VT.getVectorElementType().getSizeInBits() < 32)
3827     return false;
3828   if (!VT.is128BitVector())
3829     return false;
3830
3831   unsigned NumElts = VT.getVectorNumElements();
3832
3833   if (!isUndefOrEqual(Mask[0], NumElts))
3834     return false;
3835
3836   for (unsigned i = 1; i != NumElts; ++i)
3837     if (!isUndefOrEqual(Mask[i], i))
3838       return false;
3839
3840   return true;
3841 }
3842
3843 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3844 /// as permutations between 128-bit chunks or halves. As an example: this
3845 /// shuffle bellow:
3846 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3847 /// The first half comes from the second half of V1 and the second half from the
3848 /// the second half of V2.
3849 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3850   if (!HasFp256 || !VT.is256BitVector())
3851     return false;
3852
3853   // The shuffle result is divided into half A and half B. In total the two
3854   // sources have 4 halves, namely: C, D, E, F. The final values of A and
3855   // B must come from C, D, E or F.
3856   unsigned HalfSize = VT.getVectorNumElements()/2;
3857   bool MatchA = false, MatchB = false;
3858
3859   // Check if A comes from one of C, D, E, F.
3860   for (unsigned Half = 0; Half != 4; ++Half) {
3861     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3862       MatchA = true;
3863       break;
3864     }
3865   }
3866
3867   // Check if B comes from one of C, D, E, F.
3868   for (unsigned Half = 0; Half != 4; ++Half) {
3869     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3870       MatchB = true;
3871       break;
3872     }
3873   }
3874
3875   return MatchA && MatchB;
3876 }
3877
3878 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3879 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3880 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3881   MVT VT = SVOp->getValueType(0).getSimpleVT();
3882
3883   unsigned HalfSize = VT.getVectorNumElements()/2;
3884
3885   unsigned FstHalf = 0, SndHalf = 0;
3886   for (unsigned i = 0; i < HalfSize; ++i) {
3887     if (SVOp->getMaskElt(i) > 0) {
3888       FstHalf = SVOp->getMaskElt(i)/HalfSize;
3889       break;
3890     }
3891   }
3892   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3893     if (SVOp->getMaskElt(i) > 0) {
3894       SndHalf = SVOp->getMaskElt(i)/HalfSize;
3895       break;
3896     }
3897   }
3898
3899   return (FstHalf | (SndHalf << 4));
3900 }
3901
3902 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3903 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3904 /// Note that VPERMIL mask matching is different depending whether theunderlying
3905 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3906 /// to the same elements of the low, but to the higher half of the source.
3907 /// In VPERMILPD the two lanes could be shuffled independently of each other
3908 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
3909 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3910   if (!HasFp256)
3911     return false;
3912
3913   unsigned NumElts = VT.getVectorNumElements();
3914   // Only match 256-bit with 32/64-bit types
3915   if (!VT.is256BitVector() || (NumElts != 4 && NumElts != 8))
3916     return false;
3917
3918   unsigned NumLanes = VT.getSizeInBits()/128;
3919   unsigned LaneSize = NumElts/NumLanes;
3920   for (unsigned l = 0; l != NumElts; l += LaneSize) {
3921     for (unsigned i = 0; i != LaneSize; ++i) {
3922       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3923         return false;
3924       if (NumElts != 8 || l == 0)
3925         continue;
3926       // VPERMILPS handling
3927       if (Mask[i] < 0)
3928         continue;
3929       if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3930         return false;
3931     }
3932   }
3933
3934   return true;
3935 }
3936
3937 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
3938 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3939 /// element of vector 2 and the other elements to come from vector 1 in order.
3940 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3941                                bool V2IsSplat = false, bool V2IsUndef = false) {
3942   if (!VT.is128BitVector())
3943     return false;
3944
3945   unsigned NumOps = VT.getVectorNumElements();
3946   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3947     return false;
3948
3949   if (!isUndefOrEqual(Mask[0], 0))
3950     return false;
3951
3952   for (unsigned i = 1; i != NumOps; ++i)
3953     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3954           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3955           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3956       return false;
3957
3958   return true;
3959 }
3960
3961 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3962 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3963 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3964 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
3965                            const X86Subtarget *Subtarget) {
3966   if (!Subtarget->hasSSE3())
3967     return false;
3968
3969   unsigned NumElems = VT.getVectorNumElements();
3970
3971   if ((VT.is128BitVector() && NumElems != 4) ||
3972       (VT.is256BitVector() && NumElems != 8))
3973     return false;
3974
3975   // "i+1" is the value the indexed mask element must have
3976   for (unsigned i = 0; i != NumElems; i += 2)
3977     if (!isUndefOrEqual(Mask[i], i+1) ||
3978         !isUndefOrEqual(Mask[i+1], i+1))
3979       return false;
3980
3981   return true;
3982 }
3983
3984 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3985 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3986 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3987 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3988                            const X86Subtarget *Subtarget) {
3989   if (!Subtarget->hasSSE3())
3990     return false;
3991
3992   unsigned NumElems = VT.getVectorNumElements();
3993
3994   if ((VT.is128BitVector() && NumElems != 4) ||
3995       (VT.is256BitVector() && NumElems != 8))
3996     return false;
3997
3998   // "i" is the value the indexed mask element must have
3999   for (unsigned i = 0; i != NumElems; i += 2)
4000     if (!isUndefOrEqual(Mask[i], i) ||
4001         !isUndefOrEqual(Mask[i+1], i))
4002       return false;
4003
4004   return true;
4005 }
4006
4007 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4008 /// specifies a shuffle of elements that is suitable for input to 256-bit
4009 /// version of MOVDDUP.
4010 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
4011   if (!HasFp256 || !VT.is256BitVector())
4012     return false;
4013
4014   unsigned NumElts = VT.getVectorNumElements();
4015   if (NumElts != 4)
4016     return false;
4017
4018   for (unsigned i = 0; i != NumElts/2; ++i)
4019     if (!isUndefOrEqual(Mask[i], 0))
4020       return false;
4021   for (unsigned i = NumElts/2; i != NumElts; ++i)
4022     if (!isUndefOrEqual(Mask[i], NumElts/2))
4023       return false;
4024   return true;
4025 }
4026
4027 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4028 /// specifies a shuffle of elements that is suitable for input to 128-bit
4029 /// version of MOVDDUP.
4030 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
4031   if (!VT.is128BitVector())
4032     return false;
4033
4034   unsigned e = VT.getVectorNumElements() / 2;
4035   for (unsigned i = 0; i != e; ++i)
4036     if (!isUndefOrEqual(Mask[i], i))
4037       return false;
4038   for (unsigned i = 0; i != e; ++i)
4039     if (!isUndefOrEqual(Mask[e+i], i))
4040       return false;
4041   return true;
4042 }
4043
4044 /// isVEXTRACTF128Index - Return true if the specified
4045 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4046 /// suitable for input to VEXTRACTF128.
4047 bool X86::isVEXTRACTF128Index(SDNode *N) {
4048   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4049     return false;
4050
4051   // The index should be aligned on a 128-bit boundary.
4052   uint64_t Index =
4053     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4054
4055   MVT VT = N->getValueType(0).getSimpleVT();
4056   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4057   bool Result = (Index * ElSize) % 128 == 0;
4058
4059   return Result;
4060 }
4061
4062 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
4063 /// operand specifies a subvector insert that is suitable for input to
4064 /// VINSERTF128.
4065 bool X86::isVINSERTF128Index(SDNode *N) {
4066   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4067     return false;
4068
4069   // The index should be aligned on a 128-bit boundary.
4070   uint64_t Index =
4071     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4072
4073   MVT VT = N->getValueType(0).getSimpleVT();
4074   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4075   bool Result = (Index * ElSize) % 128 == 0;
4076
4077   return Result;
4078 }
4079
4080 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4081 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4082 /// Handles 128-bit and 256-bit.
4083 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4084   MVT VT = N->getValueType(0).getSimpleVT();
4085
4086   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4087          "Unsupported vector type for PSHUF/SHUFP");
4088
4089   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4090   // independently on 128-bit lanes.
4091   unsigned NumElts = VT.getVectorNumElements();
4092   unsigned NumLanes = VT.getSizeInBits()/128;
4093   unsigned NumLaneElts = NumElts/NumLanes;
4094
4095   assert((NumLaneElts == 2 || NumLaneElts == 4) &&
4096          "Only supports 2 or 4 elements per lane");
4097
4098   unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
4099   unsigned Mask = 0;
4100   for (unsigned i = 0; i != NumElts; ++i) {
4101     int Elt = N->getMaskElt(i);
4102     if (Elt < 0) continue;
4103     Elt &= NumLaneElts - 1;
4104     unsigned ShAmt = (i << Shift) % 8;
4105     Mask |= Elt << ShAmt;
4106   }
4107
4108   return Mask;
4109 }
4110
4111 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4112 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4113 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4114   MVT VT = N->getValueType(0).getSimpleVT();
4115
4116   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4117          "Unsupported vector type for PSHUFHW");
4118
4119   unsigned NumElts = VT.getVectorNumElements();
4120
4121   unsigned Mask = 0;
4122   for (unsigned l = 0; l != NumElts; l += 8) {
4123     // 8 nodes per lane, but we only care about the last 4.
4124     for (unsigned i = 0; i < 4; ++i) {
4125       int Elt = N->getMaskElt(l+i+4);
4126       if (Elt < 0) continue;
4127       Elt &= 0x3; // only 2-bits.
4128       Mask |= Elt << (i * 2);
4129     }
4130   }
4131
4132   return Mask;
4133 }
4134
4135 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4136 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4137 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4138   MVT VT = N->getValueType(0).getSimpleVT();
4139
4140   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4141          "Unsupported vector type for PSHUFHW");
4142
4143   unsigned NumElts = VT.getVectorNumElements();
4144
4145   unsigned Mask = 0;
4146   for (unsigned l = 0; l != NumElts; l += 8) {
4147     // 8 nodes per lane, but we only care about the first 4.
4148     for (unsigned i = 0; i < 4; ++i) {
4149       int Elt = N->getMaskElt(l+i);
4150       if (Elt < 0) continue;
4151       Elt &= 0x3; // only 2-bits
4152       Mask |= Elt << (i * 2);
4153     }
4154   }
4155
4156   return Mask;
4157 }
4158
4159 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4160 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4161 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4162   MVT VT = SVOp->getValueType(0).getSimpleVT();
4163   unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4164
4165   unsigned NumElts = VT.getVectorNumElements();
4166   unsigned NumLanes = VT.getSizeInBits()/128;
4167   unsigned NumLaneElts = NumElts/NumLanes;
4168
4169   int Val = 0;
4170   unsigned i;
4171   for (i = 0; i != NumElts; ++i) {
4172     Val = SVOp->getMaskElt(i);
4173     if (Val >= 0)
4174       break;
4175   }
4176   if (Val >= (int)NumElts)
4177     Val -= NumElts - NumLaneElts;
4178
4179   assert(Val - i > 0 && "PALIGNR imm should be positive");
4180   return (Val - i) * EltSize;
4181 }
4182
4183 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4184 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4185 /// instructions.
4186 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4187   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4188     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4189
4190   uint64_t Index =
4191     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4192
4193   MVT VecVT = N->getOperand(0).getValueType().getSimpleVT();
4194   MVT ElVT = VecVT.getVectorElementType();
4195
4196   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4197   return Index / NumElemsPerChunk;
4198 }
4199
4200 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4201 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4202 /// instructions.
4203 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4204   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4205     llvm_unreachable("Illegal insert subvector for VINSERTF128");
4206
4207   uint64_t Index =
4208     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4209
4210   MVT VecVT = N->getValueType(0).getSimpleVT();
4211   MVT ElVT = VecVT.getVectorElementType();
4212
4213   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4214   return Index / NumElemsPerChunk;
4215 }
4216
4217 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4218 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4219 /// Handles 256-bit.
4220 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4221   MVT VT = N->getValueType(0).getSimpleVT();
4222
4223   unsigned NumElts = VT.getVectorNumElements();
4224
4225   assert((VT.is256BitVector() && NumElts == 4) &&
4226          "Unsupported vector type for VPERMQ/VPERMPD");
4227
4228   unsigned Mask = 0;
4229   for (unsigned i = 0; i != NumElts; ++i) {
4230     int Elt = N->getMaskElt(i);
4231     if (Elt < 0)
4232       continue;
4233     Mask |= Elt << (i*2);
4234   }
4235
4236   return Mask;
4237 }
4238 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4239 /// constant +0.0.
4240 bool X86::isZeroNode(SDValue Elt) {
4241   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Elt))
4242     return CN->isNullValue();
4243   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4244     return CFP->getValueAPF().isPosZero();
4245   return false;
4246 }
4247
4248 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4249 /// their permute mask.
4250 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4251                                     SelectionDAG &DAG) {
4252   MVT VT = SVOp->getValueType(0).getSimpleVT();
4253   unsigned NumElems = VT.getVectorNumElements();
4254   SmallVector<int, 8> MaskVec;
4255
4256   for (unsigned i = 0; i != NumElems; ++i) {
4257     int Idx = SVOp->getMaskElt(i);
4258     if (Idx >= 0) {
4259       if (Idx < (int)NumElems)
4260         Idx += NumElems;
4261       else
4262         Idx -= NumElems;
4263     }
4264     MaskVec.push_back(Idx);
4265   }
4266   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4267                               SVOp->getOperand(0), &MaskVec[0]);
4268 }
4269
4270 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4271 /// match movhlps. The lower half elements should come from upper half of
4272 /// V1 (and in order), and the upper half elements should come from the upper
4273 /// half of V2 (and in order).
4274 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4275   if (!VT.is128BitVector())
4276     return false;
4277   if (VT.getVectorNumElements() != 4)
4278     return false;
4279   for (unsigned i = 0, e = 2; i != e; ++i)
4280     if (!isUndefOrEqual(Mask[i], i+2))
4281       return false;
4282   for (unsigned i = 2; i != 4; ++i)
4283     if (!isUndefOrEqual(Mask[i], i+4))
4284       return false;
4285   return true;
4286 }
4287
4288 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4289 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4290 /// required.
4291 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4292   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4293     return false;
4294   N = N->getOperand(0).getNode();
4295   if (!ISD::isNON_EXTLoad(N))
4296     return false;
4297   if (LD)
4298     *LD = cast<LoadSDNode>(N);
4299   return true;
4300 }
4301
4302 // Test whether the given value is a vector value which will be legalized
4303 // into a load.
4304 static bool WillBeConstantPoolLoad(SDNode *N) {
4305   if (N->getOpcode() != ISD::BUILD_VECTOR)
4306     return false;
4307
4308   // Check for any non-constant elements.
4309   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4310     switch (N->getOperand(i).getNode()->getOpcode()) {
4311     case ISD::UNDEF:
4312     case ISD::ConstantFP:
4313     case ISD::Constant:
4314       break;
4315     default:
4316       return false;
4317     }
4318
4319   // Vectors of all-zeros and all-ones are materialized with special
4320   // instructions rather than being loaded.
4321   return !ISD::isBuildVectorAllZeros(N) &&
4322          !ISD::isBuildVectorAllOnes(N);
4323 }
4324
4325 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4326 /// match movlp{s|d}. The lower half elements should come from lower half of
4327 /// V1 (and in order), and the upper half elements should come from the upper
4328 /// half of V2 (and in order). And since V1 will become the source of the
4329 /// MOVLP, it must be either a vector load or a scalar load to vector.
4330 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4331                                ArrayRef<int> Mask, EVT VT) {
4332   if (!VT.is128BitVector())
4333     return false;
4334
4335   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4336     return false;
4337   // Is V2 is a vector load, don't do this transformation. We will try to use
4338   // load folding shufps op.
4339   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4340     return false;
4341
4342   unsigned NumElems = VT.getVectorNumElements();
4343
4344   if (NumElems != 2 && NumElems != 4)
4345     return false;
4346   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4347     if (!isUndefOrEqual(Mask[i], i))
4348       return false;
4349   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4350     if (!isUndefOrEqual(Mask[i], i+NumElems))
4351       return false;
4352   return true;
4353 }
4354
4355 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4356 /// all the same.
4357 static bool isSplatVector(SDNode *N) {
4358   if (N->getOpcode() != ISD::BUILD_VECTOR)
4359     return false;
4360
4361   SDValue SplatValue = N->getOperand(0);
4362   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4363     if (N->getOperand(i) != SplatValue)
4364       return false;
4365   return true;
4366 }
4367
4368 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4369 /// to an zero vector.
4370 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4371 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4372   SDValue V1 = N->getOperand(0);
4373   SDValue V2 = N->getOperand(1);
4374   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4375   for (unsigned i = 0; i != NumElems; ++i) {
4376     int Idx = N->getMaskElt(i);
4377     if (Idx >= (int)NumElems) {
4378       unsigned Opc = V2.getOpcode();
4379       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4380         continue;
4381       if (Opc != ISD::BUILD_VECTOR ||
4382           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4383         return false;
4384     } else if (Idx >= 0) {
4385       unsigned Opc = V1.getOpcode();
4386       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4387         continue;
4388       if (Opc != ISD::BUILD_VECTOR ||
4389           !X86::isZeroNode(V1.getOperand(Idx)))
4390         return false;
4391     }
4392   }
4393   return true;
4394 }
4395
4396 /// getZeroVector - Returns a vector of specified type with all zero elements.
4397 ///
4398 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4399                              SelectionDAG &DAG, DebugLoc dl) {
4400   assert(VT.isVector() && "Expected a vector type");
4401
4402   // Always build SSE zero vectors as <4 x i32> bitcasted
4403   // to their dest type. This ensures they get CSE'd.
4404   SDValue Vec;
4405   if (VT.is128BitVector()) {  // SSE
4406     if (Subtarget->hasSSE2()) {  // SSE2
4407       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4408       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4409     } else { // SSE1
4410       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4411       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4412     }
4413   } else if (VT.is256BitVector()) { // AVX
4414     if (Subtarget->hasInt256()) { // AVX2
4415       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4416       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4417       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4418                         array_lengthof(Ops));
4419     } else {
4420       // 256-bit logic and arithmetic instructions in AVX are all
4421       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4422       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4423       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4424       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops,
4425                         array_lengthof(Ops));
4426     }
4427   } else
4428     llvm_unreachable("Unexpected vector type");
4429
4430   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4431 }
4432
4433 /// getOnesVector - Returns a vector of specified type with all bits set.
4434 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4435 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4436 /// Then bitcast to their original type, ensuring they get CSE'd.
4437 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4438                              DebugLoc dl) {
4439   assert(VT.isVector() && "Expected a vector type");
4440
4441   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4442   SDValue Vec;
4443   if (VT.is256BitVector()) {
4444     if (HasInt256) { // AVX2
4445       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4446       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4447                         array_lengthof(Ops));
4448     } else { // AVX
4449       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4450       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4451     }
4452   } else if (VT.is128BitVector()) {
4453     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4454   } else
4455     llvm_unreachable("Unexpected vector type");
4456
4457   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4458 }
4459
4460 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4461 /// that point to V2 points to its first element.
4462 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4463   for (unsigned i = 0; i != NumElems; ++i) {
4464     if (Mask[i] > (int)NumElems) {
4465       Mask[i] = NumElems;
4466     }
4467   }
4468 }
4469
4470 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4471 /// operation of specified width.
4472 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4473                        SDValue V2) {
4474   unsigned NumElems = VT.getVectorNumElements();
4475   SmallVector<int, 8> Mask;
4476   Mask.push_back(NumElems);
4477   for (unsigned i = 1; i != NumElems; ++i)
4478     Mask.push_back(i);
4479   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4480 }
4481
4482 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4483 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4484                           SDValue V2) {
4485   unsigned NumElems = VT.getVectorNumElements();
4486   SmallVector<int, 8> Mask;
4487   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4488     Mask.push_back(i);
4489     Mask.push_back(i + NumElems);
4490   }
4491   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4492 }
4493
4494 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4495 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4496                           SDValue V2) {
4497   unsigned NumElems = VT.getVectorNumElements();
4498   SmallVector<int, 8> Mask;
4499   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4500     Mask.push_back(i + Half);
4501     Mask.push_back(i + NumElems + Half);
4502   }
4503   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4504 }
4505
4506 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4507 // a generic shuffle instruction because the target has no such instructions.
4508 // Generate shuffles which repeat i16 and i8 several times until they can be
4509 // represented by v4f32 and then be manipulated by target suported shuffles.
4510 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4511   EVT VT = V.getValueType();
4512   int NumElems = VT.getVectorNumElements();
4513   DebugLoc dl = V.getDebugLoc();
4514
4515   while (NumElems > 4) {
4516     if (EltNo < NumElems/2) {
4517       V = getUnpackl(DAG, dl, VT, V, V);
4518     } else {
4519       V = getUnpackh(DAG, dl, VT, V, V);
4520       EltNo -= NumElems/2;
4521     }
4522     NumElems >>= 1;
4523   }
4524   return V;
4525 }
4526
4527 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4528 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4529   EVT VT = V.getValueType();
4530   DebugLoc dl = V.getDebugLoc();
4531
4532   if (VT.is128BitVector()) {
4533     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4534     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4535     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4536                              &SplatMask[0]);
4537   } else if (VT.is256BitVector()) {
4538     // To use VPERMILPS to splat scalars, the second half of indicies must
4539     // refer to the higher part, which is a duplication of the lower one,
4540     // because VPERMILPS can only handle in-lane permutations.
4541     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4542                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4543
4544     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4545     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4546                              &SplatMask[0]);
4547   } else
4548     llvm_unreachable("Vector size not supported");
4549
4550   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4551 }
4552
4553 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4554 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4555   EVT SrcVT = SV->getValueType(0);
4556   SDValue V1 = SV->getOperand(0);
4557   DebugLoc dl = SV->getDebugLoc();
4558
4559   int EltNo = SV->getSplatIndex();
4560   int NumElems = SrcVT.getVectorNumElements();
4561   bool Is256BitVec = SrcVT.is256BitVector();
4562
4563   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
4564          "Unknown how to promote splat for type");
4565
4566   // Extract the 128-bit part containing the splat element and update
4567   // the splat element index when it refers to the higher register.
4568   if (Is256BitVec) {
4569     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4570     if (EltNo >= NumElems/2)
4571       EltNo -= NumElems/2;
4572   }
4573
4574   // All i16 and i8 vector types can't be used directly by a generic shuffle
4575   // instruction because the target has no such instruction. Generate shuffles
4576   // which repeat i16 and i8 several times until they fit in i32, and then can
4577   // be manipulated by target suported shuffles.
4578   EVT EltVT = SrcVT.getVectorElementType();
4579   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4580     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4581
4582   // Recreate the 256-bit vector and place the same 128-bit vector
4583   // into the low and high part. This is necessary because we want
4584   // to use VPERM* to shuffle the vectors
4585   if (Is256BitVec) {
4586     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4587   }
4588
4589   return getLegalSplat(DAG, V1, EltNo);
4590 }
4591
4592 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4593 /// vector of zero or undef vector.  This produces a shuffle where the low
4594 /// element of V2 is swizzled into the zero/undef vector, landing at element
4595 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4596 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4597                                            bool IsZero,
4598                                            const X86Subtarget *Subtarget,
4599                                            SelectionDAG &DAG) {
4600   EVT VT = V2.getValueType();
4601   SDValue V1 = IsZero
4602     ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4603   unsigned NumElems = VT.getVectorNumElements();
4604   SmallVector<int, 16> MaskVec;
4605   for (unsigned i = 0; i != NumElems; ++i)
4606     // If this is the insertion idx, put the low elt of V2 here.
4607     MaskVec.push_back(i == Idx ? NumElems : i);
4608   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4609 }
4610
4611 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4612 /// target specific opcode. Returns true if the Mask could be calculated.
4613 /// Sets IsUnary to true if only uses one source.
4614 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4615                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4616   unsigned NumElems = VT.getVectorNumElements();
4617   SDValue ImmN;
4618
4619   IsUnary = false;
4620   switch(N->getOpcode()) {
4621   case X86ISD::SHUFP:
4622     ImmN = N->getOperand(N->getNumOperands()-1);
4623     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4624     break;
4625   case X86ISD::UNPCKH:
4626     DecodeUNPCKHMask(VT, Mask);
4627     break;
4628   case X86ISD::UNPCKL:
4629     DecodeUNPCKLMask(VT, Mask);
4630     break;
4631   case X86ISD::MOVHLPS:
4632     DecodeMOVHLPSMask(NumElems, Mask);
4633     break;
4634   case X86ISD::MOVLHPS:
4635     DecodeMOVLHPSMask(NumElems, Mask);
4636     break;
4637   case X86ISD::PALIGNR:
4638     ImmN = N->getOperand(N->getNumOperands()-1);
4639     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4640     break;
4641   case X86ISD::PSHUFD:
4642   case X86ISD::VPERMILP:
4643     ImmN = N->getOperand(N->getNumOperands()-1);
4644     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4645     IsUnary = true;
4646     break;
4647   case X86ISD::PSHUFHW:
4648     ImmN = N->getOperand(N->getNumOperands()-1);
4649     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4650     IsUnary = true;
4651     break;
4652   case X86ISD::PSHUFLW:
4653     ImmN = N->getOperand(N->getNumOperands()-1);
4654     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4655     IsUnary = true;
4656     break;
4657   case X86ISD::VPERMI:
4658     ImmN = N->getOperand(N->getNumOperands()-1);
4659     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4660     IsUnary = true;
4661     break;
4662   case X86ISD::MOVSS:
4663   case X86ISD::MOVSD: {
4664     // The index 0 always comes from the first element of the second source,
4665     // this is why MOVSS and MOVSD are used in the first place. The other
4666     // elements come from the other positions of the first source vector
4667     Mask.push_back(NumElems);
4668     for (unsigned i = 1; i != NumElems; ++i) {
4669       Mask.push_back(i);
4670     }
4671     break;
4672   }
4673   case X86ISD::VPERM2X128:
4674     ImmN = N->getOperand(N->getNumOperands()-1);
4675     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4676     if (Mask.empty()) return false;
4677     break;
4678   case X86ISD::MOVDDUP:
4679   case X86ISD::MOVLHPD:
4680   case X86ISD::MOVLPD:
4681   case X86ISD::MOVLPS:
4682   case X86ISD::MOVSHDUP:
4683   case X86ISD::MOVSLDUP:
4684     // Not yet implemented
4685     return false;
4686   default: llvm_unreachable("unknown target shuffle node");
4687   }
4688
4689   return true;
4690 }
4691
4692 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4693 /// element of the result of the vector shuffle.
4694 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4695                                    unsigned Depth) {
4696   if (Depth == 6)
4697     return SDValue();  // Limit search depth.
4698
4699   SDValue V = SDValue(N, 0);
4700   EVT VT = V.getValueType();
4701   unsigned Opcode = V.getOpcode();
4702
4703   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4704   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4705     int Elt = SV->getMaskElt(Index);
4706
4707     if (Elt < 0)
4708       return DAG.getUNDEF(VT.getVectorElementType());
4709
4710     unsigned NumElems = VT.getVectorNumElements();
4711     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4712                                          : SV->getOperand(1);
4713     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4714   }
4715
4716   // Recurse into target specific vector shuffles to find scalars.
4717   if (isTargetShuffle(Opcode)) {
4718     MVT ShufVT = V.getValueType().getSimpleVT();
4719     unsigned NumElems = ShufVT.getVectorNumElements();
4720     SmallVector<int, 16> ShuffleMask;
4721     bool IsUnary;
4722
4723     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4724       return SDValue();
4725
4726     int Elt = ShuffleMask[Index];
4727     if (Elt < 0)
4728       return DAG.getUNDEF(ShufVT.getVectorElementType());
4729
4730     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4731                                          : N->getOperand(1);
4732     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4733                                Depth+1);
4734   }
4735
4736   // Actual nodes that may contain scalar elements
4737   if (Opcode == ISD::BITCAST) {
4738     V = V.getOperand(0);
4739     EVT SrcVT = V.getValueType();
4740     unsigned NumElems = VT.getVectorNumElements();
4741
4742     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4743       return SDValue();
4744   }
4745
4746   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4747     return (Index == 0) ? V.getOperand(0)
4748                         : DAG.getUNDEF(VT.getVectorElementType());
4749
4750   if (V.getOpcode() == ISD::BUILD_VECTOR)
4751     return V.getOperand(Index);
4752
4753   return SDValue();
4754 }
4755
4756 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4757 /// shuffle operation which come from a consecutively from a zero. The
4758 /// search can start in two different directions, from left or right.
4759 static
4760 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, unsigned NumElems,
4761                                   bool ZerosFromLeft, SelectionDAG &DAG) {
4762   unsigned i;
4763   for (i = 0; i != NumElems; ++i) {
4764     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4765     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4766     if (!(Elt.getNode() &&
4767          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4768       break;
4769   }
4770
4771   return i;
4772 }
4773
4774 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4775 /// correspond consecutively to elements from one of the vector operands,
4776 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4777 static
4778 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4779                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4780                               unsigned NumElems, unsigned &OpNum) {
4781   bool SeenV1 = false;
4782   bool SeenV2 = false;
4783
4784   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4785     int Idx = SVOp->getMaskElt(i);
4786     // Ignore undef indicies
4787     if (Idx < 0)
4788       continue;
4789
4790     if (Idx < (int)NumElems)
4791       SeenV1 = true;
4792     else
4793       SeenV2 = true;
4794
4795     // Only accept consecutive elements from the same vector
4796     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4797       return false;
4798   }
4799
4800   OpNum = SeenV1 ? 0 : 1;
4801   return true;
4802 }
4803
4804 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4805 /// logical left shift of a vector.
4806 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4807                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4808   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4809   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4810               false /* check zeros from right */, DAG);
4811   unsigned OpSrc;
4812
4813   if (!NumZeros)
4814     return false;
4815
4816   // Considering the elements in the mask that are not consecutive zeros,
4817   // check if they consecutively come from only one of the source vectors.
4818   //
4819   //               V1 = {X, A, B, C}     0
4820   //                         \  \  \    /
4821   //   vector_shuffle V1, V2 <1, 2, 3, X>
4822   //
4823   if (!isShuffleMaskConsecutive(SVOp,
4824             0,                   // Mask Start Index
4825             NumElems-NumZeros,   // Mask End Index(exclusive)
4826             NumZeros,            // Where to start looking in the src vector
4827             NumElems,            // Number of elements in vector
4828             OpSrc))              // Which source operand ?
4829     return false;
4830
4831   isLeft = false;
4832   ShAmt = NumZeros;
4833   ShVal = SVOp->getOperand(OpSrc);
4834   return true;
4835 }
4836
4837 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4838 /// logical left shift of a vector.
4839 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4840                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4841   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4842   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4843               true /* check zeros from left */, DAG);
4844   unsigned OpSrc;
4845
4846   if (!NumZeros)
4847     return false;
4848
4849   // Considering the elements in the mask that are not consecutive zeros,
4850   // check if they consecutively come from only one of the source vectors.
4851   //
4852   //                           0    { A, B, X, X } = V2
4853   //                          / \    /  /
4854   //   vector_shuffle V1, V2 <X, X, 4, 5>
4855   //
4856   if (!isShuffleMaskConsecutive(SVOp,
4857             NumZeros,     // Mask Start Index
4858             NumElems,     // Mask End Index(exclusive)
4859             0,            // Where to start looking in the src vector
4860             NumElems,     // Number of elements in vector
4861             OpSrc))       // Which source operand ?
4862     return false;
4863
4864   isLeft = true;
4865   ShAmt = NumZeros;
4866   ShVal = SVOp->getOperand(OpSrc);
4867   return true;
4868 }
4869
4870 /// isVectorShift - Returns true if the shuffle can be implemented as a
4871 /// logical left or right shift of a vector.
4872 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4873                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4874   // Although the logic below support any bitwidth size, there are no
4875   // shift instructions which handle more than 128-bit vectors.
4876   if (!SVOp->getValueType(0).is128BitVector())
4877     return false;
4878
4879   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4880       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4881     return true;
4882
4883   return false;
4884 }
4885
4886 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4887 ///
4888 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4889                                        unsigned NumNonZero, unsigned NumZero,
4890                                        SelectionDAG &DAG,
4891                                        const X86Subtarget* Subtarget,
4892                                        const TargetLowering &TLI) {
4893   if (NumNonZero > 8)
4894     return SDValue();
4895
4896   DebugLoc dl = Op.getDebugLoc();
4897   SDValue V(0, 0);
4898   bool First = true;
4899   for (unsigned i = 0; i < 16; ++i) {
4900     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4901     if (ThisIsNonZero && First) {
4902       if (NumZero)
4903         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4904       else
4905         V = DAG.getUNDEF(MVT::v8i16);
4906       First = false;
4907     }
4908
4909     if ((i & 1) != 0) {
4910       SDValue ThisElt(0, 0), LastElt(0, 0);
4911       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4912       if (LastIsNonZero) {
4913         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4914                               MVT::i16, Op.getOperand(i-1));
4915       }
4916       if (ThisIsNonZero) {
4917         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4918         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4919                               ThisElt, DAG.getConstant(8, MVT::i8));
4920         if (LastIsNonZero)
4921           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4922       } else
4923         ThisElt = LastElt;
4924
4925       if (ThisElt.getNode())
4926         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4927                         DAG.getIntPtrConstant(i/2));
4928     }
4929   }
4930
4931   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4932 }
4933
4934 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4935 ///
4936 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4937                                      unsigned NumNonZero, unsigned NumZero,
4938                                      SelectionDAG &DAG,
4939                                      const X86Subtarget* Subtarget,
4940                                      const TargetLowering &TLI) {
4941   if (NumNonZero > 4)
4942     return SDValue();
4943
4944   DebugLoc dl = Op.getDebugLoc();
4945   SDValue V(0, 0);
4946   bool First = true;
4947   for (unsigned i = 0; i < 8; ++i) {
4948     bool isNonZero = (NonZeros & (1 << i)) != 0;
4949     if (isNonZero) {
4950       if (First) {
4951         if (NumZero)
4952           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4953         else
4954           V = DAG.getUNDEF(MVT::v8i16);
4955         First = false;
4956       }
4957       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4958                       MVT::v8i16, V, Op.getOperand(i),
4959                       DAG.getIntPtrConstant(i));
4960     }
4961   }
4962
4963   return V;
4964 }
4965
4966 /// getVShift - Return a vector logical shift node.
4967 ///
4968 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4969                          unsigned NumBits, SelectionDAG &DAG,
4970                          const TargetLowering &TLI, DebugLoc dl) {
4971   assert(VT.is128BitVector() && "Unknown type for VShift");
4972   EVT ShVT = MVT::v2i64;
4973   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4974   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4975   return DAG.getNode(ISD::BITCAST, dl, VT,
4976                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4977                              DAG.getConstant(NumBits,
4978                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
4979 }
4980
4981 SDValue
4982 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4983                                           SelectionDAG &DAG) const {
4984
4985   // Check if the scalar load can be widened into a vector load. And if
4986   // the address is "base + cst" see if the cst can be "absorbed" into
4987   // the shuffle mask.
4988   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4989     SDValue Ptr = LD->getBasePtr();
4990     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4991       return SDValue();
4992     EVT PVT = LD->getValueType(0);
4993     if (PVT != MVT::i32 && PVT != MVT::f32)
4994       return SDValue();
4995
4996     int FI = -1;
4997     int64_t Offset = 0;
4998     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4999       FI = FINode->getIndex();
5000       Offset = 0;
5001     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5002                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5003       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5004       Offset = Ptr.getConstantOperandVal(1);
5005       Ptr = Ptr.getOperand(0);
5006     } else {
5007       return SDValue();
5008     }
5009
5010     // FIXME: 256-bit vector instructions don't require a strict alignment,
5011     // improve this code to support it better.
5012     unsigned RequiredAlign = VT.getSizeInBits()/8;
5013     SDValue Chain = LD->getChain();
5014     // Make sure the stack object alignment is at least 16 or 32.
5015     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5016     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5017       if (MFI->isFixedObjectIndex(FI)) {
5018         // Can't change the alignment. FIXME: It's possible to compute
5019         // the exact stack offset and reference FI + adjust offset instead.
5020         // If someone *really* cares about this. That's the way to implement it.
5021         return SDValue();
5022       } else {
5023         MFI->setObjectAlignment(FI, RequiredAlign);
5024       }
5025     }
5026
5027     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5028     // Ptr + (Offset & ~15).
5029     if (Offset < 0)
5030       return SDValue();
5031     if ((Offset % RequiredAlign) & 3)
5032       return SDValue();
5033     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5034     if (StartOffset)
5035       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
5036                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5037
5038     int EltNo = (Offset - StartOffset) >> 2;
5039     unsigned NumElems = VT.getVectorNumElements();
5040
5041     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5042     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5043                              LD->getPointerInfo().getWithOffset(StartOffset),
5044                              false, false, false, 0);
5045
5046     SmallVector<int, 8> Mask;
5047     for (unsigned i = 0; i != NumElems; ++i)
5048       Mask.push_back(EltNo);
5049
5050     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5051   }
5052
5053   return SDValue();
5054 }
5055
5056 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5057 /// vector of type 'VT', see if the elements can be replaced by a single large
5058 /// load which has the same value as a build_vector whose operands are 'elts'.
5059 ///
5060 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5061 ///
5062 /// FIXME: we'd also like to handle the case where the last elements are zero
5063 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5064 /// There's even a handy isZeroNode for that purpose.
5065 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5066                                         DebugLoc &DL, SelectionDAG &DAG) {
5067   EVT EltVT = VT.getVectorElementType();
5068   unsigned NumElems = Elts.size();
5069
5070   LoadSDNode *LDBase = NULL;
5071   unsigned LastLoadedElt = -1U;
5072
5073   // For each element in the initializer, see if we've found a load or an undef.
5074   // If we don't find an initial load element, or later load elements are
5075   // non-consecutive, bail out.
5076   for (unsigned i = 0; i < NumElems; ++i) {
5077     SDValue Elt = Elts[i];
5078
5079     if (!Elt.getNode() ||
5080         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5081       return SDValue();
5082     if (!LDBase) {
5083       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5084         return SDValue();
5085       LDBase = cast<LoadSDNode>(Elt.getNode());
5086       LastLoadedElt = i;
5087       continue;
5088     }
5089     if (Elt.getOpcode() == ISD::UNDEF)
5090       continue;
5091
5092     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5093     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5094       return SDValue();
5095     LastLoadedElt = i;
5096   }
5097
5098   // If we have found an entire vector of loads and undefs, then return a large
5099   // load of the entire vector width starting at the base pointer.  If we found
5100   // consecutive loads for the low half, generate a vzext_load node.
5101   if (LastLoadedElt == NumElems - 1) {
5102     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5103       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5104                          LDBase->getPointerInfo(),
5105                          LDBase->isVolatile(), LDBase->isNonTemporal(),
5106                          LDBase->isInvariant(), 0);
5107     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5108                        LDBase->getPointerInfo(),
5109                        LDBase->isVolatile(), LDBase->isNonTemporal(),
5110                        LDBase->isInvariant(), LDBase->getAlignment());
5111   }
5112   if (NumElems == 4 && LastLoadedElt == 1 &&
5113       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5114     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5115     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5116     SDValue ResNode =
5117         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops,
5118                                 array_lengthof(Ops), MVT::i64,
5119                                 LDBase->getPointerInfo(),
5120                                 LDBase->getAlignment(),
5121                                 false/*isVolatile*/, true/*ReadMem*/,
5122                                 false/*WriteMem*/);
5123
5124     // Make sure the newly-created LOAD is in the same position as LDBase in
5125     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5126     // update uses of LDBase's output chain to use the TokenFactor.
5127     if (LDBase->hasAnyUseOfValue(1)) {
5128       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5129                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5130       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5131       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5132                              SDValue(ResNode.getNode(), 1));
5133     }
5134
5135     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5136   }
5137   return SDValue();
5138 }
5139
5140 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5141 /// to generate a splat value for the following cases:
5142 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5143 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5144 /// a scalar load, or a constant.
5145 /// The VBROADCAST node is returned when a pattern is found,
5146 /// or SDValue() otherwise.
5147 SDValue
5148 X86TargetLowering::LowerVectorBroadcast(SDValue Op, SelectionDAG &DAG) const {
5149   if (!Subtarget->hasFp256())
5150     return SDValue();
5151
5152   MVT VT = Op.getValueType().getSimpleVT();
5153   DebugLoc dl = Op.getDebugLoc();
5154
5155   assert((VT.is128BitVector() || VT.is256BitVector()) &&
5156          "Unsupported vector type for broadcast.");
5157
5158   SDValue Ld;
5159   bool ConstSplatVal;
5160
5161   switch (Op.getOpcode()) {
5162     default:
5163       // Unknown pattern found.
5164       return SDValue();
5165
5166     case ISD::BUILD_VECTOR: {
5167       // The BUILD_VECTOR node must be a splat.
5168       if (!isSplatVector(Op.getNode()))
5169         return SDValue();
5170
5171       Ld = Op.getOperand(0);
5172       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5173                      Ld.getOpcode() == ISD::ConstantFP);
5174
5175       // The suspected load node has several users. Make sure that all
5176       // of its users are from the BUILD_VECTOR node.
5177       // Constants may have multiple users.
5178       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5179         return SDValue();
5180       break;
5181     }
5182
5183     case ISD::VECTOR_SHUFFLE: {
5184       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5185
5186       // Shuffles must have a splat mask where the first element is
5187       // broadcasted.
5188       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5189         return SDValue();
5190
5191       SDValue Sc = Op.getOperand(0);
5192       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5193           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5194
5195         if (!Subtarget->hasInt256())
5196           return SDValue();
5197
5198         // Use the register form of the broadcast instruction available on AVX2.
5199         if (VT.is256BitVector())
5200           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5201         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5202       }
5203
5204       Ld = Sc.getOperand(0);
5205       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5206                        Ld.getOpcode() == ISD::ConstantFP);
5207
5208       // The scalar_to_vector node and the suspected
5209       // load node must have exactly one user.
5210       // Constants may have multiple users.
5211       if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5212         return SDValue();
5213       break;
5214     }
5215   }
5216
5217   bool Is256 = VT.is256BitVector();
5218
5219   // Handle the broadcasting a single constant scalar from the constant pool
5220   // into a vector. On Sandybridge it is still better to load a constant vector
5221   // from the constant pool and not to broadcast it from a scalar.
5222   if (ConstSplatVal && Subtarget->hasInt256()) {
5223     EVT CVT = Ld.getValueType();
5224     assert(!CVT.isVector() && "Must not broadcast a vector type");
5225     unsigned ScalarSize = CVT.getSizeInBits();
5226
5227     if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5228       const Constant *C = 0;
5229       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5230         C = CI->getConstantIntValue();
5231       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5232         C = CF->getConstantFPValue();
5233
5234       assert(C && "Invalid constant type");
5235
5236       SDValue CP = DAG.getConstantPool(C, getPointerTy());
5237       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5238       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5239                        MachinePointerInfo::getConstantPool(),
5240                        false, false, false, Alignment);
5241
5242       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5243     }
5244   }
5245
5246   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5247   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5248
5249   // Handle AVX2 in-register broadcasts.
5250   if (!IsLoad && Subtarget->hasInt256() &&
5251       (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5252     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5253
5254   // The scalar source must be a normal load.
5255   if (!IsLoad)
5256     return SDValue();
5257
5258   if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5259     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5260
5261   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5262   // double since there is no vbroadcastsd xmm
5263   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5264     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5265       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5266   }
5267
5268   // Unsupported broadcast.
5269   return SDValue();
5270 }
5271
5272 SDValue
5273 X86TargetLowering::buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) const {
5274   EVT VT = Op.getValueType();
5275
5276   // Skip if insert_vec_elt is not supported.
5277   if (!isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5278     return SDValue();
5279
5280   DebugLoc DL = Op.getDebugLoc();
5281   unsigned NumElems = Op.getNumOperands();
5282
5283   SDValue VecIn1;
5284   SDValue VecIn2;
5285   SmallVector<unsigned, 4> InsertIndices;
5286   SmallVector<int, 8> Mask(NumElems, -1);
5287
5288   for (unsigned i = 0; i != NumElems; ++i) {
5289     unsigned Opc = Op.getOperand(i).getOpcode();
5290
5291     if (Opc == ISD::UNDEF)
5292       continue;
5293
5294     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5295       // Quit if more than 1 elements need inserting.
5296       if (InsertIndices.size() > 1)
5297         return SDValue();
5298
5299       InsertIndices.push_back(i);
5300       continue;
5301     }
5302
5303     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5304     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5305
5306     // Quit if extracted from vector of different type.
5307     if (ExtractedFromVec.getValueType() != VT)
5308       return SDValue();
5309
5310     // Quit if non-constant index.
5311     if (!isa<ConstantSDNode>(ExtIdx))
5312       return SDValue();
5313
5314     if (VecIn1.getNode() == 0)
5315       VecIn1 = ExtractedFromVec;
5316     else if (VecIn1 != ExtractedFromVec) {
5317       if (VecIn2.getNode() == 0)
5318         VecIn2 = ExtractedFromVec;
5319       else if (VecIn2 != ExtractedFromVec)
5320         // Quit if more than 2 vectors to shuffle
5321         return SDValue();
5322     }
5323
5324     unsigned Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5325
5326     if (ExtractedFromVec == VecIn1)
5327       Mask[i] = Idx;
5328     else if (ExtractedFromVec == VecIn2)
5329       Mask[i] = Idx + NumElems;
5330   }
5331
5332   if (VecIn1.getNode() == 0)
5333     return SDValue();
5334
5335   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5336   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5337   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5338     unsigned Idx = InsertIndices[i];
5339     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5340                      DAG.getIntPtrConstant(Idx));
5341   }
5342
5343   return NV;
5344 }
5345
5346 SDValue
5347 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5348   DebugLoc dl = Op.getDebugLoc();
5349
5350   MVT VT = Op.getValueType().getSimpleVT();
5351   MVT ExtVT = VT.getVectorElementType();
5352   unsigned NumElems = Op.getNumOperands();
5353
5354   // Vectors containing all zeros can be matched by pxor and xorps later
5355   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5356     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5357     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5358     if (VT == MVT::v4i32 || VT == MVT::v8i32)
5359       return Op;
5360
5361     return getZeroVector(VT, Subtarget, DAG, dl);
5362   }
5363
5364   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5365   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5366   // vpcmpeqd on 256-bit vectors.
5367   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5368     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5369       return Op;
5370
5371     return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5372   }
5373
5374   SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5375   if (Broadcast.getNode())
5376     return Broadcast;
5377
5378   unsigned EVTBits = ExtVT.getSizeInBits();
5379
5380   unsigned NumZero  = 0;
5381   unsigned NumNonZero = 0;
5382   unsigned NonZeros = 0;
5383   bool IsAllConstants = true;
5384   SmallSet<SDValue, 8> Values;
5385   for (unsigned i = 0; i < NumElems; ++i) {
5386     SDValue Elt = Op.getOperand(i);
5387     if (Elt.getOpcode() == ISD::UNDEF)
5388       continue;
5389     Values.insert(Elt);
5390     if (Elt.getOpcode() != ISD::Constant &&
5391         Elt.getOpcode() != ISD::ConstantFP)
5392       IsAllConstants = false;
5393     if (X86::isZeroNode(Elt))
5394       NumZero++;
5395     else {
5396       NonZeros |= (1 << i);
5397       NumNonZero++;
5398     }
5399   }
5400
5401   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5402   if (NumNonZero == 0)
5403     return DAG.getUNDEF(VT);
5404
5405   // Special case for single non-zero, non-undef, element.
5406   if (NumNonZero == 1) {
5407     unsigned Idx = CountTrailingZeros_32(NonZeros);
5408     SDValue Item = Op.getOperand(Idx);
5409
5410     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5411     // the value are obviously zero, truncate the value to i32 and do the
5412     // insertion that way.  Only do this if the value is non-constant or if the
5413     // value is a constant being inserted into element 0.  It is cheaper to do
5414     // a constant pool load than it is to do a movd + shuffle.
5415     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5416         (!IsAllConstants || Idx == 0)) {
5417       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5418         // Handle SSE only.
5419         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5420         EVT VecVT = MVT::v4i32;
5421         unsigned VecElts = 4;
5422
5423         // Truncate the value (which may itself be a constant) to i32, and
5424         // convert it to a vector with movd (S2V+shuffle to zero extend).
5425         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5426         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5427         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5428
5429         // Now we have our 32-bit value zero extended in the low element of
5430         // a vector.  If Idx != 0, swizzle it into place.
5431         if (Idx != 0) {
5432           SmallVector<int, 4> Mask;
5433           Mask.push_back(Idx);
5434           for (unsigned i = 1; i != VecElts; ++i)
5435             Mask.push_back(i);
5436           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5437                                       &Mask[0]);
5438         }
5439         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5440       }
5441     }
5442
5443     // If we have a constant or non-constant insertion into the low element of
5444     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5445     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5446     // depending on what the source datatype is.
5447     if (Idx == 0) {
5448       if (NumZero == 0)
5449         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5450
5451       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5452           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5453         if (VT.is256BitVector()) {
5454           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5455           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5456                              Item, DAG.getIntPtrConstant(0));
5457         }
5458         assert(VT.is128BitVector() && "Expected an SSE value type!");
5459         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5460         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5461         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5462       }
5463
5464       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5465         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5466         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5467         if (VT.is256BitVector()) {
5468           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5469           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5470         } else {
5471           assert(VT.is128BitVector() && "Expected an SSE value type!");
5472           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5473         }
5474         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5475       }
5476     }
5477
5478     // Is it a vector logical left shift?
5479     if (NumElems == 2 && Idx == 1 &&
5480         X86::isZeroNode(Op.getOperand(0)) &&
5481         !X86::isZeroNode(Op.getOperand(1))) {
5482       unsigned NumBits = VT.getSizeInBits();
5483       return getVShift(true, VT,
5484                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5485                                    VT, Op.getOperand(1)),
5486                        NumBits/2, DAG, *this, dl);
5487     }
5488
5489     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5490       return SDValue();
5491
5492     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5493     // is a non-constant being inserted into an element other than the low one,
5494     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5495     // movd/movss) to move this into the low element, then shuffle it into
5496     // place.
5497     if (EVTBits == 32) {
5498       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5499
5500       // Turn it into a shuffle of zero and zero-extended scalar to vector.
5501       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5502       SmallVector<int, 8> MaskVec;
5503       for (unsigned i = 0; i != NumElems; ++i)
5504         MaskVec.push_back(i == Idx ? 0 : 1);
5505       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5506     }
5507   }
5508
5509   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5510   if (Values.size() == 1) {
5511     if (EVTBits == 32) {
5512       // Instead of a shuffle like this:
5513       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5514       // Check if it's possible to issue this instead.
5515       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5516       unsigned Idx = CountTrailingZeros_32(NonZeros);
5517       SDValue Item = Op.getOperand(Idx);
5518       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5519         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5520     }
5521     return SDValue();
5522   }
5523
5524   // A vector full of immediates; various special cases are already
5525   // handled, so this is best done with a single constant-pool load.
5526   if (IsAllConstants)
5527     return SDValue();
5528
5529   // For AVX-length vectors, build the individual 128-bit pieces and use
5530   // shuffles to put them in place.
5531   if (VT.is256BitVector()) {
5532     SmallVector<SDValue, 32> V;
5533     for (unsigned i = 0; i != NumElems; ++i)
5534       V.push_back(Op.getOperand(i));
5535
5536     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5537
5538     // Build both the lower and upper subvector.
5539     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5540     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5541                                 NumElems/2);
5542
5543     // Recreate the wider vector with the lower and upper part.
5544     return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5545   }
5546
5547   // Let legalizer expand 2-wide build_vectors.
5548   if (EVTBits == 64) {
5549     if (NumNonZero == 1) {
5550       // One half is zero or undef.
5551       unsigned Idx = CountTrailingZeros_32(NonZeros);
5552       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5553                                  Op.getOperand(Idx));
5554       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5555     }
5556     return SDValue();
5557   }
5558
5559   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5560   if (EVTBits == 8 && NumElems == 16) {
5561     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5562                                         Subtarget, *this);
5563     if (V.getNode()) return V;
5564   }
5565
5566   if (EVTBits == 16 && NumElems == 8) {
5567     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5568                                       Subtarget, *this);
5569     if (V.getNode()) return V;
5570   }
5571
5572   // If element VT is == 32 bits, turn it into a number of shuffles.
5573   SmallVector<SDValue, 8> V(NumElems);
5574   if (NumElems == 4 && NumZero > 0) {
5575     for (unsigned i = 0; i < 4; ++i) {
5576       bool isZero = !(NonZeros & (1 << i));
5577       if (isZero)
5578         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5579       else
5580         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5581     }
5582
5583     for (unsigned i = 0; i < 2; ++i) {
5584       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5585         default: break;
5586         case 0:
5587           V[i] = V[i*2];  // Must be a zero vector.
5588           break;
5589         case 1:
5590           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5591           break;
5592         case 2:
5593           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5594           break;
5595         case 3:
5596           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5597           break;
5598       }
5599     }
5600
5601     bool Reverse1 = (NonZeros & 0x3) == 2;
5602     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5603     int MaskVec[] = {
5604       Reverse1 ? 1 : 0,
5605       Reverse1 ? 0 : 1,
5606       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5607       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5608     };
5609     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5610   }
5611
5612   if (Values.size() > 1 && VT.is128BitVector()) {
5613     // Check for a build vector of consecutive loads.
5614     for (unsigned i = 0; i < NumElems; ++i)
5615       V[i] = Op.getOperand(i);
5616
5617     // Check for elements which are consecutive loads.
5618     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5619     if (LD.getNode())
5620       return LD;
5621
5622     // Check for a build vector from mostly shuffle plus few inserting.
5623     SDValue Sh = buildFromShuffleMostly(Op, DAG);
5624     if (Sh.getNode())
5625       return Sh;
5626
5627     // For SSE 4.1, use insertps to put the high elements into the low element.
5628     if (getSubtarget()->hasSSE41()) {
5629       SDValue Result;
5630       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5631         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5632       else
5633         Result = DAG.getUNDEF(VT);
5634
5635       for (unsigned i = 1; i < NumElems; ++i) {
5636         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5637         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5638                              Op.getOperand(i), DAG.getIntPtrConstant(i));
5639       }
5640       return Result;
5641     }
5642
5643     // Otherwise, expand into a number of unpckl*, start by extending each of
5644     // our (non-undef) elements to the full vector width with the element in the
5645     // bottom slot of the vector (which generates no code for SSE).
5646     for (unsigned i = 0; i < NumElems; ++i) {
5647       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5648         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5649       else
5650         V[i] = DAG.getUNDEF(VT);
5651     }
5652
5653     // Next, we iteratively mix elements, e.g. for v4f32:
5654     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5655     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5656     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5657     unsigned EltStride = NumElems >> 1;
5658     while (EltStride != 0) {
5659       for (unsigned i = 0; i < EltStride; ++i) {
5660         // If V[i+EltStride] is undef and this is the first round of mixing,
5661         // then it is safe to just drop this shuffle: V[i] is already in the
5662         // right place, the one element (since it's the first round) being
5663         // inserted as undef can be dropped.  This isn't safe for successive
5664         // rounds because they will permute elements within both vectors.
5665         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5666             EltStride == NumElems/2)
5667           continue;
5668
5669         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5670       }
5671       EltStride >>= 1;
5672     }
5673     return V[0];
5674   }
5675   return SDValue();
5676 }
5677
5678 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5679 // to create 256-bit vectors from two other 128-bit ones.
5680 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5681   DebugLoc dl = Op.getDebugLoc();
5682   MVT ResVT = Op.getValueType().getSimpleVT();
5683
5684   assert(ResVT.is256BitVector() && "Value type must be 256-bit wide");
5685
5686   SDValue V1 = Op.getOperand(0);
5687   SDValue V2 = Op.getOperand(1);
5688   unsigned NumElems = ResVT.getVectorNumElements();
5689
5690   return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5691 }
5692
5693 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5694   assert(Op.getNumOperands() == 2);
5695
5696   // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5697   // from two other 128-bit ones.
5698   return LowerAVXCONCAT_VECTORS(Op, DAG);
5699 }
5700
5701 // Try to lower a shuffle node into a simple blend instruction.
5702 static SDValue
5703 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5704                            const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5705   SDValue V1 = SVOp->getOperand(0);
5706   SDValue V2 = SVOp->getOperand(1);
5707   DebugLoc dl = SVOp->getDebugLoc();
5708   MVT VT = SVOp->getValueType(0).getSimpleVT();
5709   MVT EltVT = VT.getVectorElementType();
5710   unsigned NumElems = VT.getVectorNumElements();
5711
5712   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
5713     return SDValue();
5714   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
5715     return SDValue();
5716
5717   // Check the mask for BLEND and build the value.
5718   unsigned MaskValue = 0;
5719   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
5720   unsigned NumLanes = (NumElems-1)/8 + 1;
5721   unsigned NumElemsInLane = NumElems / NumLanes;
5722
5723   // Blend for v16i16 should be symetric for the both lanes.
5724   for (unsigned i = 0; i < NumElemsInLane; ++i) {
5725
5726     int SndLaneEltIdx = (NumLanes == 2) ?
5727       SVOp->getMaskElt(i + NumElemsInLane) : -1;
5728     int EltIdx = SVOp->getMaskElt(i);
5729
5730     if ((EltIdx < 0 || EltIdx == (int)i) &&
5731         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
5732       continue;
5733
5734     if (((unsigned)EltIdx == (i + NumElems)) &&
5735         (SndLaneEltIdx < 0 ||
5736          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
5737       MaskValue |= (1<<i);
5738     else
5739       return SDValue();
5740   }
5741
5742   // Convert i32 vectors to floating point if it is not AVX2.
5743   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
5744   MVT BlendVT = VT;
5745   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
5746     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
5747                                NumElems);
5748     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
5749     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
5750   }
5751
5752   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
5753                             DAG.getConstant(MaskValue, MVT::i32));
5754   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5755 }
5756
5757 // v8i16 shuffles - Prefer shuffles in the following order:
5758 // 1. [all]   pshuflw, pshufhw, optional move
5759 // 2. [ssse3] 1 x pshufb
5760 // 3. [ssse3] 2 x pshufb + 1 x por
5761 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5762 static SDValue
5763 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
5764                          SelectionDAG &DAG) {
5765   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5766   SDValue V1 = SVOp->getOperand(0);
5767   SDValue V2 = SVOp->getOperand(1);
5768   DebugLoc dl = SVOp->getDebugLoc();
5769   SmallVector<int, 8> MaskVals;
5770
5771   // Determine if more than 1 of the words in each of the low and high quadwords
5772   // of the result come from the same quadword of one of the two inputs.  Undef
5773   // mask values count as coming from any quadword, for better codegen.
5774   unsigned LoQuad[] = { 0, 0, 0, 0 };
5775   unsigned HiQuad[] = { 0, 0, 0, 0 };
5776   std::bitset<4> InputQuads;
5777   for (unsigned i = 0; i < 8; ++i) {
5778     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5779     int EltIdx = SVOp->getMaskElt(i);
5780     MaskVals.push_back(EltIdx);
5781     if (EltIdx < 0) {
5782       ++Quad[0];
5783       ++Quad[1];
5784       ++Quad[2];
5785       ++Quad[3];
5786       continue;
5787     }
5788     ++Quad[EltIdx / 4];
5789     InputQuads.set(EltIdx / 4);
5790   }
5791
5792   int BestLoQuad = -1;
5793   unsigned MaxQuad = 1;
5794   for (unsigned i = 0; i < 4; ++i) {
5795     if (LoQuad[i] > MaxQuad) {
5796       BestLoQuad = i;
5797       MaxQuad = LoQuad[i];
5798     }
5799   }
5800
5801   int BestHiQuad = -1;
5802   MaxQuad = 1;
5803   for (unsigned i = 0; i < 4; ++i) {
5804     if (HiQuad[i] > MaxQuad) {
5805       BestHiQuad = i;
5806       MaxQuad = HiQuad[i];
5807     }
5808   }
5809
5810   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5811   // of the two input vectors, shuffle them into one input vector so only a
5812   // single pshufb instruction is necessary. If There are more than 2 input
5813   // quads, disable the next transformation since it does not help SSSE3.
5814   bool V1Used = InputQuads[0] || InputQuads[1];
5815   bool V2Used = InputQuads[2] || InputQuads[3];
5816   if (Subtarget->hasSSSE3()) {
5817     if (InputQuads.count() == 2 && V1Used && V2Used) {
5818       BestLoQuad = InputQuads[0] ? 0 : 1;
5819       BestHiQuad = InputQuads[2] ? 2 : 3;
5820     }
5821     if (InputQuads.count() > 2) {
5822       BestLoQuad = -1;
5823       BestHiQuad = -1;
5824     }
5825   }
5826
5827   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5828   // the shuffle mask.  If a quad is scored as -1, that means that it contains
5829   // words from all 4 input quadwords.
5830   SDValue NewV;
5831   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5832     int MaskV[] = {
5833       BestLoQuad < 0 ? 0 : BestLoQuad,
5834       BestHiQuad < 0 ? 1 : BestHiQuad
5835     };
5836     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5837                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5838                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5839     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5840
5841     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5842     // source words for the shuffle, to aid later transformations.
5843     bool AllWordsInNewV = true;
5844     bool InOrder[2] = { true, true };
5845     for (unsigned i = 0; i != 8; ++i) {
5846       int idx = MaskVals[i];
5847       if (idx != (int)i)
5848         InOrder[i/4] = false;
5849       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5850         continue;
5851       AllWordsInNewV = false;
5852       break;
5853     }
5854
5855     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5856     if (AllWordsInNewV) {
5857       for (int i = 0; i != 8; ++i) {
5858         int idx = MaskVals[i];
5859         if (idx < 0)
5860           continue;
5861         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5862         if ((idx != i) && idx < 4)
5863           pshufhw = false;
5864         if ((idx != i) && idx > 3)
5865           pshuflw = false;
5866       }
5867       V1 = NewV;
5868       V2Used = false;
5869       BestLoQuad = 0;
5870       BestHiQuad = 1;
5871     }
5872
5873     // If we've eliminated the use of V2, and the new mask is a pshuflw or
5874     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
5875     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5876       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5877       unsigned TargetMask = 0;
5878       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5879                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5880       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5881       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5882                              getShufflePSHUFLWImmediate(SVOp);
5883       V1 = NewV.getOperand(0);
5884       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5885     }
5886   }
5887
5888   // Promote splats to a larger type which usually leads to more efficient code.
5889   // FIXME: Is this true if pshufb is available?
5890   if (SVOp->isSplat())
5891     return PromoteSplat(SVOp, DAG);
5892
5893   // If we have SSSE3, and all words of the result are from 1 input vector,
5894   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5895   // is present, fall back to case 4.
5896   if (Subtarget->hasSSSE3()) {
5897     SmallVector<SDValue,16> pshufbMask;
5898
5899     // If we have elements from both input vectors, set the high bit of the
5900     // shuffle mask element to zero out elements that come from V2 in the V1
5901     // mask, and elements that come from V1 in the V2 mask, so that the two
5902     // results can be OR'd together.
5903     bool TwoInputs = V1Used && V2Used;
5904     for (unsigned i = 0; i != 8; ++i) {
5905       int EltIdx = MaskVals[i] * 2;
5906       int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
5907       int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
5908       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5909       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5910     }
5911     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5912     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5913                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5914                                  MVT::v16i8, &pshufbMask[0], 16));
5915     if (!TwoInputs)
5916       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5917
5918     // Calculate the shuffle mask for the second input, shuffle it, and
5919     // OR it with the first shuffled input.
5920     pshufbMask.clear();
5921     for (unsigned i = 0; i != 8; ++i) {
5922       int EltIdx = MaskVals[i] * 2;
5923       int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5924       int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
5925       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5926       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5927     }
5928     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5929     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5930                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5931                                  MVT::v16i8, &pshufbMask[0], 16));
5932     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5933     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5934   }
5935
5936   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5937   // and update MaskVals with new element order.
5938   std::bitset<8> InOrder;
5939   if (BestLoQuad >= 0) {
5940     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5941     for (int i = 0; i != 4; ++i) {
5942       int idx = MaskVals[i];
5943       if (idx < 0) {
5944         InOrder.set(i);
5945       } else if ((idx / 4) == BestLoQuad) {
5946         MaskV[i] = idx & 3;
5947         InOrder.set(i);
5948       }
5949     }
5950     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5951                                 &MaskV[0]);
5952
5953     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5954       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5955       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5956                                   NewV.getOperand(0),
5957                                   getShufflePSHUFLWImmediate(SVOp), DAG);
5958     }
5959   }
5960
5961   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5962   // and update MaskVals with the new element order.
5963   if (BestHiQuad >= 0) {
5964     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5965     for (unsigned i = 4; i != 8; ++i) {
5966       int idx = MaskVals[i];
5967       if (idx < 0) {
5968         InOrder.set(i);
5969       } else if ((idx / 4) == BestHiQuad) {
5970         MaskV[i] = (idx & 3) + 4;
5971         InOrder.set(i);
5972       }
5973     }
5974     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5975                                 &MaskV[0]);
5976
5977     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5978       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5979       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5980                                   NewV.getOperand(0),
5981                                   getShufflePSHUFHWImmediate(SVOp), DAG);
5982     }
5983   }
5984
5985   // In case BestHi & BestLo were both -1, which means each quadword has a word
5986   // from each of the four input quadwords, calculate the InOrder bitvector now
5987   // before falling through to the insert/extract cleanup.
5988   if (BestLoQuad == -1 && BestHiQuad == -1) {
5989     NewV = V1;
5990     for (int i = 0; i != 8; ++i)
5991       if (MaskVals[i] < 0 || MaskVals[i] == i)
5992         InOrder.set(i);
5993   }
5994
5995   // The other elements are put in the right place using pextrw and pinsrw.
5996   for (unsigned i = 0; i != 8; ++i) {
5997     if (InOrder[i])
5998       continue;
5999     int EltIdx = MaskVals[i];
6000     if (EltIdx < 0)
6001       continue;
6002     SDValue ExtOp = (EltIdx < 8) ?
6003       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6004                   DAG.getIntPtrConstant(EltIdx)) :
6005       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6006                   DAG.getIntPtrConstant(EltIdx - 8));
6007     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6008                        DAG.getIntPtrConstant(i));
6009   }
6010   return NewV;
6011 }
6012
6013 // v16i8 shuffles - Prefer shuffles in the following order:
6014 // 1. [ssse3] 1 x pshufb
6015 // 2. [ssse3] 2 x pshufb + 1 x por
6016 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
6017 static
6018 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6019                                  SelectionDAG &DAG,
6020                                  const X86TargetLowering &TLI) {
6021   SDValue V1 = SVOp->getOperand(0);
6022   SDValue V2 = SVOp->getOperand(1);
6023   DebugLoc dl = SVOp->getDebugLoc();
6024   ArrayRef<int> MaskVals = SVOp->getMask();
6025
6026   // Promote splats to a larger type which usually leads to more efficient code.
6027   // FIXME: Is this true if pshufb is available?
6028   if (SVOp->isSplat())
6029     return PromoteSplat(SVOp, DAG);
6030
6031   // If we have SSSE3, case 1 is generated when all result bytes come from
6032   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
6033   // present, fall back to case 3.
6034
6035   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6036   if (TLI.getSubtarget()->hasSSSE3()) {
6037     SmallVector<SDValue,16> pshufbMask;
6038
6039     // If all result elements are from one input vector, then only translate
6040     // undef mask values to 0x80 (zero out result) in the pshufb mask.
6041     //
6042     // Otherwise, we have elements from both input vectors, and must zero out
6043     // elements that come from V2 in the first mask, and V1 in the second mask
6044     // so that we can OR them together.
6045     for (unsigned i = 0; i != 16; ++i) {
6046       int EltIdx = MaskVals[i];
6047       if (EltIdx < 0 || EltIdx >= 16)
6048         EltIdx = 0x80;
6049       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6050     }
6051     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6052                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6053                                  MVT::v16i8, &pshufbMask[0], 16));
6054
6055     // As PSHUFB will zero elements with negative indices, it's safe to ignore
6056     // the 2nd operand if it's undefined or zero.
6057     if (V2.getOpcode() == ISD::UNDEF ||
6058         ISD::isBuildVectorAllZeros(V2.getNode()))
6059       return V1;
6060
6061     // Calculate the shuffle mask for the second input, shuffle it, and
6062     // OR it with the first shuffled input.
6063     pshufbMask.clear();
6064     for (unsigned i = 0; i != 16; ++i) {
6065       int EltIdx = MaskVals[i];
6066       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6067       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6068     }
6069     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6070                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6071                                  MVT::v16i8, &pshufbMask[0], 16));
6072     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6073   }
6074
6075   // No SSSE3 - Calculate in place words and then fix all out of place words
6076   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
6077   // the 16 different words that comprise the two doublequadword input vectors.
6078   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6079   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6080   SDValue NewV = V1;
6081   for (int i = 0; i != 8; ++i) {
6082     int Elt0 = MaskVals[i*2];
6083     int Elt1 = MaskVals[i*2+1];
6084
6085     // This word of the result is all undef, skip it.
6086     if (Elt0 < 0 && Elt1 < 0)
6087       continue;
6088
6089     // This word of the result is already in the correct place, skip it.
6090     if ((Elt0 == i*2) && (Elt1 == i*2+1))
6091       continue;
6092
6093     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6094     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6095     SDValue InsElt;
6096
6097     // If Elt0 and Elt1 are defined, are consecutive, and can be load
6098     // using a single extract together, load it and store it.
6099     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6100       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6101                            DAG.getIntPtrConstant(Elt1 / 2));
6102       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6103                         DAG.getIntPtrConstant(i));
6104       continue;
6105     }
6106
6107     // If Elt1 is defined, extract it from the appropriate source.  If the
6108     // source byte is not also odd, shift the extracted word left 8 bits
6109     // otherwise clear the bottom 8 bits if we need to do an or.
6110     if (Elt1 >= 0) {
6111       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6112                            DAG.getIntPtrConstant(Elt1 / 2));
6113       if ((Elt1 & 1) == 0)
6114         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6115                              DAG.getConstant(8,
6116                                   TLI.getShiftAmountTy(InsElt.getValueType())));
6117       else if (Elt0 >= 0)
6118         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6119                              DAG.getConstant(0xFF00, MVT::i16));
6120     }
6121     // If Elt0 is defined, extract it from the appropriate source.  If the
6122     // source byte is not also even, shift the extracted word right 8 bits. If
6123     // Elt1 was also defined, OR the extracted values together before
6124     // inserting them in the result.
6125     if (Elt0 >= 0) {
6126       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6127                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6128       if ((Elt0 & 1) != 0)
6129         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6130                               DAG.getConstant(8,
6131                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
6132       else if (Elt1 >= 0)
6133         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6134                              DAG.getConstant(0x00FF, MVT::i16));
6135       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6136                          : InsElt0;
6137     }
6138     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6139                        DAG.getIntPtrConstant(i));
6140   }
6141   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6142 }
6143
6144 // v32i8 shuffles - Translate to VPSHUFB if possible.
6145 static
6146 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6147                                  const X86Subtarget *Subtarget,
6148                                  SelectionDAG &DAG) {
6149   MVT VT = SVOp->getValueType(0).getSimpleVT();
6150   SDValue V1 = SVOp->getOperand(0);
6151   SDValue V2 = SVOp->getOperand(1);
6152   DebugLoc dl = SVOp->getDebugLoc();
6153   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6154
6155   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6156   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6157   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6158
6159   // VPSHUFB may be generated if
6160   // (1) one of input vector is undefined or zeroinitializer.
6161   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6162   // And (2) the mask indexes don't cross the 128-bit lane.
6163   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6164       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6165     return SDValue();
6166
6167   if (V1IsAllZero && !V2IsAllZero) {
6168     CommuteVectorShuffleMask(MaskVals, 32);
6169     V1 = V2;
6170   }
6171   SmallVector<SDValue, 32> pshufbMask;
6172   for (unsigned i = 0; i != 32; i++) {
6173     int EltIdx = MaskVals[i];
6174     if (EltIdx < 0 || EltIdx >= 32)
6175       EltIdx = 0x80;
6176     else {
6177       if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6178         // Cross lane is not allowed.
6179         return SDValue();
6180       EltIdx &= 0xf;
6181     }
6182     pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6183   }
6184   return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6185                       DAG.getNode(ISD::BUILD_VECTOR, dl,
6186                                   MVT::v32i8, &pshufbMask[0], 32));
6187 }
6188
6189 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6190 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6191 /// done when every pair / quad of shuffle mask elements point to elements in
6192 /// the right sequence. e.g.
6193 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6194 static
6195 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6196                                  SelectionDAG &DAG) {
6197   MVT VT = SVOp->getValueType(0).getSimpleVT();
6198   DebugLoc dl = SVOp->getDebugLoc();
6199   unsigned NumElems = VT.getVectorNumElements();
6200   MVT NewVT;
6201   unsigned Scale;
6202   switch (VT.SimpleTy) {
6203   default: llvm_unreachable("Unexpected!");
6204   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
6205   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
6206   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
6207   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
6208   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6209   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
6210   }
6211
6212   SmallVector<int, 8> MaskVec;
6213   for (unsigned i = 0; i != NumElems; i += Scale) {
6214     int StartIdx = -1;
6215     for (unsigned j = 0; j != Scale; ++j) {
6216       int EltIdx = SVOp->getMaskElt(i+j);
6217       if (EltIdx < 0)
6218         continue;
6219       if (StartIdx < 0)
6220         StartIdx = (EltIdx / Scale);
6221       if (EltIdx != (int)(StartIdx*Scale + j))
6222         return SDValue();
6223     }
6224     MaskVec.push_back(StartIdx);
6225   }
6226
6227   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6228   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6229   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6230 }
6231
6232 /// getVZextMovL - Return a zero-extending vector move low node.
6233 ///
6234 static SDValue getVZextMovL(MVT VT, EVT OpVT,
6235                             SDValue SrcOp, SelectionDAG &DAG,
6236                             const X86Subtarget *Subtarget, DebugLoc dl) {
6237   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6238     LoadSDNode *LD = NULL;
6239     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6240       LD = dyn_cast<LoadSDNode>(SrcOp);
6241     if (!LD) {
6242       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6243       // instead.
6244       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6245       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6246           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6247           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6248           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6249         // PR2108
6250         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6251         return DAG.getNode(ISD::BITCAST, dl, VT,
6252                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6253                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6254                                                    OpVT,
6255                                                    SrcOp.getOperand(0)
6256                                                           .getOperand(0))));
6257       }
6258     }
6259   }
6260
6261   return DAG.getNode(ISD::BITCAST, dl, VT,
6262                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6263                                  DAG.getNode(ISD::BITCAST, dl,
6264                                              OpVT, SrcOp)));
6265 }
6266
6267 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6268 /// which could not be matched by any known target speficic shuffle
6269 static SDValue
6270 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6271
6272   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6273   if (NewOp.getNode())
6274     return NewOp;
6275
6276   MVT VT = SVOp->getValueType(0).getSimpleVT();
6277
6278   unsigned NumElems = VT.getVectorNumElements();
6279   unsigned NumLaneElems = NumElems / 2;
6280
6281   DebugLoc dl = SVOp->getDebugLoc();
6282   MVT EltVT = VT.getVectorElementType();
6283   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6284   SDValue Output[2];
6285
6286   SmallVector<int, 16> Mask;
6287   for (unsigned l = 0; l < 2; ++l) {
6288     // Build a shuffle mask for the output, discovering on the fly which
6289     // input vectors to use as shuffle operands (recorded in InputUsed).
6290     // If building a suitable shuffle vector proves too hard, then bail
6291     // out with UseBuildVector set.
6292     bool UseBuildVector = false;
6293     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6294     unsigned LaneStart = l * NumLaneElems;
6295     for (unsigned i = 0; i != NumLaneElems; ++i) {
6296       // The mask element.  This indexes into the input.
6297       int Idx = SVOp->getMaskElt(i+LaneStart);
6298       if (Idx < 0) {
6299         // the mask element does not index into any input vector.
6300         Mask.push_back(-1);
6301         continue;
6302       }
6303
6304       // The input vector this mask element indexes into.
6305       int Input = Idx / NumLaneElems;
6306
6307       // Turn the index into an offset from the start of the input vector.
6308       Idx -= Input * NumLaneElems;
6309
6310       // Find or create a shuffle vector operand to hold this input.
6311       unsigned OpNo;
6312       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6313         if (InputUsed[OpNo] == Input)
6314           // This input vector is already an operand.
6315           break;
6316         if (InputUsed[OpNo] < 0) {
6317           // Create a new operand for this input vector.
6318           InputUsed[OpNo] = Input;
6319           break;
6320         }
6321       }
6322
6323       if (OpNo >= array_lengthof(InputUsed)) {
6324         // More than two input vectors used!  Give up on trying to create a
6325         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6326         UseBuildVector = true;
6327         break;
6328       }
6329
6330       // Add the mask index for the new shuffle vector.
6331       Mask.push_back(Idx + OpNo * NumLaneElems);
6332     }
6333
6334     if (UseBuildVector) {
6335       SmallVector<SDValue, 16> SVOps;
6336       for (unsigned i = 0; i != NumLaneElems; ++i) {
6337         // The mask element.  This indexes into the input.
6338         int Idx = SVOp->getMaskElt(i+LaneStart);
6339         if (Idx < 0) {
6340           SVOps.push_back(DAG.getUNDEF(EltVT));
6341           continue;
6342         }
6343
6344         // The input vector this mask element indexes into.
6345         int Input = Idx / NumElems;
6346
6347         // Turn the index into an offset from the start of the input vector.
6348         Idx -= Input * NumElems;
6349
6350         // Extract the vector element by hand.
6351         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6352                                     SVOp->getOperand(Input),
6353                                     DAG.getIntPtrConstant(Idx)));
6354       }
6355
6356       // Construct the output using a BUILD_VECTOR.
6357       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6358                               SVOps.size());
6359     } else if (InputUsed[0] < 0) {
6360       // No input vectors were used! The result is undefined.
6361       Output[l] = DAG.getUNDEF(NVT);
6362     } else {
6363       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6364                                         (InputUsed[0] % 2) * NumLaneElems,
6365                                         DAG, dl);
6366       // If only one input was used, use an undefined vector for the other.
6367       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6368         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6369                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6370       // At least one input vector was used. Create a new shuffle vector.
6371       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6372     }
6373
6374     Mask.clear();
6375   }
6376
6377   // Concatenate the result back
6378   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6379 }
6380
6381 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6382 /// 4 elements, and match them with several different shuffle types.
6383 static SDValue
6384 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6385   SDValue V1 = SVOp->getOperand(0);
6386   SDValue V2 = SVOp->getOperand(1);
6387   DebugLoc dl = SVOp->getDebugLoc();
6388   MVT VT = SVOp->getValueType(0).getSimpleVT();
6389
6390   assert(VT.is128BitVector() && "Unsupported vector size");
6391
6392   std::pair<int, int> Locs[4];
6393   int Mask1[] = { -1, -1, -1, -1 };
6394   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6395
6396   unsigned NumHi = 0;
6397   unsigned NumLo = 0;
6398   for (unsigned i = 0; i != 4; ++i) {
6399     int Idx = PermMask[i];
6400     if (Idx < 0) {
6401       Locs[i] = std::make_pair(-1, -1);
6402     } else {
6403       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6404       if (Idx < 4) {
6405         Locs[i] = std::make_pair(0, NumLo);
6406         Mask1[NumLo] = Idx;
6407         NumLo++;
6408       } else {
6409         Locs[i] = std::make_pair(1, NumHi);
6410         if (2+NumHi < 4)
6411           Mask1[2+NumHi] = Idx;
6412         NumHi++;
6413       }
6414     }
6415   }
6416
6417   if (NumLo <= 2 && NumHi <= 2) {
6418     // If no more than two elements come from either vector. This can be
6419     // implemented with two shuffles. First shuffle gather the elements.
6420     // The second shuffle, which takes the first shuffle as both of its
6421     // vector operands, put the elements into the right order.
6422     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6423
6424     int Mask2[] = { -1, -1, -1, -1 };
6425
6426     for (unsigned i = 0; i != 4; ++i)
6427       if (Locs[i].first != -1) {
6428         unsigned Idx = (i < 2) ? 0 : 4;
6429         Idx += Locs[i].first * 2 + Locs[i].second;
6430         Mask2[i] = Idx;
6431       }
6432
6433     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6434   }
6435
6436   if (NumLo == 3 || NumHi == 3) {
6437     // Otherwise, we must have three elements from one vector, call it X, and
6438     // one element from the other, call it Y.  First, use a shufps to build an
6439     // intermediate vector with the one element from Y and the element from X
6440     // that will be in the same half in the final destination (the indexes don't
6441     // matter). Then, use a shufps to build the final vector, taking the half
6442     // containing the element from Y from the intermediate, and the other half
6443     // from X.
6444     if (NumHi == 3) {
6445       // Normalize it so the 3 elements come from V1.
6446       CommuteVectorShuffleMask(PermMask, 4);
6447       std::swap(V1, V2);
6448     }
6449
6450     // Find the element from V2.
6451     unsigned HiIndex;
6452     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6453       int Val = PermMask[HiIndex];
6454       if (Val < 0)
6455         continue;
6456       if (Val >= 4)
6457         break;
6458     }
6459
6460     Mask1[0] = PermMask[HiIndex];
6461     Mask1[1] = -1;
6462     Mask1[2] = PermMask[HiIndex^1];
6463     Mask1[3] = -1;
6464     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6465
6466     if (HiIndex >= 2) {
6467       Mask1[0] = PermMask[0];
6468       Mask1[1] = PermMask[1];
6469       Mask1[2] = HiIndex & 1 ? 6 : 4;
6470       Mask1[3] = HiIndex & 1 ? 4 : 6;
6471       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6472     }
6473
6474     Mask1[0] = HiIndex & 1 ? 2 : 0;
6475     Mask1[1] = HiIndex & 1 ? 0 : 2;
6476     Mask1[2] = PermMask[2];
6477     Mask1[3] = PermMask[3];
6478     if (Mask1[2] >= 0)
6479       Mask1[2] += 4;
6480     if (Mask1[3] >= 0)
6481       Mask1[3] += 4;
6482     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6483   }
6484
6485   // Break it into (shuffle shuffle_hi, shuffle_lo).
6486   int LoMask[] = { -1, -1, -1, -1 };
6487   int HiMask[] = { -1, -1, -1, -1 };
6488
6489   int *MaskPtr = LoMask;
6490   unsigned MaskIdx = 0;
6491   unsigned LoIdx = 0;
6492   unsigned HiIdx = 2;
6493   for (unsigned i = 0; i != 4; ++i) {
6494     if (i == 2) {
6495       MaskPtr = HiMask;
6496       MaskIdx = 1;
6497       LoIdx = 0;
6498       HiIdx = 2;
6499     }
6500     int Idx = PermMask[i];
6501     if (Idx < 0) {
6502       Locs[i] = std::make_pair(-1, -1);
6503     } else if (Idx < 4) {
6504       Locs[i] = std::make_pair(MaskIdx, LoIdx);
6505       MaskPtr[LoIdx] = Idx;
6506       LoIdx++;
6507     } else {
6508       Locs[i] = std::make_pair(MaskIdx, HiIdx);
6509       MaskPtr[HiIdx] = Idx;
6510       HiIdx++;
6511     }
6512   }
6513
6514   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6515   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6516   int MaskOps[] = { -1, -1, -1, -1 };
6517   for (unsigned i = 0; i != 4; ++i)
6518     if (Locs[i].first != -1)
6519       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6520   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6521 }
6522
6523 static bool MayFoldVectorLoad(SDValue V) {
6524   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6525     V = V.getOperand(0);
6526
6527   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6528     V = V.getOperand(0);
6529   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6530       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6531     // BUILD_VECTOR (load), undef
6532     V = V.getOperand(0);
6533
6534   return MayFoldLoad(V);
6535 }
6536
6537 static
6538 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6539   EVT VT = Op.getValueType();
6540
6541   // Canonizalize to v2f64.
6542   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6543   return DAG.getNode(ISD::BITCAST, dl, VT,
6544                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6545                                           V1, DAG));
6546 }
6547
6548 static
6549 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6550                         bool HasSSE2) {
6551   SDValue V1 = Op.getOperand(0);
6552   SDValue V2 = Op.getOperand(1);
6553   EVT VT = Op.getValueType();
6554
6555   assert(VT != MVT::v2i64 && "unsupported shuffle type");
6556
6557   if (HasSSE2 && VT == MVT::v2f64)
6558     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6559
6560   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6561   return DAG.getNode(ISD::BITCAST, dl, VT,
6562                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6563                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6564                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6565 }
6566
6567 static
6568 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6569   SDValue V1 = Op.getOperand(0);
6570   SDValue V2 = Op.getOperand(1);
6571   EVT VT = Op.getValueType();
6572
6573   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6574          "unsupported shuffle type");
6575
6576   if (V2.getOpcode() == ISD::UNDEF)
6577     V2 = V1;
6578
6579   // v4i32 or v4f32
6580   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6581 }
6582
6583 static
6584 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6585   SDValue V1 = Op.getOperand(0);
6586   SDValue V2 = Op.getOperand(1);
6587   EVT VT = Op.getValueType();
6588   unsigned NumElems = VT.getVectorNumElements();
6589
6590   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6591   // operand of these instructions is only memory, so check if there's a
6592   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6593   // same masks.
6594   bool CanFoldLoad = false;
6595
6596   // Trivial case, when V2 comes from a load.
6597   if (MayFoldVectorLoad(V2))
6598     CanFoldLoad = true;
6599
6600   // When V1 is a load, it can be folded later into a store in isel, example:
6601   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6602   //    turns into:
6603   //  (MOVLPSmr addr:$src1, VR128:$src2)
6604   // So, recognize this potential and also use MOVLPS or MOVLPD
6605   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6606     CanFoldLoad = true;
6607
6608   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6609   if (CanFoldLoad) {
6610     if (HasSSE2 && NumElems == 2)
6611       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6612
6613     if (NumElems == 4)
6614       // If we don't care about the second element, proceed to use movss.
6615       if (SVOp->getMaskElt(1) != -1)
6616         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6617   }
6618
6619   // movl and movlp will both match v2i64, but v2i64 is never matched by
6620   // movl earlier because we make it strict to avoid messing with the movlp load
6621   // folding logic (see the code above getMOVLP call). Match it here then,
6622   // this is horrible, but will stay like this until we move all shuffle
6623   // matching to x86 specific nodes. Note that for the 1st condition all
6624   // types are matched with movsd.
6625   if (HasSSE2) {
6626     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6627     // as to remove this logic from here, as much as possible
6628     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6629       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6630     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6631   }
6632
6633   assert(VT != MVT::v4i32 && "unsupported shuffle type");
6634
6635   // Invert the operand order and use SHUFPS to match it.
6636   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6637                               getShuffleSHUFImmediate(SVOp), DAG);
6638 }
6639
6640 // Reduce a vector shuffle to zext.
6641 SDValue
6642 X86TargetLowering::LowerVectorIntExtend(SDValue Op, SelectionDAG &DAG) const {
6643   // PMOVZX is only available from SSE41.
6644   if (!Subtarget->hasSSE41())
6645     return SDValue();
6646
6647   EVT VT = Op.getValueType();
6648
6649   // Only AVX2 support 256-bit vector integer extending.
6650   if (!Subtarget->hasInt256() && VT.is256BitVector())
6651     return SDValue();
6652
6653   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6654   DebugLoc DL = Op.getDebugLoc();
6655   SDValue V1 = Op.getOperand(0);
6656   SDValue V2 = Op.getOperand(1);
6657   unsigned NumElems = VT.getVectorNumElements();
6658
6659   // Extending is an unary operation and the element type of the source vector
6660   // won't be equal to or larger than i64.
6661   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
6662       VT.getVectorElementType() == MVT::i64)
6663     return SDValue();
6664
6665   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
6666   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
6667   while ((1U << Shift) < NumElems) {
6668     if (SVOp->getMaskElt(1U << Shift) == 1)
6669       break;
6670     Shift += 1;
6671     // The maximal ratio is 8, i.e. from i8 to i64.
6672     if (Shift > 3)
6673       return SDValue();
6674   }
6675
6676   // Check the shuffle mask.
6677   unsigned Mask = (1U << Shift) - 1;
6678   for (unsigned i = 0; i != NumElems; ++i) {
6679     int EltIdx = SVOp->getMaskElt(i);
6680     if ((i & Mask) != 0 && EltIdx != -1)
6681       return SDValue();
6682     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
6683       return SDValue();
6684   }
6685
6686   LLVMContext *Context = DAG.getContext();
6687   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
6688   EVT NeVT = EVT::getIntegerVT(*Context, NBits);
6689   EVT NVT = EVT::getVectorVT(*Context, NeVT, NumElems >> Shift);
6690
6691   if (!isTypeLegal(NVT))
6692     return SDValue();
6693
6694   // Simplify the operand as it's prepared to be fed into shuffle.
6695   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
6696   if (V1.getOpcode() == ISD::BITCAST &&
6697       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
6698       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6699       V1.getOperand(0)
6700         .getOperand(0).getValueType().getSizeInBits() == SignificantBits) {
6701     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
6702     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
6703     ConstantSDNode *CIdx =
6704       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
6705     // If it's foldable, i.e. normal load with single use, we will let code
6706     // selection to fold it. Otherwise, we will short the conversion sequence.
6707     if (CIdx && CIdx->getZExtValue() == 0 &&
6708         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
6709       if (V.getValueSizeInBits() > V1.getValueSizeInBits()) {
6710         // The "ext_vec_elt" node is wider than the result node.
6711         // In this case we should extract subvector from V.
6712         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
6713         unsigned Ratio = V.getValueSizeInBits() / V1.getValueSizeInBits();
6714         EVT FullVT = V.getValueType();
6715         EVT SubVecVT = EVT::getVectorVT(*Context, 
6716                                         FullVT.getVectorElementType(),
6717                                         FullVT.getVectorNumElements()/Ratio);
6718         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V, 
6719                         DAG.getIntPtrConstant(0));
6720       }
6721       V1 = DAG.getNode(ISD::BITCAST, DL, V1.getValueType(), V);
6722     }
6723   }
6724
6725   return DAG.getNode(ISD::BITCAST, DL, VT,
6726                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
6727 }
6728
6729 SDValue
6730 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6731   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6732   MVT VT = Op.getValueType().getSimpleVT();
6733   DebugLoc dl = Op.getDebugLoc();
6734   SDValue V1 = Op.getOperand(0);
6735   SDValue V2 = Op.getOperand(1);
6736
6737   if (isZeroShuffle(SVOp))
6738     return getZeroVector(VT, Subtarget, DAG, dl);
6739
6740   // Handle splat operations
6741   if (SVOp->isSplat()) {
6742     // Use vbroadcast whenever the splat comes from a foldable load
6743     SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6744     if (Broadcast.getNode())
6745       return Broadcast;
6746   }
6747
6748   // Check integer expanding shuffles.
6749   SDValue NewOp = LowerVectorIntExtend(Op, DAG);
6750   if (NewOp.getNode())
6751     return NewOp;
6752
6753   // If the shuffle can be profitably rewritten as a narrower shuffle, then
6754   // do it!
6755   if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
6756       VT == MVT::v16i16 || VT == MVT::v32i8) {
6757     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
6758     if (NewOp.getNode())
6759       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6760   } else if ((VT == MVT::v4i32 ||
6761              (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6762     // FIXME: Figure out a cleaner way to do this.
6763     // Try to make use of movq to zero out the top part.
6764     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6765       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
6766       if (NewOp.getNode()) {
6767         MVT NewVT = NewOp.getValueType().getSimpleVT();
6768         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6769                                NewVT, true, false))
6770           return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6771                               DAG, Subtarget, dl);
6772       }
6773     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6774       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
6775       if (NewOp.getNode()) {
6776         MVT NewVT = NewOp.getValueType().getSimpleVT();
6777         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6778           return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6779                               DAG, Subtarget, dl);
6780       }
6781     }
6782   }
6783   return SDValue();
6784 }
6785
6786 SDValue
6787 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6788   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6789   SDValue V1 = Op.getOperand(0);
6790   SDValue V2 = Op.getOperand(1);
6791   MVT VT = Op.getValueType().getSimpleVT();
6792   DebugLoc dl = Op.getDebugLoc();
6793   unsigned NumElems = VT.getVectorNumElements();
6794   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6795   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6796   bool V1IsSplat = false;
6797   bool V2IsSplat = false;
6798   bool HasSSE2 = Subtarget->hasSSE2();
6799   bool HasFp256    = Subtarget->hasFp256();
6800   bool HasInt256   = Subtarget->hasInt256();
6801   MachineFunction &MF = DAG.getMachineFunction();
6802   bool OptForSize = MF.getFunction()->getAttributes().
6803     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
6804
6805   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6806
6807   if (V1IsUndef && V2IsUndef)
6808     return DAG.getUNDEF(VT);
6809
6810   assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6811
6812   // Vector shuffle lowering takes 3 steps:
6813   //
6814   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6815   //    narrowing and commutation of operands should be handled.
6816   // 2) Matching of shuffles with known shuffle masks to x86 target specific
6817   //    shuffle nodes.
6818   // 3) Rewriting of unmatched masks into new generic shuffle operations,
6819   //    so the shuffle can be broken into other shuffles and the legalizer can
6820   //    try the lowering again.
6821   //
6822   // The general idea is that no vector_shuffle operation should be left to
6823   // be matched during isel, all of them must be converted to a target specific
6824   // node here.
6825
6826   // Normalize the input vectors. Here splats, zeroed vectors, profitable
6827   // narrowing and commutation of operands should be handled. The actual code
6828   // doesn't include all of those, work in progress...
6829   SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6830   if (NewOp.getNode())
6831     return NewOp;
6832
6833   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6834
6835   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6836   // unpckh_undef). Only use pshufd if speed is more important than size.
6837   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
6838     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6839   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
6840     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6841
6842   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6843       V2IsUndef && MayFoldVectorLoad(V1))
6844     return getMOVDDup(Op, dl, V1, DAG);
6845
6846   if (isMOVHLPS_v_undef_Mask(M, VT))
6847     return getMOVHighToLow(Op, dl, DAG);
6848
6849   // Use to match splats
6850   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
6851       (VT == MVT::v2f64 || VT == MVT::v2i64))
6852     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6853
6854   if (isPSHUFDMask(M, VT)) {
6855     // The actual implementation will match the mask in the if above and then
6856     // during isel it can match several different instructions, not only pshufd
6857     // as its name says, sad but true, emulate the behavior for now...
6858     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6859       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6860
6861     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6862
6863     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6864       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6865
6866     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
6867       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
6868                                   DAG);
6869
6870     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6871                                 TargetMask, DAG);
6872   }
6873
6874   // Check if this can be converted into a logical shift.
6875   bool isLeft = false;
6876   unsigned ShAmt = 0;
6877   SDValue ShVal;
6878   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6879   if (isShift && ShVal.hasOneUse()) {
6880     // If the shifted value has multiple uses, it may be cheaper to use
6881     // v_set0 + movlhps or movhlps, etc.
6882     MVT EltVT = VT.getVectorElementType();
6883     ShAmt *= EltVT.getSizeInBits();
6884     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6885   }
6886
6887   if (isMOVLMask(M, VT)) {
6888     if (ISD::isBuildVectorAllZeros(V1.getNode()))
6889       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6890     if (!isMOVLPMask(M, VT)) {
6891       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6892         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6893
6894       if (VT == MVT::v4i32 || VT == MVT::v4f32)
6895         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6896     }
6897   }
6898
6899   // FIXME: fold these into legal mask.
6900   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
6901     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6902
6903   if (isMOVHLPSMask(M, VT))
6904     return getMOVHighToLow(Op, dl, DAG);
6905
6906   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6907     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6908
6909   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6910     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6911
6912   if (isMOVLPMask(M, VT))
6913     return getMOVLP(Op, dl, DAG, HasSSE2);
6914
6915   if (ShouldXformToMOVHLPS(M, VT) ||
6916       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6917     return CommuteVectorShuffle(SVOp, DAG);
6918
6919   if (isShift) {
6920     // No better options. Use a vshldq / vsrldq.
6921     MVT EltVT = VT.getVectorElementType();
6922     ShAmt *= EltVT.getSizeInBits();
6923     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6924   }
6925
6926   bool Commuted = false;
6927   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
6928   // 1,1,1,1 -> v8i16 though.
6929   V1IsSplat = isSplatVector(V1.getNode());
6930   V2IsSplat = isSplatVector(V2.getNode());
6931
6932   // Canonicalize the splat or undef, if present, to be on the RHS.
6933   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6934     CommuteVectorShuffleMask(M, NumElems);
6935     std::swap(V1, V2);
6936     std::swap(V1IsSplat, V2IsSplat);
6937     Commuted = true;
6938   }
6939
6940   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6941     // Shuffling low element of v1 into undef, just return v1.
6942     if (V2IsUndef)
6943       return V1;
6944     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6945     // the instruction selector will not match, so get a canonical MOVL with
6946     // swapped operands to undo the commute.
6947     return getMOVL(DAG, dl, VT, V2, V1);
6948   }
6949
6950   if (isUNPCKLMask(M, VT, HasInt256))
6951     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6952
6953   if (isUNPCKHMask(M, VT, HasInt256))
6954     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6955
6956   if (V2IsSplat) {
6957     // Normalize mask so all entries that point to V2 points to its first
6958     // element then try to match unpck{h|l} again. If match, return a
6959     // new vector_shuffle with the corrected mask.p
6960     SmallVector<int, 8> NewMask(M.begin(), M.end());
6961     NormalizeMask(NewMask, NumElems);
6962     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
6963       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6964     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
6965       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6966   }
6967
6968   if (Commuted) {
6969     // Commute is back and try unpck* again.
6970     // FIXME: this seems wrong.
6971     CommuteVectorShuffleMask(M, NumElems);
6972     std::swap(V1, V2);
6973     std::swap(V1IsSplat, V2IsSplat);
6974     Commuted = false;
6975
6976     if (isUNPCKLMask(M, VT, HasInt256))
6977       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6978
6979     if (isUNPCKHMask(M, VT, HasInt256))
6980       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6981   }
6982
6983   // Normalize the node to match x86 shuffle ops if needed
6984   if (!V2IsUndef && (isSHUFPMask(M, VT, HasFp256, /* Commuted */ true)))
6985     return CommuteVectorShuffle(SVOp, DAG);
6986
6987   // The checks below are all present in isShuffleMaskLegal, but they are
6988   // inlined here right now to enable us to directly emit target specific
6989   // nodes, and remove one by one until they don't return Op anymore.
6990
6991   if (isPALIGNRMask(M, VT, Subtarget))
6992     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
6993                                 getShufflePALIGNRImmediate(SVOp),
6994                                 DAG);
6995
6996   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6997       SVOp->getSplatIndex() == 0 && V2IsUndef) {
6998     if (VT == MVT::v2f64 || VT == MVT::v2i64)
6999       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7000   }
7001
7002   if (isPSHUFHWMask(M, VT, HasInt256))
7003     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7004                                 getShufflePSHUFHWImmediate(SVOp),
7005                                 DAG);
7006
7007   if (isPSHUFLWMask(M, VT, HasInt256))
7008     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7009                                 getShufflePSHUFLWImmediate(SVOp),
7010                                 DAG);
7011
7012   if (isSHUFPMask(M, VT, HasFp256))
7013     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7014                                 getShuffleSHUFImmediate(SVOp), DAG);
7015
7016   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7017     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7018   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7019     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7020
7021   //===--------------------------------------------------------------------===//
7022   // Generate target specific nodes for 128 or 256-bit shuffles only
7023   // supported in the AVX instruction set.
7024   //
7025
7026   // Handle VMOVDDUPY permutations
7027   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7028     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7029
7030   // Handle VPERMILPS/D* permutations
7031   if (isVPERMILPMask(M, VT, HasFp256)) {
7032     if (HasInt256 && VT == MVT::v8i32)
7033       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7034                                   getShuffleSHUFImmediate(SVOp), DAG);
7035     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7036                                 getShuffleSHUFImmediate(SVOp), DAG);
7037   }
7038
7039   // Handle VPERM2F128/VPERM2I128 permutations
7040   if (isVPERM2X128Mask(M, VT, HasFp256))
7041     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7042                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7043
7044   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7045   if (BlendOp.getNode())
7046     return BlendOp;
7047
7048   if (V2IsUndef && HasInt256 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
7049     SmallVector<SDValue, 8> permclMask;
7050     for (unsigned i = 0; i != 8; ++i) {
7051       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
7052     }
7053     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
7054                                &permclMask[0], 8);
7055     // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7056     return DAG.getNode(X86ISD::VPERMV, dl, VT,
7057                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7058   }
7059
7060   if (V2IsUndef && HasInt256 && (VT == MVT::v4i64 || VT == MVT::v4f64))
7061     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
7062                                 getShuffleCLImmediate(SVOp), DAG);
7063
7064   //===--------------------------------------------------------------------===//
7065   // Since no target specific shuffle was selected for this generic one,
7066   // lower it into other known shuffles. FIXME: this isn't true yet, but
7067   // this is the plan.
7068   //
7069
7070   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7071   if (VT == MVT::v8i16) {
7072     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7073     if (NewOp.getNode())
7074       return NewOp;
7075   }
7076
7077   if (VT == MVT::v16i8) {
7078     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
7079     if (NewOp.getNode())
7080       return NewOp;
7081   }
7082
7083   if (VT == MVT::v32i8) {
7084     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7085     if (NewOp.getNode())
7086       return NewOp;
7087   }
7088
7089   // Handle all 128-bit wide vectors with 4 elements, and match them with
7090   // several different shuffle types.
7091   if (NumElems == 4 && VT.is128BitVector())
7092     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7093
7094   // Handle general 256-bit shuffles
7095   if (VT.is256BitVector())
7096     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7097
7098   return SDValue();
7099 }
7100
7101 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7102   MVT VT = Op.getValueType().getSimpleVT();
7103   DebugLoc dl = Op.getDebugLoc();
7104
7105   if (!Op.getOperand(0).getValueType().getSimpleVT().is128BitVector())
7106     return SDValue();
7107
7108   if (VT.getSizeInBits() == 8) {
7109     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7110                                   Op.getOperand(0), Op.getOperand(1));
7111     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7112                                   DAG.getValueType(VT));
7113     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7114   }
7115
7116   if (VT.getSizeInBits() == 16) {
7117     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7118     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7119     if (Idx == 0)
7120       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7121                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7122                                      DAG.getNode(ISD::BITCAST, dl,
7123                                                  MVT::v4i32,
7124                                                  Op.getOperand(0)),
7125                                      Op.getOperand(1)));
7126     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7127                                   Op.getOperand(0), Op.getOperand(1));
7128     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7129                                   DAG.getValueType(VT));
7130     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7131   }
7132
7133   if (VT == MVT::f32) {
7134     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7135     // the result back to FR32 register. It's only worth matching if the
7136     // result has a single use which is a store or a bitcast to i32.  And in
7137     // the case of a store, it's not worth it if the index is a constant 0,
7138     // because a MOVSSmr can be used instead, which is smaller and faster.
7139     if (!Op.hasOneUse())
7140       return SDValue();
7141     SDNode *User = *Op.getNode()->use_begin();
7142     if ((User->getOpcode() != ISD::STORE ||
7143          (isa<ConstantSDNode>(Op.getOperand(1)) &&
7144           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7145         (User->getOpcode() != ISD::BITCAST ||
7146          User->getValueType(0) != MVT::i32))
7147       return SDValue();
7148     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7149                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7150                                               Op.getOperand(0)),
7151                                               Op.getOperand(1));
7152     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7153   }
7154
7155   if (VT == MVT::i32 || VT == MVT::i64) {
7156     // ExtractPS/pextrq works with constant index.
7157     if (isa<ConstantSDNode>(Op.getOperand(1)))
7158       return Op;
7159   }
7160   return SDValue();
7161 }
7162
7163 SDValue
7164 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7165                                            SelectionDAG &DAG) const {
7166   if (!isa<ConstantSDNode>(Op.getOperand(1)))
7167     return SDValue();
7168
7169   SDValue Vec = Op.getOperand(0);
7170   MVT VecVT = Vec.getValueType().getSimpleVT();
7171
7172   // If this is a 256-bit vector result, first extract the 128-bit vector and
7173   // then extract the element from the 128-bit vector.
7174   if (VecVT.is256BitVector()) {
7175     DebugLoc dl = Op.getNode()->getDebugLoc();
7176     unsigned NumElems = VecVT.getVectorNumElements();
7177     SDValue Idx = Op.getOperand(1);
7178     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7179
7180     // Get the 128-bit vector.
7181     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7182
7183     if (IdxVal >= NumElems/2)
7184       IdxVal -= NumElems/2;
7185     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7186                        DAG.getConstant(IdxVal, MVT::i32));
7187   }
7188
7189   assert(VecVT.is128BitVector() && "Unexpected vector length");
7190
7191   if (Subtarget->hasSSE41()) {
7192     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7193     if (Res.getNode())
7194       return Res;
7195   }
7196
7197   MVT VT = Op.getValueType().getSimpleVT();
7198   DebugLoc dl = Op.getDebugLoc();
7199   // TODO: handle v16i8.
7200   if (VT.getSizeInBits() == 16) {
7201     SDValue Vec = Op.getOperand(0);
7202     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7203     if (Idx == 0)
7204       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7205                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7206                                      DAG.getNode(ISD::BITCAST, dl,
7207                                                  MVT::v4i32, Vec),
7208                                      Op.getOperand(1)));
7209     // Transform it so it match pextrw which produces a 32-bit result.
7210     MVT EltVT = MVT::i32;
7211     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7212                                   Op.getOperand(0), Op.getOperand(1));
7213     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7214                                   DAG.getValueType(VT));
7215     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7216   }
7217
7218   if (VT.getSizeInBits() == 32) {
7219     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7220     if (Idx == 0)
7221       return Op;
7222
7223     // SHUFPS the element to the lowest double word, then movss.
7224     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7225     MVT VVT = Op.getOperand(0).getValueType().getSimpleVT();
7226     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7227                                        DAG.getUNDEF(VVT), Mask);
7228     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7229                        DAG.getIntPtrConstant(0));
7230   }
7231
7232   if (VT.getSizeInBits() == 64) {
7233     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7234     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7235     //        to match extract_elt for f64.
7236     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7237     if (Idx == 0)
7238       return Op;
7239
7240     // UNPCKHPD the element to the lowest double word, then movsd.
7241     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7242     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7243     int Mask[2] = { 1, -1 };
7244     MVT VVT = Op.getOperand(0).getValueType().getSimpleVT();
7245     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7246                                        DAG.getUNDEF(VVT), Mask);
7247     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7248                        DAG.getIntPtrConstant(0));
7249   }
7250
7251   return SDValue();
7252 }
7253
7254 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7255   MVT VT = Op.getValueType().getSimpleVT();
7256   MVT EltVT = VT.getVectorElementType();
7257   DebugLoc dl = Op.getDebugLoc();
7258
7259   SDValue N0 = Op.getOperand(0);
7260   SDValue N1 = Op.getOperand(1);
7261   SDValue N2 = Op.getOperand(2);
7262
7263   if (!VT.is128BitVector())
7264     return SDValue();
7265
7266   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7267       isa<ConstantSDNode>(N2)) {
7268     unsigned Opc;
7269     if (VT == MVT::v8i16)
7270       Opc = X86ISD::PINSRW;
7271     else if (VT == MVT::v16i8)
7272       Opc = X86ISD::PINSRB;
7273     else
7274       Opc = X86ISD::PINSRB;
7275
7276     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7277     // argument.
7278     if (N1.getValueType() != MVT::i32)
7279       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7280     if (N2.getValueType() != MVT::i32)
7281       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7282     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7283   }
7284
7285   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7286     // Bits [7:6] of the constant are the source select.  This will always be
7287     //  zero here.  The DAG Combiner may combine an extract_elt index into these
7288     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
7289     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
7290     // Bits [5:4] of the constant are the destination select.  This is the
7291     //  value of the incoming immediate.
7292     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
7293     //   combine either bitwise AND or insert of float 0.0 to set these bits.
7294     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7295     // Create this as a scalar to vector..
7296     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7297     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7298   }
7299
7300   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7301     // PINSR* works with constant index.
7302     return Op;
7303   }
7304   return SDValue();
7305 }
7306
7307 SDValue
7308 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7309   MVT VT = Op.getValueType().getSimpleVT();
7310   MVT EltVT = VT.getVectorElementType();
7311
7312   DebugLoc dl = Op.getDebugLoc();
7313   SDValue N0 = Op.getOperand(0);
7314   SDValue N1 = Op.getOperand(1);
7315   SDValue N2 = Op.getOperand(2);
7316
7317   // If this is a 256-bit vector result, first extract the 128-bit vector,
7318   // insert the element into the extracted half and then place it back.
7319   if (VT.is256BitVector()) {
7320     if (!isa<ConstantSDNode>(N2))
7321       return SDValue();
7322
7323     // Get the desired 128-bit vector half.
7324     unsigned NumElems = VT.getVectorNumElements();
7325     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7326     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7327
7328     // Insert the element into the desired half.
7329     bool Upper = IdxVal >= NumElems/2;
7330     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7331                  DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
7332
7333     // Insert the changed part back to the 256-bit vector
7334     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7335   }
7336
7337   if (Subtarget->hasSSE41())
7338     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7339
7340   if (EltVT == MVT::i8)
7341     return SDValue();
7342
7343   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7344     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7345     // as its second argument.
7346     if (N1.getValueType() != MVT::i32)
7347       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7348     if (N2.getValueType() != MVT::i32)
7349       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7350     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7351   }
7352   return SDValue();
7353 }
7354
7355 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7356   LLVMContext *Context = DAG.getContext();
7357   DebugLoc dl = Op.getDebugLoc();
7358   MVT OpVT = Op.getValueType().getSimpleVT();
7359
7360   // If this is a 256-bit vector result, first insert into a 128-bit
7361   // vector and then insert into the 256-bit vector.
7362   if (!OpVT.is128BitVector()) {
7363     // Insert into a 128-bit vector.
7364     EVT VT128 = EVT::getVectorVT(*Context,
7365                                  OpVT.getVectorElementType(),
7366                                  OpVT.getVectorNumElements() / 2);
7367
7368     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7369
7370     // Insert the 128-bit vector.
7371     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7372   }
7373
7374   if (OpVT == MVT::v1i64 &&
7375       Op.getOperand(0).getValueType() == MVT::i64)
7376     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7377
7378   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7379   assert(OpVT.is128BitVector() && "Expected an SSE type!");
7380   return DAG.getNode(ISD::BITCAST, dl, OpVT,
7381                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7382 }
7383
7384 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7385 // a simple subregister reference or explicit instructions to grab
7386 // upper bits of a vector.
7387 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7388                                       SelectionDAG &DAG) {
7389   if (Subtarget->hasFp256()) {
7390     DebugLoc dl = Op.getNode()->getDebugLoc();
7391     SDValue Vec = Op.getNode()->getOperand(0);
7392     SDValue Idx = Op.getNode()->getOperand(1);
7393
7394     if (Op.getNode()->getValueType(0).is128BitVector() &&
7395         Vec.getNode()->getValueType(0).is256BitVector() &&
7396         isa<ConstantSDNode>(Idx)) {
7397       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7398       return Extract128BitVector(Vec, IdxVal, DAG, dl);
7399     }
7400   }
7401   return SDValue();
7402 }
7403
7404 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7405 // simple superregister reference or explicit instructions to insert
7406 // the upper bits of a vector.
7407 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7408                                      SelectionDAG &DAG) {
7409   if (Subtarget->hasFp256()) {
7410     DebugLoc dl = Op.getNode()->getDebugLoc();
7411     SDValue Vec = Op.getNode()->getOperand(0);
7412     SDValue SubVec = Op.getNode()->getOperand(1);
7413     SDValue Idx = Op.getNode()->getOperand(2);
7414
7415     if (Op.getNode()->getValueType(0).is256BitVector() &&
7416         SubVec.getNode()->getValueType(0).is128BitVector() &&
7417         isa<ConstantSDNode>(Idx)) {
7418       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7419       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7420     }
7421   }
7422   return SDValue();
7423 }
7424
7425 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7426 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7427 // one of the above mentioned nodes. It has to be wrapped because otherwise
7428 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7429 // be used to form addressing mode. These wrapped nodes will be selected
7430 // into MOV32ri.
7431 SDValue
7432 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7433   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7434
7435   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7436   // global base reg.
7437   unsigned char OpFlag = 0;
7438   unsigned WrapperKind = X86ISD::Wrapper;
7439   CodeModel::Model M = getTargetMachine().getCodeModel();
7440
7441   if (Subtarget->isPICStyleRIPRel() &&
7442       (M == CodeModel::Small || M == CodeModel::Kernel))
7443     WrapperKind = X86ISD::WrapperRIP;
7444   else if (Subtarget->isPICStyleGOT())
7445     OpFlag = X86II::MO_GOTOFF;
7446   else if (Subtarget->isPICStyleStubPIC())
7447     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7448
7449   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7450                                              CP->getAlignment(),
7451                                              CP->getOffset(), OpFlag);
7452   DebugLoc DL = CP->getDebugLoc();
7453   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7454   // With PIC, the address is actually $g + Offset.
7455   if (OpFlag) {
7456     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7457                          DAG.getNode(X86ISD::GlobalBaseReg,
7458                                      DebugLoc(), getPointerTy()),
7459                          Result);
7460   }
7461
7462   return Result;
7463 }
7464
7465 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7466   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7467
7468   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7469   // global base reg.
7470   unsigned char OpFlag = 0;
7471   unsigned WrapperKind = X86ISD::Wrapper;
7472   CodeModel::Model M = getTargetMachine().getCodeModel();
7473
7474   if (Subtarget->isPICStyleRIPRel() &&
7475       (M == CodeModel::Small || M == CodeModel::Kernel))
7476     WrapperKind = X86ISD::WrapperRIP;
7477   else if (Subtarget->isPICStyleGOT())
7478     OpFlag = X86II::MO_GOTOFF;
7479   else if (Subtarget->isPICStyleStubPIC())
7480     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7481
7482   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7483                                           OpFlag);
7484   DebugLoc DL = JT->getDebugLoc();
7485   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7486
7487   // With PIC, the address is actually $g + Offset.
7488   if (OpFlag)
7489     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7490                          DAG.getNode(X86ISD::GlobalBaseReg,
7491                                      DebugLoc(), getPointerTy()),
7492                          Result);
7493
7494   return Result;
7495 }
7496
7497 SDValue
7498 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7499   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7500
7501   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7502   // global base reg.
7503   unsigned char OpFlag = 0;
7504   unsigned WrapperKind = X86ISD::Wrapper;
7505   CodeModel::Model M = getTargetMachine().getCodeModel();
7506
7507   if (Subtarget->isPICStyleRIPRel() &&
7508       (M == CodeModel::Small || M == CodeModel::Kernel)) {
7509     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7510       OpFlag = X86II::MO_GOTPCREL;
7511     WrapperKind = X86ISD::WrapperRIP;
7512   } else if (Subtarget->isPICStyleGOT()) {
7513     OpFlag = X86II::MO_GOT;
7514   } else if (Subtarget->isPICStyleStubPIC()) {
7515     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7516   } else if (Subtarget->isPICStyleStubNoDynamic()) {
7517     OpFlag = X86II::MO_DARWIN_NONLAZY;
7518   }
7519
7520   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7521
7522   DebugLoc DL = Op.getDebugLoc();
7523   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7524
7525   // With PIC, the address is actually $g + Offset.
7526   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7527       !Subtarget->is64Bit()) {
7528     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7529                          DAG.getNode(X86ISD::GlobalBaseReg,
7530                                      DebugLoc(), getPointerTy()),
7531                          Result);
7532   }
7533
7534   // For symbols that require a load from a stub to get the address, emit the
7535   // load.
7536   if (isGlobalStubReference(OpFlag))
7537     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7538                          MachinePointerInfo::getGOT(), false, false, false, 0);
7539
7540   return Result;
7541 }
7542
7543 SDValue
7544 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7545   // Create the TargetBlockAddressAddress node.
7546   unsigned char OpFlags =
7547     Subtarget->ClassifyBlockAddressReference();
7548   CodeModel::Model M = getTargetMachine().getCodeModel();
7549   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7550   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
7551   DebugLoc dl = Op.getDebugLoc();
7552   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
7553                                              OpFlags);
7554
7555   if (Subtarget->isPICStyleRIPRel() &&
7556       (M == CodeModel::Small || M == CodeModel::Kernel))
7557     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7558   else
7559     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7560
7561   // With PIC, the address is actually $g + Offset.
7562   if (isGlobalRelativeToPICBase(OpFlags)) {
7563     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7564                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7565                          Result);
7566   }
7567
7568   return Result;
7569 }
7570
7571 SDValue
7572 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7573                                       int64_t Offset, SelectionDAG &DAG) const {
7574   // Create the TargetGlobalAddress node, folding in the constant
7575   // offset if it is legal.
7576   unsigned char OpFlags =
7577     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7578   CodeModel::Model M = getTargetMachine().getCodeModel();
7579   SDValue Result;
7580   if (OpFlags == X86II::MO_NO_FLAG &&
7581       X86::isOffsetSuitableForCodeModel(Offset, M)) {
7582     // A direct static reference to a global.
7583     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7584     Offset = 0;
7585   } else {
7586     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7587   }
7588
7589   if (Subtarget->isPICStyleRIPRel() &&
7590       (M == CodeModel::Small || M == CodeModel::Kernel))
7591     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7592   else
7593     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7594
7595   // With PIC, the address is actually $g + Offset.
7596   if (isGlobalRelativeToPICBase(OpFlags)) {
7597     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7598                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7599                          Result);
7600   }
7601
7602   // For globals that require a load from a stub to get the address, emit the
7603   // load.
7604   if (isGlobalStubReference(OpFlags))
7605     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7606                          MachinePointerInfo::getGOT(), false, false, false, 0);
7607
7608   // If there was a non-zero offset that we didn't fold, create an explicit
7609   // addition for it.
7610   if (Offset != 0)
7611     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7612                          DAG.getConstant(Offset, getPointerTy()));
7613
7614   return Result;
7615 }
7616
7617 SDValue
7618 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7619   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7620   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7621   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7622 }
7623
7624 static SDValue
7625 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7626            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7627            unsigned char OperandFlags, bool LocalDynamic = false) {
7628   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7629   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7630   DebugLoc dl = GA->getDebugLoc();
7631   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7632                                            GA->getValueType(0),
7633                                            GA->getOffset(),
7634                                            OperandFlags);
7635
7636   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7637                                            : X86ISD::TLSADDR;
7638
7639   if (InFlag) {
7640     SDValue Ops[] = { Chain,  TGA, *InFlag };
7641     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
7642   } else {
7643     SDValue Ops[]  = { Chain, TGA };
7644     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
7645   }
7646
7647   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7648   MFI->setAdjustsStack(true);
7649
7650   SDValue Flag = Chain.getValue(1);
7651   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7652 }
7653
7654 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7655 static SDValue
7656 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7657                                 const EVT PtrVT) {
7658   SDValue InFlag;
7659   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
7660   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7661                                    DAG.getNode(X86ISD::GlobalBaseReg,
7662                                                DebugLoc(), PtrVT), InFlag);
7663   InFlag = Chain.getValue(1);
7664
7665   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7666 }
7667
7668 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7669 static SDValue
7670 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7671                                 const EVT PtrVT) {
7672   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7673                     X86::RAX, X86II::MO_TLSGD);
7674 }
7675
7676 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7677                                            SelectionDAG &DAG,
7678                                            const EVT PtrVT,
7679                                            bool is64Bit) {
7680   DebugLoc dl = GA->getDebugLoc();
7681
7682   // Get the start address of the TLS block for this module.
7683   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7684       .getInfo<X86MachineFunctionInfo>();
7685   MFI->incNumLocalDynamicTLSAccesses();
7686
7687   SDValue Base;
7688   if (is64Bit) {
7689     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7690                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
7691   } else {
7692     SDValue InFlag;
7693     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7694         DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), InFlag);
7695     InFlag = Chain.getValue(1);
7696     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7697                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7698   }
7699
7700   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7701   // of Base.
7702
7703   // Build x@dtpoff.
7704   unsigned char OperandFlags = X86II::MO_DTPOFF;
7705   unsigned WrapperKind = X86ISD::Wrapper;
7706   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7707                                            GA->getValueType(0),
7708                                            GA->getOffset(), OperandFlags);
7709   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7710
7711   // Add x@dtpoff with the base.
7712   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7713 }
7714
7715 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7716 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7717                                    const EVT PtrVT, TLSModel::Model model,
7718                                    bool is64Bit, bool isPIC) {
7719   DebugLoc dl = GA->getDebugLoc();
7720
7721   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7722   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7723                                                          is64Bit ? 257 : 256));
7724
7725   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7726                                       DAG.getIntPtrConstant(0),
7727                                       MachinePointerInfo(Ptr),
7728                                       false, false, false, 0);
7729
7730   unsigned char OperandFlags = 0;
7731   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
7732   // initialexec.
7733   unsigned WrapperKind = X86ISD::Wrapper;
7734   if (model == TLSModel::LocalExec) {
7735     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7736   } else if (model == TLSModel::InitialExec) {
7737     if (is64Bit) {
7738       OperandFlags = X86II::MO_GOTTPOFF;
7739       WrapperKind = X86ISD::WrapperRIP;
7740     } else {
7741       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7742     }
7743   } else {
7744     llvm_unreachable("Unexpected model");
7745   }
7746
7747   // emit "addl x@ntpoff,%eax" (local exec)
7748   // or "addl x@indntpoff,%eax" (initial exec)
7749   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7750   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7751                                            GA->getValueType(0),
7752                                            GA->getOffset(), OperandFlags);
7753   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7754
7755   if (model == TLSModel::InitialExec) {
7756     if (isPIC && !is64Bit) {
7757       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7758                           DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT),
7759                            Offset);
7760     }
7761
7762     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7763                          MachinePointerInfo::getGOT(), false, false, false,
7764                          0);
7765   }
7766
7767   // The address of the thread local variable is the add of the thread
7768   // pointer with the offset of the variable.
7769   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7770 }
7771
7772 SDValue
7773 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7774
7775   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7776   const GlobalValue *GV = GA->getGlobal();
7777
7778   if (Subtarget->isTargetELF()) {
7779     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7780
7781     switch (model) {
7782       case TLSModel::GeneralDynamic:
7783         if (Subtarget->is64Bit())
7784           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7785         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7786       case TLSModel::LocalDynamic:
7787         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7788                                            Subtarget->is64Bit());
7789       case TLSModel::InitialExec:
7790       case TLSModel::LocalExec:
7791         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7792                                    Subtarget->is64Bit(),
7793                         getTargetMachine().getRelocationModel() == Reloc::PIC_);
7794     }
7795     llvm_unreachable("Unknown TLS model.");
7796   }
7797
7798   if (Subtarget->isTargetDarwin()) {
7799     // Darwin only has one model of TLS.  Lower to that.
7800     unsigned char OpFlag = 0;
7801     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7802                            X86ISD::WrapperRIP : X86ISD::Wrapper;
7803
7804     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7805     // global base reg.
7806     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7807                   !Subtarget->is64Bit();
7808     if (PIC32)
7809       OpFlag = X86II::MO_TLVP_PIC_BASE;
7810     else
7811       OpFlag = X86II::MO_TLVP;
7812     DebugLoc DL = Op.getDebugLoc();
7813     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7814                                                 GA->getValueType(0),
7815                                                 GA->getOffset(), OpFlag);
7816     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7817
7818     // With PIC32, the address is actually $g + Offset.
7819     if (PIC32)
7820       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7821                            DAG.getNode(X86ISD::GlobalBaseReg,
7822                                        DebugLoc(), getPointerTy()),
7823                            Offset);
7824
7825     // Lowering the machine isd will make sure everything is in the right
7826     // location.
7827     SDValue Chain = DAG.getEntryNode();
7828     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7829     SDValue Args[] = { Chain, Offset };
7830     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7831
7832     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7833     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7834     MFI->setAdjustsStack(true);
7835
7836     // And our return value (tls address) is in the standard call return value
7837     // location.
7838     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7839     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7840                               Chain.getValue(1));
7841   }
7842
7843   if (Subtarget->isTargetWindows() || Subtarget->isTargetMingw()) {
7844     // Just use the implicit TLS architecture
7845     // Need to generate someting similar to:
7846     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7847     //                                  ; from TEB
7848     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
7849     //   mov     rcx, qword [rdx+rcx*8]
7850     //   mov     eax, .tls$:tlsvar
7851     //   [rax+rcx] contains the address
7852     // Windows 64bit: gs:0x58
7853     // Windows 32bit: fs:__tls_array
7854
7855     // If GV is an alias then use the aliasee for determining
7856     // thread-localness.
7857     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7858       GV = GA->resolveAliasedGlobal(false);
7859     DebugLoc dl = GA->getDebugLoc();
7860     SDValue Chain = DAG.getEntryNode();
7861
7862     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7863     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
7864     // use its literal value of 0x2C.
7865     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7866                                         ? Type::getInt8PtrTy(*DAG.getContext(),
7867                                                              256)
7868                                         : Type::getInt32PtrTy(*DAG.getContext(),
7869                                                               257));
7870
7871     SDValue TlsArray = Subtarget->is64Bit() ? DAG.getIntPtrConstant(0x58) :
7872       (Subtarget->isTargetMingw() ? DAG.getIntPtrConstant(0x2C) :
7873         DAG.getExternalSymbol("_tls_array", getPointerTy()));
7874
7875     SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
7876                                         MachinePointerInfo(Ptr),
7877                                         false, false, false, 0);
7878
7879     // Load the _tls_index variable
7880     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7881     if (Subtarget->is64Bit())
7882       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7883                            IDX, MachinePointerInfo(), MVT::i32,
7884                            false, false, 0);
7885     else
7886       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7887                         false, false, false, 0);
7888
7889     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
7890                                     getPointerTy());
7891     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7892
7893     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7894     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7895                       false, false, false, 0);
7896
7897     // Get the offset of start of .tls section
7898     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7899                                              GA->getValueType(0),
7900                                              GA->getOffset(), X86II::MO_SECREL);
7901     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7902
7903     // The address of the thread local variable is the add of the thread
7904     // pointer with the offset of the variable.
7905     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7906   }
7907
7908   llvm_unreachable("TLS not implemented for this target.");
7909 }
7910
7911 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7912 /// and take a 2 x i32 value to shift plus a shift amount.
7913 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7914   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7915   EVT VT = Op.getValueType();
7916   unsigned VTBits = VT.getSizeInBits();
7917   DebugLoc dl = Op.getDebugLoc();
7918   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7919   SDValue ShOpLo = Op.getOperand(0);
7920   SDValue ShOpHi = Op.getOperand(1);
7921   SDValue ShAmt  = Op.getOperand(2);
7922   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7923                                      DAG.getConstant(VTBits - 1, MVT::i8))
7924                        : DAG.getConstant(0, VT);
7925
7926   SDValue Tmp2, Tmp3;
7927   if (Op.getOpcode() == ISD::SHL_PARTS) {
7928     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7929     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7930   } else {
7931     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7932     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7933   }
7934
7935   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7936                                 DAG.getConstant(VTBits, MVT::i8));
7937   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7938                              AndNode, DAG.getConstant(0, MVT::i8));
7939
7940   SDValue Hi, Lo;
7941   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7942   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7943   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7944
7945   if (Op.getOpcode() == ISD::SHL_PARTS) {
7946     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7947     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7948   } else {
7949     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7950     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7951   }
7952
7953   SDValue Ops[2] = { Lo, Hi };
7954   return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
7955 }
7956
7957 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7958                                            SelectionDAG &DAG) const {
7959   EVT SrcVT = Op.getOperand(0).getValueType();
7960
7961   if (SrcVT.isVector())
7962     return SDValue();
7963
7964   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7965          "Unknown SINT_TO_FP to lower!");
7966
7967   // These are really Legal; return the operand so the caller accepts it as
7968   // Legal.
7969   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7970     return Op;
7971   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7972       Subtarget->is64Bit()) {
7973     return Op;
7974   }
7975
7976   DebugLoc dl = Op.getDebugLoc();
7977   unsigned Size = SrcVT.getSizeInBits()/8;
7978   MachineFunction &MF = DAG.getMachineFunction();
7979   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7980   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7981   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7982                                StackSlot,
7983                                MachinePointerInfo::getFixedStack(SSFI),
7984                                false, false, 0);
7985   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7986 }
7987
7988 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7989                                      SDValue StackSlot,
7990                                      SelectionDAG &DAG) const {
7991   // Build the FILD
7992   DebugLoc DL = Op.getDebugLoc();
7993   SDVTList Tys;
7994   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7995   if (useSSE)
7996     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7997   else
7998     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7999
8000   unsigned ByteSize = SrcVT.getSizeInBits()/8;
8001
8002   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
8003   MachineMemOperand *MMO;
8004   if (FI) {
8005     int SSFI = FI->getIndex();
8006     MMO =
8007       DAG.getMachineFunction()
8008       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8009                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
8010   } else {
8011     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
8012     StackSlot = StackSlot.getOperand(1);
8013   }
8014   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
8015   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
8016                                            X86ISD::FILD, DL,
8017                                            Tys, Ops, array_lengthof(Ops),
8018                                            SrcVT, MMO);
8019
8020   if (useSSE) {
8021     Chain = Result.getValue(1);
8022     SDValue InFlag = Result.getValue(2);
8023
8024     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
8025     // shouldn't be necessary except that RFP cannot be live across
8026     // multiple blocks. When stackifier is fixed, they can be uncoupled.
8027     MachineFunction &MF = DAG.getMachineFunction();
8028     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
8029     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
8030     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8031     Tys = DAG.getVTList(MVT::Other);
8032     SDValue Ops[] = {
8033       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
8034     };
8035     MachineMemOperand *MMO =
8036       DAG.getMachineFunction()
8037       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8038                             MachineMemOperand::MOStore, SSFISize, SSFISize);
8039
8040     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
8041                                     Ops, array_lengthof(Ops),
8042                                     Op.getValueType(), MMO);
8043     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
8044                          MachinePointerInfo::getFixedStack(SSFI),
8045                          false, false, false, 0);
8046   }
8047
8048   return Result;
8049 }
8050
8051 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
8052 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
8053                                                SelectionDAG &DAG) const {
8054   // This algorithm is not obvious. Here it is what we're trying to output:
8055   /*
8056      movq       %rax,  %xmm0
8057      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
8058      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8059      #ifdef __SSE3__
8060        haddpd   %xmm0, %xmm0
8061      #else
8062        pshufd   $0x4e, %xmm0, %xmm1
8063        addpd    %xmm1, %xmm0
8064      #endif
8065   */
8066
8067   DebugLoc dl = Op.getDebugLoc();
8068   LLVMContext *Context = DAG.getContext();
8069
8070   // Build some magic constants.
8071   const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8072   Constant *C0 = ConstantDataVector::get(*Context, CV0);
8073   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8074
8075   SmallVector<Constant*,2> CV1;
8076   CV1.push_back(
8077     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8078                                       APInt(64, 0x4330000000000000ULL))));
8079   CV1.push_back(
8080     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8081                                       APInt(64, 0x4530000000000000ULL))));
8082   Constant *C1 = ConstantVector::get(CV1);
8083   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8084
8085   // Load the 64-bit value into an XMM register.
8086   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8087                             Op.getOperand(0));
8088   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8089                               MachinePointerInfo::getConstantPool(),
8090                               false, false, false, 16);
8091   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8092                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8093                               CLod0);
8094
8095   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8096                               MachinePointerInfo::getConstantPool(),
8097                               false, false, false, 16);
8098   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8099   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8100   SDValue Result;
8101
8102   if (Subtarget->hasSSE3()) {
8103     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8104     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8105   } else {
8106     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8107     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8108                                            S2F, 0x4E, DAG);
8109     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8110                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8111                          Sub);
8112   }
8113
8114   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8115                      DAG.getIntPtrConstant(0));
8116 }
8117
8118 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8119 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8120                                                SelectionDAG &DAG) const {
8121   DebugLoc dl = Op.getDebugLoc();
8122   // FP constant to bias correct the final result.
8123   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8124                                    MVT::f64);
8125
8126   // Load the 32-bit value into an XMM register.
8127   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8128                              Op.getOperand(0));
8129
8130   // Zero out the upper parts of the register.
8131   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8132
8133   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8134                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8135                      DAG.getIntPtrConstant(0));
8136
8137   // Or the load with the bias.
8138   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8139                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8140                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8141                                                    MVT::v2f64, Load)),
8142                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8143                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8144                                                    MVT::v2f64, Bias)));
8145   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8146                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8147                    DAG.getIntPtrConstant(0));
8148
8149   // Subtract the bias.
8150   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
8151
8152   // Handle final rounding.
8153   EVT DestVT = Op.getValueType();
8154
8155   if (DestVT.bitsLT(MVT::f64))
8156     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
8157                        DAG.getIntPtrConstant(0));
8158   if (DestVT.bitsGT(MVT::f64))
8159     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
8160
8161   // Handle final rounding.
8162   return Sub;
8163 }
8164
8165 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
8166                                                SelectionDAG &DAG) const {
8167   SDValue N0 = Op.getOperand(0);
8168   EVT SVT = N0.getValueType();
8169   DebugLoc dl = Op.getDebugLoc();
8170
8171   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
8172           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
8173          "Custom UINT_TO_FP is not supported!");
8174
8175   EVT NVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
8176                              SVT.getVectorNumElements());
8177   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
8178                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
8179 }
8180
8181 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8182                                            SelectionDAG &DAG) const {
8183   SDValue N0 = Op.getOperand(0);
8184   DebugLoc dl = Op.getDebugLoc();
8185
8186   if (Op.getValueType().isVector())
8187     return lowerUINT_TO_FP_vec(Op, DAG);
8188
8189   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8190   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8191   // the optimization here.
8192   if (DAG.SignBitIsZero(N0))
8193     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8194
8195   EVT SrcVT = N0.getValueType();
8196   EVT DstVT = Op.getValueType();
8197   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8198     return LowerUINT_TO_FP_i64(Op, DAG);
8199   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8200     return LowerUINT_TO_FP_i32(Op, DAG);
8201   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8202     return SDValue();
8203
8204   // Make a 64-bit buffer, and use it to build an FILD.
8205   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8206   if (SrcVT == MVT::i32) {
8207     SDValue WordOff = DAG.getConstant(4, getPointerTy());
8208     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8209                                      getPointerTy(), StackSlot, WordOff);
8210     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8211                                   StackSlot, MachinePointerInfo(),
8212                                   false, false, 0);
8213     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8214                                   OffsetSlot, MachinePointerInfo(),
8215                                   false, false, 0);
8216     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8217     return Fild;
8218   }
8219
8220   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8221   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8222                                StackSlot, MachinePointerInfo(),
8223                                false, false, 0);
8224   // For i64 source, we need to add the appropriate power of 2 if the input
8225   // was negative.  This is the same as the optimization in
8226   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8227   // we must be careful to do the computation in x87 extended precision, not
8228   // in SSE. (The generic code can't know it's OK to do this, or how to.)
8229   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8230   MachineMemOperand *MMO =
8231     DAG.getMachineFunction()
8232     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8233                           MachineMemOperand::MOLoad, 8, 8);
8234
8235   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8236   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8237   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
8238                                          array_lengthof(Ops), MVT::i64, MMO);
8239
8240   APInt FF(32, 0x5F800000ULL);
8241
8242   // Check whether the sign bit is set.
8243   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
8244                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8245                                  ISD::SETLT);
8246
8247   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8248   SDValue FudgePtr = DAG.getConstantPool(
8249                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8250                                          getPointerTy());
8251
8252   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8253   SDValue Zero = DAG.getIntPtrConstant(0);
8254   SDValue Four = DAG.getIntPtrConstant(4);
8255   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8256                                Zero, Four);
8257   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8258
8259   // Load the value out, extending it from f32 to f80.
8260   // FIXME: Avoid the extend by constructing the right constant pool?
8261   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8262                                  FudgePtr, MachinePointerInfo::getConstantPool(),
8263                                  MVT::f32, false, false, 4);
8264   // Extend everything to 80 bits to force it to be done on x87.
8265   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8266   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8267 }
8268
8269 std::pair<SDValue,SDValue>
8270 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
8271                                     bool IsSigned, bool IsReplace) const {
8272   DebugLoc DL = Op.getDebugLoc();
8273
8274   EVT DstTy = Op.getValueType();
8275
8276   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8277     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8278     DstTy = MVT::i64;
8279   }
8280
8281   assert(DstTy.getSimpleVT() <= MVT::i64 &&
8282          DstTy.getSimpleVT() >= MVT::i16 &&
8283          "Unknown FP_TO_INT to lower!");
8284
8285   // These are really Legal.
8286   if (DstTy == MVT::i32 &&
8287       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8288     return std::make_pair(SDValue(), SDValue());
8289   if (Subtarget->is64Bit() &&
8290       DstTy == MVT::i64 &&
8291       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8292     return std::make_pair(SDValue(), SDValue());
8293
8294   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8295   // stack slot, or into the FTOL runtime function.
8296   MachineFunction &MF = DAG.getMachineFunction();
8297   unsigned MemSize = DstTy.getSizeInBits()/8;
8298   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8299   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8300
8301   unsigned Opc;
8302   if (!IsSigned && isIntegerTypeFTOL(DstTy))
8303     Opc = X86ISD::WIN_FTOL;
8304   else
8305     switch (DstTy.getSimpleVT().SimpleTy) {
8306     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8307     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8308     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8309     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8310     }
8311
8312   SDValue Chain = DAG.getEntryNode();
8313   SDValue Value = Op.getOperand(0);
8314   EVT TheVT = Op.getOperand(0).getValueType();
8315   // FIXME This causes a redundant load/store if the SSE-class value is already
8316   // in memory, such as if it is on the callstack.
8317   if (isScalarFPTypeInSSEReg(TheVT)) {
8318     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8319     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8320                          MachinePointerInfo::getFixedStack(SSFI),
8321                          false, false, 0);
8322     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8323     SDValue Ops[] = {
8324       Chain, StackSlot, DAG.getValueType(TheVT)
8325     };
8326
8327     MachineMemOperand *MMO =
8328       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8329                               MachineMemOperand::MOLoad, MemSize, MemSize);
8330     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops,
8331                                     array_lengthof(Ops), DstTy, MMO);
8332     Chain = Value.getValue(1);
8333     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8334     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8335   }
8336
8337   MachineMemOperand *MMO =
8338     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8339                             MachineMemOperand::MOStore, MemSize, MemSize);
8340
8341   if (Opc != X86ISD::WIN_FTOL) {
8342     // Build the FP_TO_INT*_IN_MEM
8343     SDValue Ops[] = { Chain, Value, StackSlot };
8344     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8345                                            Ops, array_lengthof(Ops), DstTy,
8346                                            MMO);
8347     return std::make_pair(FIST, StackSlot);
8348   } else {
8349     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8350       DAG.getVTList(MVT::Other, MVT::Glue),
8351       Chain, Value);
8352     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8353       MVT::i32, ftol.getValue(1));
8354     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8355       MVT::i32, eax.getValue(2));
8356     SDValue Ops[] = { eax, edx };
8357     SDValue pair = IsReplace
8358       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, array_lengthof(Ops))
8359       : DAG.getMergeValues(Ops, array_lengthof(Ops), DL);
8360     return std::make_pair(pair, SDValue());
8361   }
8362 }
8363
8364 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
8365                               const X86Subtarget *Subtarget) {
8366   MVT VT = Op->getValueType(0).getSimpleVT();
8367   SDValue In = Op->getOperand(0);
8368   MVT InVT = In.getValueType().getSimpleVT();
8369   DebugLoc dl = Op->getDebugLoc();
8370
8371   // Optimize vectors in AVX mode:
8372   //
8373   //   v8i16 -> v8i32
8374   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
8375   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
8376   //   Concat upper and lower parts.
8377   //
8378   //   v4i32 -> v4i64
8379   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
8380   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
8381   //   Concat upper and lower parts.
8382   //
8383
8384   if (((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
8385       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
8386     return SDValue();
8387
8388   if (Subtarget->hasInt256())
8389     return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, In);
8390
8391   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
8392   SDValue Undef = DAG.getUNDEF(InVT);
8393   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
8394   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8395   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8396
8397   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
8398                              VT.getVectorNumElements()/2);
8399
8400   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
8401   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
8402
8403   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
8404 }
8405
8406 SDValue X86TargetLowering::LowerANY_EXTEND(SDValue Op,
8407                                            SelectionDAG &DAG) const {
8408   if (Subtarget->hasFp256()) {
8409     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8410     if (Res.getNode())
8411       return Res;
8412   }
8413
8414   return SDValue();
8415 }
8416 SDValue X86TargetLowering::LowerZERO_EXTEND(SDValue Op,
8417                                             SelectionDAG &DAG) const {
8418   DebugLoc DL = Op.getDebugLoc();
8419   MVT VT = Op.getValueType().getSimpleVT();
8420   SDValue In = Op.getOperand(0);
8421   MVT SVT = In.getValueType().getSimpleVT();
8422
8423   if (Subtarget->hasFp256()) {
8424     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8425     if (Res.getNode())
8426       return Res;
8427   }
8428
8429   if (!VT.is256BitVector() || !SVT.is128BitVector() ||
8430       VT.getVectorNumElements() != SVT.getVectorNumElements())
8431     return SDValue();
8432
8433   assert(Subtarget->hasFp256() && "256-bit vector is observed without AVX!");
8434
8435   // AVX2 has better support of integer extending.
8436   if (Subtarget->hasInt256())
8437     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
8438
8439   SDValue Lo = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32, In);
8440   static const int Mask[] = {4, 5, 6, 7, -1, -1, -1, -1};
8441   SDValue Hi = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32,
8442                            DAG.getVectorShuffle(MVT::v8i16, DL, In,
8443                                                 DAG.getUNDEF(MVT::v8i16),
8444                                                 &Mask[0]));
8445
8446   return DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i32, Lo, Hi);
8447 }
8448
8449 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
8450   DebugLoc DL = Op.getDebugLoc();
8451   MVT VT = Op.getValueType().getSimpleVT();
8452   SDValue In = Op.getOperand(0);
8453   MVT SVT = In.getValueType().getSimpleVT();
8454
8455   if ((VT == MVT::v4i32) && (SVT == MVT::v4i64)) {
8456     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
8457     if (Subtarget->hasInt256()) {
8458       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
8459       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
8460       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
8461                                 ShufMask);
8462       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
8463                          DAG.getIntPtrConstant(0));
8464     }
8465
8466     // On AVX, v4i64 -> v4i32 becomes a sequence that uses PSHUFD and MOVLHPS.
8467     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8468                                DAG.getIntPtrConstant(0));
8469     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8470                                DAG.getIntPtrConstant(2));
8471
8472     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
8473     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
8474
8475     // The PSHUFD mask:
8476     static const int ShufMask1[] = {0, 2, 0, 0};
8477     SDValue Undef = DAG.getUNDEF(VT);
8478     OpLo = DAG.getVectorShuffle(VT, DL, OpLo, Undef, ShufMask1);
8479     OpHi = DAG.getVectorShuffle(VT, DL, OpHi, Undef, ShufMask1);
8480
8481     // The MOVLHPS mask:
8482     static const int ShufMask2[] = {0, 1, 4, 5};
8483     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask2);
8484   }
8485
8486   if ((VT == MVT::v8i16) && (SVT == MVT::v8i32)) {
8487     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
8488     if (Subtarget->hasInt256()) {
8489       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
8490
8491       SmallVector<SDValue,32> pshufbMask;
8492       for (unsigned i = 0; i < 2; ++i) {
8493         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
8494         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
8495         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
8496         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
8497         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
8498         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
8499         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
8500         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
8501         for (unsigned j = 0; j < 8; ++j)
8502           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
8503       }
8504       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8,
8505                                &pshufbMask[0], 32);
8506       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
8507       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
8508
8509       static const int ShufMask[] = {0,  2,  -1,  -1};
8510       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
8511                                 &ShufMask[0]);
8512       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8513                        DAG.getIntPtrConstant(0));
8514       return DAG.getNode(ISD::BITCAST, DL, VT, In);
8515     }
8516
8517     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
8518                                DAG.getIntPtrConstant(0));
8519
8520     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
8521                                DAG.getIntPtrConstant(4));
8522
8523     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
8524     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
8525
8526     // The PSHUFB mask:
8527     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
8528                                    -1, -1, -1, -1, -1, -1, -1, -1};
8529
8530     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
8531     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
8532     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
8533
8534     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
8535     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
8536
8537     // The MOVLHPS Mask:
8538     static const int ShufMask2[] = {0, 1, 4, 5};
8539     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
8540     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
8541   }
8542
8543   // Handle truncation of V256 to V128 using shuffles.
8544   if (!VT.is128BitVector() || !SVT.is256BitVector())
8545     return SDValue();
8546
8547   assert(VT.getVectorNumElements() != SVT.getVectorNumElements() &&
8548          "Invalid op");
8549   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
8550
8551   unsigned NumElems = VT.getVectorNumElements();
8552   EVT NVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
8553                              NumElems * 2);
8554
8555   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
8556   // Prepare truncation shuffle mask
8557   for (unsigned i = 0; i != NumElems; ++i)
8558     MaskVec[i] = i * 2;
8559   SDValue V = DAG.getVectorShuffle(NVT, DL,
8560                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
8561                                    DAG.getUNDEF(NVT), &MaskVec[0]);
8562   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
8563                      DAG.getIntPtrConstant(0));
8564 }
8565
8566 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8567                                            SelectionDAG &DAG) const {
8568   MVT VT = Op.getValueType().getSimpleVT();
8569   if (VT.isVector()) {
8570     if (VT == MVT::v8i16)
8571       return DAG.getNode(ISD::TRUNCATE, Op.getDebugLoc(), VT,
8572                          DAG.getNode(ISD::FP_TO_SINT, Op.getDebugLoc(),
8573                                      MVT::v8i32, Op.getOperand(0)));
8574     return SDValue();
8575   }
8576
8577   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8578     /*IsSigned=*/ true, /*IsReplace=*/ false);
8579   SDValue FIST = Vals.first, StackSlot = Vals.second;
8580   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8581   if (FIST.getNode() == 0) return Op;
8582
8583   if (StackSlot.getNode())
8584     // Load the result.
8585     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8586                        FIST, StackSlot, MachinePointerInfo(),
8587                        false, false, false, 0);
8588
8589   // The node is the result.
8590   return FIST;
8591 }
8592
8593 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8594                                            SelectionDAG &DAG) const {
8595   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8596     /*IsSigned=*/ false, /*IsReplace=*/ false);
8597   SDValue FIST = Vals.first, StackSlot = Vals.second;
8598   assert(FIST.getNode() && "Unexpected failure");
8599
8600   if (StackSlot.getNode())
8601     // Load the result.
8602     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8603                        FIST, StackSlot, MachinePointerInfo(),
8604                        false, false, false, 0);
8605
8606   // The node is the result.
8607   return FIST;
8608 }
8609
8610 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
8611   DebugLoc DL = Op.getDebugLoc();
8612   MVT VT = Op.getValueType().getSimpleVT();
8613   SDValue In = Op.getOperand(0);
8614   MVT SVT = In.getValueType().getSimpleVT();
8615
8616   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
8617
8618   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
8619                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
8620                                  In, DAG.getUNDEF(SVT)));
8621 }
8622
8623 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
8624   LLVMContext *Context = DAG.getContext();
8625   DebugLoc dl = Op.getDebugLoc();
8626   MVT VT = Op.getValueType().getSimpleVT();
8627   MVT EltVT = VT;
8628   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8629   if (VT.isVector()) {
8630     EltVT = VT.getVectorElementType();
8631     NumElts = VT.getVectorNumElements();
8632   }
8633   Constant *C;
8634   if (EltVT == MVT::f64)
8635     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8636                                           APInt(64, ~(1ULL << 63))));
8637   else
8638     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
8639                                           APInt(32, ~(1U << 31))));
8640   C = ConstantVector::getSplat(NumElts, C);
8641   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8642   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8643   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8644                              MachinePointerInfo::getConstantPool(),
8645                              false, false, false, Alignment);
8646   if (VT.isVector()) {
8647     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8648     return DAG.getNode(ISD::BITCAST, dl, VT,
8649                        DAG.getNode(ISD::AND, dl, ANDVT,
8650                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
8651                                                Op.getOperand(0)),
8652                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
8653   }
8654   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8655 }
8656
8657 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8658   LLVMContext *Context = DAG.getContext();
8659   DebugLoc dl = Op.getDebugLoc();
8660   MVT VT = Op.getValueType().getSimpleVT();
8661   MVT EltVT = VT;
8662   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8663   if (VT.isVector()) {
8664     EltVT = VT.getVectorElementType();
8665     NumElts = VT.getVectorNumElements();
8666   }
8667   Constant *C;
8668   if (EltVT == MVT::f64)
8669     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8670                                           APInt(64, 1ULL << 63)));
8671   else
8672     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
8673                                           APInt(32, 1U << 31)));
8674   C = ConstantVector::getSplat(NumElts, C);
8675   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8676   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8677   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8678                              MachinePointerInfo::getConstantPool(),
8679                              false, false, false, Alignment);
8680   if (VT.isVector()) {
8681     MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8682     return DAG.getNode(ISD::BITCAST, dl, VT,
8683                        DAG.getNode(ISD::XOR, dl, XORVT,
8684                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
8685                                                Op.getOperand(0)),
8686                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8687   }
8688
8689   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8690 }
8691
8692 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8693   LLVMContext *Context = DAG.getContext();
8694   SDValue Op0 = Op.getOperand(0);
8695   SDValue Op1 = Op.getOperand(1);
8696   DebugLoc dl = Op.getDebugLoc();
8697   MVT VT = Op.getValueType().getSimpleVT();
8698   MVT SrcVT = Op1.getValueType().getSimpleVT();
8699
8700   // If second operand is smaller, extend it first.
8701   if (SrcVT.bitsLT(VT)) {
8702     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8703     SrcVT = VT;
8704   }
8705   // And if it is bigger, shrink it first.
8706   if (SrcVT.bitsGT(VT)) {
8707     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8708     SrcVT = VT;
8709   }
8710
8711   // At this point the operands and the result should have the same
8712   // type, and that won't be f80 since that is not custom lowered.
8713
8714   // First get the sign bit of second operand.
8715   SmallVector<Constant*,4> CV;
8716   if (SrcVT == MVT::f64) {
8717     const fltSemantics &Sem = APFloat::IEEEdouble;
8718     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
8719     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
8720   } else {
8721     const fltSemantics &Sem = APFloat::IEEEsingle;
8722     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
8723     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8724     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8725     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8726   }
8727   Constant *C = ConstantVector::get(CV);
8728   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8729   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8730                               MachinePointerInfo::getConstantPool(),
8731                               false, false, false, 16);
8732   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8733
8734   // Shift sign bit right or left if the two operands have different types.
8735   if (SrcVT.bitsGT(VT)) {
8736     // Op0 is MVT::f32, Op1 is MVT::f64.
8737     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8738     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8739                           DAG.getConstant(32, MVT::i32));
8740     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8741     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8742                           DAG.getIntPtrConstant(0));
8743   }
8744
8745   // Clear first operand sign bit.
8746   CV.clear();
8747   if (VT == MVT::f64) {
8748     const fltSemantics &Sem = APFloat::IEEEdouble;
8749     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
8750                                                    APInt(64, ~(1ULL << 63)))));
8751     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
8752   } else {
8753     const fltSemantics &Sem = APFloat::IEEEsingle;
8754     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
8755                                                    APInt(32, ~(1U << 31)))));
8756     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8757     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8758     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8759   }
8760   C = ConstantVector::get(CV);
8761   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8762   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8763                               MachinePointerInfo::getConstantPool(),
8764                               false, false, false, 16);
8765   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8766
8767   // Or the value with the sign bit.
8768   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8769 }
8770
8771 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
8772   SDValue N0 = Op.getOperand(0);
8773   DebugLoc dl = Op.getDebugLoc();
8774   MVT VT = Op.getValueType().getSimpleVT();
8775
8776   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8777   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8778                                   DAG.getConstant(1, VT));
8779   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8780 }
8781
8782 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
8783 //
8784 SDValue X86TargetLowering::LowerVectorAllZeroTest(SDValue Op,
8785                                                   SelectionDAG &DAG) const {
8786   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
8787
8788   if (!Subtarget->hasSSE41())
8789     return SDValue();
8790
8791   if (!Op->hasOneUse())
8792     return SDValue();
8793
8794   SDNode *N = Op.getNode();
8795   DebugLoc DL = N->getDebugLoc();
8796
8797   SmallVector<SDValue, 8> Opnds;
8798   DenseMap<SDValue, unsigned> VecInMap;
8799   EVT VT = MVT::Other;
8800
8801   // Recognize a special case where a vector is casted into wide integer to
8802   // test all 0s.
8803   Opnds.push_back(N->getOperand(0));
8804   Opnds.push_back(N->getOperand(1));
8805
8806   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
8807     SmallVector<SDValue, 8>::const_iterator I = Opnds.begin() + Slot;
8808     // BFS traverse all OR'd operands.
8809     if (I->getOpcode() == ISD::OR) {
8810       Opnds.push_back(I->getOperand(0));
8811       Opnds.push_back(I->getOperand(1));
8812       // Re-evaluate the number of nodes to be traversed.
8813       e += 2; // 2 more nodes (LHS and RHS) are pushed.
8814       continue;
8815     }
8816
8817     // Quit if a non-EXTRACT_VECTOR_ELT
8818     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8819       return SDValue();
8820
8821     // Quit if without a constant index.
8822     SDValue Idx = I->getOperand(1);
8823     if (!isa<ConstantSDNode>(Idx))
8824       return SDValue();
8825
8826     SDValue ExtractedFromVec = I->getOperand(0);
8827     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
8828     if (M == VecInMap.end()) {
8829       VT = ExtractedFromVec.getValueType();
8830       // Quit if not 128/256-bit vector.
8831       if (!VT.is128BitVector() && !VT.is256BitVector())
8832         return SDValue();
8833       // Quit if not the same type.
8834       if (VecInMap.begin() != VecInMap.end() &&
8835           VT != VecInMap.begin()->first.getValueType())
8836         return SDValue();
8837       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
8838     }
8839     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
8840   }
8841
8842   assert((VT.is128BitVector() || VT.is256BitVector()) &&
8843          "Not extracted from 128-/256-bit vector.");
8844
8845   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
8846   SmallVector<SDValue, 8> VecIns;
8847
8848   for (DenseMap<SDValue, unsigned>::const_iterator
8849         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
8850     // Quit if not all elements are used.
8851     if (I->second != FullMask)
8852       return SDValue();
8853     VecIns.push_back(I->first);
8854   }
8855
8856   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8857
8858   // Cast all vectors into TestVT for PTEST.
8859   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
8860     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
8861
8862   // If more than one full vectors are evaluated, OR them first before PTEST.
8863   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
8864     // Each iteration will OR 2 nodes and append the result until there is only
8865     // 1 node left, i.e. the final OR'd value of all vectors.
8866     SDValue LHS = VecIns[Slot];
8867     SDValue RHS = VecIns[Slot + 1];
8868     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
8869   }
8870
8871   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
8872                      VecIns.back(), VecIns.back());
8873 }
8874
8875 /// Emit nodes that will be selected as "test Op0,Op0", or something
8876 /// equivalent.
8877 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8878                                     SelectionDAG &DAG) const {
8879   DebugLoc dl = Op.getDebugLoc();
8880
8881   // CF and OF aren't always set the way we want. Determine which
8882   // of these we need.
8883   bool NeedCF = false;
8884   bool NeedOF = false;
8885   switch (X86CC) {
8886   default: break;
8887   case X86::COND_A: case X86::COND_AE:
8888   case X86::COND_B: case X86::COND_BE:
8889     NeedCF = true;
8890     break;
8891   case X86::COND_G: case X86::COND_GE:
8892   case X86::COND_L: case X86::COND_LE:
8893   case X86::COND_O: case X86::COND_NO:
8894     NeedOF = true;
8895     break;
8896   }
8897
8898   // See if we can use the EFLAGS value from the operand instead of
8899   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8900   // we prove that the arithmetic won't overflow, we can't use OF or CF.
8901   if (Op.getResNo() != 0 || NeedOF || NeedCF)
8902     // Emit a CMP with 0, which is the TEST pattern.
8903     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8904                        DAG.getConstant(0, Op.getValueType()));
8905
8906   unsigned Opcode = 0;
8907   unsigned NumOperands = 0;
8908
8909   // Truncate operations may prevent the merge of the SETCC instruction
8910   // and the arithmetic intruction before it. Attempt to truncate the operands
8911   // of the arithmetic instruction and use a reduced bit-width instruction.
8912   bool NeedTruncation = false;
8913   SDValue ArithOp = Op;
8914   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
8915     SDValue Arith = Op->getOperand(0);
8916     // Both the trunc and the arithmetic op need to have one user each.
8917     if (Arith->hasOneUse())
8918       switch (Arith.getOpcode()) {
8919         default: break;
8920         case ISD::ADD:
8921         case ISD::SUB:
8922         case ISD::AND:
8923         case ISD::OR:
8924         case ISD::XOR: {
8925           NeedTruncation = true;
8926           ArithOp = Arith;
8927         }
8928       }
8929   }
8930
8931   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
8932   // which may be the result of a CAST.  We use the variable 'Op', which is the
8933   // non-casted variable when we check for possible users.
8934   switch (ArithOp.getOpcode()) {
8935   case ISD::ADD:
8936     // Due to an isel shortcoming, be conservative if this add is likely to be
8937     // selected as part of a load-modify-store instruction. When the root node
8938     // in a match is a store, isel doesn't know how to remap non-chain non-flag
8939     // uses of other nodes in the match, such as the ADD in this case. This
8940     // leads to the ADD being left around and reselected, with the result being
8941     // two adds in the output.  Alas, even if none our users are stores, that
8942     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
8943     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
8944     // climbing the DAG back to the root, and it doesn't seem to be worth the
8945     // effort.
8946     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8947          UE = Op.getNode()->use_end(); UI != UE; ++UI)
8948       if (UI->getOpcode() != ISD::CopyToReg &&
8949           UI->getOpcode() != ISD::SETCC &&
8950           UI->getOpcode() != ISD::STORE)
8951         goto default_case;
8952
8953     if (ConstantSDNode *C =
8954         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
8955       // An add of one will be selected as an INC.
8956       if (C->getAPIntValue() == 1) {
8957         Opcode = X86ISD::INC;
8958         NumOperands = 1;
8959         break;
8960       }
8961
8962       // An add of negative one (subtract of one) will be selected as a DEC.
8963       if (C->getAPIntValue().isAllOnesValue()) {
8964         Opcode = X86ISD::DEC;
8965         NumOperands = 1;
8966         break;
8967       }
8968     }
8969
8970     // Otherwise use a regular EFLAGS-setting add.
8971     Opcode = X86ISD::ADD;
8972     NumOperands = 2;
8973     break;
8974   case ISD::AND: {
8975     // If the primary and result isn't used, don't bother using X86ISD::AND,
8976     // because a TEST instruction will be better.
8977     bool NonFlagUse = false;
8978     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8979            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8980       SDNode *User = *UI;
8981       unsigned UOpNo = UI.getOperandNo();
8982       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8983         // Look pass truncate.
8984         UOpNo = User->use_begin().getOperandNo();
8985         User = *User->use_begin();
8986       }
8987
8988       if (User->getOpcode() != ISD::BRCOND &&
8989           User->getOpcode() != ISD::SETCC &&
8990           !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
8991         NonFlagUse = true;
8992         break;
8993       }
8994     }
8995
8996     if (!NonFlagUse)
8997       break;
8998   }
8999     // FALL THROUGH
9000   case ISD::SUB:
9001   case ISD::OR:
9002   case ISD::XOR:
9003     // Due to the ISEL shortcoming noted above, be conservative if this op is
9004     // likely to be selected as part of a load-modify-store instruction.
9005     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9006            UE = Op.getNode()->use_end(); UI != UE; ++UI)
9007       if (UI->getOpcode() == ISD::STORE)
9008         goto default_case;
9009
9010     // Otherwise use a regular EFLAGS-setting instruction.
9011     switch (ArithOp.getOpcode()) {
9012     default: llvm_unreachable("unexpected operator!");
9013     case ISD::SUB: Opcode = X86ISD::SUB; break;
9014     case ISD::XOR: Opcode = X86ISD::XOR; break;
9015     case ISD::AND: Opcode = X86ISD::AND; break;
9016     case ISD::OR: {
9017       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
9018         SDValue EFLAGS = LowerVectorAllZeroTest(Op, DAG);
9019         if (EFLAGS.getNode())
9020           return EFLAGS;
9021       }
9022       Opcode = X86ISD::OR;
9023       break;
9024     }
9025     }
9026
9027     NumOperands = 2;
9028     break;
9029   case X86ISD::ADD:
9030   case X86ISD::SUB:
9031   case X86ISD::INC:
9032   case X86ISD::DEC:
9033   case X86ISD::OR:
9034   case X86ISD::XOR:
9035   case X86ISD::AND:
9036     return SDValue(Op.getNode(), 1);
9037   default:
9038   default_case:
9039     break;
9040   }
9041
9042   // If we found that truncation is beneficial, perform the truncation and
9043   // update 'Op'.
9044   if (NeedTruncation) {
9045     EVT VT = Op.getValueType();
9046     SDValue WideVal = Op->getOperand(0);
9047     EVT WideVT = WideVal.getValueType();
9048     unsigned ConvertedOp = 0;
9049     // Use a target machine opcode to prevent further DAGCombine
9050     // optimizations that may separate the arithmetic operations
9051     // from the setcc node.
9052     switch (WideVal.getOpcode()) {
9053       default: break;
9054       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
9055       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
9056       case ISD::AND: ConvertedOp = X86ISD::AND; break;
9057       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
9058       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
9059     }
9060
9061     if (ConvertedOp) {
9062       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9063       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
9064         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
9065         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
9066         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
9067       }
9068     }
9069   }
9070
9071   if (Opcode == 0)
9072     // Emit a CMP with 0, which is the TEST pattern.
9073     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9074                        DAG.getConstant(0, Op.getValueType()));
9075
9076   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
9077   SmallVector<SDValue, 4> Ops;
9078   for (unsigned i = 0; i != NumOperands; ++i)
9079     Ops.push_back(Op.getOperand(i));
9080
9081   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
9082   DAG.ReplaceAllUsesWith(Op, New);
9083   return SDValue(New.getNode(), 1);
9084 }
9085
9086 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
9087 /// equivalent.
9088 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
9089                                    SelectionDAG &DAG) const {
9090   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
9091     if (C->getAPIntValue() == 0)
9092       return EmitTest(Op0, X86CC, DAG);
9093
9094   DebugLoc dl = Op0.getDebugLoc();
9095   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
9096        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
9097     // Use SUB instead of CMP to enable CSE between SUB and CMP.
9098     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
9099     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
9100                               Op0, Op1);
9101     return SDValue(Sub.getNode(), 1);
9102   }
9103   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
9104 }
9105
9106 /// Convert a comparison if required by the subtarget.
9107 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
9108                                                  SelectionDAG &DAG) const {
9109   // If the subtarget does not support the FUCOMI instruction, floating-point
9110   // comparisons have to be converted.
9111   if (Subtarget->hasCMov() ||
9112       Cmp.getOpcode() != X86ISD::CMP ||
9113       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
9114       !Cmp.getOperand(1).getValueType().isFloatingPoint())
9115     return Cmp;
9116
9117   // The instruction selector will select an FUCOM instruction instead of
9118   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
9119   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
9120   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
9121   DebugLoc dl = Cmp.getDebugLoc();
9122   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
9123   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
9124   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
9125                             DAG.getConstant(8, MVT::i8));
9126   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
9127   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
9128 }
9129
9130 static bool isAllOnes(SDValue V) {
9131   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9132   return C && C->isAllOnesValue();
9133 }
9134
9135 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
9136 /// if it's possible.
9137 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
9138                                      DebugLoc dl, SelectionDAG &DAG) const {
9139   SDValue Op0 = And.getOperand(0);
9140   SDValue Op1 = And.getOperand(1);
9141   if (Op0.getOpcode() == ISD::TRUNCATE)
9142     Op0 = Op0.getOperand(0);
9143   if (Op1.getOpcode() == ISD::TRUNCATE)
9144     Op1 = Op1.getOperand(0);
9145
9146   SDValue LHS, RHS;
9147   if (Op1.getOpcode() == ISD::SHL)
9148     std::swap(Op0, Op1);
9149   if (Op0.getOpcode() == ISD::SHL) {
9150     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
9151       if (And00C->getZExtValue() == 1) {
9152         // If we looked past a truncate, check that it's only truncating away
9153         // known zeros.
9154         unsigned BitWidth = Op0.getValueSizeInBits();
9155         unsigned AndBitWidth = And.getValueSizeInBits();
9156         if (BitWidth > AndBitWidth) {
9157           APInt Zeros, Ones;
9158           DAG.ComputeMaskedBits(Op0, Zeros, Ones);
9159           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
9160             return SDValue();
9161         }
9162         LHS = Op1;
9163         RHS = Op0.getOperand(1);
9164       }
9165   } else if (Op1.getOpcode() == ISD::Constant) {
9166     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
9167     uint64_t AndRHSVal = AndRHS->getZExtValue();
9168     SDValue AndLHS = Op0;
9169
9170     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
9171       LHS = AndLHS.getOperand(0);
9172       RHS = AndLHS.getOperand(1);
9173     }
9174
9175     // Use BT if the immediate can't be encoded in a TEST instruction.
9176     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
9177       LHS = AndLHS;
9178       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
9179     }
9180   }
9181
9182   if (LHS.getNode()) {
9183     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
9184     // instruction.  Since the shift amount is in-range-or-undefined, we know
9185     // that doing a bittest on the i32 value is ok.  We extend to i32 because
9186     // the encoding for the i16 version is larger than the i32 version.
9187     // Also promote i16 to i32 for performance / code size reason.
9188     if (LHS.getValueType() == MVT::i8 ||
9189         LHS.getValueType() == MVT::i16)
9190       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
9191
9192     // If the operand types disagree, extend the shift amount to match.  Since
9193     // BT ignores high bits (like shifts) we can use anyextend.
9194     if (LHS.getValueType() != RHS.getValueType())
9195       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
9196
9197     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
9198     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
9199     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9200                        DAG.getConstant(Cond, MVT::i8), BT);
9201   }
9202
9203   return SDValue();
9204 }
9205
9206 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
9207 // ones, and then concatenate the result back.
9208 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
9209   MVT VT = Op.getValueType().getSimpleVT();
9210
9211   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
9212          "Unsupported value type for operation");
9213
9214   unsigned NumElems = VT.getVectorNumElements();
9215   DebugLoc dl = Op.getDebugLoc();
9216   SDValue CC = Op.getOperand(2);
9217
9218   // Extract the LHS vectors
9219   SDValue LHS = Op.getOperand(0);
9220   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
9221   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
9222
9223   // Extract the RHS vectors
9224   SDValue RHS = Op.getOperand(1);
9225   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
9226   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
9227
9228   // Issue the operation on the smaller types and concatenate the result back
9229   MVT EltVT = VT.getVectorElementType();
9230   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9231   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9232                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
9233                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
9234 }
9235
9236 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
9237                            SelectionDAG &DAG) {
9238   SDValue Cond;
9239   SDValue Op0 = Op.getOperand(0);
9240   SDValue Op1 = Op.getOperand(1);
9241   SDValue CC = Op.getOperand(2);
9242   MVT VT = Op.getValueType().getSimpleVT();
9243   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
9244   bool isFP = Op.getOperand(1).getValueType().getSimpleVT().isFloatingPoint();
9245   DebugLoc dl = Op.getDebugLoc();
9246
9247   if (isFP) {
9248 #ifndef NDEBUG
9249     MVT EltVT = Op0.getValueType().getVectorElementType().getSimpleVT();
9250     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
9251 #endif
9252
9253     unsigned SSECC;
9254     bool Swap = false;
9255
9256     // SSE Condition code mapping:
9257     //  0 - EQ
9258     //  1 - LT
9259     //  2 - LE
9260     //  3 - UNORD
9261     //  4 - NEQ
9262     //  5 - NLT
9263     //  6 - NLE
9264     //  7 - ORD
9265     switch (SetCCOpcode) {
9266     default: llvm_unreachable("Unexpected SETCC condition");
9267     case ISD::SETOEQ:
9268     case ISD::SETEQ:  SSECC = 0; break;
9269     case ISD::SETOGT:
9270     case ISD::SETGT: Swap = true; // Fallthrough
9271     case ISD::SETLT:
9272     case ISD::SETOLT: SSECC = 1; break;
9273     case ISD::SETOGE:
9274     case ISD::SETGE: Swap = true; // Fallthrough
9275     case ISD::SETLE:
9276     case ISD::SETOLE: SSECC = 2; break;
9277     case ISD::SETUO:  SSECC = 3; break;
9278     case ISD::SETUNE:
9279     case ISD::SETNE:  SSECC = 4; break;
9280     case ISD::SETULE: Swap = true; // Fallthrough
9281     case ISD::SETUGE: SSECC = 5; break;
9282     case ISD::SETULT: Swap = true; // Fallthrough
9283     case ISD::SETUGT: SSECC = 6; break;
9284     case ISD::SETO:   SSECC = 7; break;
9285     case ISD::SETUEQ:
9286     case ISD::SETONE: SSECC = 8; break;
9287     }
9288     if (Swap)
9289       std::swap(Op0, Op1);
9290
9291     // In the two special cases we can't handle, emit two comparisons.
9292     if (SSECC == 8) {
9293       unsigned CC0, CC1;
9294       unsigned CombineOpc;
9295       if (SetCCOpcode == ISD::SETUEQ) {
9296         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
9297       } else {
9298         assert(SetCCOpcode == ISD::SETONE);
9299         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
9300       }
9301
9302       SDValue Cmp0 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9303                                  DAG.getConstant(CC0, MVT::i8));
9304       SDValue Cmp1 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9305                                  DAG.getConstant(CC1, MVT::i8));
9306       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
9307     }
9308     // Handle all other FP comparisons here.
9309     return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9310                        DAG.getConstant(SSECC, MVT::i8));
9311   }
9312
9313   // Break 256-bit integer vector compare into smaller ones.
9314   if (VT.is256BitVector() && !Subtarget->hasInt256())
9315     return Lower256IntVSETCC(Op, DAG);
9316
9317   // We are handling one of the integer comparisons here.  Since SSE only has
9318   // GT and EQ comparisons for integer, swapping operands and multiple
9319   // operations may be required for some comparisons.
9320   unsigned Opc;
9321   bool Swap = false, Invert = false, FlipSigns = false;
9322
9323   switch (SetCCOpcode) {
9324   default: llvm_unreachable("Unexpected SETCC condition");
9325   case ISD::SETNE:  Invert = true;
9326   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
9327   case ISD::SETLT:  Swap = true;
9328   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
9329   case ISD::SETGE:  Swap = true;
9330   case ISD::SETLE:  Opc = X86ISD::PCMPGT; Invert = true; break;
9331   case ISD::SETULT: Swap = true;
9332   case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
9333   case ISD::SETUGE: Swap = true;
9334   case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
9335   }
9336   if (Swap)
9337     std::swap(Op0, Op1);
9338
9339   // Check that the operation in question is available (most are plain SSE2,
9340   // but PCMPGTQ and PCMPEQQ have different requirements).
9341   if (VT == MVT::v2i64) {
9342     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
9343       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
9344
9345       // First cast everything to the right type.
9346       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
9347       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
9348
9349       // Since SSE has no unsigned integer comparisons, we need to flip the sign
9350       // bits of the inputs before performing those operations. The lower
9351       // compare is always unsigned.
9352       SDValue SB;
9353       if (FlipSigns) {
9354         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
9355       } else {
9356         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
9357         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
9358         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
9359                          Sign, Zero, Sign, Zero);
9360       }
9361       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
9362       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
9363
9364       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
9365       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
9366       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
9367
9368       // Create masks for only the low parts/high parts of the 64 bit integers.
9369       const int MaskHi[] = { 1, 1, 3, 3 };
9370       const int MaskLo[] = { 0, 0, 2, 2 };
9371       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
9372       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
9373       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
9374
9375       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
9376       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
9377
9378       if (Invert)
9379         Result = DAG.getNOT(dl, Result, MVT::v4i32);
9380
9381       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
9382     }
9383
9384     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
9385       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
9386       // pcmpeqd + pshufd + pand.
9387       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
9388
9389       // First cast everything to the right type.
9390       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
9391       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
9392
9393       // Do the compare.
9394       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
9395
9396       // Make sure the lower and upper halves are both all-ones.
9397       const int Mask[] = { 1, 0, 3, 2 };
9398       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
9399       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
9400
9401       if (Invert)
9402         Result = DAG.getNOT(dl, Result, MVT::v4i32);
9403
9404       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
9405     }
9406   }
9407
9408   // Since SSE has no unsigned integer comparisons, we need to flip the sign
9409   // bits of the inputs before performing those operations.
9410   if (FlipSigns) {
9411     EVT EltVT = VT.getVectorElementType();
9412     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
9413     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
9414     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
9415   }
9416
9417   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
9418
9419   // If the logical-not of the result is required, perform that now.
9420   if (Invert)
9421     Result = DAG.getNOT(dl, Result, VT);
9422
9423   return Result;
9424 }
9425
9426 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
9427
9428   MVT VT = Op.getValueType().getSimpleVT();
9429
9430   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
9431
9432   assert(VT == MVT::i8 && "SetCC type must be 8-bit integer");
9433   SDValue Op0 = Op.getOperand(0);
9434   SDValue Op1 = Op.getOperand(1);
9435   DebugLoc dl = Op.getDebugLoc();
9436   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
9437
9438   // Optimize to BT if possible.
9439   // Lower (X & (1 << N)) == 0 to BT(X, N).
9440   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
9441   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
9442   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
9443       Op1.getOpcode() == ISD::Constant &&
9444       cast<ConstantSDNode>(Op1)->isNullValue() &&
9445       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9446     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
9447     if (NewSetCC.getNode())
9448       return NewSetCC;
9449   }
9450
9451   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
9452   // these.
9453   if (Op1.getOpcode() == ISD::Constant &&
9454       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
9455        cast<ConstantSDNode>(Op1)->isNullValue()) &&
9456       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9457
9458     // If the input is a setcc, then reuse the input setcc or use a new one with
9459     // the inverted condition.
9460     if (Op0.getOpcode() == X86ISD::SETCC) {
9461       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
9462       bool Invert = (CC == ISD::SETNE) ^
9463         cast<ConstantSDNode>(Op1)->isNullValue();
9464       if (!Invert) return Op0;
9465
9466       CCode = X86::GetOppositeBranchCondition(CCode);
9467       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9468                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
9469     }
9470   }
9471
9472   bool isFP = Op1.getValueType().getSimpleVT().isFloatingPoint();
9473   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
9474   if (X86CC == X86::COND_INVALID)
9475     return SDValue();
9476
9477   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
9478   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
9479   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9480                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
9481 }
9482
9483 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
9484 static bool isX86LogicalCmp(SDValue Op) {
9485   unsigned Opc = Op.getNode()->getOpcode();
9486   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
9487       Opc == X86ISD::SAHF)
9488     return true;
9489   if (Op.getResNo() == 1 &&
9490       (Opc == X86ISD::ADD ||
9491        Opc == X86ISD::SUB ||
9492        Opc == X86ISD::ADC ||
9493        Opc == X86ISD::SBB ||
9494        Opc == X86ISD::SMUL ||
9495        Opc == X86ISD::UMUL ||
9496        Opc == X86ISD::INC ||
9497        Opc == X86ISD::DEC ||
9498        Opc == X86ISD::OR ||
9499        Opc == X86ISD::XOR ||
9500        Opc == X86ISD::AND))
9501     return true;
9502
9503   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
9504     return true;
9505
9506   return false;
9507 }
9508
9509 static bool isZero(SDValue V) {
9510   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9511   return C && C->isNullValue();
9512 }
9513
9514 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
9515   if (V.getOpcode() != ISD::TRUNCATE)
9516     return false;
9517
9518   SDValue VOp0 = V.getOperand(0);
9519   unsigned InBits = VOp0.getValueSizeInBits();
9520   unsigned Bits = V.getValueSizeInBits();
9521   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
9522 }
9523
9524 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
9525   bool addTest = true;
9526   SDValue Cond  = Op.getOperand(0);
9527   SDValue Op1 = Op.getOperand(1);
9528   SDValue Op2 = Op.getOperand(2);
9529   DebugLoc DL = Op.getDebugLoc();
9530   SDValue CC;
9531
9532   if (Cond.getOpcode() == ISD::SETCC) {
9533     SDValue NewCond = LowerSETCC(Cond, DAG);
9534     if (NewCond.getNode())
9535       Cond = NewCond;
9536   }
9537
9538   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
9539   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
9540   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
9541   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
9542   if (Cond.getOpcode() == X86ISD::SETCC &&
9543       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
9544       isZero(Cond.getOperand(1).getOperand(1))) {
9545     SDValue Cmp = Cond.getOperand(1);
9546
9547     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
9548
9549     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
9550         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
9551       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
9552
9553       SDValue CmpOp0 = Cmp.getOperand(0);
9554       // Apply further optimizations for special cases
9555       // (select (x != 0), -1, 0) -> neg & sbb
9556       // (select (x == 0), 0, -1) -> neg & sbb
9557       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
9558         if (YC->isNullValue() &&
9559             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
9560           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
9561           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
9562                                     DAG.getConstant(0, CmpOp0.getValueType()),
9563                                     CmpOp0);
9564           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9565                                     DAG.getConstant(X86::COND_B, MVT::i8),
9566                                     SDValue(Neg.getNode(), 1));
9567           return Res;
9568         }
9569
9570       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
9571                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
9572       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9573
9574       SDValue Res =   // Res = 0 or -1.
9575         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9576                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
9577
9578       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
9579         Res = DAG.getNOT(DL, Res, Res.getValueType());
9580
9581       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
9582       if (N2C == 0 || !N2C->isNullValue())
9583         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
9584       return Res;
9585     }
9586   }
9587
9588   // Look past (and (setcc_carry (cmp ...)), 1).
9589   if (Cond.getOpcode() == ISD::AND &&
9590       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9591     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9592     if (C && C->getAPIntValue() == 1)
9593       Cond = Cond.getOperand(0);
9594   }
9595
9596   // If condition flag is set by a X86ISD::CMP, then use it as the condition
9597   // setting operand in place of the X86ISD::SETCC.
9598   unsigned CondOpcode = Cond.getOpcode();
9599   if (CondOpcode == X86ISD::SETCC ||
9600       CondOpcode == X86ISD::SETCC_CARRY) {
9601     CC = Cond.getOperand(0);
9602
9603     SDValue Cmp = Cond.getOperand(1);
9604     unsigned Opc = Cmp.getOpcode();
9605     MVT VT = Op.getValueType().getSimpleVT();
9606
9607     bool IllegalFPCMov = false;
9608     if (VT.isFloatingPoint() && !VT.isVector() &&
9609         !isScalarFPTypeInSSEReg(VT))  // FPStack?
9610       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
9611
9612     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
9613         Opc == X86ISD::BT) { // FIXME
9614       Cond = Cmp;
9615       addTest = false;
9616     }
9617   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9618              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9619              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9620               Cond.getOperand(0).getValueType() != MVT::i8)) {
9621     SDValue LHS = Cond.getOperand(0);
9622     SDValue RHS = Cond.getOperand(1);
9623     unsigned X86Opcode;
9624     unsigned X86Cond;
9625     SDVTList VTs;
9626     switch (CondOpcode) {
9627     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9628     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9629     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9630     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9631     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9632     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9633     default: llvm_unreachable("unexpected overflowing operator");
9634     }
9635     if (CondOpcode == ISD::UMULO)
9636       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9637                           MVT::i32);
9638     else
9639       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9640
9641     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
9642
9643     if (CondOpcode == ISD::UMULO)
9644       Cond = X86Op.getValue(2);
9645     else
9646       Cond = X86Op.getValue(1);
9647
9648     CC = DAG.getConstant(X86Cond, MVT::i8);
9649     addTest = false;
9650   }
9651
9652   if (addTest) {
9653     // Look pass the truncate if the high bits are known zero.
9654     if (isTruncWithZeroHighBitsInput(Cond, DAG))
9655         Cond = Cond.getOperand(0);
9656
9657     // We know the result of AND is compared against zero. Try to match
9658     // it to BT.
9659     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9660       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
9661       if (NewSetCC.getNode()) {
9662         CC = NewSetCC.getOperand(0);
9663         Cond = NewSetCC.getOperand(1);
9664         addTest = false;
9665       }
9666     }
9667   }
9668
9669   if (addTest) {
9670     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9671     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9672   }
9673
9674   // a <  b ? -1 :  0 -> RES = ~setcc_carry
9675   // a <  b ?  0 : -1 -> RES = setcc_carry
9676   // a >= b ? -1 :  0 -> RES = setcc_carry
9677   // a >= b ?  0 : -1 -> RES = ~setcc_carry
9678   if (Cond.getOpcode() == X86ISD::SUB) {
9679     Cond = ConvertCmpIfNecessary(Cond, DAG);
9680     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
9681
9682     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
9683         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
9684       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9685                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
9686       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
9687         return DAG.getNOT(DL, Res, Res.getValueType());
9688       return Res;
9689     }
9690   }
9691
9692   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
9693   // widen the cmov and push the truncate through. This avoids introducing a new
9694   // branch during isel and doesn't add any extensions.
9695   if (Op.getValueType() == MVT::i8 &&
9696       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
9697     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
9698     if (T1.getValueType() == T2.getValueType() &&
9699         // Blacklist CopyFromReg to avoid partial register stalls.
9700         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
9701       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
9702       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
9703       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
9704     }
9705   }
9706
9707   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
9708   // condition is true.
9709   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
9710   SDValue Ops[] = { Op2, Op1, CC, Cond };
9711   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
9712 }
9713
9714 SDValue X86TargetLowering::LowerSIGN_EXTEND(SDValue Op,
9715                                             SelectionDAG &DAG) const {
9716   MVT VT = Op->getValueType(0).getSimpleVT();
9717   SDValue In = Op->getOperand(0);
9718   MVT InVT = In.getValueType().getSimpleVT();
9719   DebugLoc dl = Op->getDebugLoc();
9720
9721   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
9722       (VT != MVT::v8i32 || InVT != MVT::v8i16))
9723     return SDValue();
9724
9725   if (Subtarget->hasInt256())
9726     return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, In);
9727
9728   // Optimize vectors in AVX mode
9729   // Sign extend  v8i16 to v8i32 and
9730   //              v4i32 to v4i64
9731   //
9732   // Divide input vector into two parts
9733   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
9734   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
9735   // concat the vectors to original VT
9736
9737   unsigned NumElems = InVT.getVectorNumElements();
9738   SDValue Undef = DAG.getUNDEF(InVT);
9739
9740   SmallVector<int,8> ShufMask1(NumElems, -1);
9741   for (unsigned i = 0; i != NumElems/2; ++i)
9742     ShufMask1[i] = i;
9743
9744   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
9745
9746   SmallVector<int,8> ShufMask2(NumElems, -1);
9747   for (unsigned i = 0; i != NumElems/2; ++i)
9748     ShufMask2[i] = i + NumElems/2;
9749
9750   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
9751
9752   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
9753                                 VT.getVectorNumElements()/2);
9754
9755   OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
9756   OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
9757
9758   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9759 }
9760
9761 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
9762 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
9763 // from the AND / OR.
9764 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
9765   Opc = Op.getOpcode();
9766   if (Opc != ISD::OR && Opc != ISD::AND)
9767     return false;
9768   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9769           Op.getOperand(0).hasOneUse() &&
9770           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
9771           Op.getOperand(1).hasOneUse());
9772 }
9773
9774 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
9775 // 1 and that the SETCC node has a single use.
9776 static bool isXor1OfSetCC(SDValue Op) {
9777   if (Op.getOpcode() != ISD::XOR)
9778     return false;
9779   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9780   if (N1C && N1C->getAPIntValue() == 1) {
9781     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9782       Op.getOperand(0).hasOneUse();
9783   }
9784   return false;
9785 }
9786
9787 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
9788   bool addTest = true;
9789   SDValue Chain = Op.getOperand(0);
9790   SDValue Cond  = Op.getOperand(1);
9791   SDValue Dest  = Op.getOperand(2);
9792   DebugLoc dl = Op.getDebugLoc();
9793   SDValue CC;
9794   bool Inverted = false;
9795
9796   if (Cond.getOpcode() == ISD::SETCC) {
9797     // Check for setcc([su]{add,sub,mul}o == 0).
9798     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
9799         isa<ConstantSDNode>(Cond.getOperand(1)) &&
9800         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
9801         Cond.getOperand(0).getResNo() == 1 &&
9802         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
9803          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
9804          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
9805          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
9806          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
9807          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
9808       Inverted = true;
9809       Cond = Cond.getOperand(0);
9810     } else {
9811       SDValue NewCond = LowerSETCC(Cond, DAG);
9812       if (NewCond.getNode())
9813         Cond = NewCond;
9814     }
9815   }
9816 #if 0
9817   // FIXME: LowerXALUO doesn't handle these!!
9818   else if (Cond.getOpcode() == X86ISD::ADD  ||
9819            Cond.getOpcode() == X86ISD::SUB  ||
9820            Cond.getOpcode() == X86ISD::SMUL ||
9821            Cond.getOpcode() == X86ISD::UMUL)
9822     Cond = LowerXALUO(Cond, DAG);
9823 #endif
9824
9825   // Look pass (and (setcc_carry (cmp ...)), 1).
9826   if (Cond.getOpcode() == ISD::AND &&
9827       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9828     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9829     if (C && C->getAPIntValue() == 1)
9830       Cond = Cond.getOperand(0);
9831   }
9832
9833   // If condition flag is set by a X86ISD::CMP, then use it as the condition
9834   // setting operand in place of the X86ISD::SETCC.
9835   unsigned CondOpcode = Cond.getOpcode();
9836   if (CondOpcode == X86ISD::SETCC ||
9837       CondOpcode == X86ISD::SETCC_CARRY) {
9838     CC = Cond.getOperand(0);
9839
9840     SDValue Cmp = Cond.getOperand(1);
9841     unsigned Opc = Cmp.getOpcode();
9842     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9843     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9844       Cond = Cmp;
9845       addTest = false;
9846     } else {
9847       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9848       default: break;
9849       case X86::COND_O:
9850       case X86::COND_B:
9851         // These can only come from an arithmetic instruction with overflow,
9852         // e.g. SADDO, UADDO.
9853         Cond = Cond.getNode()->getOperand(1);
9854         addTest = false;
9855         break;
9856       }
9857     }
9858   }
9859   CondOpcode = Cond.getOpcode();
9860   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9861       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9862       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9863        Cond.getOperand(0).getValueType() != MVT::i8)) {
9864     SDValue LHS = Cond.getOperand(0);
9865     SDValue RHS = Cond.getOperand(1);
9866     unsigned X86Opcode;
9867     unsigned X86Cond;
9868     SDVTList VTs;
9869     switch (CondOpcode) {
9870     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9871     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9872     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9873     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9874     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9875     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9876     default: llvm_unreachable("unexpected overflowing operator");
9877     }
9878     if (Inverted)
9879       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9880     if (CondOpcode == ISD::UMULO)
9881       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9882                           MVT::i32);
9883     else
9884       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9885
9886     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9887
9888     if (CondOpcode == ISD::UMULO)
9889       Cond = X86Op.getValue(2);
9890     else
9891       Cond = X86Op.getValue(1);
9892
9893     CC = DAG.getConstant(X86Cond, MVT::i8);
9894     addTest = false;
9895   } else {
9896     unsigned CondOpc;
9897     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9898       SDValue Cmp = Cond.getOperand(0).getOperand(1);
9899       if (CondOpc == ISD::OR) {
9900         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9901         // two branches instead of an explicit OR instruction with a
9902         // separate test.
9903         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9904             isX86LogicalCmp(Cmp)) {
9905           CC = Cond.getOperand(0).getOperand(0);
9906           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9907                               Chain, Dest, CC, Cmp);
9908           CC = Cond.getOperand(1).getOperand(0);
9909           Cond = Cmp;
9910           addTest = false;
9911         }
9912       } else { // ISD::AND
9913         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9914         // two branches instead of an explicit AND instruction with a
9915         // separate test. However, we only do this if this block doesn't
9916         // have a fall-through edge, because this requires an explicit
9917         // jmp when the condition is false.
9918         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9919             isX86LogicalCmp(Cmp) &&
9920             Op.getNode()->hasOneUse()) {
9921           X86::CondCode CCode =
9922             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9923           CCode = X86::GetOppositeBranchCondition(CCode);
9924           CC = DAG.getConstant(CCode, MVT::i8);
9925           SDNode *User = *Op.getNode()->use_begin();
9926           // Look for an unconditional branch following this conditional branch.
9927           // We need this because we need to reverse the successors in order
9928           // to implement FCMP_OEQ.
9929           if (User->getOpcode() == ISD::BR) {
9930             SDValue FalseBB = User->getOperand(1);
9931             SDNode *NewBR =
9932               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9933             assert(NewBR == User);
9934             (void)NewBR;
9935             Dest = FalseBB;
9936
9937             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9938                                 Chain, Dest, CC, Cmp);
9939             X86::CondCode CCode =
9940               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9941             CCode = X86::GetOppositeBranchCondition(CCode);
9942             CC = DAG.getConstant(CCode, MVT::i8);
9943             Cond = Cmp;
9944             addTest = false;
9945           }
9946         }
9947       }
9948     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9949       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9950       // It should be transformed during dag combiner except when the condition
9951       // is set by a arithmetics with overflow node.
9952       X86::CondCode CCode =
9953         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9954       CCode = X86::GetOppositeBranchCondition(CCode);
9955       CC = DAG.getConstant(CCode, MVT::i8);
9956       Cond = Cond.getOperand(0).getOperand(1);
9957       addTest = false;
9958     } else if (Cond.getOpcode() == ISD::SETCC &&
9959                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9960       // For FCMP_OEQ, we can emit
9961       // two branches instead of an explicit AND instruction with a
9962       // separate test. However, we only do this if this block doesn't
9963       // have a fall-through edge, because this requires an explicit
9964       // jmp when the condition is false.
9965       if (Op.getNode()->hasOneUse()) {
9966         SDNode *User = *Op.getNode()->use_begin();
9967         // Look for an unconditional branch following this conditional branch.
9968         // We need this because we need to reverse the successors in order
9969         // to implement FCMP_OEQ.
9970         if (User->getOpcode() == ISD::BR) {
9971           SDValue FalseBB = User->getOperand(1);
9972           SDNode *NewBR =
9973             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9974           assert(NewBR == User);
9975           (void)NewBR;
9976           Dest = FalseBB;
9977
9978           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9979                                     Cond.getOperand(0), Cond.getOperand(1));
9980           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9981           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9982           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9983                               Chain, Dest, CC, Cmp);
9984           CC = DAG.getConstant(X86::COND_P, MVT::i8);
9985           Cond = Cmp;
9986           addTest = false;
9987         }
9988       }
9989     } else if (Cond.getOpcode() == ISD::SETCC &&
9990                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9991       // For FCMP_UNE, we can emit
9992       // two branches instead of an explicit AND instruction with a
9993       // separate test. However, we only do this if this block doesn't
9994       // have a fall-through edge, because this requires an explicit
9995       // jmp when the condition is false.
9996       if (Op.getNode()->hasOneUse()) {
9997         SDNode *User = *Op.getNode()->use_begin();
9998         // Look for an unconditional branch following this conditional branch.
9999         // We need this because we need to reverse the successors in order
10000         // to implement FCMP_UNE.
10001         if (User->getOpcode() == ISD::BR) {
10002           SDValue FalseBB = User->getOperand(1);
10003           SDNode *NewBR =
10004             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10005           assert(NewBR == User);
10006           (void)NewBR;
10007
10008           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10009                                     Cond.getOperand(0), Cond.getOperand(1));
10010           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10011           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10012           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10013                               Chain, Dest, CC, Cmp);
10014           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
10015           Cond = Cmp;
10016           addTest = false;
10017           Dest = FalseBB;
10018         }
10019       }
10020     }
10021   }
10022
10023   if (addTest) {
10024     // Look pass the truncate if the high bits are known zero.
10025     if (isTruncWithZeroHighBitsInput(Cond, DAG))
10026         Cond = Cond.getOperand(0);
10027
10028     // We know the result of AND is compared against zero. Try to match
10029     // it to BT.
10030     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10031       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
10032       if (NewSetCC.getNode()) {
10033         CC = NewSetCC.getOperand(0);
10034         Cond = NewSetCC.getOperand(1);
10035         addTest = false;
10036       }
10037     }
10038   }
10039
10040   if (addTest) {
10041     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10042     Cond = EmitTest(Cond, X86::COND_NE, DAG);
10043   }
10044   Cond = ConvertCmpIfNecessary(Cond, DAG);
10045   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10046                      Chain, Dest, CC, Cond);
10047 }
10048
10049 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
10050 // Calls to _alloca is needed to probe the stack when allocating more than 4k
10051 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
10052 // that the guard pages used by the OS virtual memory manager are allocated in
10053 // correct sequence.
10054 SDValue
10055 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
10056                                            SelectionDAG &DAG) const {
10057   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
10058           getTargetMachine().Options.EnableSegmentedStacks) &&
10059          "This should be used only on Windows targets or when segmented stacks "
10060          "are being used");
10061   assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
10062   DebugLoc dl = Op.getDebugLoc();
10063
10064   // Get the inputs.
10065   SDValue Chain = Op.getOperand(0);
10066   SDValue Size  = Op.getOperand(1);
10067   // FIXME: Ensure alignment here
10068
10069   bool Is64Bit = Subtarget->is64Bit();
10070   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
10071
10072   if (getTargetMachine().Options.EnableSegmentedStacks) {
10073     MachineFunction &MF = DAG.getMachineFunction();
10074     MachineRegisterInfo &MRI = MF.getRegInfo();
10075
10076     if (Is64Bit) {
10077       // The 64 bit implementation of segmented stacks needs to clobber both r10
10078       // r11. This makes it impossible to use it along with nested parameters.
10079       const Function *F = MF.getFunction();
10080
10081       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
10082            I != E; ++I)
10083         if (I->hasNestAttr())
10084           report_fatal_error("Cannot use segmented stacks with functions that "
10085                              "have nested arguments.");
10086     }
10087
10088     const TargetRegisterClass *AddrRegClass =
10089       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
10090     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
10091     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
10092     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
10093                                 DAG.getRegister(Vreg, SPTy));
10094     SDValue Ops1[2] = { Value, Chain };
10095     return DAG.getMergeValues(Ops1, 2, dl);
10096   } else {
10097     SDValue Flag;
10098     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
10099
10100     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
10101     Flag = Chain.getValue(1);
10102     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10103
10104     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
10105     Flag = Chain.getValue(1);
10106
10107     Chain = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
10108                                SPTy).getValue(1);
10109
10110     SDValue Ops1[2] = { Chain.getValue(0), Chain };
10111     return DAG.getMergeValues(Ops1, 2, dl);
10112   }
10113 }
10114
10115 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
10116   MachineFunction &MF = DAG.getMachineFunction();
10117   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
10118
10119   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10120   DebugLoc DL = Op.getDebugLoc();
10121
10122   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
10123     // vastart just stores the address of the VarArgsFrameIndex slot into the
10124     // memory location argument.
10125     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10126                                    getPointerTy());
10127     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
10128                         MachinePointerInfo(SV), false, false, 0);
10129   }
10130
10131   // __va_list_tag:
10132   //   gp_offset         (0 - 6 * 8)
10133   //   fp_offset         (48 - 48 + 8 * 16)
10134   //   overflow_arg_area (point to parameters coming in memory).
10135   //   reg_save_area
10136   SmallVector<SDValue, 8> MemOps;
10137   SDValue FIN = Op.getOperand(1);
10138   // Store gp_offset
10139   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
10140                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
10141                                                MVT::i32),
10142                                FIN, MachinePointerInfo(SV), false, false, 0);
10143   MemOps.push_back(Store);
10144
10145   // Store fp_offset
10146   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10147                     FIN, DAG.getIntPtrConstant(4));
10148   Store = DAG.getStore(Op.getOperand(0), DL,
10149                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
10150                                        MVT::i32),
10151                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
10152   MemOps.push_back(Store);
10153
10154   // Store ptr to overflow_arg_area
10155   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10156                     FIN, DAG.getIntPtrConstant(4));
10157   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10158                                     getPointerTy());
10159   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
10160                        MachinePointerInfo(SV, 8),
10161                        false, false, 0);
10162   MemOps.push_back(Store);
10163
10164   // Store ptr to reg_save_area.
10165   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10166                     FIN, DAG.getIntPtrConstant(8));
10167   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
10168                                     getPointerTy());
10169   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
10170                        MachinePointerInfo(SV, 16), false, false, 0);
10171   MemOps.push_back(Store);
10172   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
10173                      &MemOps[0], MemOps.size());
10174 }
10175
10176 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
10177   assert(Subtarget->is64Bit() &&
10178          "LowerVAARG only handles 64-bit va_arg!");
10179   assert((Subtarget->isTargetLinux() ||
10180           Subtarget->isTargetDarwin()) &&
10181           "Unhandled target in LowerVAARG");
10182   assert(Op.getNode()->getNumOperands() == 4);
10183   SDValue Chain = Op.getOperand(0);
10184   SDValue SrcPtr = Op.getOperand(1);
10185   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10186   unsigned Align = Op.getConstantOperandVal(3);
10187   DebugLoc dl = Op.getDebugLoc();
10188
10189   EVT ArgVT = Op.getNode()->getValueType(0);
10190   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10191   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
10192   uint8_t ArgMode;
10193
10194   // Decide which area this value should be read from.
10195   // TODO: Implement the AMD64 ABI in its entirety. This simple
10196   // selection mechanism works only for the basic types.
10197   if (ArgVT == MVT::f80) {
10198     llvm_unreachable("va_arg for f80 not yet implemented");
10199   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
10200     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
10201   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
10202     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
10203   } else {
10204     llvm_unreachable("Unhandled argument type in LowerVAARG");
10205   }
10206
10207   if (ArgMode == 2) {
10208     // Sanity Check: Make sure using fp_offset makes sense.
10209     assert(!getTargetMachine().Options.UseSoftFloat &&
10210            !(DAG.getMachineFunction()
10211                 .getFunction()->getAttributes()
10212                 .hasAttribute(AttributeSet::FunctionIndex,
10213                               Attribute::NoImplicitFloat)) &&
10214            Subtarget->hasSSE1());
10215   }
10216
10217   // Insert VAARG_64 node into the DAG
10218   // VAARG_64 returns two values: Variable Argument Address, Chain
10219   SmallVector<SDValue, 11> InstOps;
10220   InstOps.push_back(Chain);
10221   InstOps.push_back(SrcPtr);
10222   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
10223   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
10224   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
10225   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
10226   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
10227                                           VTs, &InstOps[0], InstOps.size(),
10228                                           MVT::i64,
10229                                           MachinePointerInfo(SV),
10230                                           /*Align=*/0,
10231                                           /*Volatile=*/false,
10232                                           /*ReadMem=*/true,
10233                                           /*WriteMem=*/true);
10234   Chain = VAARG.getValue(1);
10235
10236   // Load the next argument and return it
10237   return DAG.getLoad(ArgVT, dl,
10238                      Chain,
10239                      VAARG,
10240                      MachinePointerInfo(),
10241                      false, false, false, 0);
10242 }
10243
10244 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
10245                            SelectionDAG &DAG) {
10246   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
10247   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
10248   SDValue Chain = Op.getOperand(0);
10249   SDValue DstPtr = Op.getOperand(1);
10250   SDValue SrcPtr = Op.getOperand(2);
10251   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
10252   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10253   DebugLoc DL = Op.getDebugLoc();
10254
10255   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
10256                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
10257                        false,
10258                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
10259 }
10260
10261 // getTargetVShiftNode - Handle vector element shifts where the shift amount
10262 // may or may not be a constant. Takes immediate version of shift as input.
10263 static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
10264                                    SDValue SrcOp, SDValue ShAmt,
10265                                    SelectionDAG &DAG) {
10266   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
10267
10268   if (isa<ConstantSDNode>(ShAmt)) {
10269     // Constant may be a TargetConstant. Use a regular constant.
10270     uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
10271     switch (Opc) {
10272       default: llvm_unreachable("Unknown target vector shift node");
10273       case X86ISD::VSHLI:
10274       case X86ISD::VSRLI:
10275       case X86ISD::VSRAI:
10276         return DAG.getNode(Opc, dl, VT, SrcOp,
10277                            DAG.getConstant(ShiftAmt, MVT::i32));
10278     }
10279   }
10280
10281   // Change opcode to non-immediate version
10282   switch (Opc) {
10283     default: llvm_unreachable("Unknown target vector shift node");
10284     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
10285     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
10286     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
10287   }
10288
10289   // Need to build a vector containing shift amount
10290   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
10291   SDValue ShOps[4];
10292   ShOps[0] = ShAmt;
10293   ShOps[1] = DAG.getConstant(0, MVT::i32);
10294   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
10295   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
10296
10297   // The return type has to be a 128-bit type with the same element
10298   // type as the input type.
10299   MVT EltVT = VT.getVectorElementType().getSimpleVT();
10300   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
10301
10302   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
10303   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
10304 }
10305
10306 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
10307   DebugLoc dl = Op.getDebugLoc();
10308   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10309   switch (IntNo) {
10310   default: return SDValue();    // Don't custom lower most intrinsics.
10311   // Comparison intrinsics.
10312   case Intrinsic::x86_sse_comieq_ss:
10313   case Intrinsic::x86_sse_comilt_ss:
10314   case Intrinsic::x86_sse_comile_ss:
10315   case Intrinsic::x86_sse_comigt_ss:
10316   case Intrinsic::x86_sse_comige_ss:
10317   case Intrinsic::x86_sse_comineq_ss:
10318   case Intrinsic::x86_sse_ucomieq_ss:
10319   case Intrinsic::x86_sse_ucomilt_ss:
10320   case Intrinsic::x86_sse_ucomile_ss:
10321   case Intrinsic::x86_sse_ucomigt_ss:
10322   case Intrinsic::x86_sse_ucomige_ss:
10323   case Intrinsic::x86_sse_ucomineq_ss:
10324   case Intrinsic::x86_sse2_comieq_sd:
10325   case Intrinsic::x86_sse2_comilt_sd:
10326   case Intrinsic::x86_sse2_comile_sd:
10327   case Intrinsic::x86_sse2_comigt_sd:
10328   case Intrinsic::x86_sse2_comige_sd:
10329   case Intrinsic::x86_sse2_comineq_sd:
10330   case Intrinsic::x86_sse2_ucomieq_sd:
10331   case Intrinsic::x86_sse2_ucomilt_sd:
10332   case Intrinsic::x86_sse2_ucomile_sd:
10333   case Intrinsic::x86_sse2_ucomigt_sd:
10334   case Intrinsic::x86_sse2_ucomige_sd:
10335   case Intrinsic::x86_sse2_ucomineq_sd: {
10336     unsigned Opc;
10337     ISD::CondCode CC;
10338     switch (IntNo) {
10339     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10340     case Intrinsic::x86_sse_comieq_ss:
10341     case Intrinsic::x86_sse2_comieq_sd:
10342       Opc = X86ISD::COMI;
10343       CC = ISD::SETEQ;
10344       break;
10345     case Intrinsic::x86_sse_comilt_ss:
10346     case Intrinsic::x86_sse2_comilt_sd:
10347       Opc = X86ISD::COMI;
10348       CC = ISD::SETLT;
10349       break;
10350     case Intrinsic::x86_sse_comile_ss:
10351     case Intrinsic::x86_sse2_comile_sd:
10352       Opc = X86ISD::COMI;
10353       CC = ISD::SETLE;
10354       break;
10355     case Intrinsic::x86_sse_comigt_ss:
10356     case Intrinsic::x86_sse2_comigt_sd:
10357       Opc = X86ISD::COMI;
10358       CC = ISD::SETGT;
10359       break;
10360     case Intrinsic::x86_sse_comige_ss:
10361     case Intrinsic::x86_sse2_comige_sd:
10362       Opc = X86ISD::COMI;
10363       CC = ISD::SETGE;
10364       break;
10365     case Intrinsic::x86_sse_comineq_ss:
10366     case Intrinsic::x86_sse2_comineq_sd:
10367       Opc = X86ISD::COMI;
10368       CC = ISD::SETNE;
10369       break;
10370     case Intrinsic::x86_sse_ucomieq_ss:
10371     case Intrinsic::x86_sse2_ucomieq_sd:
10372       Opc = X86ISD::UCOMI;
10373       CC = ISD::SETEQ;
10374       break;
10375     case Intrinsic::x86_sse_ucomilt_ss:
10376     case Intrinsic::x86_sse2_ucomilt_sd:
10377       Opc = X86ISD::UCOMI;
10378       CC = ISD::SETLT;
10379       break;
10380     case Intrinsic::x86_sse_ucomile_ss:
10381     case Intrinsic::x86_sse2_ucomile_sd:
10382       Opc = X86ISD::UCOMI;
10383       CC = ISD::SETLE;
10384       break;
10385     case Intrinsic::x86_sse_ucomigt_ss:
10386     case Intrinsic::x86_sse2_ucomigt_sd:
10387       Opc = X86ISD::UCOMI;
10388       CC = ISD::SETGT;
10389       break;
10390     case Intrinsic::x86_sse_ucomige_ss:
10391     case Intrinsic::x86_sse2_ucomige_sd:
10392       Opc = X86ISD::UCOMI;
10393       CC = ISD::SETGE;
10394       break;
10395     case Intrinsic::x86_sse_ucomineq_ss:
10396     case Intrinsic::x86_sse2_ucomineq_sd:
10397       Opc = X86ISD::UCOMI;
10398       CC = ISD::SETNE;
10399       break;
10400     }
10401
10402     SDValue LHS = Op.getOperand(1);
10403     SDValue RHS = Op.getOperand(2);
10404     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
10405     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
10406     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
10407     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10408                                 DAG.getConstant(X86CC, MVT::i8), Cond);
10409     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10410   }
10411
10412   // Arithmetic intrinsics.
10413   case Intrinsic::x86_sse2_pmulu_dq:
10414   case Intrinsic::x86_avx2_pmulu_dq:
10415     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
10416                        Op.getOperand(1), Op.getOperand(2));
10417
10418   // SSE2/AVX2 sub with unsigned saturation intrinsics
10419   case Intrinsic::x86_sse2_psubus_b:
10420   case Intrinsic::x86_sse2_psubus_w:
10421   case Intrinsic::x86_avx2_psubus_b:
10422   case Intrinsic::x86_avx2_psubus_w:
10423     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
10424                        Op.getOperand(1), Op.getOperand(2));
10425
10426   // SSE3/AVX horizontal add/sub intrinsics
10427   case Intrinsic::x86_sse3_hadd_ps:
10428   case Intrinsic::x86_sse3_hadd_pd:
10429   case Intrinsic::x86_avx_hadd_ps_256:
10430   case Intrinsic::x86_avx_hadd_pd_256:
10431   case Intrinsic::x86_sse3_hsub_ps:
10432   case Intrinsic::x86_sse3_hsub_pd:
10433   case Intrinsic::x86_avx_hsub_ps_256:
10434   case Intrinsic::x86_avx_hsub_pd_256:
10435   case Intrinsic::x86_ssse3_phadd_w_128:
10436   case Intrinsic::x86_ssse3_phadd_d_128:
10437   case Intrinsic::x86_avx2_phadd_w:
10438   case Intrinsic::x86_avx2_phadd_d:
10439   case Intrinsic::x86_ssse3_phsub_w_128:
10440   case Intrinsic::x86_ssse3_phsub_d_128:
10441   case Intrinsic::x86_avx2_phsub_w:
10442   case Intrinsic::x86_avx2_phsub_d: {
10443     unsigned Opcode;
10444     switch (IntNo) {
10445     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10446     case Intrinsic::x86_sse3_hadd_ps:
10447     case Intrinsic::x86_sse3_hadd_pd:
10448     case Intrinsic::x86_avx_hadd_ps_256:
10449     case Intrinsic::x86_avx_hadd_pd_256:
10450       Opcode = X86ISD::FHADD;
10451       break;
10452     case Intrinsic::x86_sse3_hsub_ps:
10453     case Intrinsic::x86_sse3_hsub_pd:
10454     case Intrinsic::x86_avx_hsub_ps_256:
10455     case Intrinsic::x86_avx_hsub_pd_256:
10456       Opcode = X86ISD::FHSUB;
10457       break;
10458     case Intrinsic::x86_ssse3_phadd_w_128:
10459     case Intrinsic::x86_ssse3_phadd_d_128:
10460     case Intrinsic::x86_avx2_phadd_w:
10461     case Intrinsic::x86_avx2_phadd_d:
10462       Opcode = X86ISD::HADD;
10463       break;
10464     case Intrinsic::x86_ssse3_phsub_w_128:
10465     case Intrinsic::x86_ssse3_phsub_d_128:
10466     case Intrinsic::x86_avx2_phsub_w:
10467     case Intrinsic::x86_avx2_phsub_d:
10468       Opcode = X86ISD::HSUB;
10469       break;
10470     }
10471     return DAG.getNode(Opcode, dl, Op.getValueType(),
10472                        Op.getOperand(1), Op.getOperand(2));
10473   }
10474
10475   // SSE2/SSE41/AVX2 integer max/min intrinsics.
10476   case Intrinsic::x86_sse2_pmaxu_b:
10477   case Intrinsic::x86_sse41_pmaxuw:
10478   case Intrinsic::x86_sse41_pmaxud:
10479   case Intrinsic::x86_avx2_pmaxu_b:
10480   case Intrinsic::x86_avx2_pmaxu_w:
10481   case Intrinsic::x86_avx2_pmaxu_d:
10482   case Intrinsic::x86_sse2_pminu_b:
10483   case Intrinsic::x86_sse41_pminuw:
10484   case Intrinsic::x86_sse41_pminud:
10485   case Intrinsic::x86_avx2_pminu_b:
10486   case Intrinsic::x86_avx2_pminu_w:
10487   case Intrinsic::x86_avx2_pminu_d:
10488   case Intrinsic::x86_sse41_pmaxsb:
10489   case Intrinsic::x86_sse2_pmaxs_w:
10490   case Intrinsic::x86_sse41_pmaxsd:
10491   case Intrinsic::x86_avx2_pmaxs_b:
10492   case Intrinsic::x86_avx2_pmaxs_w:
10493   case Intrinsic::x86_avx2_pmaxs_d:
10494   case Intrinsic::x86_sse41_pminsb:
10495   case Intrinsic::x86_sse2_pmins_w:
10496   case Intrinsic::x86_sse41_pminsd:
10497   case Intrinsic::x86_avx2_pmins_b:
10498   case Intrinsic::x86_avx2_pmins_w:
10499   case Intrinsic::x86_avx2_pmins_d: {
10500     unsigned Opcode;
10501     switch (IntNo) {
10502     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10503     case Intrinsic::x86_sse2_pmaxu_b:
10504     case Intrinsic::x86_sse41_pmaxuw:
10505     case Intrinsic::x86_sse41_pmaxud:
10506     case Intrinsic::x86_avx2_pmaxu_b:
10507     case Intrinsic::x86_avx2_pmaxu_w:
10508     case Intrinsic::x86_avx2_pmaxu_d:
10509       Opcode = X86ISD::UMAX;
10510       break;
10511     case Intrinsic::x86_sse2_pminu_b:
10512     case Intrinsic::x86_sse41_pminuw:
10513     case Intrinsic::x86_sse41_pminud:
10514     case Intrinsic::x86_avx2_pminu_b:
10515     case Intrinsic::x86_avx2_pminu_w:
10516     case Intrinsic::x86_avx2_pminu_d:
10517       Opcode = X86ISD::UMIN;
10518       break;
10519     case Intrinsic::x86_sse41_pmaxsb:
10520     case Intrinsic::x86_sse2_pmaxs_w:
10521     case Intrinsic::x86_sse41_pmaxsd:
10522     case Intrinsic::x86_avx2_pmaxs_b:
10523     case Intrinsic::x86_avx2_pmaxs_w:
10524     case Intrinsic::x86_avx2_pmaxs_d:
10525       Opcode = X86ISD::SMAX;
10526       break;
10527     case Intrinsic::x86_sse41_pminsb:
10528     case Intrinsic::x86_sse2_pmins_w:
10529     case Intrinsic::x86_sse41_pminsd:
10530     case Intrinsic::x86_avx2_pmins_b:
10531     case Intrinsic::x86_avx2_pmins_w:
10532     case Intrinsic::x86_avx2_pmins_d:
10533       Opcode = X86ISD::SMIN;
10534       break;
10535     }
10536     return DAG.getNode(Opcode, dl, Op.getValueType(),
10537                        Op.getOperand(1), Op.getOperand(2));
10538   }
10539
10540   // SSE/SSE2/AVX floating point max/min intrinsics.
10541   case Intrinsic::x86_sse_max_ps:
10542   case Intrinsic::x86_sse2_max_pd:
10543   case Intrinsic::x86_avx_max_ps_256:
10544   case Intrinsic::x86_avx_max_pd_256:
10545   case Intrinsic::x86_sse_min_ps:
10546   case Intrinsic::x86_sse2_min_pd:
10547   case Intrinsic::x86_avx_min_ps_256:
10548   case Intrinsic::x86_avx_min_pd_256: {
10549     unsigned Opcode;
10550     switch (IntNo) {
10551     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10552     case Intrinsic::x86_sse_max_ps:
10553     case Intrinsic::x86_sse2_max_pd:
10554     case Intrinsic::x86_avx_max_ps_256:
10555     case Intrinsic::x86_avx_max_pd_256:
10556       Opcode = X86ISD::FMAX;
10557       break;
10558     case Intrinsic::x86_sse_min_ps:
10559     case Intrinsic::x86_sse2_min_pd:
10560     case Intrinsic::x86_avx_min_ps_256:
10561     case Intrinsic::x86_avx_min_pd_256:
10562       Opcode = X86ISD::FMIN;
10563       break;
10564     }
10565     return DAG.getNode(Opcode, dl, Op.getValueType(),
10566                        Op.getOperand(1), Op.getOperand(2));
10567   }
10568
10569   // AVX2 variable shift intrinsics
10570   case Intrinsic::x86_avx2_psllv_d:
10571   case Intrinsic::x86_avx2_psllv_q:
10572   case Intrinsic::x86_avx2_psllv_d_256:
10573   case Intrinsic::x86_avx2_psllv_q_256:
10574   case Intrinsic::x86_avx2_psrlv_d:
10575   case Intrinsic::x86_avx2_psrlv_q:
10576   case Intrinsic::x86_avx2_psrlv_d_256:
10577   case Intrinsic::x86_avx2_psrlv_q_256:
10578   case Intrinsic::x86_avx2_psrav_d:
10579   case Intrinsic::x86_avx2_psrav_d_256: {
10580     unsigned Opcode;
10581     switch (IntNo) {
10582     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10583     case Intrinsic::x86_avx2_psllv_d:
10584     case Intrinsic::x86_avx2_psllv_q:
10585     case Intrinsic::x86_avx2_psllv_d_256:
10586     case Intrinsic::x86_avx2_psllv_q_256:
10587       Opcode = ISD::SHL;
10588       break;
10589     case Intrinsic::x86_avx2_psrlv_d:
10590     case Intrinsic::x86_avx2_psrlv_q:
10591     case Intrinsic::x86_avx2_psrlv_d_256:
10592     case Intrinsic::x86_avx2_psrlv_q_256:
10593       Opcode = ISD::SRL;
10594       break;
10595     case Intrinsic::x86_avx2_psrav_d:
10596     case Intrinsic::x86_avx2_psrav_d_256:
10597       Opcode = ISD::SRA;
10598       break;
10599     }
10600     return DAG.getNode(Opcode, dl, Op.getValueType(),
10601                        Op.getOperand(1), Op.getOperand(2));
10602   }
10603
10604   case Intrinsic::x86_ssse3_pshuf_b_128:
10605   case Intrinsic::x86_avx2_pshuf_b:
10606     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
10607                        Op.getOperand(1), Op.getOperand(2));
10608
10609   case Intrinsic::x86_ssse3_psign_b_128:
10610   case Intrinsic::x86_ssse3_psign_w_128:
10611   case Intrinsic::x86_ssse3_psign_d_128:
10612   case Intrinsic::x86_avx2_psign_b:
10613   case Intrinsic::x86_avx2_psign_w:
10614   case Intrinsic::x86_avx2_psign_d:
10615     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
10616                        Op.getOperand(1), Op.getOperand(2));
10617
10618   case Intrinsic::x86_sse41_insertps:
10619     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
10620                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10621
10622   case Intrinsic::x86_avx_vperm2f128_ps_256:
10623   case Intrinsic::x86_avx_vperm2f128_pd_256:
10624   case Intrinsic::x86_avx_vperm2f128_si_256:
10625   case Intrinsic::x86_avx2_vperm2i128:
10626     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
10627                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10628
10629   case Intrinsic::x86_avx2_permd:
10630   case Intrinsic::x86_avx2_permps:
10631     // Operands intentionally swapped. Mask is last operand to intrinsic,
10632     // but second operand for node/intruction.
10633     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
10634                        Op.getOperand(2), Op.getOperand(1));
10635
10636   case Intrinsic::x86_sse_sqrt_ps:
10637   case Intrinsic::x86_sse2_sqrt_pd:
10638   case Intrinsic::x86_avx_sqrt_ps_256:
10639   case Intrinsic::x86_avx_sqrt_pd_256:
10640     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
10641
10642   // ptest and testp intrinsics. The intrinsic these come from are designed to
10643   // return an integer value, not just an instruction so lower it to the ptest
10644   // or testp pattern and a setcc for the result.
10645   case Intrinsic::x86_sse41_ptestz:
10646   case Intrinsic::x86_sse41_ptestc:
10647   case Intrinsic::x86_sse41_ptestnzc:
10648   case Intrinsic::x86_avx_ptestz_256:
10649   case Intrinsic::x86_avx_ptestc_256:
10650   case Intrinsic::x86_avx_ptestnzc_256:
10651   case Intrinsic::x86_avx_vtestz_ps:
10652   case Intrinsic::x86_avx_vtestc_ps:
10653   case Intrinsic::x86_avx_vtestnzc_ps:
10654   case Intrinsic::x86_avx_vtestz_pd:
10655   case Intrinsic::x86_avx_vtestc_pd:
10656   case Intrinsic::x86_avx_vtestnzc_pd:
10657   case Intrinsic::x86_avx_vtestz_ps_256:
10658   case Intrinsic::x86_avx_vtestc_ps_256:
10659   case Intrinsic::x86_avx_vtestnzc_ps_256:
10660   case Intrinsic::x86_avx_vtestz_pd_256:
10661   case Intrinsic::x86_avx_vtestc_pd_256:
10662   case Intrinsic::x86_avx_vtestnzc_pd_256: {
10663     bool IsTestPacked = false;
10664     unsigned X86CC;
10665     switch (IntNo) {
10666     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
10667     case Intrinsic::x86_avx_vtestz_ps:
10668     case Intrinsic::x86_avx_vtestz_pd:
10669     case Intrinsic::x86_avx_vtestz_ps_256:
10670     case Intrinsic::x86_avx_vtestz_pd_256:
10671       IsTestPacked = true; // Fallthrough
10672     case Intrinsic::x86_sse41_ptestz:
10673     case Intrinsic::x86_avx_ptestz_256:
10674       // ZF = 1
10675       X86CC = X86::COND_E;
10676       break;
10677     case Intrinsic::x86_avx_vtestc_ps:
10678     case Intrinsic::x86_avx_vtestc_pd:
10679     case Intrinsic::x86_avx_vtestc_ps_256:
10680     case Intrinsic::x86_avx_vtestc_pd_256:
10681       IsTestPacked = true; // Fallthrough
10682     case Intrinsic::x86_sse41_ptestc:
10683     case Intrinsic::x86_avx_ptestc_256:
10684       // CF = 1
10685       X86CC = X86::COND_B;
10686       break;
10687     case Intrinsic::x86_avx_vtestnzc_ps:
10688     case Intrinsic::x86_avx_vtestnzc_pd:
10689     case Intrinsic::x86_avx_vtestnzc_ps_256:
10690     case Intrinsic::x86_avx_vtestnzc_pd_256:
10691       IsTestPacked = true; // Fallthrough
10692     case Intrinsic::x86_sse41_ptestnzc:
10693     case Intrinsic::x86_avx_ptestnzc_256:
10694       // ZF and CF = 0
10695       X86CC = X86::COND_A;
10696       break;
10697     }
10698
10699     SDValue LHS = Op.getOperand(1);
10700     SDValue RHS = Op.getOperand(2);
10701     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
10702     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
10703     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
10704     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
10705     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10706   }
10707
10708   // SSE/AVX shift intrinsics
10709   case Intrinsic::x86_sse2_psll_w:
10710   case Intrinsic::x86_sse2_psll_d:
10711   case Intrinsic::x86_sse2_psll_q:
10712   case Intrinsic::x86_avx2_psll_w:
10713   case Intrinsic::x86_avx2_psll_d:
10714   case Intrinsic::x86_avx2_psll_q:
10715   case Intrinsic::x86_sse2_psrl_w:
10716   case Intrinsic::x86_sse2_psrl_d:
10717   case Intrinsic::x86_sse2_psrl_q:
10718   case Intrinsic::x86_avx2_psrl_w:
10719   case Intrinsic::x86_avx2_psrl_d:
10720   case Intrinsic::x86_avx2_psrl_q:
10721   case Intrinsic::x86_sse2_psra_w:
10722   case Intrinsic::x86_sse2_psra_d:
10723   case Intrinsic::x86_avx2_psra_w:
10724   case Intrinsic::x86_avx2_psra_d: {
10725     unsigned Opcode;
10726     switch (IntNo) {
10727     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10728     case Intrinsic::x86_sse2_psll_w:
10729     case Intrinsic::x86_sse2_psll_d:
10730     case Intrinsic::x86_sse2_psll_q:
10731     case Intrinsic::x86_avx2_psll_w:
10732     case Intrinsic::x86_avx2_psll_d:
10733     case Intrinsic::x86_avx2_psll_q:
10734       Opcode = X86ISD::VSHL;
10735       break;
10736     case Intrinsic::x86_sse2_psrl_w:
10737     case Intrinsic::x86_sse2_psrl_d:
10738     case Intrinsic::x86_sse2_psrl_q:
10739     case Intrinsic::x86_avx2_psrl_w:
10740     case Intrinsic::x86_avx2_psrl_d:
10741     case Intrinsic::x86_avx2_psrl_q:
10742       Opcode = X86ISD::VSRL;
10743       break;
10744     case Intrinsic::x86_sse2_psra_w:
10745     case Intrinsic::x86_sse2_psra_d:
10746     case Intrinsic::x86_avx2_psra_w:
10747     case Intrinsic::x86_avx2_psra_d:
10748       Opcode = X86ISD::VSRA;
10749       break;
10750     }
10751     return DAG.getNode(Opcode, dl, Op.getValueType(),
10752                        Op.getOperand(1), Op.getOperand(2));
10753   }
10754
10755   // SSE/AVX immediate shift intrinsics
10756   case Intrinsic::x86_sse2_pslli_w:
10757   case Intrinsic::x86_sse2_pslli_d:
10758   case Intrinsic::x86_sse2_pslli_q:
10759   case Intrinsic::x86_avx2_pslli_w:
10760   case Intrinsic::x86_avx2_pslli_d:
10761   case Intrinsic::x86_avx2_pslli_q:
10762   case Intrinsic::x86_sse2_psrli_w:
10763   case Intrinsic::x86_sse2_psrli_d:
10764   case Intrinsic::x86_sse2_psrli_q:
10765   case Intrinsic::x86_avx2_psrli_w:
10766   case Intrinsic::x86_avx2_psrli_d:
10767   case Intrinsic::x86_avx2_psrli_q:
10768   case Intrinsic::x86_sse2_psrai_w:
10769   case Intrinsic::x86_sse2_psrai_d:
10770   case Intrinsic::x86_avx2_psrai_w:
10771   case Intrinsic::x86_avx2_psrai_d: {
10772     unsigned Opcode;
10773     switch (IntNo) {
10774     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10775     case Intrinsic::x86_sse2_pslli_w:
10776     case Intrinsic::x86_sse2_pslli_d:
10777     case Intrinsic::x86_sse2_pslli_q:
10778     case Intrinsic::x86_avx2_pslli_w:
10779     case Intrinsic::x86_avx2_pslli_d:
10780     case Intrinsic::x86_avx2_pslli_q:
10781       Opcode = X86ISD::VSHLI;
10782       break;
10783     case Intrinsic::x86_sse2_psrli_w:
10784     case Intrinsic::x86_sse2_psrli_d:
10785     case Intrinsic::x86_sse2_psrli_q:
10786     case Intrinsic::x86_avx2_psrli_w:
10787     case Intrinsic::x86_avx2_psrli_d:
10788     case Intrinsic::x86_avx2_psrli_q:
10789       Opcode = X86ISD::VSRLI;
10790       break;
10791     case Intrinsic::x86_sse2_psrai_w:
10792     case Intrinsic::x86_sse2_psrai_d:
10793     case Intrinsic::x86_avx2_psrai_w:
10794     case Intrinsic::x86_avx2_psrai_d:
10795       Opcode = X86ISD::VSRAI;
10796       break;
10797     }
10798     return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
10799                                Op.getOperand(1), Op.getOperand(2), DAG);
10800   }
10801
10802   case Intrinsic::x86_sse42_pcmpistria128:
10803   case Intrinsic::x86_sse42_pcmpestria128:
10804   case Intrinsic::x86_sse42_pcmpistric128:
10805   case Intrinsic::x86_sse42_pcmpestric128:
10806   case Intrinsic::x86_sse42_pcmpistrio128:
10807   case Intrinsic::x86_sse42_pcmpestrio128:
10808   case Intrinsic::x86_sse42_pcmpistris128:
10809   case Intrinsic::x86_sse42_pcmpestris128:
10810   case Intrinsic::x86_sse42_pcmpistriz128:
10811   case Intrinsic::x86_sse42_pcmpestriz128: {
10812     unsigned Opcode;
10813     unsigned X86CC;
10814     switch (IntNo) {
10815     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10816     case Intrinsic::x86_sse42_pcmpistria128:
10817       Opcode = X86ISD::PCMPISTRI;
10818       X86CC = X86::COND_A;
10819       break;
10820     case Intrinsic::x86_sse42_pcmpestria128:
10821       Opcode = X86ISD::PCMPESTRI;
10822       X86CC = X86::COND_A;
10823       break;
10824     case Intrinsic::x86_sse42_pcmpistric128:
10825       Opcode = X86ISD::PCMPISTRI;
10826       X86CC = X86::COND_B;
10827       break;
10828     case Intrinsic::x86_sse42_pcmpestric128:
10829       Opcode = X86ISD::PCMPESTRI;
10830       X86CC = X86::COND_B;
10831       break;
10832     case Intrinsic::x86_sse42_pcmpistrio128:
10833       Opcode = X86ISD::PCMPISTRI;
10834       X86CC = X86::COND_O;
10835       break;
10836     case Intrinsic::x86_sse42_pcmpestrio128:
10837       Opcode = X86ISD::PCMPESTRI;
10838       X86CC = X86::COND_O;
10839       break;
10840     case Intrinsic::x86_sse42_pcmpistris128:
10841       Opcode = X86ISD::PCMPISTRI;
10842       X86CC = X86::COND_S;
10843       break;
10844     case Intrinsic::x86_sse42_pcmpestris128:
10845       Opcode = X86ISD::PCMPESTRI;
10846       X86CC = X86::COND_S;
10847       break;
10848     case Intrinsic::x86_sse42_pcmpistriz128:
10849       Opcode = X86ISD::PCMPISTRI;
10850       X86CC = X86::COND_E;
10851       break;
10852     case Intrinsic::x86_sse42_pcmpestriz128:
10853       Opcode = X86ISD::PCMPESTRI;
10854       X86CC = X86::COND_E;
10855       break;
10856     }
10857     SmallVector<SDValue, 5> NewOps;
10858     NewOps.append(Op->op_begin()+1, Op->op_end());
10859     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10860     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10861     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10862                                 DAG.getConstant(X86CC, MVT::i8),
10863                                 SDValue(PCMP.getNode(), 1));
10864     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10865   }
10866
10867   case Intrinsic::x86_sse42_pcmpistri128:
10868   case Intrinsic::x86_sse42_pcmpestri128: {
10869     unsigned Opcode;
10870     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
10871       Opcode = X86ISD::PCMPISTRI;
10872     else
10873       Opcode = X86ISD::PCMPESTRI;
10874
10875     SmallVector<SDValue, 5> NewOps;
10876     NewOps.append(Op->op_begin()+1, Op->op_end());
10877     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10878     return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10879   }
10880   case Intrinsic::x86_fma_vfmadd_ps:
10881   case Intrinsic::x86_fma_vfmadd_pd:
10882   case Intrinsic::x86_fma_vfmsub_ps:
10883   case Intrinsic::x86_fma_vfmsub_pd:
10884   case Intrinsic::x86_fma_vfnmadd_ps:
10885   case Intrinsic::x86_fma_vfnmadd_pd:
10886   case Intrinsic::x86_fma_vfnmsub_ps:
10887   case Intrinsic::x86_fma_vfnmsub_pd:
10888   case Intrinsic::x86_fma_vfmaddsub_ps:
10889   case Intrinsic::x86_fma_vfmaddsub_pd:
10890   case Intrinsic::x86_fma_vfmsubadd_ps:
10891   case Intrinsic::x86_fma_vfmsubadd_pd:
10892   case Intrinsic::x86_fma_vfmadd_ps_256:
10893   case Intrinsic::x86_fma_vfmadd_pd_256:
10894   case Intrinsic::x86_fma_vfmsub_ps_256:
10895   case Intrinsic::x86_fma_vfmsub_pd_256:
10896   case Intrinsic::x86_fma_vfnmadd_ps_256:
10897   case Intrinsic::x86_fma_vfnmadd_pd_256:
10898   case Intrinsic::x86_fma_vfnmsub_ps_256:
10899   case Intrinsic::x86_fma_vfnmsub_pd_256:
10900   case Intrinsic::x86_fma_vfmaddsub_ps_256:
10901   case Intrinsic::x86_fma_vfmaddsub_pd_256:
10902   case Intrinsic::x86_fma_vfmsubadd_ps_256:
10903   case Intrinsic::x86_fma_vfmsubadd_pd_256: {
10904     unsigned Opc;
10905     switch (IntNo) {
10906     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10907     case Intrinsic::x86_fma_vfmadd_ps:
10908     case Intrinsic::x86_fma_vfmadd_pd:
10909     case Intrinsic::x86_fma_vfmadd_ps_256:
10910     case Intrinsic::x86_fma_vfmadd_pd_256:
10911       Opc = X86ISD::FMADD;
10912       break;
10913     case Intrinsic::x86_fma_vfmsub_ps:
10914     case Intrinsic::x86_fma_vfmsub_pd:
10915     case Intrinsic::x86_fma_vfmsub_ps_256:
10916     case Intrinsic::x86_fma_vfmsub_pd_256:
10917       Opc = X86ISD::FMSUB;
10918       break;
10919     case Intrinsic::x86_fma_vfnmadd_ps:
10920     case Intrinsic::x86_fma_vfnmadd_pd:
10921     case Intrinsic::x86_fma_vfnmadd_ps_256:
10922     case Intrinsic::x86_fma_vfnmadd_pd_256:
10923       Opc = X86ISD::FNMADD;
10924       break;
10925     case Intrinsic::x86_fma_vfnmsub_ps:
10926     case Intrinsic::x86_fma_vfnmsub_pd:
10927     case Intrinsic::x86_fma_vfnmsub_ps_256:
10928     case Intrinsic::x86_fma_vfnmsub_pd_256:
10929       Opc = X86ISD::FNMSUB;
10930       break;
10931     case Intrinsic::x86_fma_vfmaddsub_ps:
10932     case Intrinsic::x86_fma_vfmaddsub_pd:
10933     case Intrinsic::x86_fma_vfmaddsub_ps_256:
10934     case Intrinsic::x86_fma_vfmaddsub_pd_256:
10935       Opc = X86ISD::FMADDSUB;
10936       break;
10937     case Intrinsic::x86_fma_vfmsubadd_ps:
10938     case Intrinsic::x86_fma_vfmsubadd_pd:
10939     case Intrinsic::x86_fma_vfmsubadd_ps_256:
10940     case Intrinsic::x86_fma_vfmsubadd_pd_256:
10941       Opc = X86ISD::FMSUBADD;
10942       break;
10943     }
10944
10945     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
10946                        Op.getOperand(2), Op.getOperand(3));
10947   }
10948   }
10949 }
10950
10951 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) {
10952   DebugLoc dl = Op.getDebugLoc();
10953   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10954   switch (IntNo) {
10955   default: return SDValue();    // Don't custom lower most intrinsics.
10956
10957   // RDRAND/RDSEED intrinsics.
10958   case Intrinsic::x86_rdrand_16:
10959   case Intrinsic::x86_rdrand_32:
10960   case Intrinsic::x86_rdrand_64:
10961   case Intrinsic::x86_rdseed_16:
10962   case Intrinsic::x86_rdseed_32:
10963   case Intrinsic::x86_rdseed_64: {
10964     unsigned Opcode = (IntNo == Intrinsic::x86_rdseed_16 ||
10965                        IntNo == Intrinsic::x86_rdseed_32 ||
10966                        IntNo == Intrinsic::x86_rdseed_64) ? X86ISD::RDSEED :
10967                                                             X86ISD::RDRAND;
10968     // Emit the node with the right value type.
10969     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
10970     SDValue Result = DAG.getNode(Opcode, dl, VTs, Op.getOperand(0));
10971
10972     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
10973     // Otherwise return the value from Rand, which is always 0, casted to i32.
10974     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
10975                       DAG.getConstant(1, Op->getValueType(1)),
10976                       DAG.getConstant(X86::COND_B, MVT::i32),
10977                       SDValue(Result.getNode(), 1) };
10978     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
10979                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
10980                                   Ops, array_lengthof(Ops));
10981
10982     // Return { result, isValid, chain }.
10983     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
10984                        SDValue(Result.getNode(), 2));
10985   }
10986
10987   // XTEST intrinsics.
10988   case Intrinsic::x86_xtest: {
10989     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
10990     SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
10991     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10992                                 DAG.getConstant(X86::COND_NE, MVT::i8),
10993                                 InTrans);
10994     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
10995     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
10996                        Ret, SDValue(InTrans.getNode(), 1));
10997   }
10998   }
10999 }
11000
11001 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
11002                                            SelectionDAG &DAG) const {
11003   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11004   MFI->setReturnAddressIsTaken(true);
11005
11006   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11007   DebugLoc dl = Op.getDebugLoc();
11008   EVT PtrVT = getPointerTy();
11009
11010   if (Depth > 0) {
11011     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
11012     SDValue Offset =
11013       DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
11014     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
11015                        DAG.getNode(ISD::ADD, dl, PtrVT,
11016                                    FrameAddr, Offset),
11017                        MachinePointerInfo(), false, false, false, 0);
11018   }
11019
11020   // Just load the return address.
11021   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
11022   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
11023                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
11024 }
11025
11026 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
11027   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11028   MFI->setFrameAddressIsTaken(true);
11029
11030   EVT VT = Op.getValueType();
11031   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
11032   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11033   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
11034   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
11035           (FrameReg == X86::EBP && VT == MVT::i32)) &&
11036          "Invalid Frame Register!");
11037   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
11038   while (Depth--)
11039     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
11040                             MachinePointerInfo(),
11041                             false, false, false, 0);
11042   return FrameAddr;
11043 }
11044
11045 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
11046                                                      SelectionDAG &DAG) const {
11047   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
11048 }
11049
11050 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
11051   SDValue Chain     = Op.getOperand(0);
11052   SDValue Offset    = Op.getOperand(1);
11053   SDValue Handler   = Op.getOperand(2);
11054   DebugLoc dl       = Op.getDebugLoc();
11055
11056   EVT PtrVT = getPointerTy();
11057   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
11058   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
11059           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
11060          "Invalid Frame Register!");
11061   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
11062   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
11063
11064   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
11065                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
11066   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
11067   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
11068                        false, false, 0);
11069   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
11070
11071   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
11072                      DAG.getRegister(StoreAddrReg, PtrVT));
11073 }
11074
11075 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
11076                                                SelectionDAG &DAG) const {
11077   DebugLoc DL = Op.getDebugLoc();
11078   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
11079                      DAG.getVTList(MVT::i32, MVT::Other),
11080                      Op.getOperand(0), Op.getOperand(1));
11081 }
11082
11083 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
11084                                                 SelectionDAG &DAG) const {
11085   DebugLoc DL = Op.getDebugLoc();
11086   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
11087                      Op.getOperand(0), Op.getOperand(1));
11088 }
11089
11090 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
11091   return Op.getOperand(0);
11092 }
11093
11094 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
11095                                                 SelectionDAG &DAG) const {
11096   SDValue Root = Op.getOperand(0);
11097   SDValue Trmp = Op.getOperand(1); // trampoline
11098   SDValue FPtr = Op.getOperand(2); // nested function
11099   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
11100   DebugLoc dl  = Op.getDebugLoc();
11101
11102   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11103   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
11104
11105   if (Subtarget->is64Bit()) {
11106     SDValue OutChains[6];
11107
11108     // Large code-model.
11109     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
11110     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
11111
11112     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
11113     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
11114
11115     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
11116
11117     // Load the pointer to the nested function into R11.
11118     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
11119     SDValue Addr = Trmp;
11120     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11121                                 Addr, MachinePointerInfo(TrmpAddr),
11122                                 false, false, 0);
11123
11124     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11125                        DAG.getConstant(2, MVT::i64));
11126     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
11127                                 MachinePointerInfo(TrmpAddr, 2),
11128                                 false, false, 2);
11129
11130     // Load the 'nest' parameter value into R10.
11131     // R10 is specified in X86CallingConv.td
11132     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
11133     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11134                        DAG.getConstant(10, MVT::i64));
11135     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11136                                 Addr, MachinePointerInfo(TrmpAddr, 10),
11137                                 false, false, 0);
11138
11139     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11140                        DAG.getConstant(12, MVT::i64));
11141     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
11142                                 MachinePointerInfo(TrmpAddr, 12),
11143                                 false, false, 2);
11144
11145     // Jump to the nested function.
11146     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
11147     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11148                        DAG.getConstant(20, MVT::i64));
11149     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11150                                 Addr, MachinePointerInfo(TrmpAddr, 20),
11151                                 false, false, 0);
11152
11153     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
11154     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11155                        DAG.getConstant(22, MVT::i64));
11156     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
11157                                 MachinePointerInfo(TrmpAddr, 22),
11158                                 false, false, 0);
11159
11160     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
11161   } else {
11162     const Function *Func =
11163       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
11164     CallingConv::ID CC = Func->getCallingConv();
11165     unsigned NestReg;
11166
11167     switch (CC) {
11168     default:
11169       llvm_unreachable("Unsupported calling convention");
11170     case CallingConv::C:
11171     case CallingConv::X86_StdCall: {
11172       // Pass 'nest' parameter in ECX.
11173       // Must be kept in sync with X86CallingConv.td
11174       NestReg = X86::ECX;
11175
11176       // Check that ECX wasn't needed by an 'inreg' parameter.
11177       FunctionType *FTy = Func->getFunctionType();
11178       const AttributeSet &Attrs = Func->getAttributes();
11179
11180       if (!Attrs.isEmpty() && !Func->isVarArg()) {
11181         unsigned InRegCount = 0;
11182         unsigned Idx = 1;
11183
11184         for (FunctionType::param_iterator I = FTy->param_begin(),
11185              E = FTy->param_end(); I != E; ++I, ++Idx)
11186           if (Attrs.hasAttribute(Idx, Attribute::InReg))
11187             // FIXME: should only count parameters that are lowered to integers.
11188             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
11189
11190         if (InRegCount > 2) {
11191           report_fatal_error("Nest register in use - reduce number of inreg"
11192                              " parameters!");
11193         }
11194       }
11195       break;
11196     }
11197     case CallingConv::X86_FastCall:
11198     case CallingConv::X86_ThisCall:
11199     case CallingConv::Fast:
11200       // Pass 'nest' parameter in EAX.
11201       // Must be kept in sync with X86CallingConv.td
11202       NestReg = X86::EAX;
11203       break;
11204     }
11205
11206     SDValue OutChains[4];
11207     SDValue Addr, Disp;
11208
11209     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11210                        DAG.getConstant(10, MVT::i32));
11211     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
11212
11213     // This is storing the opcode for MOV32ri.
11214     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
11215     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
11216     OutChains[0] = DAG.getStore(Root, dl,
11217                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
11218                                 Trmp, MachinePointerInfo(TrmpAddr),
11219                                 false, false, 0);
11220
11221     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11222                        DAG.getConstant(1, MVT::i32));
11223     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
11224                                 MachinePointerInfo(TrmpAddr, 1),
11225                                 false, false, 1);
11226
11227     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
11228     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11229                        DAG.getConstant(5, MVT::i32));
11230     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
11231                                 MachinePointerInfo(TrmpAddr, 5),
11232                                 false, false, 1);
11233
11234     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11235                        DAG.getConstant(6, MVT::i32));
11236     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
11237                                 MachinePointerInfo(TrmpAddr, 6),
11238                                 false, false, 1);
11239
11240     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
11241   }
11242 }
11243
11244 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
11245                                             SelectionDAG &DAG) const {
11246   /*
11247    The rounding mode is in bits 11:10 of FPSR, and has the following
11248    settings:
11249      00 Round to nearest
11250      01 Round to -inf
11251      10 Round to +inf
11252      11 Round to 0
11253
11254   FLT_ROUNDS, on the other hand, expects the following:
11255     -1 Undefined
11256      0 Round to 0
11257      1 Round to nearest
11258      2 Round to +inf
11259      3 Round to -inf
11260
11261   To perform the conversion, we do:
11262     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
11263   */
11264
11265   MachineFunction &MF = DAG.getMachineFunction();
11266   const TargetMachine &TM = MF.getTarget();
11267   const TargetFrameLowering &TFI = *TM.getFrameLowering();
11268   unsigned StackAlignment = TFI.getStackAlignment();
11269   EVT VT = Op.getValueType();
11270   DebugLoc DL = Op.getDebugLoc();
11271
11272   // Save FP Control Word to stack slot
11273   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
11274   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11275
11276   MachineMemOperand *MMO =
11277    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11278                            MachineMemOperand::MOStore, 2, 2);
11279
11280   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
11281   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
11282                                           DAG.getVTList(MVT::Other),
11283                                           Ops, array_lengthof(Ops), MVT::i16,
11284                                           MMO);
11285
11286   // Load FP Control Word from stack slot
11287   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
11288                             MachinePointerInfo(), false, false, false, 0);
11289
11290   // Transform as necessary
11291   SDValue CWD1 =
11292     DAG.getNode(ISD::SRL, DL, MVT::i16,
11293                 DAG.getNode(ISD::AND, DL, MVT::i16,
11294                             CWD, DAG.getConstant(0x800, MVT::i16)),
11295                 DAG.getConstant(11, MVT::i8));
11296   SDValue CWD2 =
11297     DAG.getNode(ISD::SRL, DL, MVT::i16,
11298                 DAG.getNode(ISD::AND, DL, MVT::i16,
11299                             CWD, DAG.getConstant(0x400, MVT::i16)),
11300                 DAG.getConstant(9, MVT::i8));
11301
11302   SDValue RetVal =
11303     DAG.getNode(ISD::AND, DL, MVT::i16,
11304                 DAG.getNode(ISD::ADD, DL, MVT::i16,
11305                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
11306                             DAG.getConstant(1, MVT::i16)),
11307                 DAG.getConstant(3, MVT::i16));
11308
11309   return DAG.getNode((VT.getSizeInBits() < 16 ?
11310                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
11311 }
11312
11313 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
11314   EVT VT = Op.getValueType();
11315   EVT OpVT = VT;
11316   unsigned NumBits = VT.getSizeInBits();
11317   DebugLoc dl = Op.getDebugLoc();
11318
11319   Op = Op.getOperand(0);
11320   if (VT == MVT::i8) {
11321     // Zero extend to i32 since there is not an i8 bsr.
11322     OpVT = MVT::i32;
11323     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
11324   }
11325
11326   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
11327   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
11328   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
11329
11330   // If src is zero (i.e. bsr sets ZF), returns NumBits.
11331   SDValue Ops[] = {
11332     Op,
11333     DAG.getConstant(NumBits+NumBits-1, OpVT),
11334     DAG.getConstant(X86::COND_E, MVT::i8),
11335     Op.getValue(1)
11336   };
11337   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
11338
11339   // Finally xor with NumBits-1.
11340   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
11341
11342   if (VT == MVT::i8)
11343     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
11344   return Op;
11345 }
11346
11347 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
11348   EVT VT = Op.getValueType();
11349   EVT OpVT = VT;
11350   unsigned NumBits = VT.getSizeInBits();
11351   DebugLoc dl = Op.getDebugLoc();
11352
11353   Op = Op.getOperand(0);
11354   if (VT == MVT::i8) {
11355     // Zero extend to i32 since there is not an i8 bsr.
11356     OpVT = MVT::i32;
11357     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
11358   }
11359
11360   // Issue a bsr (scan bits in reverse).
11361   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
11362   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
11363
11364   // And xor with NumBits-1.
11365   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
11366
11367   if (VT == MVT::i8)
11368     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
11369   return Op;
11370 }
11371
11372 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
11373   EVT VT = Op.getValueType();
11374   unsigned NumBits = VT.getSizeInBits();
11375   DebugLoc dl = Op.getDebugLoc();
11376   Op = Op.getOperand(0);
11377
11378   // Issue a bsf (scan bits forward) which also sets EFLAGS.
11379   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11380   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
11381
11382   // If src is zero (i.e. bsf sets ZF), returns NumBits.
11383   SDValue Ops[] = {
11384     Op,
11385     DAG.getConstant(NumBits, VT),
11386     DAG.getConstant(X86::COND_E, MVT::i8),
11387     Op.getValue(1)
11388   };
11389   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
11390 }
11391
11392 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
11393 // ones, and then concatenate the result back.
11394 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
11395   EVT VT = Op.getValueType();
11396
11397   assert(VT.is256BitVector() && VT.isInteger() &&
11398          "Unsupported value type for operation");
11399
11400   unsigned NumElems = VT.getVectorNumElements();
11401   DebugLoc dl = Op.getDebugLoc();
11402
11403   // Extract the LHS vectors
11404   SDValue LHS = Op.getOperand(0);
11405   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11406   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11407
11408   // Extract the RHS vectors
11409   SDValue RHS = Op.getOperand(1);
11410   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
11411   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
11412
11413   MVT EltVT = VT.getVectorElementType().getSimpleVT();
11414   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11415
11416   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
11417                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
11418                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
11419 }
11420
11421 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
11422   assert(Op.getValueType().is256BitVector() &&
11423          Op.getValueType().isInteger() &&
11424          "Only handle AVX 256-bit vector integer operation");
11425   return Lower256IntArith(Op, DAG);
11426 }
11427
11428 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
11429   assert(Op.getValueType().is256BitVector() &&
11430          Op.getValueType().isInteger() &&
11431          "Only handle AVX 256-bit vector integer operation");
11432   return Lower256IntArith(Op, DAG);
11433 }
11434
11435 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
11436                         SelectionDAG &DAG) {
11437   DebugLoc dl = Op.getDebugLoc();
11438   EVT VT = Op.getValueType();
11439
11440   // Decompose 256-bit ops into smaller 128-bit ops.
11441   if (VT.is256BitVector() && !Subtarget->hasInt256())
11442     return Lower256IntArith(Op, DAG);
11443
11444   SDValue A = Op.getOperand(0);
11445   SDValue B = Op.getOperand(1);
11446
11447   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
11448   if (VT == MVT::v4i32) {
11449     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
11450            "Should not custom lower when pmuldq is available!");
11451
11452     // Extract the odd parts.
11453     const int UnpackMask[] = { 1, -1, 3, -1 };
11454     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
11455     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
11456
11457     // Multiply the even parts.
11458     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
11459     // Now multiply odd parts.
11460     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
11461
11462     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
11463     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
11464
11465     // Merge the two vectors back together with a shuffle. This expands into 2
11466     // shuffles.
11467     const int ShufMask[] = { 0, 4, 2, 6 };
11468     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
11469   }
11470
11471   assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
11472          "Only know how to lower V2I64/V4I64 multiply");
11473
11474   //  Ahi = psrlqi(a, 32);
11475   //  Bhi = psrlqi(b, 32);
11476   //
11477   //  AloBlo = pmuludq(a, b);
11478   //  AloBhi = pmuludq(a, Bhi);
11479   //  AhiBlo = pmuludq(Ahi, b);
11480
11481   //  AloBhi = psllqi(AloBhi, 32);
11482   //  AhiBlo = psllqi(AhiBlo, 32);
11483   //  return AloBlo + AloBhi + AhiBlo;
11484
11485   SDValue ShAmt = DAG.getConstant(32, MVT::i32);
11486
11487   SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
11488   SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
11489
11490   // Bit cast to 32-bit vectors for MULUDQ
11491   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
11492   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
11493   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
11494   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
11495   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
11496
11497   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
11498   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
11499   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
11500
11501   AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
11502   AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
11503
11504   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
11505   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
11506 }
11507
11508 SDValue X86TargetLowering::LowerSDIV(SDValue Op, SelectionDAG &DAG) const {
11509   EVT VT = Op.getValueType();
11510   EVT EltTy = VT.getVectorElementType();
11511   unsigned NumElts = VT.getVectorNumElements();
11512   SDValue N0 = Op.getOperand(0);
11513   DebugLoc dl = Op.getDebugLoc();
11514
11515   // Lower sdiv X, pow2-const.
11516   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(Op.getOperand(1));
11517   if (!C)
11518     return SDValue();
11519
11520   APInt SplatValue, SplatUndef;
11521   unsigned MinSplatBits;
11522   bool HasAnyUndefs;
11523   if (!C->isConstantSplat(SplatValue, SplatUndef, MinSplatBits, HasAnyUndefs))
11524     return SDValue();
11525
11526   if ((SplatValue != 0) &&
11527       (SplatValue.isPowerOf2() || (-SplatValue).isPowerOf2())) {
11528     unsigned lg2 = SplatValue.countTrailingZeros();
11529     // Splat the sign bit.
11530     SDValue Sz = DAG.getConstant(EltTy.getSizeInBits()-1, MVT::i32);
11531     SDValue SGN = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, N0, Sz, DAG);
11532     // Add (N0 < 0) ? abs2 - 1 : 0;
11533     SDValue Amt = DAG.getConstant(EltTy.getSizeInBits() - lg2, MVT::i32);
11534     SDValue SRL = getTargetVShiftNode(X86ISD::VSRLI, dl, VT, SGN, Amt, DAG);
11535     SDValue ADD = DAG.getNode(ISD::ADD, dl, VT, N0, SRL);
11536     SDValue Lg2Amt = DAG.getConstant(lg2, MVT::i32);
11537     SDValue SRA = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, ADD, Lg2Amt, DAG);
11538
11539     // If we're dividing by a positive value, we're done.  Otherwise, we must
11540     // negate the result.
11541     if (SplatValue.isNonNegative())
11542       return SRA;
11543
11544     SmallVector<SDValue, 16> V(NumElts, DAG.getConstant(0, EltTy));
11545     SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], NumElts);
11546     return DAG.getNode(ISD::SUB, dl, VT, Zero, SRA);
11547   }
11548   return SDValue();
11549 }
11550
11551 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
11552                                          const X86Subtarget *Subtarget) {
11553   EVT VT = Op.getValueType();
11554   DebugLoc dl = Op.getDebugLoc();
11555   SDValue R = Op.getOperand(0);
11556   SDValue Amt = Op.getOperand(1);
11557
11558   // Optimize shl/srl/sra with constant shift amount.
11559   if (isSplatVector(Amt.getNode())) {
11560     SDValue SclrAmt = Amt->getOperand(0);
11561     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
11562       uint64_t ShiftAmt = C->getZExtValue();
11563
11564       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
11565           (Subtarget->hasInt256() &&
11566            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
11567         if (Op.getOpcode() == ISD::SHL)
11568           return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
11569                              DAG.getConstant(ShiftAmt, MVT::i32));
11570         if (Op.getOpcode() == ISD::SRL)
11571           return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
11572                              DAG.getConstant(ShiftAmt, MVT::i32));
11573         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
11574           return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
11575                              DAG.getConstant(ShiftAmt, MVT::i32));
11576       }
11577
11578       if (VT == MVT::v16i8) {
11579         if (Op.getOpcode() == ISD::SHL) {
11580           // Make a large shift.
11581           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
11582                                     DAG.getConstant(ShiftAmt, MVT::i32));
11583           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11584           // Zero out the rightmost bits.
11585           SmallVector<SDValue, 16> V(16,
11586                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
11587                                                      MVT::i8));
11588           return DAG.getNode(ISD::AND, dl, VT, SHL,
11589                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11590         }
11591         if (Op.getOpcode() == ISD::SRL) {
11592           // Make a large shift.
11593           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
11594                                     DAG.getConstant(ShiftAmt, MVT::i32));
11595           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11596           // Zero out the leftmost bits.
11597           SmallVector<SDValue, 16> V(16,
11598                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11599                                                      MVT::i8));
11600           return DAG.getNode(ISD::AND, dl, VT, SRL,
11601                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11602         }
11603         if (Op.getOpcode() == ISD::SRA) {
11604           if (ShiftAmt == 7) {
11605             // R s>> 7  ===  R s< 0
11606             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11607             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11608           }
11609
11610           // R s>> a === ((R u>> a) ^ m) - m
11611           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11612           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
11613                                                          MVT::i8));
11614           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
11615           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11616           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11617           return Res;
11618         }
11619         llvm_unreachable("Unknown shift opcode.");
11620       }
11621
11622       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
11623         if (Op.getOpcode() == ISD::SHL) {
11624           // Make a large shift.
11625           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
11626                                     DAG.getConstant(ShiftAmt, MVT::i32));
11627           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11628           // Zero out the rightmost bits.
11629           SmallVector<SDValue, 32> V(32,
11630                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
11631                                                      MVT::i8));
11632           return DAG.getNode(ISD::AND, dl, VT, SHL,
11633                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11634         }
11635         if (Op.getOpcode() == ISD::SRL) {
11636           // Make a large shift.
11637           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
11638                                     DAG.getConstant(ShiftAmt, MVT::i32));
11639           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11640           // Zero out the leftmost bits.
11641           SmallVector<SDValue, 32> V(32,
11642                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11643                                                      MVT::i8));
11644           return DAG.getNode(ISD::AND, dl, VT, SRL,
11645                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11646         }
11647         if (Op.getOpcode() == ISD::SRA) {
11648           if (ShiftAmt == 7) {
11649             // R s>> 7  ===  R s< 0
11650             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11651             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11652           }
11653
11654           // R s>> a === ((R u>> a) ^ m) - m
11655           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11656           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
11657                                                          MVT::i8));
11658           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
11659           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11660           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11661           return Res;
11662         }
11663         llvm_unreachable("Unknown shift opcode.");
11664       }
11665     }
11666   }
11667
11668   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
11669   if (!Subtarget->is64Bit() &&
11670       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
11671       Amt.getOpcode() == ISD::BITCAST &&
11672       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
11673     Amt = Amt.getOperand(0);
11674     unsigned Ratio = Amt.getValueType().getVectorNumElements() /
11675                      VT.getVectorNumElements();
11676     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
11677     uint64_t ShiftAmt = 0;
11678     for (unsigned i = 0; i != Ratio; ++i) {
11679       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
11680       if (C == 0)
11681         return SDValue();
11682       // 6 == Log2(64)
11683       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
11684     }
11685     // Check remaining shift amounts.
11686     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
11687       uint64_t ShAmt = 0;
11688       for (unsigned j = 0; j != Ratio; ++j) {
11689         ConstantSDNode *C =
11690           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
11691         if (C == 0)
11692           return SDValue();
11693         // 6 == Log2(64)
11694         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
11695       }
11696       if (ShAmt != ShiftAmt)
11697         return SDValue();
11698     }
11699     switch (Op.getOpcode()) {
11700     default:
11701       llvm_unreachable("Unknown shift opcode!");
11702     case ISD::SHL:
11703       return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
11704                          DAG.getConstant(ShiftAmt, MVT::i32));
11705     case ISD::SRL:
11706       return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
11707                          DAG.getConstant(ShiftAmt, MVT::i32));
11708     case ISD::SRA:
11709       return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
11710                          DAG.getConstant(ShiftAmt, MVT::i32));
11711     }
11712   }
11713
11714   return SDValue();
11715 }
11716
11717 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
11718                                         const X86Subtarget* Subtarget) {
11719   EVT VT = Op.getValueType();
11720   DebugLoc dl = Op.getDebugLoc();
11721   SDValue R = Op.getOperand(0);
11722   SDValue Amt = Op.getOperand(1);
11723
11724   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
11725       VT == MVT::v4i32 || VT == MVT::v8i16 ||
11726       (Subtarget->hasInt256() &&
11727        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
11728         VT == MVT::v8i32 || VT == MVT::v16i16))) {
11729     SDValue BaseShAmt;
11730     EVT EltVT = VT.getVectorElementType();
11731
11732     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
11733       unsigned NumElts = VT.getVectorNumElements();
11734       unsigned i, j;
11735       for (i = 0; i != NumElts; ++i) {
11736         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
11737           continue;
11738         break;
11739       }
11740       for (j = i; j != NumElts; ++j) {
11741         SDValue Arg = Amt.getOperand(j);
11742         if (Arg.getOpcode() == ISD::UNDEF) continue;
11743         if (Arg != Amt.getOperand(i))
11744           break;
11745       }
11746       if (i != NumElts && j == NumElts)
11747         BaseShAmt = Amt.getOperand(i);
11748     } else {
11749       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
11750         Amt = Amt.getOperand(0);
11751       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
11752                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
11753         SDValue InVec = Amt.getOperand(0);
11754         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
11755           unsigned NumElts = InVec.getValueType().getVectorNumElements();
11756           unsigned i = 0;
11757           for (; i != NumElts; ++i) {
11758             SDValue Arg = InVec.getOperand(i);
11759             if (Arg.getOpcode() == ISD::UNDEF) continue;
11760             BaseShAmt = Arg;
11761             break;
11762           }
11763         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
11764            if (ConstantSDNode *C =
11765                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
11766              unsigned SplatIdx =
11767                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
11768              if (C->getZExtValue() == SplatIdx)
11769                BaseShAmt = InVec.getOperand(1);
11770            }
11771         }
11772         if (BaseShAmt.getNode() == 0)
11773           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
11774                                   DAG.getIntPtrConstant(0));
11775       }
11776     }
11777
11778     if (BaseShAmt.getNode()) {
11779       if (EltVT.bitsGT(MVT::i32))
11780         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
11781       else if (EltVT.bitsLT(MVT::i32))
11782         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
11783
11784       switch (Op.getOpcode()) {
11785       default:
11786         llvm_unreachable("Unknown shift opcode!");
11787       case ISD::SHL:
11788         switch (VT.getSimpleVT().SimpleTy) {
11789         default: return SDValue();
11790         case MVT::v2i64:
11791         case MVT::v4i32:
11792         case MVT::v8i16:
11793         case MVT::v4i64:
11794         case MVT::v8i32:
11795         case MVT::v16i16:
11796           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
11797         }
11798       case ISD::SRA:
11799         switch (VT.getSimpleVT().SimpleTy) {
11800         default: return SDValue();
11801         case MVT::v4i32:
11802         case MVT::v8i16:
11803         case MVT::v8i32:
11804         case MVT::v16i16:
11805           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
11806         }
11807       case ISD::SRL:
11808         switch (VT.getSimpleVT().SimpleTy) {
11809         default: return SDValue();
11810         case MVT::v2i64:
11811         case MVT::v4i32:
11812         case MVT::v8i16:
11813         case MVT::v4i64:
11814         case MVT::v8i32:
11815         case MVT::v16i16:
11816           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
11817         }
11818       }
11819     }
11820   }
11821
11822   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
11823   if (!Subtarget->is64Bit() &&
11824       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
11825       Amt.getOpcode() == ISD::BITCAST &&
11826       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
11827     Amt = Amt.getOperand(0);
11828     unsigned Ratio = Amt.getValueType().getVectorNumElements() /
11829                      VT.getVectorNumElements();
11830     std::vector<SDValue> Vals(Ratio);
11831     for (unsigned i = 0; i != Ratio; ++i)
11832       Vals[i] = Amt.getOperand(i);
11833     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
11834       for (unsigned j = 0; j != Ratio; ++j)
11835         if (Vals[j] != Amt.getOperand(i + j))
11836           return SDValue();
11837     }
11838     switch (Op.getOpcode()) {
11839     default:
11840       llvm_unreachable("Unknown shift opcode!");
11841     case ISD::SHL:
11842       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
11843     case ISD::SRL:
11844       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
11845     case ISD::SRA:
11846       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
11847     }
11848   }
11849
11850   return SDValue();
11851 }
11852
11853 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
11854
11855   EVT VT = Op.getValueType();
11856   DebugLoc dl = Op.getDebugLoc();
11857   SDValue R = Op.getOperand(0);
11858   SDValue Amt = Op.getOperand(1);
11859   SDValue V;
11860
11861   if (!Subtarget->hasSSE2())
11862     return SDValue();
11863
11864   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
11865   if (V.getNode())
11866     return V;
11867
11868   V = LowerScalarVariableShift(Op, DAG, Subtarget);
11869   if (V.getNode())
11870       return V;
11871
11872   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
11873   if (Subtarget->hasInt256()) {
11874     if (Op.getOpcode() == ISD::SRL &&
11875         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
11876          VT == MVT::v4i64 || VT == MVT::v8i32))
11877       return Op;
11878     if (Op.getOpcode() == ISD::SHL &&
11879         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
11880          VT == MVT::v4i64 || VT == MVT::v8i32))
11881       return Op;
11882     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
11883       return Op;
11884   }
11885
11886   // Lower SHL with variable shift amount.
11887   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
11888     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
11889
11890     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
11891     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
11892     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
11893     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
11894   }
11895   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
11896     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
11897
11898     // a = a << 5;
11899     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
11900     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
11901
11902     // Turn 'a' into a mask suitable for VSELECT
11903     SDValue VSelM = DAG.getConstant(0x80, VT);
11904     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11905     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11906
11907     SDValue CM1 = DAG.getConstant(0x0f, VT);
11908     SDValue CM2 = DAG.getConstant(0x3f, VT);
11909
11910     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
11911     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
11912     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11913                             DAG.getConstant(4, MVT::i32), DAG);
11914     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11915     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11916
11917     // a += a
11918     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11919     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11920     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11921
11922     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
11923     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
11924     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11925                             DAG.getConstant(2, MVT::i32), DAG);
11926     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11927     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11928
11929     // a += a
11930     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11931     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11932     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11933
11934     // return VSELECT(r, r+r, a);
11935     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
11936                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
11937     return R;
11938   }
11939
11940   // Decompose 256-bit shifts into smaller 128-bit shifts.
11941   if (VT.is256BitVector()) {
11942     unsigned NumElems = VT.getVectorNumElements();
11943     MVT EltVT = VT.getVectorElementType().getSimpleVT();
11944     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11945
11946     // Extract the two vectors
11947     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
11948     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
11949
11950     // Recreate the shift amount vectors
11951     SDValue Amt1, Amt2;
11952     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
11953       // Constant shift amount
11954       SmallVector<SDValue, 4> Amt1Csts;
11955       SmallVector<SDValue, 4> Amt2Csts;
11956       for (unsigned i = 0; i != NumElems/2; ++i)
11957         Amt1Csts.push_back(Amt->getOperand(i));
11958       for (unsigned i = NumElems/2; i != NumElems; ++i)
11959         Amt2Csts.push_back(Amt->getOperand(i));
11960
11961       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11962                                  &Amt1Csts[0], NumElems/2);
11963       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11964                                  &Amt2Csts[0], NumElems/2);
11965     } else {
11966       // Variable shift amount
11967       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
11968       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
11969     }
11970
11971     // Issue new vector shifts for the smaller types
11972     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
11973     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
11974
11975     // Concatenate the result back
11976     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
11977   }
11978
11979   return SDValue();
11980 }
11981
11982 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
11983   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
11984   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
11985   // looks for this combo and may remove the "setcc" instruction if the "setcc"
11986   // has only one use.
11987   SDNode *N = Op.getNode();
11988   SDValue LHS = N->getOperand(0);
11989   SDValue RHS = N->getOperand(1);
11990   unsigned BaseOp = 0;
11991   unsigned Cond = 0;
11992   DebugLoc DL = Op.getDebugLoc();
11993   switch (Op.getOpcode()) {
11994   default: llvm_unreachable("Unknown ovf instruction!");
11995   case ISD::SADDO:
11996     // A subtract of one will be selected as a INC. Note that INC doesn't
11997     // set CF, so we can't do this for UADDO.
11998     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11999       if (C->isOne()) {
12000         BaseOp = X86ISD::INC;
12001         Cond = X86::COND_O;
12002         break;
12003       }
12004     BaseOp = X86ISD::ADD;
12005     Cond = X86::COND_O;
12006     break;
12007   case ISD::UADDO:
12008     BaseOp = X86ISD::ADD;
12009     Cond = X86::COND_B;
12010     break;
12011   case ISD::SSUBO:
12012     // A subtract of one will be selected as a DEC. Note that DEC doesn't
12013     // set CF, so we can't do this for USUBO.
12014     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12015       if (C->isOne()) {
12016         BaseOp = X86ISD::DEC;
12017         Cond = X86::COND_O;
12018         break;
12019       }
12020     BaseOp = X86ISD::SUB;
12021     Cond = X86::COND_O;
12022     break;
12023   case ISD::USUBO:
12024     BaseOp = X86ISD::SUB;
12025     Cond = X86::COND_B;
12026     break;
12027   case ISD::SMULO:
12028     BaseOp = X86ISD::SMUL;
12029     Cond = X86::COND_O;
12030     break;
12031   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
12032     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
12033                                  MVT::i32);
12034     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
12035
12036     SDValue SetCC =
12037       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
12038                   DAG.getConstant(X86::COND_O, MVT::i32),
12039                   SDValue(Sum.getNode(), 2));
12040
12041     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
12042   }
12043   }
12044
12045   // Also sets EFLAGS.
12046   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
12047   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
12048
12049   SDValue SetCC =
12050     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
12051                 DAG.getConstant(Cond, MVT::i32),
12052                 SDValue(Sum.getNode(), 1));
12053
12054   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
12055 }
12056
12057 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
12058                                                   SelectionDAG &DAG) const {
12059   DebugLoc dl = Op.getDebugLoc();
12060   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
12061   EVT VT = Op.getValueType();
12062
12063   if (!Subtarget->hasSSE2() || !VT.isVector())
12064     return SDValue();
12065
12066   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
12067                       ExtraVT.getScalarType().getSizeInBits();
12068   SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
12069
12070   switch (VT.getSimpleVT().SimpleTy) {
12071     default: return SDValue();
12072     case MVT::v8i32:
12073     case MVT::v16i16:
12074       if (!Subtarget->hasFp256())
12075         return SDValue();
12076       if (!Subtarget->hasInt256()) {
12077         // needs to be split
12078         unsigned NumElems = VT.getVectorNumElements();
12079
12080         // Extract the LHS vectors
12081         SDValue LHS = Op.getOperand(0);
12082         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12083         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12084
12085         MVT EltVT = VT.getVectorElementType().getSimpleVT();
12086         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12087
12088         EVT ExtraEltVT = ExtraVT.getVectorElementType();
12089         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
12090         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
12091                                    ExtraNumElems/2);
12092         SDValue Extra = DAG.getValueType(ExtraVT);
12093
12094         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
12095         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
12096
12097         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
12098       }
12099       // fall through
12100     case MVT::v4i32:
12101     case MVT::v8i16: {
12102       // (sext (vzext x)) -> (vsext x)
12103       SDValue Op0 = Op.getOperand(0);
12104       SDValue Op00 = Op0.getOperand(0);
12105       SDValue Tmp1;
12106       // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
12107       if (Op0.getOpcode() == ISD::BITCAST &&
12108           Op00.getOpcode() == ISD::VECTOR_SHUFFLE)
12109         Tmp1 = LowerVectorIntExtend(Op00, DAG);
12110       if (Tmp1.getNode()) {
12111         SDValue Tmp1Op0 = Tmp1.getOperand(0);
12112         assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
12113                "This optimization is invalid without a VZEXT.");
12114         return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
12115       }
12116
12117       // If the above didn't work, then just use Shift-Left + Shift-Right.
12118       Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT, Op0, ShAmt, DAG);
12119       return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
12120     }
12121   }
12122 }
12123
12124 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
12125                                  SelectionDAG &DAG) {
12126   DebugLoc dl = Op.getDebugLoc();
12127   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
12128     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
12129   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
12130     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
12131
12132   // The only fence that needs an instruction is a sequentially-consistent
12133   // cross-thread fence.
12134   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
12135     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
12136     // no-sse2). There isn't any reason to disable it if the target processor
12137     // supports it.
12138     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
12139       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
12140
12141     SDValue Chain = Op.getOperand(0);
12142     SDValue Zero = DAG.getConstant(0, MVT::i32);
12143     SDValue Ops[] = {
12144       DAG.getRegister(X86::ESP, MVT::i32), // Base
12145       DAG.getTargetConstant(1, MVT::i8),   // Scale
12146       DAG.getRegister(0, MVT::i32),        // Index
12147       DAG.getTargetConstant(0, MVT::i32),  // Disp
12148       DAG.getRegister(0, MVT::i32),        // Segment.
12149       Zero,
12150       Chain
12151     };
12152     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
12153     return SDValue(Res, 0);
12154   }
12155
12156   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
12157   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
12158 }
12159
12160 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
12161                              SelectionDAG &DAG) {
12162   EVT T = Op.getValueType();
12163   DebugLoc DL = Op.getDebugLoc();
12164   unsigned Reg = 0;
12165   unsigned size = 0;
12166   switch(T.getSimpleVT().SimpleTy) {
12167   default: llvm_unreachable("Invalid value type!");
12168   case MVT::i8:  Reg = X86::AL;  size = 1; break;
12169   case MVT::i16: Reg = X86::AX;  size = 2; break;
12170   case MVT::i32: Reg = X86::EAX; size = 4; break;
12171   case MVT::i64:
12172     assert(Subtarget->is64Bit() && "Node not type legal!");
12173     Reg = X86::RAX; size = 8;
12174     break;
12175   }
12176   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
12177                                     Op.getOperand(2), SDValue());
12178   SDValue Ops[] = { cpIn.getValue(0),
12179                     Op.getOperand(1),
12180                     Op.getOperand(3),
12181                     DAG.getTargetConstant(size, MVT::i8),
12182                     cpIn.getValue(1) };
12183   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12184   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
12185   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
12186                                            Ops, array_lengthof(Ops), T, MMO);
12187   SDValue cpOut =
12188     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
12189   return cpOut;
12190 }
12191
12192 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
12193                                      SelectionDAG &DAG) {
12194   assert(Subtarget->is64Bit() && "Result not type legalized?");
12195   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12196   SDValue TheChain = Op.getOperand(0);
12197   DebugLoc dl = Op.getDebugLoc();
12198   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
12199   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
12200   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
12201                                    rax.getValue(2));
12202   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
12203                             DAG.getConstant(32, MVT::i8));
12204   SDValue Ops[] = {
12205     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
12206     rdx.getValue(1)
12207   };
12208   return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
12209 }
12210
12211 SDValue X86TargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
12212   EVT SrcVT = Op.getOperand(0).getValueType();
12213   EVT DstVT = Op.getValueType();
12214   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
12215          Subtarget->hasMMX() && "Unexpected custom BITCAST");
12216   assert((DstVT == MVT::i64 ||
12217           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
12218          "Unexpected custom BITCAST");
12219   // i64 <=> MMX conversions are Legal.
12220   if (SrcVT==MVT::i64 && DstVT.isVector())
12221     return Op;
12222   if (DstVT==MVT::i64 && SrcVT.isVector())
12223     return Op;
12224   // MMX <=> MMX conversions are Legal.
12225   if (SrcVT.isVector() && DstVT.isVector())
12226     return Op;
12227   // All other conversions need to be expanded.
12228   return SDValue();
12229 }
12230
12231 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
12232   SDNode *Node = Op.getNode();
12233   DebugLoc dl = Node->getDebugLoc();
12234   EVT T = Node->getValueType(0);
12235   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
12236                               DAG.getConstant(0, T), Node->getOperand(2));
12237   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
12238                        cast<AtomicSDNode>(Node)->getMemoryVT(),
12239                        Node->getOperand(0),
12240                        Node->getOperand(1), negOp,
12241                        cast<AtomicSDNode>(Node)->getSrcValue(),
12242                        cast<AtomicSDNode>(Node)->getAlignment(),
12243                        cast<AtomicSDNode>(Node)->getOrdering(),
12244                        cast<AtomicSDNode>(Node)->getSynchScope());
12245 }
12246
12247 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
12248   SDNode *Node = Op.getNode();
12249   DebugLoc dl = Node->getDebugLoc();
12250   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
12251
12252   // Convert seq_cst store -> xchg
12253   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
12254   // FIXME: On 32-bit, store -> fist or movq would be more efficient
12255   //        (The only way to get a 16-byte store is cmpxchg16b)
12256   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
12257   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
12258       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
12259     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
12260                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
12261                                  Node->getOperand(0),
12262                                  Node->getOperand(1), Node->getOperand(2),
12263                                  cast<AtomicSDNode>(Node)->getMemOperand(),
12264                                  cast<AtomicSDNode>(Node)->getOrdering(),
12265                                  cast<AtomicSDNode>(Node)->getSynchScope());
12266     return Swap.getValue(1);
12267   }
12268   // Other atomic stores have a simple pattern.
12269   return Op;
12270 }
12271
12272 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
12273   EVT VT = Op.getNode()->getValueType(0);
12274
12275   // Let legalize expand this if it isn't a legal type yet.
12276   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
12277     return SDValue();
12278
12279   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
12280
12281   unsigned Opc;
12282   bool ExtraOp = false;
12283   switch (Op.getOpcode()) {
12284   default: llvm_unreachable("Invalid code");
12285   case ISD::ADDC: Opc = X86ISD::ADD; break;
12286   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
12287   case ISD::SUBC: Opc = X86ISD::SUB; break;
12288   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
12289   }
12290
12291   if (!ExtraOp)
12292     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
12293                        Op.getOperand(1));
12294   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
12295                      Op.getOperand(1), Op.getOperand(2));
12296 }
12297
12298 SDValue X86TargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
12299   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
12300
12301   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
12302   // which returns the values as { float, float } (in XMM0) or
12303   // { double, double } (which is returned in XMM0, XMM1).
12304   DebugLoc dl = Op.getDebugLoc();
12305   SDValue Arg = Op.getOperand(0);
12306   EVT ArgVT = Arg.getValueType();
12307   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
12308
12309   ArgListTy Args;
12310   ArgListEntry Entry;
12311
12312   Entry.Node = Arg;
12313   Entry.Ty = ArgTy;
12314   Entry.isSExt = false;
12315   Entry.isZExt = false;
12316   Args.push_back(Entry);
12317
12318   bool isF64 = ArgVT == MVT::f64;
12319   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
12320   // the small struct {f32, f32} is returned in (eax, edx). For f64,
12321   // the results are returned via SRet in memory.
12322   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
12323   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
12324
12325   Type *RetTy = isF64
12326     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
12327     : (Type*)VectorType::get(ArgTy, 4);
12328   TargetLowering::
12329     CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
12330                          false, false, false, false, 0,
12331                          CallingConv::C, /*isTaillCall=*/false,
12332                          /*doesNotRet=*/false, /*isReturnValueUsed*/true,
12333                          Callee, Args, DAG, dl);
12334   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
12335
12336   if (isF64)
12337     // Returned in xmm0 and xmm1.
12338     return CallResult.first;
12339
12340   // Returned in bits 0:31 and 32:64 xmm0.
12341   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
12342                                CallResult.first, DAG.getIntPtrConstant(0));
12343   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
12344                                CallResult.first, DAG.getIntPtrConstant(1));
12345   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
12346   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
12347 }
12348
12349 /// LowerOperation - Provide custom lowering hooks for some operations.
12350 ///
12351 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
12352   switch (Op.getOpcode()) {
12353   default: llvm_unreachable("Should not custom lower this!");
12354   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
12355   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
12356   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
12357   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
12358   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
12359   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
12360   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
12361   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
12362   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
12363   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
12364   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
12365   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
12366   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
12367   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
12368   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
12369   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
12370   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
12371   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
12372   case ISD::SHL_PARTS:
12373   case ISD::SRA_PARTS:
12374   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
12375   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
12376   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
12377   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
12378   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, DAG);
12379   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, DAG);
12380   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, DAG);
12381   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
12382   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
12383   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
12384   case ISD::FABS:               return LowerFABS(Op, DAG);
12385   case ISD::FNEG:               return LowerFNEG(Op, DAG);
12386   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
12387   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
12388   case ISD::SETCC:              return LowerSETCC(Op, DAG);
12389   case ISD::SELECT:             return LowerSELECT(Op, DAG);
12390   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
12391   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
12392   case ISD::VASTART:            return LowerVASTART(Op, DAG);
12393   case ISD::VAARG:              return LowerVAARG(Op, DAG);
12394   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
12395   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
12396   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, DAG);
12397   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
12398   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
12399   case ISD::FRAME_TO_ARGS_OFFSET:
12400                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
12401   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
12402   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
12403   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
12404   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
12405   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
12406   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
12407   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
12408   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
12409   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
12410   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
12411   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
12412   case ISD::SRA:
12413   case ISD::SRL:
12414   case ISD::SHL:                return LowerShift(Op, DAG);
12415   case ISD::SADDO:
12416   case ISD::UADDO:
12417   case ISD::SSUBO:
12418   case ISD::USUBO:
12419   case ISD::SMULO:
12420   case ISD::UMULO:              return LowerXALUO(Op, DAG);
12421   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
12422   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
12423   case ISD::ADDC:
12424   case ISD::ADDE:
12425   case ISD::SUBC:
12426   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
12427   case ISD::ADD:                return LowerADD(Op, DAG);
12428   case ISD::SUB:                return LowerSUB(Op, DAG);
12429   case ISD::SDIV:               return LowerSDIV(Op, DAG);
12430   case ISD::FSINCOS:            return LowerFSINCOS(Op, DAG);
12431   }
12432 }
12433
12434 static void ReplaceATOMIC_LOAD(SDNode *Node,
12435                                   SmallVectorImpl<SDValue> &Results,
12436                                   SelectionDAG &DAG) {
12437   DebugLoc dl = Node->getDebugLoc();
12438   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
12439
12440   // Convert wide load -> cmpxchg8b/cmpxchg16b
12441   // FIXME: On 32-bit, load -> fild or movq would be more efficient
12442   //        (The only way to get a 16-byte load is cmpxchg16b)
12443   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
12444   SDValue Zero = DAG.getConstant(0, VT);
12445   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
12446                                Node->getOperand(0),
12447                                Node->getOperand(1), Zero, Zero,
12448                                cast<AtomicSDNode>(Node)->getMemOperand(),
12449                                cast<AtomicSDNode>(Node)->getOrdering(),
12450                                cast<AtomicSDNode>(Node)->getSynchScope());
12451   Results.push_back(Swap.getValue(0));
12452   Results.push_back(Swap.getValue(1));
12453 }
12454
12455 static void
12456 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
12457                         SelectionDAG &DAG, unsigned NewOp) {
12458   DebugLoc dl = Node->getDebugLoc();
12459   assert (Node->getValueType(0) == MVT::i64 &&
12460           "Only know how to expand i64 atomics");
12461
12462   SDValue Chain = Node->getOperand(0);
12463   SDValue In1 = Node->getOperand(1);
12464   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
12465                              Node->getOperand(2), DAG.getIntPtrConstant(0));
12466   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
12467                              Node->getOperand(2), DAG.getIntPtrConstant(1));
12468   SDValue Ops[] = { Chain, In1, In2L, In2H };
12469   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
12470   SDValue Result =
12471     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, array_lengthof(Ops), MVT::i64,
12472                             cast<MemSDNode>(Node)->getMemOperand());
12473   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
12474   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
12475   Results.push_back(Result.getValue(2));
12476 }
12477
12478 /// ReplaceNodeResults - Replace a node with an illegal result type
12479 /// with a new node built out of custom code.
12480 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
12481                                            SmallVectorImpl<SDValue>&Results,
12482                                            SelectionDAG &DAG) const {
12483   DebugLoc dl = N->getDebugLoc();
12484   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12485   switch (N->getOpcode()) {
12486   default:
12487     llvm_unreachable("Do not know how to custom type legalize this operation!");
12488   case ISD::SIGN_EXTEND_INREG:
12489   case ISD::ADDC:
12490   case ISD::ADDE:
12491   case ISD::SUBC:
12492   case ISD::SUBE:
12493     // We don't want to expand or promote these.
12494     return;
12495   case ISD::FP_TO_SINT:
12496   case ISD::FP_TO_UINT: {
12497     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
12498
12499     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
12500       return;
12501
12502     std::pair<SDValue,SDValue> Vals =
12503         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
12504     SDValue FIST = Vals.first, StackSlot = Vals.second;
12505     if (FIST.getNode() != 0) {
12506       EVT VT = N->getValueType(0);
12507       // Return a load from the stack slot.
12508       if (StackSlot.getNode() != 0)
12509         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
12510                                       MachinePointerInfo(),
12511                                       false, false, false, 0));
12512       else
12513         Results.push_back(FIST);
12514     }
12515     return;
12516   }
12517   case ISD::UINT_TO_FP: {
12518     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
12519     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
12520         N->getValueType(0) != MVT::v2f32)
12521       return;
12522     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
12523                                  N->getOperand(0));
12524     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
12525                                      MVT::f64);
12526     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
12527     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
12528                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
12529     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
12530     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
12531     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
12532     return;
12533   }
12534   case ISD::FP_ROUND: {
12535     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
12536         return;
12537     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
12538     Results.push_back(V);
12539     return;
12540   }
12541   case ISD::READCYCLECOUNTER: {
12542     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12543     SDValue TheChain = N->getOperand(0);
12544     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
12545     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
12546                                      rd.getValue(1));
12547     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
12548                                      eax.getValue(2));
12549     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
12550     SDValue Ops[] = { eax, edx };
12551     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops,
12552                                   array_lengthof(Ops)));
12553     Results.push_back(edx.getValue(1));
12554     return;
12555   }
12556   case ISD::ATOMIC_CMP_SWAP: {
12557     EVT T = N->getValueType(0);
12558     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
12559     bool Regs64bit = T == MVT::i128;
12560     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
12561     SDValue cpInL, cpInH;
12562     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
12563                         DAG.getConstant(0, HalfT));
12564     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
12565                         DAG.getConstant(1, HalfT));
12566     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
12567                              Regs64bit ? X86::RAX : X86::EAX,
12568                              cpInL, SDValue());
12569     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
12570                              Regs64bit ? X86::RDX : X86::EDX,
12571                              cpInH, cpInL.getValue(1));
12572     SDValue swapInL, swapInH;
12573     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
12574                           DAG.getConstant(0, HalfT));
12575     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
12576                           DAG.getConstant(1, HalfT));
12577     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
12578                                Regs64bit ? X86::RBX : X86::EBX,
12579                                swapInL, cpInH.getValue(1));
12580     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
12581                                Regs64bit ? X86::RCX : X86::ECX,
12582                                swapInH, swapInL.getValue(1));
12583     SDValue Ops[] = { swapInH.getValue(0),
12584                       N->getOperand(1),
12585                       swapInH.getValue(1) };
12586     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12587     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
12588     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
12589                                   X86ISD::LCMPXCHG8_DAG;
12590     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
12591                                              Ops, array_lengthof(Ops), T, MMO);
12592     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
12593                                         Regs64bit ? X86::RAX : X86::EAX,
12594                                         HalfT, Result.getValue(1));
12595     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
12596                                         Regs64bit ? X86::RDX : X86::EDX,
12597                                         HalfT, cpOutL.getValue(2));
12598     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
12599     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
12600     Results.push_back(cpOutH.getValue(1));
12601     return;
12602   }
12603   case ISD::ATOMIC_LOAD_ADD:
12604   case ISD::ATOMIC_LOAD_AND:
12605   case ISD::ATOMIC_LOAD_NAND:
12606   case ISD::ATOMIC_LOAD_OR:
12607   case ISD::ATOMIC_LOAD_SUB:
12608   case ISD::ATOMIC_LOAD_XOR:
12609   case ISD::ATOMIC_LOAD_MAX:
12610   case ISD::ATOMIC_LOAD_MIN:
12611   case ISD::ATOMIC_LOAD_UMAX:
12612   case ISD::ATOMIC_LOAD_UMIN:
12613   case ISD::ATOMIC_SWAP: {
12614     unsigned Opc;
12615     switch (N->getOpcode()) {
12616     default: llvm_unreachable("Unexpected opcode");
12617     case ISD::ATOMIC_LOAD_ADD:
12618       Opc = X86ISD::ATOMADD64_DAG;
12619       break;
12620     case ISD::ATOMIC_LOAD_AND:
12621       Opc = X86ISD::ATOMAND64_DAG;
12622       break;
12623     case ISD::ATOMIC_LOAD_NAND:
12624       Opc = X86ISD::ATOMNAND64_DAG;
12625       break;
12626     case ISD::ATOMIC_LOAD_OR:
12627       Opc = X86ISD::ATOMOR64_DAG;
12628       break;
12629     case ISD::ATOMIC_LOAD_SUB:
12630       Opc = X86ISD::ATOMSUB64_DAG;
12631       break;
12632     case ISD::ATOMIC_LOAD_XOR:
12633       Opc = X86ISD::ATOMXOR64_DAG;
12634       break;
12635     case ISD::ATOMIC_LOAD_MAX:
12636       Opc = X86ISD::ATOMMAX64_DAG;
12637       break;
12638     case ISD::ATOMIC_LOAD_MIN:
12639       Opc = X86ISD::ATOMMIN64_DAG;
12640       break;
12641     case ISD::ATOMIC_LOAD_UMAX:
12642       Opc = X86ISD::ATOMUMAX64_DAG;
12643       break;
12644     case ISD::ATOMIC_LOAD_UMIN:
12645       Opc = X86ISD::ATOMUMIN64_DAG;
12646       break;
12647     case ISD::ATOMIC_SWAP:
12648       Opc = X86ISD::ATOMSWAP64_DAG;
12649       break;
12650     }
12651     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
12652     return;
12653   }
12654   case ISD::ATOMIC_LOAD:
12655     ReplaceATOMIC_LOAD(N, Results, DAG);
12656   }
12657 }
12658
12659 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
12660   switch (Opcode) {
12661   default: return NULL;
12662   case X86ISD::BSF:                return "X86ISD::BSF";
12663   case X86ISD::BSR:                return "X86ISD::BSR";
12664   case X86ISD::SHLD:               return "X86ISD::SHLD";
12665   case X86ISD::SHRD:               return "X86ISD::SHRD";
12666   case X86ISD::FAND:               return "X86ISD::FAND";
12667   case X86ISD::FOR:                return "X86ISD::FOR";
12668   case X86ISD::FXOR:               return "X86ISD::FXOR";
12669   case X86ISD::FSRL:               return "X86ISD::FSRL";
12670   case X86ISD::FILD:               return "X86ISD::FILD";
12671   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
12672   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
12673   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
12674   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
12675   case X86ISD::FLD:                return "X86ISD::FLD";
12676   case X86ISD::FST:                return "X86ISD::FST";
12677   case X86ISD::CALL:               return "X86ISD::CALL";
12678   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
12679   case X86ISD::BT:                 return "X86ISD::BT";
12680   case X86ISD::CMP:                return "X86ISD::CMP";
12681   case X86ISD::COMI:               return "X86ISD::COMI";
12682   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
12683   case X86ISD::SETCC:              return "X86ISD::SETCC";
12684   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
12685   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
12686   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
12687   case X86ISD::CMOV:               return "X86ISD::CMOV";
12688   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
12689   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
12690   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
12691   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
12692   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
12693   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
12694   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
12695   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
12696   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
12697   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
12698   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
12699   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
12700   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
12701   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
12702   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
12703   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
12704   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
12705   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
12706   case X86ISD::HADD:               return "X86ISD::HADD";
12707   case X86ISD::HSUB:               return "X86ISD::HSUB";
12708   case X86ISD::FHADD:              return "X86ISD::FHADD";
12709   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
12710   case X86ISD::UMAX:               return "X86ISD::UMAX";
12711   case X86ISD::UMIN:               return "X86ISD::UMIN";
12712   case X86ISD::SMAX:               return "X86ISD::SMAX";
12713   case X86ISD::SMIN:               return "X86ISD::SMIN";
12714   case X86ISD::FMAX:               return "X86ISD::FMAX";
12715   case X86ISD::FMIN:               return "X86ISD::FMIN";
12716   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
12717   case X86ISD::FMINC:              return "X86ISD::FMINC";
12718   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
12719   case X86ISD::FRCP:               return "X86ISD::FRCP";
12720   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
12721   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
12722   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
12723   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
12724   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
12725   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
12726   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
12727   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
12728   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
12729   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
12730   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
12731   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
12732   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
12733   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
12734   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
12735   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
12736   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
12737   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
12738   case X86ISD::VSEXT_MOVL:         return "X86ISD::VSEXT_MOVL";
12739   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
12740   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
12741   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
12742   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
12743   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
12744   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
12745   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
12746   case X86ISD::VSHL:               return "X86ISD::VSHL";
12747   case X86ISD::VSRL:               return "X86ISD::VSRL";
12748   case X86ISD::VSRA:               return "X86ISD::VSRA";
12749   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
12750   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
12751   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
12752   case X86ISD::CMPP:               return "X86ISD::CMPP";
12753   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
12754   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
12755   case X86ISD::ADD:                return "X86ISD::ADD";
12756   case X86ISD::SUB:                return "X86ISD::SUB";
12757   case X86ISD::ADC:                return "X86ISD::ADC";
12758   case X86ISD::SBB:                return "X86ISD::SBB";
12759   case X86ISD::SMUL:               return "X86ISD::SMUL";
12760   case X86ISD::UMUL:               return "X86ISD::UMUL";
12761   case X86ISD::INC:                return "X86ISD::INC";
12762   case X86ISD::DEC:                return "X86ISD::DEC";
12763   case X86ISD::OR:                 return "X86ISD::OR";
12764   case X86ISD::XOR:                return "X86ISD::XOR";
12765   case X86ISD::AND:                return "X86ISD::AND";
12766   case X86ISD::BLSI:               return "X86ISD::BLSI";
12767   case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
12768   case X86ISD::BLSR:               return "X86ISD::BLSR";
12769   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
12770   case X86ISD::PTEST:              return "X86ISD::PTEST";
12771   case X86ISD::TESTP:              return "X86ISD::TESTP";
12772   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
12773   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
12774   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
12775   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
12776   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
12777   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
12778   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
12779   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
12780   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
12781   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
12782   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
12783   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
12784   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
12785   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
12786   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
12787   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
12788   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
12789   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
12790   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
12791   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
12792   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
12793   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
12794   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
12795   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
12796   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
12797   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
12798   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
12799   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
12800   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
12801   case X86ISD::SAHF:               return "X86ISD::SAHF";
12802   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
12803   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
12804   case X86ISD::FMADD:              return "X86ISD::FMADD";
12805   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
12806   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
12807   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
12808   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
12809   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
12810   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
12811   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
12812   case X86ISD::XTEST:              return "X86ISD::XTEST";
12813   }
12814 }
12815
12816 // isLegalAddressingMode - Return true if the addressing mode represented
12817 // by AM is legal for this target, for a load/store of the specified type.
12818 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
12819                                               Type *Ty) const {
12820   // X86 supports extremely general addressing modes.
12821   CodeModel::Model M = getTargetMachine().getCodeModel();
12822   Reloc::Model R = getTargetMachine().getRelocationModel();
12823
12824   // X86 allows a sign-extended 32-bit immediate field as a displacement.
12825   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
12826     return false;
12827
12828   if (AM.BaseGV) {
12829     unsigned GVFlags =
12830       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
12831
12832     // If a reference to this global requires an extra load, we can't fold it.
12833     if (isGlobalStubReference(GVFlags))
12834       return false;
12835
12836     // If BaseGV requires a register for the PIC base, we cannot also have a
12837     // BaseReg specified.
12838     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
12839       return false;
12840
12841     // If lower 4G is not available, then we must use rip-relative addressing.
12842     if ((M != CodeModel::Small || R != Reloc::Static) &&
12843         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
12844       return false;
12845   }
12846
12847   switch (AM.Scale) {
12848   case 0:
12849   case 1:
12850   case 2:
12851   case 4:
12852   case 8:
12853     // These scales always work.
12854     break;
12855   case 3:
12856   case 5:
12857   case 9:
12858     // These scales are formed with basereg+scalereg.  Only accept if there is
12859     // no basereg yet.
12860     if (AM.HasBaseReg)
12861       return false;
12862     break;
12863   default:  // Other stuff never works.
12864     return false;
12865   }
12866
12867   return true;
12868 }
12869
12870 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
12871   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
12872     return false;
12873   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
12874   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
12875   return NumBits1 > NumBits2;
12876 }
12877
12878 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
12879   return isInt<32>(Imm);
12880 }
12881
12882 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
12883   // Can also use sub to handle negated immediates.
12884   return isInt<32>(Imm);
12885 }
12886
12887 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
12888   if (!VT1.isInteger() || !VT2.isInteger())
12889     return false;
12890   unsigned NumBits1 = VT1.getSizeInBits();
12891   unsigned NumBits2 = VT2.getSizeInBits();
12892   return NumBits1 > NumBits2;
12893 }
12894
12895 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
12896   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12897   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
12898 }
12899
12900 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
12901   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12902   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
12903 }
12904
12905 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
12906   EVT VT1 = Val.getValueType();
12907   if (isZExtFree(VT1, VT2))
12908     return true;
12909
12910   if (Val.getOpcode() != ISD::LOAD)
12911     return false;
12912
12913   if (!VT1.isSimple() || !VT1.isInteger() ||
12914       !VT2.isSimple() || !VT2.isInteger())
12915     return false;
12916
12917   switch (VT1.getSimpleVT().SimpleTy) {
12918   default: break;
12919   case MVT::i8:
12920   case MVT::i16:
12921   case MVT::i32:
12922     // X86 has 8, 16, and 32-bit zero-extending loads.
12923     return true;
12924   }
12925
12926   return false;
12927 }
12928
12929 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
12930   // i16 instructions are longer (0x66 prefix) and potentially slower.
12931   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
12932 }
12933
12934 /// isShuffleMaskLegal - Targets can use this to indicate that they only
12935 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
12936 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
12937 /// are assumed to be legal.
12938 bool
12939 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
12940                                       EVT VT) const {
12941   // Very little shuffling can be done for 64-bit vectors right now.
12942   if (VT.getSizeInBits() == 64)
12943     return false;
12944
12945   // FIXME: pshufb, blends, shifts.
12946   return (VT.getVectorNumElements() == 2 ||
12947           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
12948           isMOVLMask(M, VT) ||
12949           isSHUFPMask(M, VT, Subtarget->hasFp256()) ||
12950           isPSHUFDMask(M, VT) ||
12951           isPSHUFHWMask(M, VT, Subtarget->hasInt256()) ||
12952           isPSHUFLWMask(M, VT, Subtarget->hasInt256()) ||
12953           isPALIGNRMask(M, VT, Subtarget) ||
12954           isUNPCKLMask(M, VT, Subtarget->hasInt256()) ||
12955           isUNPCKHMask(M, VT, Subtarget->hasInt256()) ||
12956           isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasInt256()) ||
12957           isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasInt256()));
12958 }
12959
12960 bool
12961 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
12962                                           EVT VT) const {
12963   unsigned NumElts = VT.getVectorNumElements();
12964   // FIXME: This collection of masks seems suspect.
12965   if (NumElts == 2)
12966     return true;
12967   if (NumElts == 4 && VT.is128BitVector()) {
12968     return (isMOVLMask(Mask, VT)  ||
12969             isCommutedMOVLMask(Mask, VT, true) ||
12970             isSHUFPMask(Mask, VT, Subtarget->hasFp256()) ||
12971             isSHUFPMask(Mask, VT, Subtarget->hasFp256(), /* Commuted */ true));
12972   }
12973   return false;
12974 }
12975
12976 //===----------------------------------------------------------------------===//
12977 //                           X86 Scheduler Hooks
12978 //===----------------------------------------------------------------------===//
12979
12980 /// Utility function to emit xbegin specifying the start of an RTM region.
12981 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
12982                                      const TargetInstrInfo *TII) {
12983   DebugLoc DL = MI->getDebugLoc();
12984
12985   const BasicBlock *BB = MBB->getBasicBlock();
12986   MachineFunction::iterator I = MBB;
12987   ++I;
12988
12989   // For the v = xbegin(), we generate
12990   //
12991   // thisMBB:
12992   //  xbegin sinkMBB
12993   //
12994   // mainMBB:
12995   //  eax = -1
12996   //
12997   // sinkMBB:
12998   //  v = eax
12999
13000   MachineBasicBlock *thisMBB = MBB;
13001   MachineFunction *MF = MBB->getParent();
13002   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13003   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13004   MF->insert(I, mainMBB);
13005   MF->insert(I, sinkMBB);
13006
13007   // Transfer the remainder of BB and its successor edges to sinkMBB.
13008   sinkMBB->splice(sinkMBB->begin(), MBB,
13009                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13010   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13011
13012   // thisMBB:
13013   //  xbegin sinkMBB
13014   //  # fallthrough to mainMBB
13015   //  # abortion to sinkMBB
13016   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
13017   thisMBB->addSuccessor(mainMBB);
13018   thisMBB->addSuccessor(sinkMBB);
13019
13020   // mainMBB:
13021   //  EAX = -1
13022   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
13023   mainMBB->addSuccessor(sinkMBB);
13024
13025   // sinkMBB:
13026   // EAX is live into the sinkMBB
13027   sinkMBB->addLiveIn(X86::EAX);
13028   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13029           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13030     .addReg(X86::EAX);
13031
13032   MI->eraseFromParent();
13033   return sinkMBB;
13034 }
13035
13036 // Get CMPXCHG opcode for the specified data type.
13037 static unsigned getCmpXChgOpcode(EVT VT) {
13038   switch (VT.getSimpleVT().SimpleTy) {
13039   case MVT::i8:  return X86::LCMPXCHG8;
13040   case MVT::i16: return X86::LCMPXCHG16;
13041   case MVT::i32: return X86::LCMPXCHG32;
13042   case MVT::i64: return X86::LCMPXCHG64;
13043   default:
13044     break;
13045   }
13046   llvm_unreachable("Invalid operand size!");
13047 }
13048
13049 // Get LOAD opcode for the specified data type.
13050 static unsigned getLoadOpcode(EVT VT) {
13051   switch (VT.getSimpleVT().SimpleTy) {
13052   case MVT::i8:  return X86::MOV8rm;
13053   case MVT::i16: return X86::MOV16rm;
13054   case MVT::i32: return X86::MOV32rm;
13055   case MVT::i64: return X86::MOV64rm;
13056   default:
13057     break;
13058   }
13059   llvm_unreachable("Invalid operand size!");
13060 }
13061
13062 // Get opcode of the non-atomic one from the specified atomic instruction.
13063 static unsigned getNonAtomicOpcode(unsigned Opc) {
13064   switch (Opc) {
13065   case X86::ATOMAND8:  return X86::AND8rr;
13066   case X86::ATOMAND16: return X86::AND16rr;
13067   case X86::ATOMAND32: return X86::AND32rr;
13068   case X86::ATOMAND64: return X86::AND64rr;
13069   case X86::ATOMOR8:   return X86::OR8rr;
13070   case X86::ATOMOR16:  return X86::OR16rr;
13071   case X86::ATOMOR32:  return X86::OR32rr;
13072   case X86::ATOMOR64:  return X86::OR64rr;
13073   case X86::ATOMXOR8:  return X86::XOR8rr;
13074   case X86::ATOMXOR16: return X86::XOR16rr;
13075   case X86::ATOMXOR32: return X86::XOR32rr;
13076   case X86::ATOMXOR64: return X86::XOR64rr;
13077   }
13078   llvm_unreachable("Unhandled atomic-load-op opcode!");
13079 }
13080
13081 // Get opcode of the non-atomic one from the specified atomic instruction with
13082 // extra opcode.
13083 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
13084                                                unsigned &ExtraOpc) {
13085   switch (Opc) {
13086   case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
13087   case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
13088   case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
13089   case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
13090   case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
13091   case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
13092   case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
13093   case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
13094   case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
13095   case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
13096   case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
13097   case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
13098   case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
13099   case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
13100   case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
13101   case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
13102   case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
13103   case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
13104   case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
13105   case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
13106   }
13107   llvm_unreachable("Unhandled atomic-load-op opcode!");
13108 }
13109
13110 // Get opcode of the non-atomic one from the specified atomic instruction for
13111 // 64-bit data type on 32-bit target.
13112 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
13113   switch (Opc) {
13114   case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
13115   case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
13116   case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
13117   case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
13118   case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
13119   case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
13120   case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
13121   case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
13122   case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
13123   case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
13124   }
13125   llvm_unreachable("Unhandled atomic-load-op opcode!");
13126 }
13127
13128 // Get opcode of the non-atomic one from the specified atomic instruction for
13129 // 64-bit data type on 32-bit target with extra opcode.
13130 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
13131                                                    unsigned &HiOpc,
13132                                                    unsigned &ExtraOpc) {
13133   switch (Opc) {
13134   case X86::ATOMNAND6432:
13135     ExtraOpc = X86::NOT32r;
13136     HiOpc = X86::AND32rr;
13137     return X86::AND32rr;
13138   }
13139   llvm_unreachable("Unhandled atomic-load-op opcode!");
13140 }
13141
13142 // Get pseudo CMOV opcode from the specified data type.
13143 static unsigned getPseudoCMOVOpc(EVT VT) {
13144   switch (VT.getSimpleVT().SimpleTy) {
13145   case MVT::i8:  return X86::CMOV_GR8;
13146   case MVT::i16: return X86::CMOV_GR16;
13147   case MVT::i32: return X86::CMOV_GR32;
13148   default:
13149     break;
13150   }
13151   llvm_unreachable("Unknown CMOV opcode!");
13152 }
13153
13154 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
13155 // They will be translated into a spin-loop or compare-exchange loop from
13156 //
13157 //    ...
13158 //    dst = atomic-fetch-op MI.addr, MI.val
13159 //    ...
13160 //
13161 // to
13162 //
13163 //    ...
13164 //    t1 = LOAD MI.addr
13165 // loop:
13166 //    t4 = phi(t1, t3 / loop)
13167 //    t2 = OP MI.val, t4
13168 //    EAX = t4
13169 //    LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
13170 //    t3 = EAX
13171 //    JNE loop
13172 // sink:
13173 //    dst = t3
13174 //    ...
13175 MachineBasicBlock *
13176 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
13177                                        MachineBasicBlock *MBB) const {
13178   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13179   DebugLoc DL = MI->getDebugLoc();
13180
13181   MachineFunction *MF = MBB->getParent();
13182   MachineRegisterInfo &MRI = MF->getRegInfo();
13183
13184   const BasicBlock *BB = MBB->getBasicBlock();
13185   MachineFunction::iterator I = MBB;
13186   ++I;
13187
13188   assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
13189          "Unexpected number of operands");
13190
13191   assert(MI->hasOneMemOperand() &&
13192          "Expected atomic-load-op to have one memoperand");
13193
13194   // Memory Reference
13195   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13196   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13197
13198   unsigned DstReg, SrcReg;
13199   unsigned MemOpndSlot;
13200
13201   unsigned CurOp = 0;
13202
13203   DstReg = MI->getOperand(CurOp++).getReg();
13204   MemOpndSlot = CurOp;
13205   CurOp += X86::AddrNumOperands;
13206   SrcReg = MI->getOperand(CurOp++).getReg();
13207
13208   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
13209   MVT::SimpleValueType VT = *RC->vt_begin();
13210   unsigned t1 = MRI.createVirtualRegister(RC);
13211   unsigned t2 = MRI.createVirtualRegister(RC);
13212   unsigned t3 = MRI.createVirtualRegister(RC);
13213   unsigned t4 = MRI.createVirtualRegister(RC);
13214   unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
13215
13216   unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
13217   unsigned LOADOpc = getLoadOpcode(VT);
13218
13219   // For the atomic load-arith operator, we generate
13220   //
13221   //  thisMBB:
13222   //    t1 = LOAD [MI.addr]
13223   //  mainMBB:
13224   //    t4 = phi(t1 / thisMBB, t3 / mainMBB)
13225   //    t1 = OP MI.val, EAX
13226   //    EAX = t4
13227   //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
13228   //    t3 = EAX
13229   //    JNE mainMBB
13230   //  sinkMBB:
13231   //    dst = t3
13232
13233   MachineBasicBlock *thisMBB = MBB;
13234   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13235   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13236   MF->insert(I, mainMBB);
13237   MF->insert(I, sinkMBB);
13238
13239   MachineInstrBuilder MIB;
13240
13241   // Transfer the remainder of BB and its successor edges to sinkMBB.
13242   sinkMBB->splice(sinkMBB->begin(), MBB,
13243                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13244   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13245
13246   // thisMBB:
13247   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
13248   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13249     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13250     if (NewMO.isReg())
13251       NewMO.setIsKill(false);
13252     MIB.addOperand(NewMO);
13253   }
13254   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
13255     unsigned flags = (*MMOI)->getFlags();
13256     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
13257     MachineMemOperand *MMO =
13258       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
13259                                (*MMOI)->getSize(),
13260                                (*MMOI)->getBaseAlignment(),
13261                                (*MMOI)->getTBAAInfo(),
13262                                (*MMOI)->getRanges());
13263     MIB.addMemOperand(MMO);
13264   }
13265
13266   thisMBB->addSuccessor(mainMBB);
13267
13268   // mainMBB:
13269   MachineBasicBlock *origMainMBB = mainMBB;
13270
13271   // Add a PHI.
13272   MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
13273                         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
13274
13275   unsigned Opc = MI->getOpcode();
13276   switch (Opc) {
13277   default:
13278     llvm_unreachable("Unhandled atomic-load-op opcode!");
13279   case X86::ATOMAND8:
13280   case X86::ATOMAND16:
13281   case X86::ATOMAND32:
13282   case X86::ATOMAND64:
13283   case X86::ATOMOR8:
13284   case X86::ATOMOR16:
13285   case X86::ATOMOR32:
13286   case X86::ATOMOR64:
13287   case X86::ATOMXOR8:
13288   case X86::ATOMXOR16:
13289   case X86::ATOMXOR32:
13290   case X86::ATOMXOR64: {
13291     unsigned ARITHOpc = getNonAtomicOpcode(Opc);
13292     BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
13293       .addReg(t4);
13294     break;
13295   }
13296   case X86::ATOMNAND8:
13297   case X86::ATOMNAND16:
13298   case X86::ATOMNAND32:
13299   case X86::ATOMNAND64: {
13300     unsigned Tmp = MRI.createVirtualRegister(RC);
13301     unsigned NOTOpc;
13302     unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
13303     BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
13304       .addReg(t4);
13305     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
13306     break;
13307   }
13308   case X86::ATOMMAX8:
13309   case X86::ATOMMAX16:
13310   case X86::ATOMMAX32:
13311   case X86::ATOMMAX64:
13312   case X86::ATOMMIN8:
13313   case X86::ATOMMIN16:
13314   case X86::ATOMMIN32:
13315   case X86::ATOMMIN64:
13316   case X86::ATOMUMAX8:
13317   case X86::ATOMUMAX16:
13318   case X86::ATOMUMAX32:
13319   case X86::ATOMUMAX64:
13320   case X86::ATOMUMIN8:
13321   case X86::ATOMUMIN16:
13322   case X86::ATOMUMIN32:
13323   case X86::ATOMUMIN64: {
13324     unsigned CMPOpc;
13325     unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
13326
13327     BuildMI(mainMBB, DL, TII->get(CMPOpc))
13328       .addReg(SrcReg)
13329       .addReg(t4);
13330
13331     if (Subtarget->hasCMov()) {
13332       if (VT != MVT::i8) {
13333         // Native support
13334         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
13335           .addReg(SrcReg)
13336           .addReg(t4);
13337       } else {
13338         // Promote i8 to i32 to use CMOV32
13339         const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
13340         const TargetRegisterClass *RC32 =
13341           TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
13342         unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
13343         unsigned AccReg32 = MRI.createVirtualRegister(RC32);
13344         unsigned Tmp = MRI.createVirtualRegister(RC32);
13345
13346         unsigned Undef = MRI.createVirtualRegister(RC32);
13347         BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
13348
13349         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
13350           .addReg(Undef)
13351           .addReg(SrcReg)
13352           .addImm(X86::sub_8bit);
13353         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
13354           .addReg(Undef)
13355           .addReg(t4)
13356           .addImm(X86::sub_8bit);
13357
13358         BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
13359           .addReg(SrcReg32)
13360           .addReg(AccReg32);
13361
13362         BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
13363           .addReg(Tmp, 0, X86::sub_8bit);
13364       }
13365     } else {
13366       // Use pseudo select and lower them.
13367       assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
13368              "Invalid atomic-load-op transformation!");
13369       unsigned SelOpc = getPseudoCMOVOpc(VT);
13370       X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
13371       assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
13372       MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
13373               .addReg(SrcReg).addReg(t4)
13374               .addImm(CC);
13375       mainMBB = EmitLoweredSelect(MIB, mainMBB);
13376       // Replace the original PHI node as mainMBB is changed after CMOV
13377       // lowering.
13378       BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
13379         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
13380       Phi->eraseFromParent();
13381     }
13382     break;
13383   }
13384   }
13385
13386   // Copy PhyReg back from virtual register.
13387   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
13388     .addReg(t4);
13389
13390   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
13391   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13392     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13393     if (NewMO.isReg())
13394       NewMO.setIsKill(false);
13395     MIB.addOperand(NewMO);
13396   }
13397   MIB.addReg(t2);
13398   MIB.setMemRefs(MMOBegin, MMOEnd);
13399
13400   // Copy PhyReg back to virtual register.
13401   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
13402     .addReg(PhyReg);
13403
13404   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
13405
13406   mainMBB->addSuccessor(origMainMBB);
13407   mainMBB->addSuccessor(sinkMBB);
13408
13409   // sinkMBB:
13410   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13411           TII->get(TargetOpcode::COPY), DstReg)
13412     .addReg(t3);
13413
13414   MI->eraseFromParent();
13415   return sinkMBB;
13416 }
13417
13418 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
13419 // instructions. They will be translated into a spin-loop or compare-exchange
13420 // loop from
13421 //
13422 //    ...
13423 //    dst = atomic-fetch-op MI.addr, MI.val
13424 //    ...
13425 //
13426 // to
13427 //
13428 //    ...
13429 //    t1L = LOAD [MI.addr + 0]
13430 //    t1H = LOAD [MI.addr + 4]
13431 // loop:
13432 //    t4L = phi(t1L, t3L / loop)
13433 //    t4H = phi(t1H, t3H / loop)
13434 //    t2L = OP MI.val.lo, t4L
13435 //    t2H = OP MI.val.hi, t4H
13436 //    EAX = t4L
13437 //    EDX = t4H
13438 //    EBX = t2L
13439 //    ECX = t2H
13440 //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
13441 //    t3L = EAX
13442 //    t3H = EDX
13443 //    JNE loop
13444 // sink:
13445 //    dstL = t3L
13446 //    dstH = t3H
13447 //    ...
13448 MachineBasicBlock *
13449 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
13450                                            MachineBasicBlock *MBB) const {
13451   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13452   DebugLoc DL = MI->getDebugLoc();
13453
13454   MachineFunction *MF = MBB->getParent();
13455   MachineRegisterInfo &MRI = MF->getRegInfo();
13456
13457   const BasicBlock *BB = MBB->getBasicBlock();
13458   MachineFunction::iterator I = MBB;
13459   ++I;
13460
13461   assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
13462          "Unexpected number of operands");
13463
13464   assert(MI->hasOneMemOperand() &&
13465          "Expected atomic-load-op32 to have one memoperand");
13466
13467   // Memory Reference
13468   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13469   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13470
13471   unsigned DstLoReg, DstHiReg;
13472   unsigned SrcLoReg, SrcHiReg;
13473   unsigned MemOpndSlot;
13474
13475   unsigned CurOp = 0;
13476
13477   DstLoReg = MI->getOperand(CurOp++).getReg();
13478   DstHiReg = MI->getOperand(CurOp++).getReg();
13479   MemOpndSlot = CurOp;
13480   CurOp += X86::AddrNumOperands;
13481   SrcLoReg = MI->getOperand(CurOp++).getReg();
13482   SrcHiReg = MI->getOperand(CurOp++).getReg();
13483
13484   const TargetRegisterClass *RC = &X86::GR32RegClass;
13485   const TargetRegisterClass *RC8 = &X86::GR8RegClass;
13486
13487   unsigned t1L = MRI.createVirtualRegister(RC);
13488   unsigned t1H = MRI.createVirtualRegister(RC);
13489   unsigned t2L = MRI.createVirtualRegister(RC);
13490   unsigned t2H = MRI.createVirtualRegister(RC);
13491   unsigned t3L = MRI.createVirtualRegister(RC);
13492   unsigned t3H = MRI.createVirtualRegister(RC);
13493   unsigned t4L = MRI.createVirtualRegister(RC);
13494   unsigned t4H = MRI.createVirtualRegister(RC);
13495
13496   unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
13497   unsigned LOADOpc = X86::MOV32rm;
13498
13499   // For the atomic load-arith operator, we generate
13500   //
13501   //  thisMBB:
13502   //    t1L = LOAD [MI.addr + 0]
13503   //    t1H = LOAD [MI.addr + 4]
13504   //  mainMBB:
13505   //    t4L = phi(t1L / thisMBB, t3L / mainMBB)
13506   //    t4H = phi(t1H / thisMBB, t3H / mainMBB)
13507   //    t2L = OP MI.val.lo, t4L
13508   //    t2H = OP MI.val.hi, t4H
13509   //    EBX = t2L
13510   //    ECX = t2H
13511   //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
13512   //    t3L = EAX
13513   //    t3H = EDX
13514   //    JNE loop
13515   //  sinkMBB:
13516   //    dstL = t3L
13517   //    dstH = t3H
13518
13519   MachineBasicBlock *thisMBB = MBB;
13520   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13521   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13522   MF->insert(I, mainMBB);
13523   MF->insert(I, sinkMBB);
13524
13525   MachineInstrBuilder MIB;
13526
13527   // Transfer the remainder of BB and its successor edges to sinkMBB.
13528   sinkMBB->splice(sinkMBB->begin(), MBB,
13529                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13530   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13531
13532   // thisMBB:
13533   // Lo
13534   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
13535   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13536     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13537     if (NewMO.isReg())
13538       NewMO.setIsKill(false);
13539     MIB.addOperand(NewMO);
13540   }
13541   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
13542     unsigned flags = (*MMOI)->getFlags();
13543     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
13544     MachineMemOperand *MMO =
13545       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
13546                                (*MMOI)->getSize(),
13547                                (*MMOI)->getBaseAlignment(),
13548                                (*MMOI)->getTBAAInfo(),
13549                                (*MMOI)->getRanges());
13550     MIB.addMemOperand(MMO);
13551   };
13552   MachineInstr *LowMI = MIB;
13553
13554   // Hi
13555   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
13556   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13557     if (i == X86::AddrDisp) {
13558       MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
13559     } else {
13560       MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13561       if (NewMO.isReg())
13562         NewMO.setIsKill(false);
13563       MIB.addOperand(NewMO);
13564     }
13565   }
13566   MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
13567
13568   thisMBB->addSuccessor(mainMBB);
13569
13570   // mainMBB:
13571   MachineBasicBlock *origMainMBB = mainMBB;
13572
13573   // Add PHIs.
13574   MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
13575                         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
13576   MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
13577                         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
13578
13579   unsigned Opc = MI->getOpcode();
13580   switch (Opc) {
13581   default:
13582     llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
13583   case X86::ATOMAND6432:
13584   case X86::ATOMOR6432:
13585   case X86::ATOMXOR6432:
13586   case X86::ATOMADD6432:
13587   case X86::ATOMSUB6432: {
13588     unsigned HiOpc;
13589     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13590     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
13591       .addReg(SrcLoReg);
13592     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
13593       .addReg(SrcHiReg);
13594     break;
13595   }
13596   case X86::ATOMNAND6432: {
13597     unsigned HiOpc, NOTOpc;
13598     unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
13599     unsigned TmpL = MRI.createVirtualRegister(RC);
13600     unsigned TmpH = MRI.createVirtualRegister(RC);
13601     BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
13602       .addReg(t4L);
13603     BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
13604       .addReg(t4H);
13605     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
13606     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
13607     break;
13608   }
13609   case X86::ATOMMAX6432:
13610   case X86::ATOMMIN6432:
13611   case X86::ATOMUMAX6432:
13612   case X86::ATOMUMIN6432: {
13613     unsigned HiOpc;
13614     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13615     unsigned cL = MRI.createVirtualRegister(RC8);
13616     unsigned cH = MRI.createVirtualRegister(RC8);
13617     unsigned cL32 = MRI.createVirtualRegister(RC);
13618     unsigned cH32 = MRI.createVirtualRegister(RC);
13619     unsigned cc = MRI.createVirtualRegister(RC);
13620     // cl := cmp src_lo, lo
13621     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
13622       .addReg(SrcLoReg).addReg(t4L);
13623     BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
13624     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
13625     // ch := cmp src_hi, hi
13626     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
13627       .addReg(SrcHiReg).addReg(t4H);
13628     BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
13629     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
13630     // cc := if (src_hi == hi) ? cl : ch;
13631     if (Subtarget->hasCMov()) {
13632       BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
13633         .addReg(cH32).addReg(cL32);
13634     } else {
13635       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
13636               .addReg(cH32).addReg(cL32)
13637               .addImm(X86::COND_E);
13638       mainMBB = EmitLoweredSelect(MIB, mainMBB);
13639     }
13640     BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
13641     if (Subtarget->hasCMov()) {
13642       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
13643         .addReg(SrcLoReg).addReg(t4L);
13644       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
13645         .addReg(SrcHiReg).addReg(t4H);
13646     } else {
13647       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
13648               .addReg(SrcLoReg).addReg(t4L)
13649               .addImm(X86::COND_NE);
13650       mainMBB = EmitLoweredSelect(MIB, mainMBB);
13651       // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
13652       // 2nd CMOV lowering.
13653       mainMBB->addLiveIn(X86::EFLAGS);
13654       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
13655               .addReg(SrcHiReg).addReg(t4H)
13656               .addImm(X86::COND_NE);
13657       mainMBB = EmitLoweredSelect(MIB, mainMBB);
13658       // Replace the original PHI node as mainMBB is changed after CMOV
13659       // lowering.
13660       BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
13661         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
13662       BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
13663         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
13664       PhiL->eraseFromParent();
13665       PhiH->eraseFromParent();
13666     }
13667     break;
13668   }
13669   case X86::ATOMSWAP6432: {
13670     unsigned HiOpc;
13671     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13672     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
13673     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
13674     break;
13675   }
13676   }
13677
13678   // Copy EDX:EAX back from HiReg:LoReg
13679   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
13680   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
13681   // Copy ECX:EBX from t1H:t1L
13682   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
13683   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
13684
13685   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
13686   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13687     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13688     if (NewMO.isReg())
13689       NewMO.setIsKill(false);
13690     MIB.addOperand(NewMO);
13691   }
13692   MIB.setMemRefs(MMOBegin, MMOEnd);
13693
13694   // Copy EDX:EAX back to t3H:t3L
13695   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
13696   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
13697
13698   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
13699
13700   mainMBB->addSuccessor(origMainMBB);
13701   mainMBB->addSuccessor(sinkMBB);
13702
13703   // sinkMBB:
13704   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13705           TII->get(TargetOpcode::COPY), DstLoReg)
13706     .addReg(t3L);
13707   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13708           TII->get(TargetOpcode::COPY), DstHiReg)
13709     .addReg(t3H);
13710
13711   MI->eraseFromParent();
13712   return sinkMBB;
13713 }
13714
13715 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
13716 // or XMM0_V32I8 in AVX all of this code can be replaced with that
13717 // in the .td file.
13718 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
13719                                        const TargetInstrInfo *TII) {
13720   unsigned Opc;
13721   switch (MI->getOpcode()) {
13722   default: llvm_unreachable("illegal opcode!");
13723   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
13724   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
13725   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
13726   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
13727   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
13728   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
13729   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
13730   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
13731   }
13732
13733   DebugLoc dl = MI->getDebugLoc();
13734   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
13735
13736   unsigned NumArgs = MI->getNumOperands();
13737   for (unsigned i = 1; i < NumArgs; ++i) {
13738     MachineOperand &Op = MI->getOperand(i);
13739     if (!(Op.isReg() && Op.isImplicit()))
13740       MIB.addOperand(Op);
13741   }
13742   if (MI->hasOneMemOperand())
13743     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
13744
13745   BuildMI(*BB, MI, dl,
13746     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13747     .addReg(X86::XMM0);
13748
13749   MI->eraseFromParent();
13750   return BB;
13751 }
13752
13753 // FIXME: Custom handling because TableGen doesn't support multiple implicit
13754 // defs in an instruction pattern
13755 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
13756                                        const TargetInstrInfo *TII) {
13757   unsigned Opc;
13758   switch (MI->getOpcode()) {
13759   default: llvm_unreachable("illegal opcode!");
13760   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
13761   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
13762   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
13763   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
13764   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
13765   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
13766   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
13767   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
13768   }
13769
13770   DebugLoc dl = MI->getDebugLoc();
13771   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
13772
13773   unsigned NumArgs = MI->getNumOperands(); // remove the results
13774   for (unsigned i = 1; i < NumArgs; ++i) {
13775     MachineOperand &Op = MI->getOperand(i);
13776     if (!(Op.isReg() && Op.isImplicit()))
13777       MIB.addOperand(Op);
13778   }
13779   if (MI->hasOneMemOperand())
13780     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
13781
13782   BuildMI(*BB, MI, dl,
13783     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13784     .addReg(X86::ECX);
13785
13786   MI->eraseFromParent();
13787   return BB;
13788 }
13789
13790 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
13791                                        const TargetInstrInfo *TII,
13792                                        const X86Subtarget* Subtarget) {
13793   DebugLoc dl = MI->getDebugLoc();
13794
13795   // Address into RAX/EAX, other two args into ECX, EDX.
13796   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
13797   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
13798   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
13799   for (int i = 0; i < X86::AddrNumOperands; ++i)
13800     MIB.addOperand(MI->getOperand(i));
13801
13802   unsigned ValOps = X86::AddrNumOperands;
13803   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
13804     .addReg(MI->getOperand(ValOps).getReg());
13805   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
13806     .addReg(MI->getOperand(ValOps+1).getReg());
13807
13808   // The instruction doesn't actually take any operands though.
13809   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
13810
13811   MI->eraseFromParent(); // The pseudo is gone now.
13812   return BB;
13813 }
13814
13815 MachineBasicBlock *
13816 X86TargetLowering::EmitVAARG64WithCustomInserter(
13817                    MachineInstr *MI,
13818                    MachineBasicBlock *MBB) const {
13819   // Emit va_arg instruction on X86-64.
13820
13821   // Operands to this pseudo-instruction:
13822   // 0  ) Output        : destination address (reg)
13823   // 1-5) Input         : va_list address (addr, i64mem)
13824   // 6  ) ArgSize       : Size (in bytes) of vararg type
13825   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
13826   // 8  ) Align         : Alignment of type
13827   // 9  ) EFLAGS (implicit-def)
13828
13829   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
13830   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
13831
13832   unsigned DestReg = MI->getOperand(0).getReg();
13833   MachineOperand &Base = MI->getOperand(1);
13834   MachineOperand &Scale = MI->getOperand(2);
13835   MachineOperand &Index = MI->getOperand(3);
13836   MachineOperand &Disp = MI->getOperand(4);
13837   MachineOperand &Segment = MI->getOperand(5);
13838   unsigned ArgSize = MI->getOperand(6).getImm();
13839   unsigned ArgMode = MI->getOperand(7).getImm();
13840   unsigned Align = MI->getOperand(8).getImm();
13841
13842   // Memory Reference
13843   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
13844   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13845   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13846
13847   // Machine Information
13848   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13849   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
13850   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
13851   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
13852   DebugLoc DL = MI->getDebugLoc();
13853
13854   // struct va_list {
13855   //   i32   gp_offset
13856   //   i32   fp_offset
13857   //   i64   overflow_area (address)
13858   //   i64   reg_save_area (address)
13859   // }
13860   // sizeof(va_list) = 24
13861   // alignment(va_list) = 8
13862
13863   unsigned TotalNumIntRegs = 6;
13864   unsigned TotalNumXMMRegs = 8;
13865   bool UseGPOffset = (ArgMode == 1);
13866   bool UseFPOffset = (ArgMode == 2);
13867   unsigned MaxOffset = TotalNumIntRegs * 8 +
13868                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
13869
13870   /* Align ArgSize to a multiple of 8 */
13871   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
13872   bool NeedsAlign = (Align > 8);
13873
13874   MachineBasicBlock *thisMBB = MBB;
13875   MachineBasicBlock *overflowMBB;
13876   MachineBasicBlock *offsetMBB;
13877   MachineBasicBlock *endMBB;
13878
13879   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
13880   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
13881   unsigned OffsetReg = 0;
13882
13883   if (!UseGPOffset && !UseFPOffset) {
13884     // If we only pull from the overflow region, we don't create a branch.
13885     // We don't need to alter control flow.
13886     OffsetDestReg = 0; // unused
13887     OverflowDestReg = DestReg;
13888
13889     offsetMBB = NULL;
13890     overflowMBB = thisMBB;
13891     endMBB = thisMBB;
13892   } else {
13893     // First emit code to check if gp_offset (or fp_offset) is below the bound.
13894     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
13895     // If not, pull from overflow_area. (branch to overflowMBB)
13896     //
13897     //       thisMBB
13898     //         |     .
13899     //         |        .
13900     //     offsetMBB   overflowMBB
13901     //         |        .
13902     //         |     .
13903     //        endMBB
13904
13905     // Registers for the PHI in endMBB
13906     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
13907     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
13908
13909     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
13910     MachineFunction *MF = MBB->getParent();
13911     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13912     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13913     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13914
13915     MachineFunction::iterator MBBIter = MBB;
13916     ++MBBIter;
13917
13918     // Insert the new basic blocks
13919     MF->insert(MBBIter, offsetMBB);
13920     MF->insert(MBBIter, overflowMBB);
13921     MF->insert(MBBIter, endMBB);
13922
13923     // Transfer the remainder of MBB and its successor edges to endMBB.
13924     endMBB->splice(endMBB->begin(), thisMBB,
13925                     llvm::next(MachineBasicBlock::iterator(MI)),
13926                     thisMBB->end());
13927     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
13928
13929     // Make offsetMBB and overflowMBB successors of thisMBB
13930     thisMBB->addSuccessor(offsetMBB);
13931     thisMBB->addSuccessor(overflowMBB);
13932
13933     // endMBB is a successor of both offsetMBB and overflowMBB
13934     offsetMBB->addSuccessor(endMBB);
13935     overflowMBB->addSuccessor(endMBB);
13936
13937     // Load the offset value into a register
13938     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
13939     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
13940       .addOperand(Base)
13941       .addOperand(Scale)
13942       .addOperand(Index)
13943       .addDisp(Disp, UseFPOffset ? 4 : 0)
13944       .addOperand(Segment)
13945       .setMemRefs(MMOBegin, MMOEnd);
13946
13947     // Check if there is enough room left to pull this argument.
13948     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
13949       .addReg(OffsetReg)
13950       .addImm(MaxOffset + 8 - ArgSizeA8);
13951
13952     // Branch to "overflowMBB" if offset >= max
13953     // Fall through to "offsetMBB" otherwise
13954     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
13955       .addMBB(overflowMBB);
13956   }
13957
13958   // In offsetMBB, emit code to use the reg_save_area.
13959   if (offsetMBB) {
13960     assert(OffsetReg != 0);
13961
13962     // Read the reg_save_area address.
13963     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
13964     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
13965       .addOperand(Base)
13966       .addOperand(Scale)
13967       .addOperand(Index)
13968       .addDisp(Disp, 16)
13969       .addOperand(Segment)
13970       .setMemRefs(MMOBegin, MMOEnd);
13971
13972     // Zero-extend the offset
13973     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
13974       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
13975         .addImm(0)
13976         .addReg(OffsetReg)
13977         .addImm(X86::sub_32bit);
13978
13979     // Add the offset to the reg_save_area to get the final address.
13980     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
13981       .addReg(OffsetReg64)
13982       .addReg(RegSaveReg);
13983
13984     // Compute the offset for the next argument
13985     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
13986     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
13987       .addReg(OffsetReg)
13988       .addImm(UseFPOffset ? 16 : 8);
13989
13990     // Store it back into the va_list.
13991     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
13992       .addOperand(Base)
13993       .addOperand(Scale)
13994       .addOperand(Index)
13995       .addDisp(Disp, UseFPOffset ? 4 : 0)
13996       .addOperand(Segment)
13997       .addReg(NextOffsetReg)
13998       .setMemRefs(MMOBegin, MMOEnd);
13999
14000     // Jump to endMBB
14001     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
14002       .addMBB(endMBB);
14003   }
14004
14005   //
14006   // Emit code to use overflow area
14007   //
14008
14009   // Load the overflow_area address into a register.
14010   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
14011   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
14012     .addOperand(Base)
14013     .addOperand(Scale)
14014     .addOperand(Index)
14015     .addDisp(Disp, 8)
14016     .addOperand(Segment)
14017     .setMemRefs(MMOBegin, MMOEnd);
14018
14019   // If we need to align it, do so. Otherwise, just copy the address
14020   // to OverflowDestReg.
14021   if (NeedsAlign) {
14022     // Align the overflow address
14023     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
14024     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
14025
14026     // aligned_addr = (addr + (align-1)) & ~(align-1)
14027     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
14028       .addReg(OverflowAddrReg)
14029       .addImm(Align-1);
14030
14031     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
14032       .addReg(TmpReg)
14033       .addImm(~(uint64_t)(Align-1));
14034   } else {
14035     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
14036       .addReg(OverflowAddrReg);
14037   }
14038
14039   // Compute the next overflow address after this argument.
14040   // (the overflow address should be kept 8-byte aligned)
14041   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
14042   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
14043     .addReg(OverflowDestReg)
14044     .addImm(ArgSizeA8);
14045
14046   // Store the new overflow address.
14047   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
14048     .addOperand(Base)
14049     .addOperand(Scale)
14050     .addOperand(Index)
14051     .addDisp(Disp, 8)
14052     .addOperand(Segment)
14053     .addReg(NextAddrReg)
14054     .setMemRefs(MMOBegin, MMOEnd);
14055
14056   // If we branched, emit the PHI to the front of endMBB.
14057   if (offsetMBB) {
14058     BuildMI(*endMBB, endMBB->begin(), DL,
14059             TII->get(X86::PHI), DestReg)
14060       .addReg(OffsetDestReg).addMBB(offsetMBB)
14061       .addReg(OverflowDestReg).addMBB(overflowMBB);
14062   }
14063
14064   // Erase the pseudo instruction
14065   MI->eraseFromParent();
14066
14067   return endMBB;
14068 }
14069
14070 MachineBasicBlock *
14071 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
14072                                                  MachineInstr *MI,
14073                                                  MachineBasicBlock *MBB) const {
14074   // Emit code to save XMM registers to the stack. The ABI says that the
14075   // number of registers to save is given in %al, so it's theoretically
14076   // possible to do an indirect jump trick to avoid saving all of them,
14077   // however this code takes a simpler approach and just executes all
14078   // of the stores if %al is non-zero. It's less code, and it's probably
14079   // easier on the hardware branch predictor, and stores aren't all that
14080   // expensive anyway.
14081
14082   // Create the new basic blocks. One block contains all the XMM stores,
14083   // and one block is the final destination regardless of whether any
14084   // stores were performed.
14085   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
14086   MachineFunction *F = MBB->getParent();
14087   MachineFunction::iterator MBBIter = MBB;
14088   ++MBBIter;
14089   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
14090   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
14091   F->insert(MBBIter, XMMSaveMBB);
14092   F->insert(MBBIter, EndMBB);
14093
14094   // Transfer the remainder of MBB and its successor edges to EndMBB.
14095   EndMBB->splice(EndMBB->begin(), MBB,
14096                  llvm::next(MachineBasicBlock::iterator(MI)),
14097                  MBB->end());
14098   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
14099
14100   // The original block will now fall through to the XMM save block.
14101   MBB->addSuccessor(XMMSaveMBB);
14102   // The XMMSaveMBB will fall through to the end block.
14103   XMMSaveMBB->addSuccessor(EndMBB);
14104
14105   // Now add the instructions.
14106   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14107   DebugLoc DL = MI->getDebugLoc();
14108
14109   unsigned CountReg = MI->getOperand(0).getReg();
14110   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
14111   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
14112
14113   if (!Subtarget->isTargetWin64()) {
14114     // If %al is 0, branch around the XMM save block.
14115     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
14116     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
14117     MBB->addSuccessor(EndMBB);
14118   }
14119
14120   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
14121   // In the XMM save block, save all the XMM argument registers.
14122   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
14123     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
14124     MachineMemOperand *MMO =
14125       F->getMachineMemOperand(
14126           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
14127         MachineMemOperand::MOStore,
14128         /*Size=*/16, /*Align=*/16);
14129     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
14130       .addFrameIndex(RegSaveFrameIndex)
14131       .addImm(/*Scale=*/1)
14132       .addReg(/*IndexReg=*/0)
14133       .addImm(/*Disp=*/Offset)
14134       .addReg(/*Segment=*/0)
14135       .addReg(MI->getOperand(i).getReg())
14136       .addMemOperand(MMO);
14137   }
14138
14139   MI->eraseFromParent();   // The pseudo instruction is gone now.
14140
14141   return EndMBB;
14142 }
14143
14144 // The EFLAGS operand of SelectItr might be missing a kill marker
14145 // because there were multiple uses of EFLAGS, and ISel didn't know
14146 // which to mark. Figure out whether SelectItr should have had a
14147 // kill marker, and set it if it should. Returns the correct kill
14148 // marker value.
14149 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
14150                                      MachineBasicBlock* BB,
14151                                      const TargetRegisterInfo* TRI) {
14152   // Scan forward through BB for a use/def of EFLAGS.
14153   MachineBasicBlock::iterator miI(llvm::next(SelectItr));
14154   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
14155     const MachineInstr& mi = *miI;
14156     if (mi.readsRegister(X86::EFLAGS))
14157       return false;
14158     if (mi.definesRegister(X86::EFLAGS))
14159       break; // Should have kill-flag - update below.
14160   }
14161
14162   // If we hit the end of the block, check whether EFLAGS is live into a
14163   // successor.
14164   if (miI == BB->end()) {
14165     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
14166                                           sEnd = BB->succ_end();
14167          sItr != sEnd; ++sItr) {
14168       MachineBasicBlock* succ = *sItr;
14169       if (succ->isLiveIn(X86::EFLAGS))
14170         return false;
14171     }
14172   }
14173
14174   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
14175   // out. SelectMI should have a kill flag on EFLAGS.
14176   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
14177   return true;
14178 }
14179
14180 MachineBasicBlock *
14181 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
14182                                      MachineBasicBlock *BB) const {
14183   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14184   DebugLoc DL = MI->getDebugLoc();
14185
14186   // To "insert" a SELECT_CC instruction, we actually have to insert the
14187   // diamond control-flow pattern.  The incoming instruction knows the
14188   // destination vreg to set, the condition code register to branch on, the
14189   // true/false values to select between, and a branch opcode to use.
14190   const BasicBlock *LLVM_BB = BB->getBasicBlock();
14191   MachineFunction::iterator It = BB;
14192   ++It;
14193
14194   //  thisMBB:
14195   //  ...
14196   //   TrueVal = ...
14197   //   cmpTY ccX, r1, r2
14198   //   bCC copy1MBB
14199   //   fallthrough --> copy0MBB
14200   MachineBasicBlock *thisMBB = BB;
14201   MachineFunction *F = BB->getParent();
14202   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
14203   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
14204   F->insert(It, copy0MBB);
14205   F->insert(It, sinkMBB);
14206
14207   // If the EFLAGS register isn't dead in the terminator, then claim that it's
14208   // live into the sink and copy blocks.
14209   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
14210   if (!MI->killsRegister(X86::EFLAGS) &&
14211       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
14212     copy0MBB->addLiveIn(X86::EFLAGS);
14213     sinkMBB->addLiveIn(X86::EFLAGS);
14214   }
14215
14216   // Transfer the remainder of BB and its successor edges to sinkMBB.
14217   sinkMBB->splice(sinkMBB->begin(), BB,
14218                   llvm::next(MachineBasicBlock::iterator(MI)),
14219                   BB->end());
14220   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
14221
14222   // Add the true and fallthrough blocks as its successors.
14223   BB->addSuccessor(copy0MBB);
14224   BB->addSuccessor(sinkMBB);
14225
14226   // Create the conditional branch instruction.
14227   unsigned Opc =
14228     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
14229   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
14230
14231   //  copy0MBB:
14232   //   %FalseValue = ...
14233   //   # fallthrough to sinkMBB
14234   copy0MBB->addSuccessor(sinkMBB);
14235
14236   //  sinkMBB:
14237   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
14238   //  ...
14239   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14240           TII->get(X86::PHI), MI->getOperand(0).getReg())
14241     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
14242     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
14243
14244   MI->eraseFromParent();   // The pseudo instruction is gone now.
14245   return sinkMBB;
14246 }
14247
14248 MachineBasicBlock *
14249 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
14250                                         bool Is64Bit) const {
14251   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14252   DebugLoc DL = MI->getDebugLoc();
14253   MachineFunction *MF = BB->getParent();
14254   const BasicBlock *LLVM_BB = BB->getBasicBlock();
14255
14256   assert(getTargetMachine().Options.EnableSegmentedStacks);
14257
14258   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
14259   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
14260
14261   // BB:
14262   //  ... [Till the alloca]
14263   // If stacklet is not large enough, jump to mallocMBB
14264   //
14265   // bumpMBB:
14266   //  Allocate by subtracting from RSP
14267   //  Jump to continueMBB
14268   //
14269   // mallocMBB:
14270   //  Allocate by call to runtime
14271   //
14272   // continueMBB:
14273   //  ...
14274   //  [rest of original BB]
14275   //
14276
14277   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14278   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14279   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14280
14281   MachineRegisterInfo &MRI = MF->getRegInfo();
14282   const TargetRegisterClass *AddrRegClass =
14283     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
14284
14285   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
14286     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
14287     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
14288     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
14289     sizeVReg = MI->getOperand(1).getReg(),
14290     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
14291
14292   MachineFunction::iterator MBBIter = BB;
14293   ++MBBIter;
14294
14295   MF->insert(MBBIter, bumpMBB);
14296   MF->insert(MBBIter, mallocMBB);
14297   MF->insert(MBBIter, continueMBB);
14298
14299   continueMBB->splice(continueMBB->begin(), BB, llvm::next
14300                       (MachineBasicBlock::iterator(MI)), BB->end());
14301   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
14302
14303   // Add code to the main basic block to check if the stack limit has been hit,
14304   // and if so, jump to mallocMBB otherwise to bumpMBB.
14305   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
14306   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
14307     .addReg(tmpSPVReg).addReg(sizeVReg);
14308   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
14309     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
14310     .addReg(SPLimitVReg);
14311   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
14312
14313   // bumpMBB simply decreases the stack pointer, since we know the current
14314   // stacklet has enough space.
14315   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
14316     .addReg(SPLimitVReg);
14317   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
14318     .addReg(SPLimitVReg);
14319   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
14320
14321   // Calls into a routine in libgcc to allocate more space from the heap.
14322   const uint32_t *RegMask =
14323     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
14324   if (Is64Bit) {
14325     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
14326       .addReg(sizeVReg);
14327     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
14328       .addExternalSymbol("__morestack_allocate_stack_space")
14329       .addRegMask(RegMask)
14330       .addReg(X86::RDI, RegState::Implicit)
14331       .addReg(X86::RAX, RegState::ImplicitDefine);
14332   } else {
14333     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
14334       .addImm(12);
14335     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
14336     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
14337       .addExternalSymbol("__morestack_allocate_stack_space")
14338       .addRegMask(RegMask)
14339       .addReg(X86::EAX, RegState::ImplicitDefine);
14340   }
14341
14342   if (!Is64Bit)
14343     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
14344       .addImm(16);
14345
14346   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
14347     .addReg(Is64Bit ? X86::RAX : X86::EAX);
14348   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
14349
14350   // Set up the CFG correctly.
14351   BB->addSuccessor(bumpMBB);
14352   BB->addSuccessor(mallocMBB);
14353   mallocMBB->addSuccessor(continueMBB);
14354   bumpMBB->addSuccessor(continueMBB);
14355
14356   // Take care of the PHI nodes.
14357   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
14358           MI->getOperand(0).getReg())
14359     .addReg(mallocPtrVReg).addMBB(mallocMBB)
14360     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
14361
14362   // Delete the original pseudo instruction.
14363   MI->eraseFromParent();
14364
14365   // And we're done.
14366   return continueMBB;
14367 }
14368
14369 MachineBasicBlock *
14370 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
14371                                           MachineBasicBlock *BB) const {
14372   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14373   DebugLoc DL = MI->getDebugLoc();
14374
14375   assert(!Subtarget->isTargetEnvMacho());
14376
14377   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
14378   // non-trivial part is impdef of ESP.
14379
14380   if (Subtarget->isTargetWin64()) {
14381     if (Subtarget->isTargetCygMing()) {
14382       // ___chkstk(Mingw64):
14383       // Clobbers R10, R11, RAX and EFLAGS.
14384       // Updates RSP.
14385       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
14386         .addExternalSymbol("___chkstk")
14387         .addReg(X86::RAX, RegState::Implicit)
14388         .addReg(X86::RSP, RegState::Implicit)
14389         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
14390         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
14391         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14392     } else {
14393       // __chkstk(MSVCRT): does not update stack pointer.
14394       // Clobbers R10, R11 and EFLAGS.
14395       // FIXME: RAX(allocated size) might be reused and not killed.
14396       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
14397         .addExternalSymbol("__chkstk")
14398         .addReg(X86::RAX, RegState::Implicit)
14399         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14400       // RAX has the offset to subtracted from RSP.
14401       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
14402         .addReg(X86::RSP)
14403         .addReg(X86::RAX);
14404     }
14405   } else {
14406     const char *StackProbeSymbol =
14407       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
14408
14409     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
14410       .addExternalSymbol(StackProbeSymbol)
14411       .addReg(X86::EAX, RegState::Implicit)
14412       .addReg(X86::ESP, RegState::Implicit)
14413       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
14414       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
14415       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14416   }
14417
14418   MI->eraseFromParent();   // The pseudo instruction is gone now.
14419   return BB;
14420 }
14421
14422 MachineBasicBlock *
14423 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
14424                                       MachineBasicBlock *BB) const {
14425   // This is pretty easy.  We're taking the value that we received from
14426   // our load from the relocation, sticking it in either RDI (x86-64)
14427   // or EAX and doing an indirect call.  The return value will then
14428   // be in the normal return register.
14429   const X86InstrInfo *TII
14430     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
14431   DebugLoc DL = MI->getDebugLoc();
14432   MachineFunction *F = BB->getParent();
14433
14434   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
14435   assert(MI->getOperand(3).isGlobal() && "This should be a global");
14436
14437   // Get a register mask for the lowered call.
14438   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
14439   // proper register mask.
14440   const uint32_t *RegMask =
14441     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
14442   if (Subtarget->is64Bit()) {
14443     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14444                                       TII->get(X86::MOV64rm), X86::RDI)
14445     .addReg(X86::RIP)
14446     .addImm(0).addReg(0)
14447     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14448                       MI->getOperand(3).getTargetFlags())
14449     .addReg(0);
14450     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
14451     addDirectMem(MIB, X86::RDI);
14452     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
14453   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
14454     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14455                                       TII->get(X86::MOV32rm), X86::EAX)
14456     .addReg(0)
14457     .addImm(0).addReg(0)
14458     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14459                       MI->getOperand(3).getTargetFlags())
14460     .addReg(0);
14461     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
14462     addDirectMem(MIB, X86::EAX);
14463     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
14464   } else {
14465     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14466                                       TII->get(X86::MOV32rm), X86::EAX)
14467     .addReg(TII->getGlobalBaseReg(F))
14468     .addImm(0).addReg(0)
14469     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14470                       MI->getOperand(3).getTargetFlags())
14471     .addReg(0);
14472     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
14473     addDirectMem(MIB, X86::EAX);
14474     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
14475   }
14476
14477   MI->eraseFromParent(); // The pseudo instruction is gone now.
14478   return BB;
14479 }
14480
14481 MachineBasicBlock *
14482 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
14483                                     MachineBasicBlock *MBB) const {
14484   DebugLoc DL = MI->getDebugLoc();
14485   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14486
14487   MachineFunction *MF = MBB->getParent();
14488   MachineRegisterInfo &MRI = MF->getRegInfo();
14489
14490   const BasicBlock *BB = MBB->getBasicBlock();
14491   MachineFunction::iterator I = MBB;
14492   ++I;
14493
14494   // Memory Reference
14495   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14496   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14497
14498   unsigned DstReg;
14499   unsigned MemOpndSlot = 0;
14500
14501   unsigned CurOp = 0;
14502
14503   DstReg = MI->getOperand(CurOp++).getReg();
14504   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
14505   assert(RC->hasType(MVT::i32) && "Invalid destination!");
14506   unsigned mainDstReg = MRI.createVirtualRegister(RC);
14507   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
14508
14509   MemOpndSlot = CurOp;
14510
14511   MVT PVT = getPointerTy();
14512   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
14513          "Invalid Pointer Size!");
14514
14515   // For v = setjmp(buf), we generate
14516   //
14517   // thisMBB:
14518   //  buf[LabelOffset] = restoreMBB
14519   //  SjLjSetup restoreMBB
14520   //
14521   // mainMBB:
14522   //  v_main = 0
14523   //
14524   // sinkMBB:
14525   //  v = phi(main, restore)
14526   //
14527   // restoreMBB:
14528   //  v_restore = 1
14529
14530   MachineBasicBlock *thisMBB = MBB;
14531   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14532   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14533   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
14534   MF->insert(I, mainMBB);
14535   MF->insert(I, sinkMBB);
14536   MF->push_back(restoreMBB);
14537
14538   MachineInstrBuilder MIB;
14539
14540   // Transfer the remainder of BB and its successor edges to sinkMBB.
14541   sinkMBB->splice(sinkMBB->begin(), MBB,
14542                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
14543   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14544
14545   // thisMBB:
14546   unsigned PtrStoreOpc = 0;
14547   unsigned LabelReg = 0;
14548   const int64_t LabelOffset = 1 * PVT.getStoreSize();
14549   Reloc::Model RM = getTargetMachine().getRelocationModel();
14550   bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
14551                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
14552
14553   // Prepare IP either in reg or imm.
14554   if (!UseImmLabel) {
14555     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
14556     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
14557     LabelReg = MRI.createVirtualRegister(PtrRC);
14558     if (Subtarget->is64Bit()) {
14559       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
14560               .addReg(X86::RIP)
14561               .addImm(0)
14562               .addReg(0)
14563               .addMBB(restoreMBB)
14564               .addReg(0);
14565     } else {
14566       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
14567       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
14568               .addReg(XII->getGlobalBaseReg(MF))
14569               .addImm(0)
14570               .addReg(0)
14571               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
14572               .addReg(0);
14573     }
14574   } else
14575     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
14576   // Store IP
14577   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
14578   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14579     if (i == X86::AddrDisp)
14580       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
14581     else
14582       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
14583   }
14584   if (!UseImmLabel)
14585     MIB.addReg(LabelReg);
14586   else
14587     MIB.addMBB(restoreMBB);
14588   MIB.setMemRefs(MMOBegin, MMOEnd);
14589   // Setup
14590   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
14591           .addMBB(restoreMBB);
14592   MIB.addRegMask(RegInfo->getNoPreservedMask());
14593   thisMBB->addSuccessor(mainMBB);
14594   thisMBB->addSuccessor(restoreMBB);
14595
14596   // mainMBB:
14597   //  EAX = 0
14598   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
14599   mainMBB->addSuccessor(sinkMBB);
14600
14601   // sinkMBB:
14602   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14603           TII->get(X86::PHI), DstReg)
14604     .addReg(mainDstReg).addMBB(mainMBB)
14605     .addReg(restoreDstReg).addMBB(restoreMBB);
14606
14607   // restoreMBB:
14608   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
14609   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
14610   restoreMBB->addSuccessor(sinkMBB);
14611
14612   MI->eraseFromParent();
14613   return sinkMBB;
14614 }
14615
14616 MachineBasicBlock *
14617 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
14618                                      MachineBasicBlock *MBB) const {
14619   DebugLoc DL = MI->getDebugLoc();
14620   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14621
14622   MachineFunction *MF = MBB->getParent();
14623   MachineRegisterInfo &MRI = MF->getRegInfo();
14624
14625   // Memory Reference
14626   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14627   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14628
14629   MVT PVT = getPointerTy();
14630   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
14631          "Invalid Pointer Size!");
14632
14633   const TargetRegisterClass *RC =
14634     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
14635   unsigned Tmp = MRI.createVirtualRegister(RC);
14636   // Since FP is only updated here but NOT referenced, it's treated as GPR.
14637   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
14638   unsigned SP = RegInfo->getStackRegister();
14639
14640   MachineInstrBuilder MIB;
14641
14642   const int64_t LabelOffset = 1 * PVT.getStoreSize();
14643   const int64_t SPOffset = 2 * PVT.getStoreSize();
14644
14645   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
14646   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
14647
14648   // Reload FP
14649   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
14650   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
14651     MIB.addOperand(MI->getOperand(i));
14652   MIB.setMemRefs(MMOBegin, MMOEnd);
14653   // Reload IP
14654   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
14655   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14656     if (i == X86::AddrDisp)
14657       MIB.addDisp(MI->getOperand(i), LabelOffset);
14658     else
14659       MIB.addOperand(MI->getOperand(i));
14660   }
14661   MIB.setMemRefs(MMOBegin, MMOEnd);
14662   // Reload SP
14663   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
14664   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14665     if (i == X86::AddrDisp)
14666       MIB.addDisp(MI->getOperand(i), SPOffset);
14667     else
14668       MIB.addOperand(MI->getOperand(i));
14669   }
14670   MIB.setMemRefs(MMOBegin, MMOEnd);
14671   // Jump
14672   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
14673
14674   MI->eraseFromParent();
14675   return MBB;
14676 }
14677
14678 MachineBasicBlock *
14679 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
14680                                                MachineBasicBlock *BB) const {
14681   switch (MI->getOpcode()) {
14682   default: llvm_unreachable("Unexpected instr type to insert");
14683   case X86::TAILJMPd64:
14684   case X86::TAILJMPr64:
14685   case X86::TAILJMPm64:
14686     llvm_unreachable("TAILJMP64 would not be touched here.");
14687   case X86::TCRETURNdi64:
14688   case X86::TCRETURNri64:
14689   case X86::TCRETURNmi64:
14690     return BB;
14691   case X86::WIN_ALLOCA:
14692     return EmitLoweredWinAlloca(MI, BB);
14693   case X86::SEG_ALLOCA_32:
14694     return EmitLoweredSegAlloca(MI, BB, false);
14695   case X86::SEG_ALLOCA_64:
14696     return EmitLoweredSegAlloca(MI, BB, true);
14697   case X86::TLSCall_32:
14698   case X86::TLSCall_64:
14699     return EmitLoweredTLSCall(MI, BB);
14700   case X86::CMOV_GR8:
14701   case X86::CMOV_FR32:
14702   case X86::CMOV_FR64:
14703   case X86::CMOV_V4F32:
14704   case X86::CMOV_V2F64:
14705   case X86::CMOV_V2I64:
14706   case X86::CMOV_V8F32:
14707   case X86::CMOV_V4F64:
14708   case X86::CMOV_V4I64:
14709   case X86::CMOV_GR16:
14710   case X86::CMOV_GR32:
14711   case X86::CMOV_RFP32:
14712   case X86::CMOV_RFP64:
14713   case X86::CMOV_RFP80:
14714     return EmitLoweredSelect(MI, BB);
14715
14716   case X86::FP32_TO_INT16_IN_MEM:
14717   case X86::FP32_TO_INT32_IN_MEM:
14718   case X86::FP32_TO_INT64_IN_MEM:
14719   case X86::FP64_TO_INT16_IN_MEM:
14720   case X86::FP64_TO_INT32_IN_MEM:
14721   case X86::FP64_TO_INT64_IN_MEM:
14722   case X86::FP80_TO_INT16_IN_MEM:
14723   case X86::FP80_TO_INT32_IN_MEM:
14724   case X86::FP80_TO_INT64_IN_MEM: {
14725     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14726     DebugLoc DL = MI->getDebugLoc();
14727
14728     // Change the floating point control register to use "round towards zero"
14729     // mode when truncating to an integer value.
14730     MachineFunction *F = BB->getParent();
14731     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
14732     addFrameReference(BuildMI(*BB, MI, DL,
14733                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
14734
14735     // Load the old value of the high byte of the control word...
14736     unsigned OldCW =
14737       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
14738     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
14739                       CWFrameIdx);
14740
14741     // Set the high part to be round to zero...
14742     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
14743       .addImm(0xC7F);
14744
14745     // Reload the modified control word now...
14746     addFrameReference(BuildMI(*BB, MI, DL,
14747                               TII->get(X86::FLDCW16m)), CWFrameIdx);
14748
14749     // Restore the memory image of control word to original value
14750     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
14751       .addReg(OldCW);
14752
14753     // Get the X86 opcode to use.
14754     unsigned Opc;
14755     switch (MI->getOpcode()) {
14756     default: llvm_unreachable("illegal opcode!");
14757     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
14758     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
14759     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
14760     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
14761     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
14762     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
14763     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
14764     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
14765     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
14766     }
14767
14768     X86AddressMode AM;
14769     MachineOperand &Op = MI->getOperand(0);
14770     if (Op.isReg()) {
14771       AM.BaseType = X86AddressMode::RegBase;
14772       AM.Base.Reg = Op.getReg();
14773     } else {
14774       AM.BaseType = X86AddressMode::FrameIndexBase;
14775       AM.Base.FrameIndex = Op.getIndex();
14776     }
14777     Op = MI->getOperand(1);
14778     if (Op.isImm())
14779       AM.Scale = Op.getImm();
14780     Op = MI->getOperand(2);
14781     if (Op.isImm())
14782       AM.IndexReg = Op.getImm();
14783     Op = MI->getOperand(3);
14784     if (Op.isGlobal()) {
14785       AM.GV = Op.getGlobal();
14786     } else {
14787       AM.Disp = Op.getImm();
14788     }
14789     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
14790                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
14791
14792     // Reload the original control word now.
14793     addFrameReference(BuildMI(*BB, MI, DL,
14794                               TII->get(X86::FLDCW16m)), CWFrameIdx);
14795
14796     MI->eraseFromParent();   // The pseudo instruction is gone now.
14797     return BB;
14798   }
14799     // String/text processing lowering.
14800   case X86::PCMPISTRM128REG:
14801   case X86::VPCMPISTRM128REG:
14802   case X86::PCMPISTRM128MEM:
14803   case X86::VPCMPISTRM128MEM:
14804   case X86::PCMPESTRM128REG:
14805   case X86::VPCMPESTRM128REG:
14806   case X86::PCMPESTRM128MEM:
14807   case X86::VPCMPESTRM128MEM:
14808     assert(Subtarget->hasSSE42() &&
14809            "Target must have SSE4.2 or AVX features enabled");
14810     return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
14811
14812   // String/text processing lowering.
14813   case X86::PCMPISTRIREG:
14814   case X86::VPCMPISTRIREG:
14815   case X86::PCMPISTRIMEM:
14816   case X86::VPCMPISTRIMEM:
14817   case X86::PCMPESTRIREG:
14818   case X86::VPCMPESTRIREG:
14819   case X86::PCMPESTRIMEM:
14820   case X86::VPCMPESTRIMEM:
14821     assert(Subtarget->hasSSE42() &&
14822            "Target must have SSE4.2 or AVX features enabled");
14823     return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
14824
14825   // Thread synchronization.
14826   case X86::MONITOR:
14827     return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
14828
14829   // xbegin
14830   case X86::XBEGIN:
14831     return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
14832
14833   // Atomic Lowering.
14834   case X86::ATOMAND8:
14835   case X86::ATOMAND16:
14836   case X86::ATOMAND32:
14837   case X86::ATOMAND64:
14838     // Fall through
14839   case X86::ATOMOR8:
14840   case X86::ATOMOR16:
14841   case X86::ATOMOR32:
14842   case X86::ATOMOR64:
14843     // Fall through
14844   case X86::ATOMXOR16:
14845   case X86::ATOMXOR8:
14846   case X86::ATOMXOR32:
14847   case X86::ATOMXOR64:
14848     // Fall through
14849   case X86::ATOMNAND8:
14850   case X86::ATOMNAND16:
14851   case X86::ATOMNAND32:
14852   case X86::ATOMNAND64:
14853     // Fall through
14854   case X86::ATOMMAX8:
14855   case X86::ATOMMAX16:
14856   case X86::ATOMMAX32:
14857   case X86::ATOMMAX64:
14858     // Fall through
14859   case X86::ATOMMIN8:
14860   case X86::ATOMMIN16:
14861   case X86::ATOMMIN32:
14862   case X86::ATOMMIN64:
14863     // Fall through
14864   case X86::ATOMUMAX8:
14865   case X86::ATOMUMAX16:
14866   case X86::ATOMUMAX32:
14867   case X86::ATOMUMAX64:
14868     // Fall through
14869   case X86::ATOMUMIN8:
14870   case X86::ATOMUMIN16:
14871   case X86::ATOMUMIN32:
14872   case X86::ATOMUMIN64:
14873     return EmitAtomicLoadArith(MI, BB);
14874
14875   // This group does 64-bit operations on a 32-bit host.
14876   case X86::ATOMAND6432:
14877   case X86::ATOMOR6432:
14878   case X86::ATOMXOR6432:
14879   case X86::ATOMNAND6432:
14880   case X86::ATOMADD6432:
14881   case X86::ATOMSUB6432:
14882   case X86::ATOMMAX6432:
14883   case X86::ATOMMIN6432:
14884   case X86::ATOMUMAX6432:
14885   case X86::ATOMUMIN6432:
14886   case X86::ATOMSWAP6432:
14887     return EmitAtomicLoadArith6432(MI, BB);
14888
14889   case X86::VASTART_SAVE_XMM_REGS:
14890     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
14891
14892   case X86::VAARG_64:
14893     return EmitVAARG64WithCustomInserter(MI, BB);
14894
14895   case X86::EH_SjLj_SetJmp32:
14896   case X86::EH_SjLj_SetJmp64:
14897     return emitEHSjLjSetJmp(MI, BB);
14898
14899   case X86::EH_SjLj_LongJmp32:
14900   case X86::EH_SjLj_LongJmp64:
14901     return emitEHSjLjLongJmp(MI, BB);
14902   }
14903 }
14904
14905 //===----------------------------------------------------------------------===//
14906 //                           X86 Optimization Hooks
14907 //===----------------------------------------------------------------------===//
14908
14909 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
14910                                                        APInt &KnownZero,
14911                                                        APInt &KnownOne,
14912                                                        const SelectionDAG &DAG,
14913                                                        unsigned Depth) const {
14914   unsigned BitWidth = KnownZero.getBitWidth();
14915   unsigned Opc = Op.getOpcode();
14916   assert((Opc >= ISD::BUILTIN_OP_END ||
14917           Opc == ISD::INTRINSIC_WO_CHAIN ||
14918           Opc == ISD::INTRINSIC_W_CHAIN ||
14919           Opc == ISD::INTRINSIC_VOID) &&
14920          "Should use MaskedValueIsZero if you don't know whether Op"
14921          " is a target node!");
14922
14923   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
14924   switch (Opc) {
14925   default: break;
14926   case X86ISD::ADD:
14927   case X86ISD::SUB:
14928   case X86ISD::ADC:
14929   case X86ISD::SBB:
14930   case X86ISD::SMUL:
14931   case X86ISD::UMUL:
14932   case X86ISD::INC:
14933   case X86ISD::DEC:
14934   case X86ISD::OR:
14935   case X86ISD::XOR:
14936   case X86ISD::AND:
14937     // These nodes' second result is a boolean.
14938     if (Op.getResNo() == 0)
14939       break;
14940     // Fallthrough
14941   case X86ISD::SETCC:
14942     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
14943     break;
14944   case ISD::INTRINSIC_WO_CHAIN: {
14945     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14946     unsigned NumLoBits = 0;
14947     switch (IntId) {
14948     default: break;
14949     case Intrinsic::x86_sse_movmsk_ps:
14950     case Intrinsic::x86_avx_movmsk_ps_256:
14951     case Intrinsic::x86_sse2_movmsk_pd:
14952     case Intrinsic::x86_avx_movmsk_pd_256:
14953     case Intrinsic::x86_mmx_pmovmskb:
14954     case Intrinsic::x86_sse2_pmovmskb_128:
14955     case Intrinsic::x86_avx2_pmovmskb: {
14956       // High bits of movmskp{s|d}, pmovmskb are known zero.
14957       switch (IntId) {
14958         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14959         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
14960         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
14961         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
14962         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
14963         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
14964         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
14965         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
14966       }
14967       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
14968       break;
14969     }
14970     }
14971     break;
14972   }
14973   }
14974 }
14975
14976 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
14977                                                          unsigned Depth) const {
14978   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
14979   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
14980     return Op.getValueType().getScalarType().getSizeInBits();
14981
14982   // Fallback case.
14983   return 1;
14984 }
14985
14986 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
14987 /// node is a GlobalAddress + offset.
14988 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
14989                                        const GlobalValue* &GA,
14990                                        int64_t &Offset) const {
14991   if (N->getOpcode() == X86ISD::Wrapper) {
14992     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
14993       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
14994       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
14995       return true;
14996     }
14997   }
14998   return TargetLowering::isGAPlusOffset(N, GA, Offset);
14999 }
15000
15001 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
15002 /// same as extracting the high 128-bit part of 256-bit vector and then
15003 /// inserting the result into the low part of a new 256-bit vector
15004 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
15005   EVT VT = SVOp->getValueType(0);
15006   unsigned NumElems = VT.getVectorNumElements();
15007
15008   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
15009   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
15010     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
15011         SVOp->getMaskElt(j) >= 0)
15012       return false;
15013
15014   return true;
15015 }
15016
15017 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
15018 /// same as extracting the low 128-bit part of 256-bit vector and then
15019 /// inserting the result into the high part of a new 256-bit vector
15020 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
15021   EVT VT = SVOp->getValueType(0);
15022   unsigned NumElems = VT.getVectorNumElements();
15023
15024   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
15025   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
15026     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
15027         SVOp->getMaskElt(j) >= 0)
15028       return false;
15029
15030   return true;
15031 }
15032
15033 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
15034 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
15035                                         TargetLowering::DAGCombinerInfo &DCI,
15036                                         const X86Subtarget* Subtarget) {
15037   DebugLoc dl = N->getDebugLoc();
15038   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
15039   SDValue V1 = SVOp->getOperand(0);
15040   SDValue V2 = SVOp->getOperand(1);
15041   EVT VT = SVOp->getValueType(0);
15042   unsigned NumElems = VT.getVectorNumElements();
15043
15044   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
15045       V2.getOpcode() == ISD::CONCAT_VECTORS) {
15046     //
15047     //                   0,0,0,...
15048     //                      |
15049     //    V      UNDEF    BUILD_VECTOR    UNDEF
15050     //     \      /           \           /
15051     //  CONCAT_VECTOR         CONCAT_VECTOR
15052     //         \                  /
15053     //          \                /
15054     //          RESULT: V + zero extended
15055     //
15056     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
15057         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
15058         V1.getOperand(1).getOpcode() != ISD::UNDEF)
15059       return SDValue();
15060
15061     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
15062       return SDValue();
15063
15064     // To match the shuffle mask, the first half of the mask should
15065     // be exactly the first vector, and all the rest a splat with the
15066     // first element of the second one.
15067     for (unsigned i = 0; i != NumElems/2; ++i)
15068       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
15069           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
15070         return SDValue();
15071
15072     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
15073     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
15074       if (Ld->hasNUsesOfValue(1, 0)) {
15075         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
15076         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
15077         SDValue ResNode =
15078           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
15079                                   array_lengthof(Ops),
15080                                   Ld->getMemoryVT(),
15081                                   Ld->getPointerInfo(),
15082                                   Ld->getAlignment(),
15083                                   false/*isVolatile*/, true/*ReadMem*/,
15084                                   false/*WriteMem*/);
15085
15086         // Make sure the newly-created LOAD is in the same position as Ld in
15087         // terms of dependency. We create a TokenFactor for Ld and ResNode,
15088         // and update uses of Ld's output chain to use the TokenFactor.
15089         if (Ld->hasAnyUseOfValue(1)) {
15090           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
15091                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
15092           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
15093           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
15094                                  SDValue(ResNode.getNode(), 1));
15095         }
15096
15097         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
15098       }
15099     }
15100
15101     // Emit a zeroed vector and insert the desired subvector on its
15102     // first half.
15103     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15104     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
15105     return DCI.CombineTo(N, InsV);
15106   }
15107
15108   //===--------------------------------------------------------------------===//
15109   // Combine some shuffles into subvector extracts and inserts:
15110   //
15111
15112   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
15113   if (isShuffleHigh128VectorInsertLow(SVOp)) {
15114     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
15115     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
15116     return DCI.CombineTo(N, InsV);
15117   }
15118
15119   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
15120   if (isShuffleLow128VectorInsertHigh(SVOp)) {
15121     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
15122     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
15123     return DCI.CombineTo(N, InsV);
15124   }
15125
15126   return SDValue();
15127 }
15128
15129 /// PerformShuffleCombine - Performs several different shuffle combines.
15130 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
15131                                      TargetLowering::DAGCombinerInfo &DCI,
15132                                      const X86Subtarget *Subtarget) {
15133   DebugLoc dl = N->getDebugLoc();
15134   EVT VT = N->getValueType(0);
15135
15136   // Don't create instructions with illegal types after legalize types has run.
15137   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15138   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
15139     return SDValue();
15140
15141   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
15142   if (Subtarget->hasFp256() && VT.is256BitVector() &&
15143       N->getOpcode() == ISD::VECTOR_SHUFFLE)
15144     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
15145
15146   // Only handle 128 wide vector from here on.
15147   if (!VT.is128BitVector())
15148     return SDValue();
15149
15150   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
15151   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
15152   // consecutive, non-overlapping, and in the right order.
15153   SmallVector<SDValue, 16> Elts;
15154   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
15155     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
15156
15157   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
15158 }
15159
15160 /// PerformTruncateCombine - Converts truncate operation to
15161 /// a sequence of vector shuffle operations.
15162 /// It is possible when we truncate 256-bit vector to 128-bit vector
15163 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
15164                                       TargetLowering::DAGCombinerInfo &DCI,
15165                                       const X86Subtarget *Subtarget)  {
15166   return SDValue();
15167 }
15168
15169 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
15170 /// specific shuffle of a load can be folded into a single element load.
15171 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
15172 /// shuffles have been customed lowered so we need to handle those here.
15173 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
15174                                          TargetLowering::DAGCombinerInfo &DCI) {
15175   if (DCI.isBeforeLegalizeOps())
15176     return SDValue();
15177
15178   SDValue InVec = N->getOperand(0);
15179   SDValue EltNo = N->getOperand(1);
15180
15181   if (!isa<ConstantSDNode>(EltNo))
15182     return SDValue();
15183
15184   EVT VT = InVec.getValueType();
15185
15186   bool HasShuffleIntoBitcast = false;
15187   if (InVec.getOpcode() == ISD::BITCAST) {
15188     // Don't duplicate a load with other uses.
15189     if (!InVec.hasOneUse())
15190       return SDValue();
15191     EVT BCVT = InVec.getOperand(0).getValueType();
15192     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
15193       return SDValue();
15194     InVec = InVec.getOperand(0);
15195     HasShuffleIntoBitcast = true;
15196   }
15197
15198   if (!isTargetShuffle(InVec.getOpcode()))
15199     return SDValue();
15200
15201   // Don't duplicate a load with other uses.
15202   if (!InVec.hasOneUse())
15203     return SDValue();
15204
15205   SmallVector<int, 16> ShuffleMask;
15206   bool UnaryShuffle;
15207   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
15208                             UnaryShuffle))
15209     return SDValue();
15210
15211   // Select the input vector, guarding against out of range extract vector.
15212   unsigned NumElems = VT.getVectorNumElements();
15213   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
15214   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
15215   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
15216                                          : InVec.getOperand(1);
15217
15218   // If inputs to shuffle are the same for both ops, then allow 2 uses
15219   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
15220
15221   if (LdNode.getOpcode() == ISD::BITCAST) {
15222     // Don't duplicate a load with other uses.
15223     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
15224       return SDValue();
15225
15226     AllowedUses = 1; // only allow 1 load use if we have a bitcast
15227     LdNode = LdNode.getOperand(0);
15228   }
15229
15230   if (!ISD::isNormalLoad(LdNode.getNode()))
15231     return SDValue();
15232
15233   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
15234
15235   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
15236     return SDValue();
15237
15238   if (HasShuffleIntoBitcast) {
15239     // If there's a bitcast before the shuffle, check if the load type and
15240     // alignment is valid.
15241     unsigned Align = LN0->getAlignment();
15242     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15243     unsigned NewAlign = TLI.getDataLayout()->
15244       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
15245
15246     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
15247       return SDValue();
15248   }
15249
15250   // All checks match so transform back to vector_shuffle so that DAG combiner
15251   // can finish the job
15252   DebugLoc dl = N->getDebugLoc();
15253
15254   // Create shuffle node taking into account the case that its a unary shuffle
15255   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
15256   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
15257                                  InVec.getOperand(0), Shuffle,
15258                                  &ShuffleMask[0]);
15259   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
15260   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
15261                      EltNo);
15262 }
15263
15264 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
15265 /// generation and convert it from being a bunch of shuffles and extracts
15266 /// to a simple store and scalar loads to extract the elements.
15267 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
15268                                          TargetLowering::DAGCombinerInfo &DCI) {
15269   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
15270   if (NewOp.getNode())
15271     return NewOp;
15272
15273   SDValue InputVector = N->getOperand(0);
15274   // Detect whether we are trying to convert from mmx to i32 and the bitcast
15275   // from mmx to v2i32 has a single usage.
15276   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
15277       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
15278       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
15279     return DAG.getNode(X86ISD::MMX_MOVD2W, InputVector.getDebugLoc(),
15280                        N->getValueType(0),
15281                        InputVector.getNode()->getOperand(0));
15282
15283   // Only operate on vectors of 4 elements, where the alternative shuffling
15284   // gets to be more expensive.
15285   if (InputVector.getValueType() != MVT::v4i32)
15286     return SDValue();
15287
15288   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
15289   // single use which is a sign-extend or zero-extend, and all elements are
15290   // used.
15291   SmallVector<SDNode *, 4> Uses;
15292   unsigned ExtractedElements = 0;
15293   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
15294        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
15295     if (UI.getUse().getResNo() != InputVector.getResNo())
15296       return SDValue();
15297
15298     SDNode *Extract = *UI;
15299     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
15300       return SDValue();
15301
15302     if (Extract->getValueType(0) != MVT::i32)
15303       return SDValue();
15304     if (!Extract->hasOneUse())
15305       return SDValue();
15306     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
15307         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
15308       return SDValue();
15309     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
15310       return SDValue();
15311
15312     // Record which element was extracted.
15313     ExtractedElements |=
15314       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
15315
15316     Uses.push_back(Extract);
15317   }
15318
15319   // If not all the elements were used, this may not be worthwhile.
15320   if (ExtractedElements != 15)
15321     return SDValue();
15322
15323   // Ok, we've now decided to do the transformation.
15324   DebugLoc dl = InputVector.getDebugLoc();
15325
15326   // Store the value to a temporary stack slot.
15327   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
15328   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
15329                             MachinePointerInfo(), false, false, 0);
15330
15331   // Replace each use (extract) with a load of the appropriate element.
15332   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
15333        UE = Uses.end(); UI != UE; ++UI) {
15334     SDNode *Extract = *UI;
15335
15336     // cOMpute the element's address.
15337     SDValue Idx = Extract->getOperand(1);
15338     unsigned EltSize =
15339         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
15340     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
15341     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15342     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
15343
15344     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
15345                                      StackPtr, OffsetVal);
15346
15347     // Load the scalar.
15348     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
15349                                      ScalarAddr, MachinePointerInfo(),
15350                                      false, false, false, 0);
15351
15352     // Replace the exact with the load.
15353     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
15354   }
15355
15356   // The replacement was made in place; don't return anything.
15357   return SDValue();
15358 }
15359
15360 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
15361 static unsigned matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS,
15362                                    SDValue RHS, SelectionDAG &DAG,
15363                                    const X86Subtarget *Subtarget) {
15364   if (!VT.isVector())
15365     return 0;
15366
15367   switch (VT.getSimpleVT().SimpleTy) {
15368   default: return 0;
15369   case MVT::v32i8:
15370   case MVT::v16i16:
15371   case MVT::v8i32:
15372     if (!Subtarget->hasAVX2())
15373       return 0;
15374   case MVT::v16i8:
15375   case MVT::v8i16:
15376   case MVT::v4i32:
15377     if (!Subtarget->hasSSE2())
15378       return 0;
15379   }
15380
15381   // SSE2 has only a small subset of the operations.
15382   bool hasUnsigned = Subtarget->hasSSE41() ||
15383                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
15384   bool hasSigned = Subtarget->hasSSE41() ||
15385                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
15386
15387   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15388
15389   // Check for x CC y ? x : y.
15390   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15391       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15392     switch (CC) {
15393     default: break;
15394     case ISD::SETULT:
15395     case ISD::SETULE:
15396       return hasUnsigned ? X86ISD::UMIN : 0;
15397     case ISD::SETUGT:
15398     case ISD::SETUGE:
15399       return hasUnsigned ? X86ISD::UMAX : 0;
15400     case ISD::SETLT:
15401     case ISD::SETLE:
15402       return hasSigned ? X86ISD::SMIN : 0;
15403     case ISD::SETGT:
15404     case ISD::SETGE:
15405       return hasSigned ? X86ISD::SMAX : 0;
15406     }
15407   // Check for x CC y ? y : x -- a min/max with reversed arms.
15408   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
15409              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
15410     switch (CC) {
15411     default: break;
15412     case ISD::SETULT:
15413     case ISD::SETULE:
15414       return hasUnsigned ? X86ISD::UMAX : 0;
15415     case ISD::SETUGT:
15416     case ISD::SETUGE:
15417       return hasUnsigned ? X86ISD::UMIN : 0;
15418     case ISD::SETLT:
15419     case ISD::SETLE:
15420       return hasSigned ? X86ISD::SMAX : 0;
15421     case ISD::SETGT:
15422     case ISD::SETGE:
15423       return hasSigned ? X86ISD::SMIN : 0;
15424     }
15425   }
15426
15427   return 0;
15428 }
15429
15430 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
15431 /// nodes.
15432 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
15433                                     TargetLowering::DAGCombinerInfo &DCI,
15434                                     const X86Subtarget *Subtarget) {
15435   DebugLoc DL = N->getDebugLoc();
15436   SDValue Cond = N->getOperand(0);
15437   // Get the LHS/RHS of the select.
15438   SDValue LHS = N->getOperand(1);
15439   SDValue RHS = N->getOperand(2);
15440   EVT VT = LHS.getValueType();
15441
15442   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
15443   // instructions match the semantics of the common C idiom x<y?x:y but not
15444   // x<=y?x:y, because of how they handle negative zero (which can be
15445   // ignored in unsafe-math mode).
15446   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
15447       VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
15448       (Subtarget->hasSSE2() ||
15449        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
15450     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15451
15452     unsigned Opcode = 0;
15453     // Check for x CC y ? x : y.
15454     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15455         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15456       switch (CC) {
15457       default: break;
15458       case ISD::SETULT:
15459         // Converting this to a min would handle NaNs incorrectly, and swapping
15460         // the operands would cause it to handle comparisons between positive
15461         // and negative zero incorrectly.
15462         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
15463           if (!DAG.getTarget().Options.UnsafeFPMath &&
15464               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
15465             break;
15466           std::swap(LHS, RHS);
15467         }
15468         Opcode = X86ISD::FMIN;
15469         break;
15470       case ISD::SETOLE:
15471         // Converting this to a min would handle comparisons between positive
15472         // and negative zero incorrectly.
15473         if (!DAG.getTarget().Options.UnsafeFPMath &&
15474             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
15475           break;
15476         Opcode = X86ISD::FMIN;
15477         break;
15478       case ISD::SETULE:
15479         // Converting this to a min would handle both negative zeros and NaNs
15480         // incorrectly, but we can swap the operands to fix both.
15481         std::swap(LHS, RHS);
15482       case ISD::SETOLT:
15483       case ISD::SETLT:
15484       case ISD::SETLE:
15485         Opcode = X86ISD::FMIN;
15486         break;
15487
15488       case ISD::SETOGE:
15489         // Converting this to a max would handle comparisons between positive
15490         // and negative zero incorrectly.
15491         if (!DAG.getTarget().Options.UnsafeFPMath &&
15492             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
15493           break;
15494         Opcode = X86ISD::FMAX;
15495         break;
15496       case ISD::SETUGT:
15497         // Converting this to a max would handle NaNs incorrectly, and swapping
15498         // the operands would cause it to handle comparisons between positive
15499         // and negative zero incorrectly.
15500         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
15501           if (!DAG.getTarget().Options.UnsafeFPMath &&
15502               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
15503             break;
15504           std::swap(LHS, RHS);
15505         }
15506         Opcode = X86ISD::FMAX;
15507         break;
15508       case ISD::SETUGE:
15509         // Converting this to a max would handle both negative zeros and NaNs
15510         // incorrectly, but we can swap the operands to fix both.
15511         std::swap(LHS, RHS);
15512       case ISD::SETOGT:
15513       case ISD::SETGT:
15514       case ISD::SETGE:
15515         Opcode = X86ISD::FMAX;
15516         break;
15517       }
15518     // Check for x CC y ? y : x -- a min/max with reversed arms.
15519     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
15520                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
15521       switch (CC) {
15522       default: break;
15523       case ISD::SETOGE:
15524         // Converting this to a min would handle comparisons between positive
15525         // and negative zero incorrectly, and swapping the operands would
15526         // cause it to handle NaNs incorrectly.
15527         if (!DAG.getTarget().Options.UnsafeFPMath &&
15528             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
15529           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15530             break;
15531           std::swap(LHS, RHS);
15532         }
15533         Opcode = X86ISD::FMIN;
15534         break;
15535       case ISD::SETUGT:
15536         // Converting this to a min would handle NaNs incorrectly.
15537         if (!DAG.getTarget().Options.UnsafeFPMath &&
15538             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
15539           break;
15540         Opcode = X86ISD::FMIN;
15541         break;
15542       case ISD::SETUGE:
15543         // Converting this to a min would handle both negative zeros and NaNs
15544         // incorrectly, but we can swap the operands to fix both.
15545         std::swap(LHS, RHS);
15546       case ISD::SETOGT:
15547       case ISD::SETGT:
15548       case ISD::SETGE:
15549         Opcode = X86ISD::FMIN;
15550         break;
15551
15552       case ISD::SETULT:
15553         // Converting this to a max would handle NaNs incorrectly.
15554         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15555           break;
15556         Opcode = X86ISD::FMAX;
15557         break;
15558       case ISD::SETOLE:
15559         // Converting this to a max would handle comparisons between positive
15560         // and negative zero incorrectly, and swapping the operands would
15561         // cause it to handle NaNs incorrectly.
15562         if (!DAG.getTarget().Options.UnsafeFPMath &&
15563             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
15564           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15565             break;
15566           std::swap(LHS, RHS);
15567         }
15568         Opcode = X86ISD::FMAX;
15569         break;
15570       case ISD::SETULE:
15571         // Converting this to a max would handle both negative zeros and NaNs
15572         // incorrectly, but we can swap the operands to fix both.
15573         std::swap(LHS, RHS);
15574       case ISD::SETOLT:
15575       case ISD::SETLT:
15576       case ISD::SETLE:
15577         Opcode = X86ISD::FMAX;
15578         break;
15579       }
15580     }
15581
15582     if (Opcode)
15583       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
15584   }
15585
15586   // If this is a select between two integer constants, try to do some
15587   // optimizations.
15588   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
15589     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
15590       // Don't do this for crazy integer types.
15591       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
15592         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
15593         // so that TrueC (the true value) is larger than FalseC.
15594         bool NeedsCondInvert = false;
15595
15596         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
15597             // Efficiently invertible.
15598             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
15599              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
15600               isa<ConstantSDNode>(Cond.getOperand(1))))) {
15601           NeedsCondInvert = true;
15602           std::swap(TrueC, FalseC);
15603         }
15604
15605         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
15606         if (FalseC->getAPIntValue() == 0 &&
15607             TrueC->getAPIntValue().isPowerOf2()) {
15608           if (NeedsCondInvert) // Invert the condition if needed.
15609             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15610                                DAG.getConstant(1, Cond.getValueType()));
15611
15612           // Zero extend the condition if needed.
15613           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
15614
15615           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
15616           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
15617                              DAG.getConstant(ShAmt, MVT::i8));
15618         }
15619
15620         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
15621         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
15622           if (NeedsCondInvert) // Invert the condition if needed.
15623             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15624                                DAG.getConstant(1, Cond.getValueType()));
15625
15626           // Zero extend the condition if needed.
15627           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
15628                              FalseC->getValueType(0), Cond);
15629           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15630                              SDValue(FalseC, 0));
15631         }
15632
15633         // Optimize cases that will turn into an LEA instruction.  This requires
15634         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
15635         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
15636           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
15637           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
15638
15639           bool isFastMultiplier = false;
15640           if (Diff < 10) {
15641             switch ((unsigned char)Diff) {
15642               default: break;
15643               case 1:  // result = add base, cond
15644               case 2:  // result = lea base(    , cond*2)
15645               case 3:  // result = lea base(cond, cond*2)
15646               case 4:  // result = lea base(    , cond*4)
15647               case 5:  // result = lea base(cond, cond*4)
15648               case 8:  // result = lea base(    , cond*8)
15649               case 9:  // result = lea base(cond, cond*8)
15650                 isFastMultiplier = true;
15651                 break;
15652             }
15653           }
15654
15655           if (isFastMultiplier) {
15656             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
15657             if (NeedsCondInvert) // Invert the condition if needed.
15658               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15659                                  DAG.getConstant(1, Cond.getValueType()));
15660
15661             // Zero extend the condition if needed.
15662             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
15663                                Cond);
15664             // Scale the condition by the difference.
15665             if (Diff != 1)
15666               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
15667                                  DAG.getConstant(Diff, Cond.getValueType()));
15668
15669             // Add the base if non-zero.
15670             if (FalseC->getAPIntValue() != 0)
15671               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15672                                  SDValue(FalseC, 0));
15673             return Cond;
15674           }
15675         }
15676       }
15677   }
15678
15679   // Canonicalize max and min:
15680   // (x > y) ? x : y -> (x >= y) ? x : y
15681   // (x < y) ? x : y -> (x <= y) ? x : y
15682   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
15683   // the need for an extra compare
15684   // against zero. e.g.
15685   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
15686   // subl   %esi, %edi
15687   // testl  %edi, %edi
15688   // movl   $0, %eax
15689   // cmovgl %edi, %eax
15690   // =>
15691   // xorl   %eax, %eax
15692   // subl   %esi, $edi
15693   // cmovsl %eax, %edi
15694   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
15695       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15696       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15697     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15698     switch (CC) {
15699     default: break;
15700     case ISD::SETLT:
15701     case ISD::SETGT: {
15702       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
15703       Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
15704                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
15705       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
15706     }
15707     }
15708   }
15709
15710   // Match VSELECTs into subs with unsigned saturation.
15711   if (!DCI.isBeforeLegalize() &&
15712       N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
15713       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
15714       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
15715        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
15716     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15717
15718     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
15719     // left side invert the predicate to simplify logic below.
15720     SDValue Other;
15721     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
15722       Other = RHS;
15723       CC = ISD::getSetCCInverse(CC, true);
15724     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
15725       Other = LHS;
15726     }
15727
15728     if (Other.getNode() && Other->getNumOperands() == 2 &&
15729         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
15730       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
15731       SDValue CondRHS = Cond->getOperand(1);
15732
15733       // Look for a general sub with unsigned saturation first.
15734       // x >= y ? x-y : 0 --> subus x, y
15735       // x >  y ? x-y : 0 --> subus x, y
15736       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
15737           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
15738         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
15739
15740       // If the RHS is a constant we have to reverse the const canonicalization.
15741       // x > C-1 ? x+-C : 0 --> subus x, C
15742       if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
15743           isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
15744         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
15745         if (CondRHS.getConstantOperandVal(0) == -A-1)
15746           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
15747                              DAG.getConstant(-A, VT));
15748       }
15749
15750       // Another special case: If C was a sign bit, the sub has been
15751       // canonicalized into a xor.
15752       // FIXME: Would it be better to use ComputeMaskedBits to determine whether
15753       //        it's safe to decanonicalize the xor?
15754       // x s< 0 ? x^C : 0 --> subus x, C
15755       if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
15756           ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
15757           isSplatVector(OpRHS.getNode())) {
15758         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
15759         if (A.isSignBit())
15760           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
15761       }
15762     }
15763   }
15764
15765   // Try to match a min/max vector operation.
15766   if (!DCI.isBeforeLegalize() &&
15767       N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC)
15768     if (unsigned Op = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget))
15769       return DAG.getNode(Op, DL, N->getValueType(0), LHS, RHS);
15770
15771   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
15772   if (!DCI.isBeforeLegalize() && N->getOpcode() == ISD::VSELECT &&
15773       Cond.getOpcode() == ISD::SETCC) {
15774
15775     assert(Cond.getValueType().isVector() &&
15776            "vector select expects a vector selector!");
15777
15778     EVT IntVT = Cond.getValueType();
15779     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
15780     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
15781
15782     if (!TValIsAllOnes && !FValIsAllZeros) {
15783       // Try invert the condition if true value is not all 1s and false value
15784       // is not all 0s.
15785       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
15786       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
15787
15788       if (TValIsAllZeros || FValIsAllOnes) {
15789         SDValue CC = Cond.getOperand(2);
15790         ISD::CondCode NewCC =
15791           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
15792                                Cond.getOperand(0).getValueType().isInteger());
15793         Cond = DAG.getSetCC(DL, IntVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
15794         std::swap(LHS, RHS);
15795         TValIsAllOnes = FValIsAllOnes;
15796         FValIsAllZeros = TValIsAllZeros;
15797       }
15798     }
15799
15800     if (TValIsAllOnes || FValIsAllZeros) {
15801       SDValue Ret;
15802
15803       if (TValIsAllOnes && FValIsAllZeros)
15804         Ret = Cond;
15805       else if (TValIsAllOnes)
15806         Ret = DAG.getNode(ISD::OR, DL, IntVT, Cond,
15807                           DAG.getNode(ISD::BITCAST, DL, IntVT, RHS));
15808       else if (FValIsAllZeros)
15809         Ret = DAG.getNode(ISD::AND, DL, IntVT, Cond,
15810                           DAG.getNode(ISD::BITCAST, DL, IntVT, LHS));
15811
15812       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
15813     }
15814   }
15815
15816   // If we know that this node is legal then we know that it is going to be
15817   // matched by one of the SSE/AVX BLEND instructions. These instructions only
15818   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
15819   // to simplify previous instructions.
15820   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15821   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
15822       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
15823     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
15824
15825     // Don't optimize vector selects that map to mask-registers.
15826     if (BitWidth == 1)
15827       return SDValue();
15828
15829     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
15830     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
15831
15832     APInt KnownZero, KnownOne;
15833     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
15834                                           DCI.isBeforeLegalizeOps());
15835     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
15836         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
15837       DCI.CommitTargetLoweringOpt(TLO);
15838   }
15839
15840   return SDValue();
15841 }
15842
15843 // Check whether a boolean test is testing a boolean value generated by
15844 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
15845 // code.
15846 //
15847 // Simplify the following patterns:
15848 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
15849 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
15850 // to (Op EFLAGS Cond)
15851 //
15852 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
15853 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
15854 // to (Op EFLAGS !Cond)
15855 //
15856 // where Op could be BRCOND or CMOV.
15857 //
15858 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
15859   // Quit if not CMP and SUB with its value result used.
15860   if (Cmp.getOpcode() != X86ISD::CMP &&
15861       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
15862       return SDValue();
15863
15864   // Quit if not used as a boolean value.
15865   if (CC != X86::COND_E && CC != X86::COND_NE)
15866     return SDValue();
15867
15868   // Check CMP operands. One of them should be 0 or 1 and the other should be
15869   // an SetCC or extended from it.
15870   SDValue Op1 = Cmp.getOperand(0);
15871   SDValue Op2 = Cmp.getOperand(1);
15872
15873   SDValue SetCC;
15874   const ConstantSDNode* C = 0;
15875   bool needOppositeCond = (CC == X86::COND_E);
15876   bool checkAgainstTrue = false; // Is it a comparison against 1?
15877
15878   if ((C = dyn_cast<ConstantSDNode>(Op1)))
15879     SetCC = Op2;
15880   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
15881     SetCC = Op1;
15882   else // Quit if all operands are not constants.
15883     return SDValue();
15884
15885   if (C->getZExtValue() == 1) {
15886     needOppositeCond = !needOppositeCond;
15887     checkAgainstTrue = true;
15888   } else if (C->getZExtValue() != 0)
15889     // Quit if the constant is neither 0 or 1.
15890     return SDValue();
15891
15892   bool truncatedToBoolWithAnd = false;
15893   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
15894   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
15895          SetCC.getOpcode() == ISD::TRUNCATE ||
15896          SetCC.getOpcode() == ISD::AND) {
15897     if (SetCC.getOpcode() == ISD::AND) {
15898       int OpIdx = -1;
15899       ConstantSDNode *CS;
15900       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
15901           CS->getZExtValue() == 1)
15902         OpIdx = 1;
15903       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
15904           CS->getZExtValue() == 1)
15905         OpIdx = 0;
15906       if (OpIdx == -1)
15907         break;
15908       SetCC = SetCC.getOperand(OpIdx);
15909       truncatedToBoolWithAnd = true;
15910     } else
15911       SetCC = SetCC.getOperand(0);
15912   }
15913
15914   switch (SetCC.getOpcode()) {
15915   case X86ISD::SETCC_CARRY:
15916     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
15917     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
15918     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
15919     // truncated to i1 using 'and'.
15920     if (checkAgainstTrue && !truncatedToBoolWithAnd)
15921       break;
15922     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
15923            "Invalid use of SETCC_CARRY!");
15924     // FALL THROUGH
15925   case X86ISD::SETCC:
15926     // Set the condition code or opposite one if necessary.
15927     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
15928     if (needOppositeCond)
15929       CC = X86::GetOppositeBranchCondition(CC);
15930     return SetCC.getOperand(1);
15931   case X86ISD::CMOV: {
15932     // Check whether false/true value has canonical one, i.e. 0 or 1.
15933     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
15934     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
15935     // Quit if true value is not a constant.
15936     if (!TVal)
15937       return SDValue();
15938     // Quit if false value is not a constant.
15939     if (!FVal) {
15940       SDValue Op = SetCC.getOperand(0);
15941       // Skip 'zext' or 'trunc' node.
15942       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
15943           Op.getOpcode() == ISD::TRUNCATE)
15944         Op = Op.getOperand(0);
15945       // A special case for rdrand/rdseed, where 0 is set if false cond is
15946       // found.
15947       if ((Op.getOpcode() != X86ISD::RDRAND &&
15948            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
15949         return SDValue();
15950     }
15951     // Quit if false value is not the constant 0 or 1.
15952     bool FValIsFalse = true;
15953     if (FVal && FVal->getZExtValue() != 0) {
15954       if (FVal->getZExtValue() != 1)
15955         return SDValue();
15956       // If FVal is 1, opposite cond is needed.
15957       needOppositeCond = !needOppositeCond;
15958       FValIsFalse = false;
15959     }
15960     // Quit if TVal is not the constant opposite of FVal.
15961     if (FValIsFalse && TVal->getZExtValue() != 1)
15962       return SDValue();
15963     if (!FValIsFalse && TVal->getZExtValue() != 0)
15964       return SDValue();
15965     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
15966     if (needOppositeCond)
15967       CC = X86::GetOppositeBranchCondition(CC);
15968     return SetCC.getOperand(3);
15969   }
15970   }
15971
15972   return SDValue();
15973 }
15974
15975 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
15976 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
15977                                   TargetLowering::DAGCombinerInfo &DCI,
15978                                   const X86Subtarget *Subtarget) {
15979   DebugLoc DL = N->getDebugLoc();
15980
15981   // If the flag operand isn't dead, don't touch this CMOV.
15982   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
15983     return SDValue();
15984
15985   SDValue FalseOp = N->getOperand(0);
15986   SDValue TrueOp = N->getOperand(1);
15987   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
15988   SDValue Cond = N->getOperand(3);
15989
15990   if (CC == X86::COND_E || CC == X86::COND_NE) {
15991     switch (Cond.getOpcode()) {
15992     default: break;
15993     case X86ISD::BSR:
15994     case X86ISD::BSF:
15995       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
15996       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
15997         return (CC == X86::COND_E) ? FalseOp : TrueOp;
15998     }
15999   }
16000
16001   SDValue Flags;
16002
16003   Flags = checkBoolTestSetCCCombine(Cond, CC);
16004   if (Flags.getNode() &&
16005       // Extra check as FCMOV only supports a subset of X86 cond.
16006       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
16007     SDValue Ops[] = { FalseOp, TrueOp,
16008                       DAG.getConstant(CC, MVT::i8), Flags };
16009     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
16010                        Ops, array_lengthof(Ops));
16011   }
16012
16013   // If this is a select between two integer constants, try to do some
16014   // optimizations.  Note that the operands are ordered the opposite of SELECT
16015   // operands.
16016   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
16017     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
16018       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
16019       // larger than FalseC (the false value).
16020       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
16021         CC = X86::GetOppositeBranchCondition(CC);
16022         std::swap(TrueC, FalseC);
16023         std::swap(TrueOp, FalseOp);
16024       }
16025
16026       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
16027       // This is efficient for any integer data type (including i8/i16) and
16028       // shift amount.
16029       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
16030         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16031                            DAG.getConstant(CC, MVT::i8), Cond);
16032
16033         // Zero extend the condition if needed.
16034         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
16035
16036         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
16037         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
16038                            DAG.getConstant(ShAmt, MVT::i8));
16039         if (N->getNumValues() == 2)  // Dead flag value?
16040           return DCI.CombineTo(N, Cond, SDValue());
16041         return Cond;
16042       }
16043
16044       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
16045       // for any integer data type, including i8/i16.
16046       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
16047         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16048                            DAG.getConstant(CC, MVT::i8), Cond);
16049
16050         // Zero extend the condition if needed.
16051         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
16052                            FalseC->getValueType(0), Cond);
16053         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16054                            SDValue(FalseC, 0));
16055
16056         if (N->getNumValues() == 2)  // Dead flag value?
16057           return DCI.CombineTo(N, Cond, SDValue());
16058         return Cond;
16059       }
16060
16061       // Optimize cases that will turn into an LEA instruction.  This requires
16062       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
16063       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
16064         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
16065         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
16066
16067         bool isFastMultiplier = false;
16068         if (Diff < 10) {
16069           switch ((unsigned char)Diff) {
16070           default: break;
16071           case 1:  // result = add base, cond
16072           case 2:  // result = lea base(    , cond*2)
16073           case 3:  // result = lea base(cond, cond*2)
16074           case 4:  // result = lea base(    , cond*4)
16075           case 5:  // result = lea base(cond, cond*4)
16076           case 8:  // result = lea base(    , cond*8)
16077           case 9:  // result = lea base(cond, cond*8)
16078             isFastMultiplier = true;
16079             break;
16080           }
16081         }
16082
16083         if (isFastMultiplier) {
16084           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
16085           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16086                              DAG.getConstant(CC, MVT::i8), Cond);
16087           // Zero extend the condition if needed.
16088           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
16089                              Cond);
16090           // Scale the condition by the difference.
16091           if (Diff != 1)
16092             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
16093                                DAG.getConstant(Diff, Cond.getValueType()));
16094
16095           // Add the base if non-zero.
16096           if (FalseC->getAPIntValue() != 0)
16097             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16098                                SDValue(FalseC, 0));
16099           if (N->getNumValues() == 2)  // Dead flag value?
16100             return DCI.CombineTo(N, Cond, SDValue());
16101           return Cond;
16102         }
16103       }
16104     }
16105   }
16106
16107   // Handle these cases:
16108   //   (select (x != c), e, c) -> select (x != c), e, x),
16109   //   (select (x == c), c, e) -> select (x == c), x, e)
16110   // where the c is an integer constant, and the "select" is the combination
16111   // of CMOV and CMP.
16112   //
16113   // The rationale for this change is that the conditional-move from a constant
16114   // needs two instructions, however, conditional-move from a register needs
16115   // only one instruction.
16116   //
16117   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
16118   //  some instruction-combining opportunities. This opt needs to be
16119   //  postponed as late as possible.
16120   //
16121   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
16122     // the DCI.xxxx conditions are provided to postpone the optimization as
16123     // late as possible.
16124
16125     ConstantSDNode *CmpAgainst = 0;
16126     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
16127         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
16128         !isa<ConstantSDNode>(Cond.getOperand(0))) {
16129
16130       if (CC == X86::COND_NE &&
16131           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
16132         CC = X86::GetOppositeBranchCondition(CC);
16133         std::swap(TrueOp, FalseOp);
16134       }
16135
16136       if (CC == X86::COND_E &&
16137           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
16138         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
16139                           DAG.getConstant(CC, MVT::i8), Cond };
16140         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
16141                            array_lengthof(Ops));
16142       }
16143     }
16144   }
16145
16146   return SDValue();
16147 }
16148
16149 /// PerformMulCombine - Optimize a single multiply with constant into two
16150 /// in order to implement it with two cheaper instructions, e.g.
16151 /// LEA + SHL, LEA + LEA.
16152 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
16153                                  TargetLowering::DAGCombinerInfo &DCI) {
16154   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
16155     return SDValue();
16156
16157   EVT VT = N->getValueType(0);
16158   if (VT != MVT::i64)
16159     return SDValue();
16160
16161   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
16162   if (!C)
16163     return SDValue();
16164   uint64_t MulAmt = C->getZExtValue();
16165   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
16166     return SDValue();
16167
16168   uint64_t MulAmt1 = 0;
16169   uint64_t MulAmt2 = 0;
16170   if ((MulAmt % 9) == 0) {
16171     MulAmt1 = 9;
16172     MulAmt2 = MulAmt / 9;
16173   } else if ((MulAmt % 5) == 0) {
16174     MulAmt1 = 5;
16175     MulAmt2 = MulAmt / 5;
16176   } else if ((MulAmt % 3) == 0) {
16177     MulAmt1 = 3;
16178     MulAmt2 = MulAmt / 3;
16179   }
16180   if (MulAmt2 &&
16181       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
16182     DebugLoc DL = N->getDebugLoc();
16183
16184     if (isPowerOf2_64(MulAmt2) &&
16185         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
16186       // If second multiplifer is pow2, issue it first. We want the multiply by
16187       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
16188       // is an add.
16189       std::swap(MulAmt1, MulAmt2);
16190
16191     SDValue NewMul;
16192     if (isPowerOf2_64(MulAmt1))
16193       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
16194                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
16195     else
16196       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
16197                            DAG.getConstant(MulAmt1, VT));
16198
16199     if (isPowerOf2_64(MulAmt2))
16200       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
16201                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
16202     else
16203       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
16204                            DAG.getConstant(MulAmt2, VT));
16205
16206     // Do not add new nodes to DAG combiner worklist.
16207     DCI.CombineTo(N, NewMul, false);
16208   }
16209   return SDValue();
16210 }
16211
16212 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
16213   SDValue N0 = N->getOperand(0);
16214   SDValue N1 = N->getOperand(1);
16215   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
16216   EVT VT = N0.getValueType();
16217
16218   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
16219   // since the result of setcc_c is all zero's or all ones.
16220   if (VT.isInteger() && !VT.isVector() &&
16221       N1C && N0.getOpcode() == ISD::AND &&
16222       N0.getOperand(1).getOpcode() == ISD::Constant) {
16223     SDValue N00 = N0.getOperand(0);
16224     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
16225         ((N00.getOpcode() == ISD::ANY_EXTEND ||
16226           N00.getOpcode() == ISD::ZERO_EXTEND) &&
16227          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
16228       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
16229       APInt ShAmt = N1C->getAPIntValue();
16230       Mask = Mask.shl(ShAmt);
16231       if (Mask != 0)
16232         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
16233                            N00, DAG.getConstant(Mask, VT));
16234     }
16235   }
16236
16237   // Hardware support for vector shifts is sparse which makes us scalarize the
16238   // vector operations in many cases. Also, on sandybridge ADD is faster than
16239   // shl.
16240   // (shl V, 1) -> add V,V
16241   if (isSplatVector(N1.getNode())) {
16242     assert(N0.getValueType().isVector() && "Invalid vector shift type");
16243     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
16244     // We shift all of the values by one. In many cases we do not have
16245     // hardware support for this operation. This is better expressed as an ADD
16246     // of two values.
16247     if (N1C && (1 == N1C->getZExtValue())) {
16248       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
16249     }
16250   }
16251
16252   return SDValue();
16253 }
16254
16255 /// PerformShiftCombine - Combine shifts.
16256 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
16257                                    TargetLowering::DAGCombinerInfo &DCI,
16258                                    const X86Subtarget *Subtarget) {
16259   if (N->getOpcode() == ISD::SHL) {
16260     SDValue V = PerformSHLCombine(N, DAG);
16261     if (V.getNode()) return V;
16262   }
16263
16264   return SDValue();
16265 }
16266
16267 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
16268 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
16269 // and friends.  Likewise for OR -> CMPNEQSS.
16270 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
16271                             TargetLowering::DAGCombinerInfo &DCI,
16272                             const X86Subtarget *Subtarget) {
16273   unsigned opcode;
16274
16275   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
16276   // we're requiring SSE2 for both.
16277   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
16278     SDValue N0 = N->getOperand(0);
16279     SDValue N1 = N->getOperand(1);
16280     SDValue CMP0 = N0->getOperand(1);
16281     SDValue CMP1 = N1->getOperand(1);
16282     DebugLoc DL = N->getDebugLoc();
16283
16284     // The SETCCs should both refer to the same CMP.
16285     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
16286       return SDValue();
16287
16288     SDValue CMP00 = CMP0->getOperand(0);
16289     SDValue CMP01 = CMP0->getOperand(1);
16290     EVT     VT    = CMP00.getValueType();
16291
16292     if (VT == MVT::f32 || VT == MVT::f64) {
16293       bool ExpectingFlags = false;
16294       // Check for any users that want flags:
16295       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
16296            !ExpectingFlags && UI != UE; ++UI)
16297         switch (UI->getOpcode()) {
16298         default:
16299         case ISD::BR_CC:
16300         case ISD::BRCOND:
16301         case ISD::SELECT:
16302           ExpectingFlags = true;
16303           break;
16304         case ISD::CopyToReg:
16305         case ISD::SIGN_EXTEND:
16306         case ISD::ZERO_EXTEND:
16307         case ISD::ANY_EXTEND:
16308           break;
16309         }
16310
16311       if (!ExpectingFlags) {
16312         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
16313         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
16314
16315         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
16316           X86::CondCode tmp = cc0;
16317           cc0 = cc1;
16318           cc1 = tmp;
16319         }
16320
16321         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
16322             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
16323           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
16324           X86ISD::NodeType NTOperator = is64BitFP ?
16325             X86ISD::FSETCCsd : X86ISD::FSETCCss;
16326           // FIXME: need symbolic constants for these magic numbers.
16327           // See X86ATTInstPrinter.cpp:printSSECC().
16328           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
16329           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
16330                                               DAG.getConstant(x86cc, MVT::i8));
16331           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
16332                                               OnesOrZeroesF);
16333           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
16334                                       DAG.getConstant(1, MVT::i32));
16335           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
16336           return OneBitOfTruth;
16337         }
16338       }
16339     }
16340   }
16341   return SDValue();
16342 }
16343
16344 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
16345 /// so it can be folded inside ANDNP.
16346 static bool CanFoldXORWithAllOnes(const SDNode *N) {
16347   EVT VT = N->getValueType(0);
16348
16349   // Match direct AllOnes for 128 and 256-bit vectors
16350   if (ISD::isBuildVectorAllOnes(N))
16351     return true;
16352
16353   // Look through a bit convert.
16354   if (N->getOpcode() == ISD::BITCAST)
16355     N = N->getOperand(0).getNode();
16356
16357   // Sometimes the operand may come from a insert_subvector building a 256-bit
16358   // allones vector
16359   if (VT.is256BitVector() &&
16360       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
16361     SDValue V1 = N->getOperand(0);
16362     SDValue V2 = N->getOperand(1);
16363
16364     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
16365         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
16366         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
16367         ISD::isBuildVectorAllOnes(V2.getNode()))
16368       return true;
16369   }
16370
16371   return false;
16372 }
16373
16374 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
16375 // register. In most cases we actually compare or select YMM-sized registers
16376 // and mixing the two types creates horrible code. This method optimizes
16377 // some of the transition sequences.
16378 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
16379                                  TargetLowering::DAGCombinerInfo &DCI,
16380                                  const X86Subtarget *Subtarget) {
16381   EVT VT = N->getValueType(0);
16382   if (!VT.is256BitVector())
16383     return SDValue();
16384
16385   assert((N->getOpcode() == ISD::ANY_EXTEND ||
16386           N->getOpcode() == ISD::ZERO_EXTEND ||
16387           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
16388
16389   SDValue Narrow = N->getOperand(0);
16390   EVT NarrowVT = Narrow->getValueType(0);
16391   if (!NarrowVT.is128BitVector())
16392     return SDValue();
16393
16394   if (Narrow->getOpcode() != ISD::XOR &&
16395       Narrow->getOpcode() != ISD::AND &&
16396       Narrow->getOpcode() != ISD::OR)
16397     return SDValue();
16398
16399   SDValue N0  = Narrow->getOperand(0);
16400   SDValue N1  = Narrow->getOperand(1);
16401   DebugLoc DL = Narrow->getDebugLoc();
16402
16403   // The Left side has to be a trunc.
16404   if (N0.getOpcode() != ISD::TRUNCATE)
16405     return SDValue();
16406
16407   // The type of the truncated inputs.
16408   EVT WideVT = N0->getOperand(0)->getValueType(0);
16409   if (WideVT != VT)
16410     return SDValue();
16411
16412   // The right side has to be a 'trunc' or a constant vector.
16413   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
16414   bool RHSConst = (isSplatVector(N1.getNode()) &&
16415                    isa<ConstantSDNode>(N1->getOperand(0)));
16416   if (!RHSTrunc && !RHSConst)
16417     return SDValue();
16418
16419   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16420
16421   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
16422     return SDValue();
16423
16424   // Set N0 and N1 to hold the inputs to the new wide operation.
16425   N0 = N0->getOperand(0);
16426   if (RHSConst) {
16427     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
16428                      N1->getOperand(0));
16429     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
16430     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, &C[0], C.size());
16431   } else if (RHSTrunc) {
16432     N1 = N1->getOperand(0);
16433   }
16434
16435   // Generate the wide operation.
16436   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
16437   unsigned Opcode = N->getOpcode();
16438   switch (Opcode) {
16439   case ISD::ANY_EXTEND:
16440     return Op;
16441   case ISD::ZERO_EXTEND: {
16442     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
16443     APInt Mask = APInt::getAllOnesValue(InBits);
16444     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
16445     return DAG.getNode(ISD::AND, DL, VT,
16446                        Op, DAG.getConstant(Mask, VT));
16447   }
16448   case ISD::SIGN_EXTEND:
16449     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
16450                        Op, DAG.getValueType(NarrowVT));
16451   default:
16452     llvm_unreachable("Unexpected opcode");
16453   }
16454 }
16455
16456 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
16457                                  TargetLowering::DAGCombinerInfo &DCI,
16458                                  const X86Subtarget *Subtarget) {
16459   EVT VT = N->getValueType(0);
16460   if (DCI.isBeforeLegalizeOps())
16461     return SDValue();
16462
16463   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
16464   if (R.getNode())
16465     return R;
16466
16467   // Create BLSI, and BLSR instructions
16468   // BLSI is X & (-X)
16469   // BLSR is X & (X-1)
16470   if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
16471     SDValue N0 = N->getOperand(0);
16472     SDValue N1 = N->getOperand(1);
16473     DebugLoc DL = N->getDebugLoc();
16474
16475     // Check LHS for neg
16476     if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
16477         isZero(N0.getOperand(0)))
16478       return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
16479
16480     // Check RHS for neg
16481     if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
16482         isZero(N1.getOperand(0)))
16483       return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
16484
16485     // Check LHS for X-1
16486     if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
16487         isAllOnes(N0.getOperand(1)))
16488       return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
16489
16490     // Check RHS for X-1
16491     if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
16492         isAllOnes(N1.getOperand(1)))
16493       return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
16494
16495     return SDValue();
16496   }
16497
16498   // Want to form ANDNP nodes:
16499   // 1) In the hopes of then easily combining them with OR and AND nodes
16500   //    to form PBLEND/PSIGN.
16501   // 2) To match ANDN packed intrinsics
16502   if (VT != MVT::v2i64 && VT != MVT::v4i64)
16503     return SDValue();
16504
16505   SDValue N0 = N->getOperand(0);
16506   SDValue N1 = N->getOperand(1);
16507   DebugLoc DL = N->getDebugLoc();
16508
16509   // Check LHS for vnot
16510   if (N0.getOpcode() == ISD::XOR &&
16511       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
16512       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
16513     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
16514
16515   // Check RHS for vnot
16516   if (N1.getOpcode() == ISD::XOR &&
16517       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
16518       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
16519     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
16520
16521   return SDValue();
16522 }
16523
16524 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
16525                                 TargetLowering::DAGCombinerInfo &DCI,
16526                                 const X86Subtarget *Subtarget) {
16527   EVT VT = N->getValueType(0);
16528   if (DCI.isBeforeLegalizeOps())
16529     return SDValue();
16530
16531   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
16532   if (R.getNode())
16533     return R;
16534
16535   SDValue N0 = N->getOperand(0);
16536   SDValue N1 = N->getOperand(1);
16537
16538   // look for psign/blend
16539   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
16540     if (!Subtarget->hasSSSE3() ||
16541         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
16542       return SDValue();
16543
16544     // Canonicalize pandn to RHS
16545     if (N0.getOpcode() == X86ISD::ANDNP)
16546       std::swap(N0, N1);
16547     // or (and (m, y), (pandn m, x))
16548     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
16549       SDValue Mask = N1.getOperand(0);
16550       SDValue X    = N1.getOperand(1);
16551       SDValue Y;
16552       if (N0.getOperand(0) == Mask)
16553         Y = N0.getOperand(1);
16554       if (N0.getOperand(1) == Mask)
16555         Y = N0.getOperand(0);
16556
16557       // Check to see if the mask appeared in both the AND and ANDNP and
16558       if (!Y.getNode())
16559         return SDValue();
16560
16561       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
16562       // Look through mask bitcast.
16563       if (Mask.getOpcode() == ISD::BITCAST)
16564         Mask = Mask.getOperand(0);
16565       if (X.getOpcode() == ISD::BITCAST)
16566         X = X.getOperand(0);
16567       if (Y.getOpcode() == ISD::BITCAST)
16568         Y = Y.getOperand(0);
16569
16570       EVT MaskVT = Mask.getValueType();
16571
16572       // Validate that the Mask operand is a vector sra node.
16573       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
16574       // there is no psrai.b
16575       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
16576       unsigned SraAmt = ~0;
16577       if (Mask.getOpcode() == ISD::SRA) {
16578         SDValue Amt = Mask.getOperand(1);
16579         if (isSplatVector(Amt.getNode())) {
16580           SDValue SclrAmt = Amt->getOperand(0);
16581           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
16582             SraAmt = C->getZExtValue();
16583         }
16584       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
16585         SDValue SraC = Mask.getOperand(1);
16586         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
16587       }
16588       if ((SraAmt + 1) != EltBits)
16589         return SDValue();
16590
16591       DebugLoc DL = N->getDebugLoc();
16592
16593       // Now we know we at least have a plendvb with the mask val.  See if
16594       // we can form a psignb/w/d.
16595       // psign = x.type == y.type == mask.type && y = sub(0, x);
16596       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
16597           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
16598           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
16599         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
16600                "Unsupported VT for PSIGN");
16601         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
16602         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
16603       }
16604       // PBLENDVB only available on SSE 4.1
16605       if (!Subtarget->hasSSE41())
16606         return SDValue();
16607
16608       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
16609
16610       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
16611       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
16612       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
16613       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
16614       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
16615     }
16616   }
16617
16618   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
16619     return SDValue();
16620
16621   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
16622   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
16623     std::swap(N0, N1);
16624   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
16625     return SDValue();
16626   if (!N0.hasOneUse() || !N1.hasOneUse())
16627     return SDValue();
16628
16629   SDValue ShAmt0 = N0.getOperand(1);
16630   if (ShAmt0.getValueType() != MVT::i8)
16631     return SDValue();
16632   SDValue ShAmt1 = N1.getOperand(1);
16633   if (ShAmt1.getValueType() != MVT::i8)
16634     return SDValue();
16635   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
16636     ShAmt0 = ShAmt0.getOperand(0);
16637   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
16638     ShAmt1 = ShAmt1.getOperand(0);
16639
16640   DebugLoc DL = N->getDebugLoc();
16641   unsigned Opc = X86ISD::SHLD;
16642   SDValue Op0 = N0.getOperand(0);
16643   SDValue Op1 = N1.getOperand(0);
16644   if (ShAmt0.getOpcode() == ISD::SUB) {
16645     Opc = X86ISD::SHRD;
16646     std::swap(Op0, Op1);
16647     std::swap(ShAmt0, ShAmt1);
16648   }
16649
16650   unsigned Bits = VT.getSizeInBits();
16651   if (ShAmt1.getOpcode() == ISD::SUB) {
16652     SDValue Sum = ShAmt1.getOperand(0);
16653     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
16654       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
16655       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
16656         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
16657       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
16658         return DAG.getNode(Opc, DL, VT,
16659                            Op0, Op1,
16660                            DAG.getNode(ISD::TRUNCATE, DL,
16661                                        MVT::i8, ShAmt0));
16662     }
16663   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
16664     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
16665     if (ShAmt0C &&
16666         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
16667       return DAG.getNode(Opc, DL, VT,
16668                          N0.getOperand(0), N1.getOperand(0),
16669                          DAG.getNode(ISD::TRUNCATE, DL,
16670                                        MVT::i8, ShAmt0));
16671   }
16672
16673   return SDValue();
16674 }
16675
16676 // Generate NEG and CMOV for integer abs.
16677 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
16678   EVT VT = N->getValueType(0);
16679
16680   // Since X86 does not have CMOV for 8-bit integer, we don't convert
16681   // 8-bit integer abs to NEG and CMOV.
16682   if (VT.isInteger() && VT.getSizeInBits() == 8)
16683     return SDValue();
16684
16685   SDValue N0 = N->getOperand(0);
16686   SDValue N1 = N->getOperand(1);
16687   DebugLoc DL = N->getDebugLoc();
16688
16689   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
16690   // and change it to SUB and CMOV.
16691   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
16692       N0.getOpcode() == ISD::ADD &&
16693       N0.getOperand(1) == N1 &&
16694       N1.getOpcode() == ISD::SRA &&
16695       N1.getOperand(0) == N0.getOperand(0))
16696     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
16697       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
16698         // Generate SUB & CMOV.
16699         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
16700                                   DAG.getConstant(0, VT), N0.getOperand(0));
16701
16702         SDValue Ops[] = { N0.getOperand(0), Neg,
16703                           DAG.getConstant(X86::COND_GE, MVT::i8),
16704                           SDValue(Neg.getNode(), 1) };
16705         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
16706                            Ops, array_lengthof(Ops));
16707       }
16708   return SDValue();
16709 }
16710
16711 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
16712 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
16713                                  TargetLowering::DAGCombinerInfo &DCI,
16714                                  const X86Subtarget *Subtarget) {
16715   EVT VT = N->getValueType(0);
16716   if (DCI.isBeforeLegalizeOps())
16717     return SDValue();
16718
16719   if (Subtarget->hasCMov()) {
16720     SDValue RV = performIntegerAbsCombine(N, DAG);
16721     if (RV.getNode())
16722       return RV;
16723   }
16724
16725   // Try forming BMI if it is available.
16726   if (!Subtarget->hasBMI())
16727     return SDValue();
16728
16729   if (VT != MVT::i32 && VT != MVT::i64)
16730     return SDValue();
16731
16732   assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
16733
16734   // Create BLSMSK instructions by finding X ^ (X-1)
16735   SDValue N0 = N->getOperand(0);
16736   SDValue N1 = N->getOperand(1);
16737   DebugLoc DL = N->getDebugLoc();
16738
16739   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
16740       isAllOnes(N0.getOperand(1)))
16741     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
16742
16743   if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
16744       isAllOnes(N1.getOperand(1)))
16745     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
16746
16747   return SDValue();
16748 }
16749
16750 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
16751 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
16752                                   TargetLowering::DAGCombinerInfo &DCI,
16753                                   const X86Subtarget *Subtarget) {
16754   LoadSDNode *Ld = cast<LoadSDNode>(N);
16755   EVT RegVT = Ld->getValueType(0);
16756   EVT MemVT = Ld->getMemoryVT();
16757   DebugLoc dl = Ld->getDebugLoc();
16758   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16759   unsigned RegSz = RegVT.getSizeInBits();
16760
16761   // On Sandybridge unaligned 256bit loads are inefficient.
16762   ISD::LoadExtType Ext = Ld->getExtensionType();
16763   unsigned Alignment = Ld->getAlignment();
16764   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
16765   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
16766       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
16767     unsigned NumElems = RegVT.getVectorNumElements();
16768     if (NumElems < 2)
16769       return SDValue();
16770
16771     SDValue Ptr = Ld->getBasePtr();
16772     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
16773
16774     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
16775                                   NumElems/2);
16776     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
16777                                 Ld->getPointerInfo(), Ld->isVolatile(),
16778                                 Ld->isNonTemporal(), Ld->isInvariant(),
16779                                 Alignment);
16780     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16781     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
16782                                 Ld->getPointerInfo(), Ld->isVolatile(),
16783                                 Ld->isNonTemporal(), Ld->isInvariant(),
16784                                 std::min(16U, Alignment));
16785     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
16786                              Load1.getValue(1),
16787                              Load2.getValue(1));
16788
16789     SDValue NewVec = DAG.getUNDEF(RegVT);
16790     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
16791     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
16792     return DCI.CombineTo(N, NewVec, TF, true);
16793   }
16794
16795   // If this is a vector EXT Load then attempt to optimize it using a
16796   // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
16797   // expansion is still better than scalar code.
16798   // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
16799   // emit a shuffle and a arithmetic shift.
16800   // TODO: It is possible to support ZExt by zeroing the undef values
16801   // during the shuffle phase or after the shuffle.
16802   if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
16803       (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
16804     assert(MemVT != RegVT && "Cannot extend to the same type");
16805     assert(MemVT.isVector() && "Must load a vector from memory");
16806
16807     unsigned NumElems = RegVT.getVectorNumElements();
16808     unsigned MemSz = MemVT.getSizeInBits();
16809     assert(RegSz > MemSz && "Register size must be greater than the mem size");
16810
16811     if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
16812       return SDValue();
16813
16814     // All sizes must be a power of two.
16815     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
16816       return SDValue();
16817
16818     // Attempt to load the original value using scalar loads.
16819     // Find the largest scalar type that divides the total loaded size.
16820     MVT SclrLoadTy = MVT::i8;
16821     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
16822          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
16823       MVT Tp = (MVT::SimpleValueType)tp;
16824       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
16825         SclrLoadTy = Tp;
16826       }
16827     }
16828
16829     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
16830     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
16831         (64 <= MemSz))
16832       SclrLoadTy = MVT::f64;
16833
16834     // Calculate the number of scalar loads that we need to perform
16835     // in order to load our vector from memory.
16836     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
16837     if (Ext == ISD::SEXTLOAD && NumLoads > 1)
16838       return SDValue();
16839
16840     unsigned loadRegZize = RegSz;
16841     if (Ext == ISD::SEXTLOAD && RegSz == 256)
16842       loadRegZize /= 2;
16843
16844     // Represent our vector as a sequence of elements which are the
16845     // largest scalar that we can load.
16846     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
16847       loadRegZize/SclrLoadTy.getSizeInBits());
16848
16849     // Represent the data using the same element type that is stored in
16850     // memory. In practice, we ''widen'' MemVT.
16851     EVT WideVecVT =
16852           EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
16853                        loadRegZize/MemVT.getScalarType().getSizeInBits());
16854
16855     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
16856       "Invalid vector type");
16857
16858     // We can't shuffle using an illegal type.
16859     if (!TLI.isTypeLegal(WideVecVT))
16860       return SDValue();
16861
16862     SmallVector<SDValue, 8> Chains;
16863     SDValue Ptr = Ld->getBasePtr();
16864     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
16865                                         TLI.getPointerTy());
16866     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
16867
16868     for (unsigned i = 0; i < NumLoads; ++i) {
16869       // Perform a single load.
16870       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
16871                                        Ptr, Ld->getPointerInfo(),
16872                                        Ld->isVolatile(), Ld->isNonTemporal(),
16873                                        Ld->isInvariant(), Ld->getAlignment());
16874       Chains.push_back(ScalarLoad.getValue(1));
16875       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
16876       // another round of DAGCombining.
16877       if (i == 0)
16878         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
16879       else
16880         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
16881                           ScalarLoad, DAG.getIntPtrConstant(i));
16882
16883       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16884     }
16885
16886     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
16887                                Chains.size());
16888
16889     // Bitcast the loaded value to a vector of the original element type, in
16890     // the size of the target vector type.
16891     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
16892     unsigned SizeRatio = RegSz/MemSz;
16893
16894     if (Ext == ISD::SEXTLOAD) {
16895       // If we have SSE4.1 we can directly emit a VSEXT node.
16896       if (Subtarget->hasSSE41()) {
16897         SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
16898         return DCI.CombineTo(N, Sext, TF, true);
16899       }
16900
16901       // Otherwise we'll shuffle the small elements in the high bits of the
16902       // larger type and perform an arithmetic shift. If the shift is not legal
16903       // it's better to scalarize.
16904       if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
16905         return SDValue();
16906
16907       // Redistribute the loaded elements into the different locations.
16908       SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16909       for (unsigned i = 0; i != NumElems; ++i)
16910         ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
16911
16912       SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
16913                                            DAG.getUNDEF(WideVecVT),
16914                                            &ShuffleVec[0]);
16915
16916       Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
16917
16918       // Build the arithmetic shift.
16919       unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
16920                      MemVT.getVectorElementType().getSizeInBits();
16921       Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
16922                           DAG.getConstant(Amt, RegVT));
16923
16924       return DCI.CombineTo(N, Shuff, TF, true);
16925     }
16926
16927     // Redistribute the loaded elements into the different locations.
16928     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16929     for (unsigned i = 0; i != NumElems; ++i)
16930       ShuffleVec[i*SizeRatio] = i;
16931
16932     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
16933                                          DAG.getUNDEF(WideVecVT),
16934                                          &ShuffleVec[0]);
16935
16936     // Bitcast to the requested type.
16937     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
16938     // Replace the original load with the new sequence
16939     // and return the new chain.
16940     return DCI.CombineTo(N, Shuff, TF, true);
16941   }
16942
16943   return SDValue();
16944 }
16945
16946 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
16947 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
16948                                    const X86Subtarget *Subtarget) {
16949   StoreSDNode *St = cast<StoreSDNode>(N);
16950   EVT VT = St->getValue().getValueType();
16951   EVT StVT = St->getMemoryVT();
16952   DebugLoc dl = St->getDebugLoc();
16953   SDValue StoredVal = St->getOperand(1);
16954   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16955
16956   // If we are saving a concatenation of two XMM registers, perform two stores.
16957   // On Sandy Bridge, 256-bit memory operations are executed by two
16958   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
16959   // memory  operation.
16960   unsigned Alignment = St->getAlignment();
16961   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
16962   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
16963       StVT == VT && !IsAligned) {
16964     unsigned NumElems = VT.getVectorNumElements();
16965     if (NumElems < 2)
16966       return SDValue();
16967
16968     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
16969     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
16970
16971     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
16972     SDValue Ptr0 = St->getBasePtr();
16973     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
16974
16975     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
16976                                 St->getPointerInfo(), St->isVolatile(),
16977                                 St->isNonTemporal(), Alignment);
16978     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
16979                                 St->getPointerInfo(), St->isVolatile(),
16980                                 St->isNonTemporal(),
16981                                 std::min(16U, Alignment));
16982     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
16983   }
16984
16985   // Optimize trunc store (of multiple scalars) to shuffle and store.
16986   // First, pack all of the elements in one place. Next, store to memory
16987   // in fewer chunks.
16988   if (St->isTruncatingStore() && VT.isVector()) {
16989     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16990     unsigned NumElems = VT.getVectorNumElements();
16991     assert(StVT != VT && "Cannot truncate to the same type");
16992     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
16993     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
16994
16995     // From, To sizes and ElemCount must be pow of two
16996     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
16997     // We are going to use the original vector elt for storing.
16998     // Accumulated smaller vector elements must be a multiple of the store size.
16999     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
17000
17001     unsigned SizeRatio  = FromSz / ToSz;
17002
17003     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
17004
17005     // Create a type on which we perform the shuffle
17006     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
17007             StVT.getScalarType(), NumElems*SizeRatio);
17008
17009     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
17010
17011     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
17012     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
17013     for (unsigned i = 0; i != NumElems; ++i)
17014       ShuffleVec[i] = i * SizeRatio;
17015
17016     // Can't shuffle using an illegal type.
17017     if (!TLI.isTypeLegal(WideVecVT))
17018       return SDValue();
17019
17020     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
17021                                          DAG.getUNDEF(WideVecVT),
17022                                          &ShuffleVec[0]);
17023     // At this point all of the data is stored at the bottom of the
17024     // register. We now need to save it to mem.
17025
17026     // Find the largest store unit
17027     MVT StoreType = MVT::i8;
17028     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
17029          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
17030       MVT Tp = (MVT::SimpleValueType)tp;
17031       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
17032         StoreType = Tp;
17033     }
17034
17035     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
17036     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
17037         (64 <= NumElems * ToSz))
17038       StoreType = MVT::f64;
17039
17040     // Bitcast the original vector into a vector of store-size units
17041     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
17042             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
17043     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
17044     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
17045     SmallVector<SDValue, 8> Chains;
17046     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
17047                                         TLI.getPointerTy());
17048     SDValue Ptr = St->getBasePtr();
17049
17050     // Perform one or more big stores into memory.
17051     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
17052       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
17053                                    StoreType, ShuffWide,
17054                                    DAG.getIntPtrConstant(i));
17055       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
17056                                 St->getPointerInfo(), St->isVolatile(),
17057                                 St->isNonTemporal(), St->getAlignment());
17058       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
17059       Chains.push_back(Ch);
17060     }
17061
17062     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
17063                                Chains.size());
17064   }
17065
17066   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
17067   // the FP state in cases where an emms may be missing.
17068   // A preferable solution to the general problem is to figure out the right
17069   // places to insert EMMS.  This qualifies as a quick hack.
17070
17071   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
17072   if (VT.getSizeInBits() != 64)
17073     return SDValue();
17074
17075   const Function *F = DAG.getMachineFunction().getFunction();
17076   bool NoImplicitFloatOps = F->getAttributes().
17077     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
17078   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
17079                      && Subtarget->hasSSE2();
17080   if ((VT.isVector() ||
17081        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
17082       isa<LoadSDNode>(St->getValue()) &&
17083       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
17084       St->getChain().hasOneUse() && !St->isVolatile()) {
17085     SDNode* LdVal = St->getValue().getNode();
17086     LoadSDNode *Ld = 0;
17087     int TokenFactorIndex = -1;
17088     SmallVector<SDValue, 8> Ops;
17089     SDNode* ChainVal = St->getChain().getNode();
17090     // Must be a store of a load.  We currently handle two cases:  the load
17091     // is a direct child, and it's under an intervening TokenFactor.  It is
17092     // possible to dig deeper under nested TokenFactors.
17093     if (ChainVal == LdVal)
17094       Ld = cast<LoadSDNode>(St->getChain());
17095     else if (St->getValue().hasOneUse() &&
17096              ChainVal->getOpcode() == ISD::TokenFactor) {
17097       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
17098         if (ChainVal->getOperand(i).getNode() == LdVal) {
17099           TokenFactorIndex = i;
17100           Ld = cast<LoadSDNode>(St->getValue());
17101         } else
17102           Ops.push_back(ChainVal->getOperand(i));
17103       }
17104     }
17105
17106     if (!Ld || !ISD::isNormalLoad(Ld))
17107       return SDValue();
17108
17109     // If this is not the MMX case, i.e. we are just turning i64 load/store
17110     // into f64 load/store, avoid the transformation if there are multiple
17111     // uses of the loaded value.
17112     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
17113       return SDValue();
17114
17115     DebugLoc LdDL = Ld->getDebugLoc();
17116     DebugLoc StDL = N->getDebugLoc();
17117     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
17118     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
17119     // pair instead.
17120     if (Subtarget->is64Bit() || F64IsLegal) {
17121       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
17122       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
17123                                   Ld->getPointerInfo(), Ld->isVolatile(),
17124                                   Ld->isNonTemporal(), Ld->isInvariant(),
17125                                   Ld->getAlignment());
17126       SDValue NewChain = NewLd.getValue(1);
17127       if (TokenFactorIndex != -1) {
17128         Ops.push_back(NewChain);
17129         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
17130                                Ops.size());
17131       }
17132       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
17133                           St->getPointerInfo(),
17134                           St->isVolatile(), St->isNonTemporal(),
17135                           St->getAlignment());
17136     }
17137
17138     // Otherwise, lower to two pairs of 32-bit loads / stores.
17139     SDValue LoAddr = Ld->getBasePtr();
17140     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
17141                                  DAG.getConstant(4, MVT::i32));
17142
17143     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
17144                                Ld->getPointerInfo(),
17145                                Ld->isVolatile(), Ld->isNonTemporal(),
17146                                Ld->isInvariant(), Ld->getAlignment());
17147     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
17148                                Ld->getPointerInfo().getWithOffset(4),
17149                                Ld->isVolatile(), Ld->isNonTemporal(),
17150                                Ld->isInvariant(),
17151                                MinAlign(Ld->getAlignment(), 4));
17152
17153     SDValue NewChain = LoLd.getValue(1);
17154     if (TokenFactorIndex != -1) {
17155       Ops.push_back(LoLd);
17156       Ops.push_back(HiLd);
17157       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
17158                              Ops.size());
17159     }
17160
17161     LoAddr = St->getBasePtr();
17162     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
17163                          DAG.getConstant(4, MVT::i32));
17164
17165     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
17166                                 St->getPointerInfo(),
17167                                 St->isVolatile(), St->isNonTemporal(),
17168                                 St->getAlignment());
17169     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
17170                                 St->getPointerInfo().getWithOffset(4),
17171                                 St->isVolatile(),
17172                                 St->isNonTemporal(),
17173                                 MinAlign(St->getAlignment(), 4));
17174     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
17175   }
17176   return SDValue();
17177 }
17178
17179 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
17180 /// and return the operands for the horizontal operation in LHS and RHS.  A
17181 /// horizontal operation performs the binary operation on successive elements
17182 /// of its first operand, then on successive elements of its second operand,
17183 /// returning the resulting values in a vector.  For example, if
17184 ///   A = < float a0, float a1, float a2, float a3 >
17185 /// and
17186 ///   B = < float b0, float b1, float b2, float b3 >
17187 /// then the result of doing a horizontal operation on A and B is
17188 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
17189 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
17190 /// A horizontal-op B, for some already available A and B, and if so then LHS is
17191 /// set to A, RHS to B, and the routine returns 'true'.
17192 /// Note that the binary operation should have the property that if one of the
17193 /// operands is UNDEF then the result is UNDEF.
17194 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
17195   // Look for the following pattern: if
17196   //   A = < float a0, float a1, float a2, float a3 >
17197   //   B = < float b0, float b1, float b2, float b3 >
17198   // and
17199   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
17200   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
17201   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
17202   // which is A horizontal-op B.
17203
17204   // At least one of the operands should be a vector shuffle.
17205   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
17206       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
17207     return false;
17208
17209   EVT VT = LHS.getValueType();
17210
17211   assert((VT.is128BitVector() || VT.is256BitVector()) &&
17212          "Unsupported vector type for horizontal add/sub");
17213
17214   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
17215   // operate independently on 128-bit lanes.
17216   unsigned NumElts = VT.getVectorNumElements();
17217   unsigned NumLanes = VT.getSizeInBits()/128;
17218   unsigned NumLaneElts = NumElts / NumLanes;
17219   assert((NumLaneElts % 2 == 0) &&
17220          "Vector type should have an even number of elements in each lane");
17221   unsigned HalfLaneElts = NumLaneElts/2;
17222
17223   // View LHS in the form
17224   //   LHS = VECTOR_SHUFFLE A, B, LMask
17225   // If LHS is not a shuffle then pretend it is the shuffle
17226   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
17227   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
17228   // type VT.
17229   SDValue A, B;
17230   SmallVector<int, 16> LMask(NumElts);
17231   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
17232     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
17233       A = LHS.getOperand(0);
17234     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
17235       B = LHS.getOperand(1);
17236     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
17237     std::copy(Mask.begin(), Mask.end(), LMask.begin());
17238   } else {
17239     if (LHS.getOpcode() != ISD::UNDEF)
17240       A = LHS;
17241     for (unsigned i = 0; i != NumElts; ++i)
17242       LMask[i] = i;
17243   }
17244
17245   // Likewise, view RHS in the form
17246   //   RHS = VECTOR_SHUFFLE C, D, RMask
17247   SDValue C, D;
17248   SmallVector<int, 16> RMask(NumElts);
17249   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
17250     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
17251       C = RHS.getOperand(0);
17252     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
17253       D = RHS.getOperand(1);
17254     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
17255     std::copy(Mask.begin(), Mask.end(), RMask.begin());
17256   } else {
17257     if (RHS.getOpcode() != ISD::UNDEF)
17258       C = RHS;
17259     for (unsigned i = 0; i != NumElts; ++i)
17260       RMask[i] = i;
17261   }
17262
17263   // Check that the shuffles are both shuffling the same vectors.
17264   if (!(A == C && B == D) && !(A == D && B == C))
17265     return false;
17266
17267   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
17268   if (!A.getNode() && !B.getNode())
17269     return false;
17270
17271   // If A and B occur in reverse order in RHS, then "swap" them (which means
17272   // rewriting the mask).
17273   if (A != C)
17274     CommuteVectorShuffleMask(RMask, NumElts);
17275
17276   // At this point LHS and RHS are equivalent to
17277   //   LHS = VECTOR_SHUFFLE A, B, LMask
17278   //   RHS = VECTOR_SHUFFLE A, B, RMask
17279   // Check that the masks correspond to performing a horizontal operation.
17280   for (unsigned i = 0; i != NumElts; ++i) {
17281     int LIdx = LMask[i], RIdx = RMask[i];
17282
17283     // Ignore any UNDEF components.
17284     if (LIdx < 0 || RIdx < 0 ||
17285         (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
17286         (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
17287       continue;
17288
17289     // Check that successive elements are being operated on.  If not, this is
17290     // not a horizontal operation.
17291     unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
17292     unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
17293     int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
17294     if (!(LIdx == Index && RIdx == Index + 1) &&
17295         !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
17296       return false;
17297   }
17298
17299   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
17300   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
17301   return true;
17302 }
17303
17304 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
17305 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
17306                                   const X86Subtarget *Subtarget) {
17307   EVT VT = N->getValueType(0);
17308   SDValue LHS = N->getOperand(0);
17309   SDValue RHS = N->getOperand(1);
17310
17311   // Try to synthesize horizontal adds from adds of shuffles.
17312   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
17313        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
17314       isHorizontalBinOp(LHS, RHS, true))
17315     return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
17316   return SDValue();
17317 }
17318
17319 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
17320 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
17321                                   const X86Subtarget *Subtarget) {
17322   EVT VT = N->getValueType(0);
17323   SDValue LHS = N->getOperand(0);
17324   SDValue RHS = N->getOperand(1);
17325
17326   // Try to synthesize horizontal subs from subs of shuffles.
17327   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
17328        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
17329       isHorizontalBinOp(LHS, RHS, false))
17330     return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
17331   return SDValue();
17332 }
17333
17334 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
17335 /// X86ISD::FXOR nodes.
17336 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
17337   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
17338   // F[X]OR(0.0, x) -> x
17339   // F[X]OR(x, 0.0) -> x
17340   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
17341     if (C->getValueAPF().isPosZero())
17342       return N->getOperand(1);
17343   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
17344     if (C->getValueAPF().isPosZero())
17345       return N->getOperand(0);
17346   return SDValue();
17347 }
17348
17349 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
17350 /// X86ISD::FMAX nodes.
17351 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
17352   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
17353
17354   // Only perform optimizations if UnsafeMath is used.
17355   if (!DAG.getTarget().Options.UnsafeFPMath)
17356     return SDValue();
17357
17358   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
17359   // into FMINC and FMAXC, which are Commutative operations.
17360   unsigned NewOp = 0;
17361   switch (N->getOpcode()) {
17362     default: llvm_unreachable("unknown opcode");
17363     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
17364     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
17365   }
17366
17367   return DAG.getNode(NewOp, N->getDebugLoc(), N->getValueType(0),
17368                      N->getOperand(0), N->getOperand(1));
17369 }
17370
17371 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
17372 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
17373   // FAND(0.0, x) -> 0.0
17374   // FAND(x, 0.0) -> 0.0
17375   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
17376     if (C->getValueAPF().isPosZero())
17377       return N->getOperand(0);
17378   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
17379     if (C->getValueAPF().isPosZero())
17380       return N->getOperand(1);
17381   return SDValue();
17382 }
17383
17384 static SDValue PerformBTCombine(SDNode *N,
17385                                 SelectionDAG &DAG,
17386                                 TargetLowering::DAGCombinerInfo &DCI) {
17387   // BT ignores high bits in the bit index operand.
17388   SDValue Op1 = N->getOperand(1);
17389   if (Op1.hasOneUse()) {
17390     unsigned BitWidth = Op1.getValueSizeInBits();
17391     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
17392     APInt KnownZero, KnownOne;
17393     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
17394                                           !DCI.isBeforeLegalizeOps());
17395     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17396     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
17397         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
17398       DCI.CommitTargetLoweringOpt(TLO);
17399   }
17400   return SDValue();
17401 }
17402
17403 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
17404   SDValue Op = N->getOperand(0);
17405   if (Op.getOpcode() == ISD::BITCAST)
17406     Op = Op.getOperand(0);
17407   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
17408   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
17409       VT.getVectorElementType().getSizeInBits() ==
17410       OpVT.getVectorElementType().getSizeInBits()) {
17411     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
17412   }
17413   return SDValue();
17414 }
17415
17416 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG, 
17417                                                const X86Subtarget *Subtarget) {
17418   EVT VT = N->getValueType(0);
17419   if (!VT.isVector())
17420     return SDValue();
17421
17422   SDValue N0 = N->getOperand(0);
17423   SDValue N1 = N->getOperand(1);
17424   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
17425   DebugLoc dl = N->getDebugLoc();
17426
17427   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
17428   // both SSE and AVX2 since there is no sign-extended shift right
17429   // operation on a vector with 64-bit elements.
17430   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
17431   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
17432   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
17433       N0.getOpcode() == ISD::SIGN_EXTEND)) {
17434     SDValue N00 = N0.getOperand(0);
17435
17436     // EXTLOAD has a better solution on AVX2, 
17437     // it may be replaced with X86ISD::VSEXT node.
17438     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
17439       if (!ISD::isNormalLoad(N00.getNode()))
17440         return SDValue();
17441
17442     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
17443         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, 
17444                                   N00, N1);
17445       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
17446     }
17447   }
17448   return SDValue();
17449 }
17450
17451 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
17452                                   TargetLowering::DAGCombinerInfo &DCI,
17453                                   const X86Subtarget *Subtarget) {
17454   if (!DCI.isBeforeLegalizeOps())
17455     return SDValue();
17456
17457   if (!Subtarget->hasFp256())
17458     return SDValue();
17459
17460   EVT VT = N->getValueType(0);
17461   if (VT.isVector() && VT.getSizeInBits() == 256) {
17462     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
17463     if (R.getNode())
17464       return R;
17465   }
17466
17467   return SDValue();
17468 }
17469
17470 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
17471                                  const X86Subtarget* Subtarget) {
17472   DebugLoc dl = N->getDebugLoc();
17473   EVT VT = N->getValueType(0);
17474
17475   // Let legalize expand this if it isn't a legal type yet.
17476   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
17477     return SDValue();
17478
17479   EVT ScalarVT = VT.getScalarType();
17480   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
17481       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
17482     return SDValue();
17483
17484   SDValue A = N->getOperand(0);
17485   SDValue B = N->getOperand(1);
17486   SDValue C = N->getOperand(2);
17487
17488   bool NegA = (A.getOpcode() == ISD::FNEG);
17489   bool NegB = (B.getOpcode() == ISD::FNEG);
17490   bool NegC = (C.getOpcode() == ISD::FNEG);
17491
17492   // Negative multiplication when NegA xor NegB
17493   bool NegMul = (NegA != NegB);
17494   if (NegA)
17495     A = A.getOperand(0);
17496   if (NegB)
17497     B = B.getOperand(0);
17498   if (NegC)
17499     C = C.getOperand(0);
17500
17501   unsigned Opcode;
17502   if (!NegMul)
17503     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
17504   else
17505     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
17506
17507   return DAG.getNode(Opcode, dl, VT, A, B, C);
17508 }
17509
17510 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
17511                                   TargetLowering::DAGCombinerInfo &DCI,
17512                                   const X86Subtarget *Subtarget) {
17513   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
17514   //           (and (i32 x86isd::setcc_carry), 1)
17515   // This eliminates the zext. This transformation is necessary because
17516   // ISD::SETCC is always legalized to i8.
17517   DebugLoc dl = N->getDebugLoc();
17518   SDValue N0 = N->getOperand(0);
17519   EVT VT = N->getValueType(0);
17520
17521   if (N0.getOpcode() == ISD::AND &&
17522       N0.hasOneUse() &&
17523       N0.getOperand(0).hasOneUse()) {
17524     SDValue N00 = N0.getOperand(0);
17525     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
17526       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
17527       if (!C || C->getZExtValue() != 1)
17528         return SDValue();
17529       return DAG.getNode(ISD::AND, dl, VT,
17530                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
17531                                      N00.getOperand(0), N00.getOperand(1)),
17532                          DAG.getConstant(1, VT));
17533     }
17534   }
17535
17536   if (VT.is256BitVector()) {
17537     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
17538     if (R.getNode())
17539       return R;
17540   }
17541
17542   return SDValue();
17543 }
17544
17545 // Optimize x == -y --> x+y == 0
17546 //          x != -y --> x+y != 0
17547 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
17548   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
17549   SDValue LHS = N->getOperand(0);
17550   SDValue RHS = N->getOperand(1);
17551
17552   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
17553     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
17554       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
17555         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
17556                                    LHS.getValueType(), RHS, LHS.getOperand(1));
17557         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
17558                             addV, DAG.getConstant(0, addV.getValueType()), CC);
17559       }
17560   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
17561     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
17562       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
17563         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
17564                                    RHS.getValueType(), LHS, RHS.getOperand(1));
17565         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
17566                             addV, DAG.getConstant(0, addV.getValueType()), CC);
17567       }
17568   return SDValue();
17569 }
17570
17571 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
17572 // as "sbb reg,reg", since it can be extended without zext and produces
17573 // an all-ones bit which is more useful than 0/1 in some cases.
17574 static SDValue MaterializeSETB(DebugLoc DL, SDValue EFLAGS, SelectionDAG &DAG) {
17575   return DAG.getNode(ISD::AND, DL, MVT::i8,
17576                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
17577                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
17578                      DAG.getConstant(1, MVT::i8));
17579 }
17580
17581 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
17582 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
17583                                    TargetLowering::DAGCombinerInfo &DCI,
17584                                    const X86Subtarget *Subtarget) {
17585   DebugLoc DL = N->getDebugLoc();
17586   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
17587   SDValue EFLAGS = N->getOperand(1);
17588
17589   if (CC == X86::COND_A) {
17590     // Try to convert COND_A into COND_B in an attempt to facilitate
17591     // materializing "setb reg".
17592     //
17593     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
17594     // cannot take an immediate as its first operand.
17595     //
17596     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
17597         EFLAGS.getValueType().isInteger() &&
17598         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
17599       SDValue NewSub = DAG.getNode(X86ISD::SUB, EFLAGS.getDebugLoc(),
17600                                    EFLAGS.getNode()->getVTList(),
17601                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
17602       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
17603       return MaterializeSETB(DL, NewEFLAGS, DAG);
17604     }
17605   }
17606
17607   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
17608   // a zext and produces an all-ones bit which is more useful than 0/1 in some
17609   // cases.
17610   if (CC == X86::COND_B)
17611     return MaterializeSETB(DL, EFLAGS, DAG);
17612
17613   SDValue Flags;
17614
17615   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
17616   if (Flags.getNode()) {
17617     SDValue Cond = DAG.getConstant(CC, MVT::i8);
17618     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
17619   }
17620
17621   return SDValue();
17622 }
17623
17624 // Optimize branch condition evaluation.
17625 //
17626 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
17627                                     TargetLowering::DAGCombinerInfo &DCI,
17628                                     const X86Subtarget *Subtarget) {
17629   DebugLoc DL = N->getDebugLoc();
17630   SDValue Chain = N->getOperand(0);
17631   SDValue Dest = N->getOperand(1);
17632   SDValue EFLAGS = N->getOperand(3);
17633   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
17634
17635   SDValue Flags;
17636
17637   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
17638   if (Flags.getNode()) {
17639     SDValue Cond = DAG.getConstant(CC, MVT::i8);
17640     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
17641                        Flags);
17642   }
17643
17644   return SDValue();
17645 }
17646
17647 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
17648                                         const X86TargetLowering *XTLI) {
17649   SDValue Op0 = N->getOperand(0);
17650   EVT InVT = Op0->getValueType(0);
17651
17652   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
17653   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
17654     DebugLoc dl = N->getDebugLoc();
17655     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
17656     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
17657     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
17658   }
17659
17660   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
17661   // a 32-bit target where SSE doesn't support i64->FP operations.
17662   if (Op0.getOpcode() == ISD::LOAD) {
17663     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
17664     EVT VT = Ld->getValueType(0);
17665     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
17666         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
17667         !XTLI->getSubtarget()->is64Bit() &&
17668         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
17669       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
17670                                           Ld->getChain(), Op0, DAG);
17671       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
17672       return FILDChain;
17673     }
17674   }
17675   return SDValue();
17676 }
17677
17678 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
17679 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
17680                                  X86TargetLowering::DAGCombinerInfo &DCI) {
17681   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
17682   // the result is either zero or one (depending on the input carry bit).
17683   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
17684   if (X86::isZeroNode(N->getOperand(0)) &&
17685       X86::isZeroNode(N->getOperand(1)) &&
17686       // We don't have a good way to replace an EFLAGS use, so only do this when
17687       // dead right now.
17688       SDValue(N, 1).use_empty()) {
17689     DebugLoc DL = N->getDebugLoc();
17690     EVT VT = N->getValueType(0);
17691     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
17692     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
17693                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
17694                                            DAG.getConstant(X86::COND_B,MVT::i8),
17695                                            N->getOperand(2)),
17696                                DAG.getConstant(1, VT));
17697     return DCI.CombineTo(N, Res1, CarryOut);
17698   }
17699
17700   return SDValue();
17701 }
17702
17703 // fold (add Y, (sete  X, 0)) -> adc  0, Y
17704 //      (add Y, (setne X, 0)) -> sbb -1, Y
17705 //      (sub (sete  X, 0), Y) -> sbb  0, Y
17706 //      (sub (setne X, 0), Y) -> adc -1, Y
17707 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
17708   DebugLoc DL = N->getDebugLoc();
17709
17710   // Look through ZExts.
17711   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
17712   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
17713     return SDValue();
17714
17715   SDValue SetCC = Ext.getOperand(0);
17716   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
17717     return SDValue();
17718
17719   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
17720   if (CC != X86::COND_E && CC != X86::COND_NE)
17721     return SDValue();
17722
17723   SDValue Cmp = SetCC.getOperand(1);
17724   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
17725       !X86::isZeroNode(Cmp.getOperand(1)) ||
17726       !Cmp.getOperand(0).getValueType().isInteger())
17727     return SDValue();
17728
17729   SDValue CmpOp0 = Cmp.getOperand(0);
17730   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
17731                                DAG.getConstant(1, CmpOp0.getValueType()));
17732
17733   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
17734   if (CC == X86::COND_NE)
17735     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
17736                        DL, OtherVal.getValueType(), OtherVal,
17737                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
17738   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
17739                      DL, OtherVal.getValueType(), OtherVal,
17740                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
17741 }
17742
17743 /// PerformADDCombine - Do target-specific dag combines on integer adds.
17744 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
17745                                  const X86Subtarget *Subtarget) {
17746   EVT VT = N->getValueType(0);
17747   SDValue Op0 = N->getOperand(0);
17748   SDValue Op1 = N->getOperand(1);
17749
17750   // Try to synthesize horizontal adds from adds of shuffles.
17751   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
17752        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
17753       isHorizontalBinOp(Op0, Op1, true))
17754     return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
17755
17756   return OptimizeConditionalInDecrement(N, DAG);
17757 }
17758
17759 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
17760                                  const X86Subtarget *Subtarget) {
17761   SDValue Op0 = N->getOperand(0);
17762   SDValue Op1 = N->getOperand(1);
17763
17764   // X86 can't encode an immediate LHS of a sub. See if we can push the
17765   // negation into a preceding instruction.
17766   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
17767     // If the RHS of the sub is a XOR with one use and a constant, invert the
17768     // immediate. Then add one to the LHS of the sub so we can turn
17769     // X-Y -> X+~Y+1, saving one register.
17770     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
17771         isa<ConstantSDNode>(Op1.getOperand(1))) {
17772       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
17773       EVT VT = Op0.getValueType();
17774       SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
17775                                    Op1.getOperand(0),
17776                                    DAG.getConstant(~XorC, VT));
17777       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
17778                          DAG.getConstant(C->getAPIntValue()+1, VT));
17779     }
17780   }
17781
17782   // Try to synthesize horizontal adds from adds of shuffles.
17783   EVT VT = N->getValueType(0);
17784   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
17785        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
17786       isHorizontalBinOp(Op0, Op1, true))
17787     return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
17788
17789   return OptimizeConditionalInDecrement(N, DAG);
17790 }
17791
17792 /// performVZEXTCombine - Performs build vector combines
17793 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
17794                                         TargetLowering::DAGCombinerInfo &DCI,
17795                                         const X86Subtarget *Subtarget) {
17796   // (vzext (bitcast (vzext (x)) -> (vzext x)
17797   SDValue In = N->getOperand(0);
17798   while (In.getOpcode() == ISD::BITCAST)
17799     In = In.getOperand(0);
17800
17801   if (In.getOpcode() != X86ISD::VZEXT)
17802     return SDValue();
17803
17804   return DAG.getNode(X86ISD::VZEXT, N->getDebugLoc(), N->getValueType(0),
17805                      In.getOperand(0));
17806 }
17807
17808 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
17809                                              DAGCombinerInfo &DCI) const {
17810   SelectionDAG &DAG = DCI.DAG;
17811   switch (N->getOpcode()) {
17812   default: break;
17813   case ISD::EXTRACT_VECTOR_ELT:
17814     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
17815   case ISD::VSELECT:
17816   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
17817   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
17818   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
17819   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
17820   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
17821   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
17822   case ISD::SHL:
17823   case ISD::SRA:
17824   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
17825   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
17826   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
17827   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
17828   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
17829   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
17830   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
17831   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
17832   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
17833   case X86ISD::FXOR:
17834   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
17835   case X86ISD::FMIN:
17836   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
17837   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
17838   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
17839   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
17840   case ISD::ANY_EXTEND:
17841   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
17842   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
17843   case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
17844   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
17845   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG);
17846   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
17847   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
17848   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
17849   case X86ISD::SHUFP:       // Handle all target specific shuffles
17850   case X86ISD::PALIGNR:
17851   case X86ISD::UNPCKH:
17852   case X86ISD::UNPCKL:
17853   case X86ISD::MOVHLPS:
17854   case X86ISD::MOVLHPS:
17855   case X86ISD::PSHUFD:
17856   case X86ISD::PSHUFHW:
17857   case X86ISD::PSHUFLW:
17858   case X86ISD::MOVSS:
17859   case X86ISD::MOVSD:
17860   case X86ISD::VPERMILP:
17861   case X86ISD::VPERM2X128:
17862   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
17863   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
17864   }
17865
17866   return SDValue();
17867 }
17868
17869 /// isTypeDesirableForOp - Return true if the target has native support for
17870 /// the specified value type and it is 'desirable' to use the type for the
17871 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
17872 /// instruction encodings are longer and some i16 instructions are slow.
17873 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
17874   if (!isTypeLegal(VT))
17875     return false;
17876   if (VT != MVT::i16)
17877     return true;
17878
17879   switch (Opc) {
17880   default:
17881     return true;
17882   case ISD::LOAD:
17883   case ISD::SIGN_EXTEND:
17884   case ISD::ZERO_EXTEND:
17885   case ISD::ANY_EXTEND:
17886   case ISD::SHL:
17887   case ISD::SRL:
17888   case ISD::SUB:
17889   case ISD::ADD:
17890   case ISD::MUL:
17891   case ISD::AND:
17892   case ISD::OR:
17893   case ISD::XOR:
17894     return false;
17895   }
17896 }
17897
17898 /// IsDesirableToPromoteOp - This method query the target whether it is
17899 /// beneficial for dag combiner to promote the specified node. If true, it
17900 /// should return the desired promotion type by reference.
17901 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
17902   EVT VT = Op.getValueType();
17903   if (VT != MVT::i16)
17904     return false;
17905
17906   bool Promote = false;
17907   bool Commute = false;
17908   switch (Op.getOpcode()) {
17909   default: break;
17910   case ISD::LOAD: {
17911     LoadSDNode *LD = cast<LoadSDNode>(Op);
17912     // If the non-extending load has a single use and it's not live out, then it
17913     // might be folded.
17914     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
17915                                                      Op.hasOneUse()*/) {
17916       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
17917              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
17918         // The only case where we'd want to promote LOAD (rather then it being
17919         // promoted as an operand is when it's only use is liveout.
17920         if (UI->getOpcode() != ISD::CopyToReg)
17921           return false;
17922       }
17923     }
17924     Promote = true;
17925     break;
17926   }
17927   case ISD::SIGN_EXTEND:
17928   case ISD::ZERO_EXTEND:
17929   case ISD::ANY_EXTEND:
17930     Promote = true;
17931     break;
17932   case ISD::SHL:
17933   case ISD::SRL: {
17934     SDValue N0 = Op.getOperand(0);
17935     // Look out for (store (shl (load), x)).
17936     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
17937       return false;
17938     Promote = true;
17939     break;
17940   }
17941   case ISD::ADD:
17942   case ISD::MUL:
17943   case ISD::AND:
17944   case ISD::OR:
17945   case ISD::XOR:
17946     Commute = true;
17947     // fallthrough
17948   case ISD::SUB: {
17949     SDValue N0 = Op.getOperand(0);
17950     SDValue N1 = Op.getOperand(1);
17951     if (!Commute && MayFoldLoad(N1))
17952       return false;
17953     // Avoid disabling potential load folding opportunities.
17954     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
17955       return false;
17956     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
17957       return false;
17958     Promote = true;
17959   }
17960   }
17961
17962   PVT = MVT::i32;
17963   return Promote;
17964 }
17965
17966 //===----------------------------------------------------------------------===//
17967 //                           X86 Inline Assembly Support
17968 //===----------------------------------------------------------------------===//
17969
17970 namespace {
17971   // Helper to match a string separated by whitespace.
17972   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
17973     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
17974
17975     for (unsigned i = 0, e = args.size(); i != e; ++i) {
17976       StringRef piece(*args[i]);
17977       if (!s.startswith(piece)) // Check if the piece matches.
17978         return false;
17979
17980       s = s.substr(piece.size());
17981       StringRef::size_type pos = s.find_first_not_of(" \t");
17982       if (pos == 0) // We matched a prefix.
17983         return false;
17984
17985       s = s.substr(pos);
17986     }
17987
17988     return s.empty();
17989   }
17990   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
17991 }
17992
17993 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
17994   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
17995
17996   std::string AsmStr = IA->getAsmString();
17997
17998   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
17999   if (!Ty || Ty->getBitWidth() % 16 != 0)
18000     return false;
18001
18002   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
18003   SmallVector<StringRef, 4> AsmPieces;
18004   SplitString(AsmStr, AsmPieces, ";\n");
18005
18006   switch (AsmPieces.size()) {
18007   default: return false;
18008   case 1:
18009     // FIXME: this should verify that we are targeting a 486 or better.  If not,
18010     // we will turn this bswap into something that will be lowered to logical
18011     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
18012     // lower so don't worry about this.
18013     // bswap $0
18014     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
18015         matchAsm(AsmPieces[0], "bswapl", "$0") ||
18016         matchAsm(AsmPieces[0], "bswapq", "$0") ||
18017         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
18018         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
18019         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
18020       // No need to check constraints, nothing other than the equivalent of
18021       // "=r,0" would be valid here.
18022       return IntrinsicLowering::LowerToByteSwap(CI);
18023     }
18024
18025     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
18026     if (CI->getType()->isIntegerTy(16) &&
18027         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
18028         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
18029          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
18030       AsmPieces.clear();
18031       const std::string &ConstraintsStr = IA->getConstraintString();
18032       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
18033       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
18034       if (AsmPieces.size() == 4 &&
18035           AsmPieces[0] == "~{cc}" &&
18036           AsmPieces[1] == "~{dirflag}" &&
18037           AsmPieces[2] == "~{flags}" &&
18038           AsmPieces[3] == "~{fpsr}")
18039       return IntrinsicLowering::LowerToByteSwap(CI);
18040     }
18041     break;
18042   case 3:
18043     if (CI->getType()->isIntegerTy(32) &&
18044         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
18045         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
18046         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
18047         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
18048       AsmPieces.clear();
18049       const std::string &ConstraintsStr = IA->getConstraintString();
18050       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
18051       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
18052       if (AsmPieces.size() == 4 &&
18053           AsmPieces[0] == "~{cc}" &&
18054           AsmPieces[1] == "~{dirflag}" &&
18055           AsmPieces[2] == "~{flags}" &&
18056           AsmPieces[3] == "~{fpsr}")
18057         return IntrinsicLowering::LowerToByteSwap(CI);
18058     }
18059
18060     if (CI->getType()->isIntegerTy(64)) {
18061       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
18062       if (Constraints.size() >= 2 &&
18063           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
18064           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
18065         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
18066         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
18067             matchAsm(AsmPieces[1], "bswap", "%edx") &&
18068             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
18069           return IntrinsicLowering::LowerToByteSwap(CI);
18070       }
18071     }
18072     break;
18073   }
18074   return false;
18075 }
18076
18077 /// getConstraintType - Given a constraint letter, return the type of
18078 /// constraint it is for this target.
18079 X86TargetLowering::ConstraintType
18080 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
18081   if (Constraint.size() == 1) {
18082     switch (Constraint[0]) {
18083     case 'R':
18084     case 'q':
18085     case 'Q':
18086     case 'f':
18087     case 't':
18088     case 'u':
18089     case 'y':
18090     case 'x':
18091     case 'Y':
18092     case 'l':
18093       return C_RegisterClass;
18094     case 'a':
18095     case 'b':
18096     case 'c':
18097     case 'd':
18098     case 'S':
18099     case 'D':
18100     case 'A':
18101       return C_Register;
18102     case 'I':
18103     case 'J':
18104     case 'K':
18105     case 'L':
18106     case 'M':
18107     case 'N':
18108     case 'G':
18109     case 'C':
18110     case 'e':
18111     case 'Z':
18112       return C_Other;
18113     default:
18114       break;
18115     }
18116   }
18117   return TargetLowering::getConstraintType(Constraint);
18118 }
18119
18120 /// Examine constraint type and operand type and determine a weight value.
18121 /// This object must already have been set up with the operand type
18122 /// and the current alternative constraint selected.
18123 TargetLowering::ConstraintWeight
18124   X86TargetLowering::getSingleConstraintMatchWeight(
18125     AsmOperandInfo &info, const char *constraint) const {
18126   ConstraintWeight weight = CW_Invalid;
18127   Value *CallOperandVal = info.CallOperandVal;
18128     // If we don't have a value, we can't do a match,
18129     // but allow it at the lowest weight.
18130   if (CallOperandVal == NULL)
18131     return CW_Default;
18132   Type *type = CallOperandVal->getType();
18133   // Look at the constraint type.
18134   switch (*constraint) {
18135   default:
18136     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
18137   case 'R':
18138   case 'q':
18139   case 'Q':
18140   case 'a':
18141   case 'b':
18142   case 'c':
18143   case 'd':
18144   case 'S':
18145   case 'D':
18146   case 'A':
18147     if (CallOperandVal->getType()->isIntegerTy())
18148       weight = CW_SpecificReg;
18149     break;
18150   case 'f':
18151   case 't':
18152   case 'u':
18153     if (type->isFloatingPointTy())
18154       weight = CW_SpecificReg;
18155     break;
18156   case 'y':
18157     if (type->isX86_MMXTy() && Subtarget->hasMMX())
18158       weight = CW_SpecificReg;
18159     break;
18160   case 'x':
18161   case 'Y':
18162     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
18163         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
18164       weight = CW_Register;
18165     break;
18166   case 'I':
18167     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
18168       if (C->getZExtValue() <= 31)
18169         weight = CW_Constant;
18170     }
18171     break;
18172   case 'J':
18173     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18174       if (C->getZExtValue() <= 63)
18175         weight = CW_Constant;
18176     }
18177     break;
18178   case 'K':
18179     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18180       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
18181         weight = CW_Constant;
18182     }
18183     break;
18184   case 'L':
18185     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18186       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
18187         weight = CW_Constant;
18188     }
18189     break;
18190   case 'M':
18191     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18192       if (C->getZExtValue() <= 3)
18193         weight = CW_Constant;
18194     }
18195     break;
18196   case 'N':
18197     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18198       if (C->getZExtValue() <= 0xff)
18199         weight = CW_Constant;
18200     }
18201     break;
18202   case 'G':
18203   case 'C':
18204     if (dyn_cast<ConstantFP>(CallOperandVal)) {
18205       weight = CW_Constant;
18206     }
18207     break;
18208   case 'e':
18209     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18210       if ((C->getSExtValue() >= -0x80000000LL) &&
18211           (C->getSExtValue() <= 0x7fffffffLL))
18212         weight = CW_Constant;
18213     }
18214     break;
18215   case 'Z':
18216     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18217       if (C->getZExtValue() <= 0xffffffff)
18218         weight = CW_Constant;
18219     }
18220     break;
18221   }
18222   return weight;
18223 }
18224
18225 /// LowerXConstraint - try to replace an X constraint, which matches anything,
18226 /// with another that has more specific requirements based on the type of the
18227 /// corresponding operand.
18228 const char *X86TargetLowering::
18229 LowerXConstraint(EVT ConstraintVT) const {
18230   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
18231   // 'f' like normal targets.
18232   if (ConstraintVT.isFloatingPoint()) {
18233     if (Subtarget->hasSSE2())
18234       return "Y";
18235     if (Subtarget->hasSSE1())
18236       return "x";
18237   }
18238
18239   return TargetLowering::LowerXConstraint(ConstraintVT);
18240 }
18241
18242 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
18243 /// vector.  If it is invalid, don't add anything to Ops.
18244 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
18245                                                      std::string &Constraint,
18246                                                      std::vector<SDValue>&Ops,
18247                                                      SelectionDAG &DAG) const {
18248   SDValue Result(0, 0);
18249
18250   // Only support length 1 constraints for now.
18251   if (Constraint.length() > 1) return;
18252
18253   char ConstraintLetter = Constraint[0];
18254   switch (ConstraintLetter) {
18255   default: break;
18256   case 'I':
18257     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18258       if (C->getZExtValue() <= 31) {
18259         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18260         break;
18261       }
18262     }
18263     return;
18264   case 'J':
18265     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18266       if (C->getZExtValue() <= 63) {
18267         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18268         break;
18269       }
18270     }
18271     return;
18272   case 'K':
18273     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18274       if (isInt<8>(C->getSExtValue())) {
18275         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18276         break;
18277       }
18278     }
18279     return;
18280   case 'N':
18281     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18282       if (C->getZExtValue() <= 255) {
18283         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18284         break;
18285       }
18286     }
18287     return;
18288   case 'e': {
18289     // 32-bit signed value
18290     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18291       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
18292                                            C->getSExtValue())) {
18293         // Widen to 64 bits here to get it sign extended.
18294         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
18295         break;
18296       }
18297     // FIXME gcc accepts some relocatable values here too, but only in certain
18298     // memory models; it's complicated.
18299     }
18300     return;
18301   }
18302   case 'Z': {
18303     // 32-bit unsigned value
18304     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18305       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
18306                                            C->getZExtValue())) {
18307         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18308         break;
18309       }
18310     }
18311     // FIXME gcc accepts some relocatable values here too, but only in certain
18312     // memory models; it's complicated.
18313     return;
18314   }
18315   case 'i': {
18316     // Literal immediates are always ok.
18317     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
18318       // Widen to 64 bits here to get it sign extended.
18319       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
18320       break;
18321     }
18322
18323     // In any sort of PIC mode addresses need to be computed at runtime by
18324     // adding in a register or some sort of table lookup.  These can't
18325     // be used as immediates.
18326     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
18327       return;
18328
18329     // If we are in non-pic codegen mode, we allow the address of a global (with
18330     // an optional displacement) to be used with 'i'.
18331     GlobalAddressSDNode *GA = 0;
18332     int64_t Offset = 0;
18333
18334     // Match either (GA), (GA+C), (GA+C1+C2), etc.
18335     while (1) {
18336       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
18337         Offset += GA->getOffset();
18338         break;
18339       } else if (Op.getOpcode() == ISD::ADD) {
18340         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
18341           Offset += C->getZExtValue();
18342           Op = Op.getOperand(0);
18343           continue;
18344         }
18345       } else if (Op.getOpcode() == ISD::SUB) {
18346         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
18347           Offset += -C->getZExtValue();
18348           Op = Op.getOperand(0);
18349           continue;
18350         }
18351       }
18352
18353       // Otherwise, this isn't something we can handle, reject it.
18354       return;
18355     }
18356
18357     const GlobalValue *GV = GA->getGlobal();
18358     // If we require an extra load to get this address, as in PIC mode, we
18359     // can't accept it.
18360     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
18361                                                         getTargetMachine())))
18362       return;
18363
18364     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
18365                                         GA->getValueType(0), Offset);
18366     break;
18367   }
18368   }
18369
18370   if (Result.getNode()) {
18371     Ops.push_back(Result);
18372     return;
18373   }
18374   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
18375 }
18376
18377 std::pair<unsigned, const TargetRegisterClass*>
18378 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
18379                                                 EVT VT) const {
18380   // First, see if this is a constraint that directly corresponds to an LLVM
18381   // register class.
18382   if (Constraint.size() == 1) {
18383     // GCC Constraint Letters
18384     switch (Constraint[0]) {
18385     default: break;
18386       // TODO: Slight differences here in allocation order and leaving
18387       // RIP in the class. Do they matter any more here than they do
18388       // in the normal allocation?
18389     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
18390       if (Subtarget->is64Bit()) {
18391         if (VT == MVT::i32 || VT == MVT::f32)
18392           return std::make_pair(0U, &X86::GR32RegClass);
18393         if (VT == MVT::i16)
18394           return std::make_pair(0U, &X86::GR16RegClass);
18395         if (VT == MVT::i8 || VT == MVT::i1)
18396           return std::make_pair(0U, &X86::GR8RegClass);
18397         if (VT == MVT::i64 || VT == MVT::f64)
18398           return std::make_pair(0U, &X86::GR64RegClass);
18399         break;
18400       }
18401       // 32-bit fallthrough
18402     case 'Q':   // Q_REGS
18403       if (VT == MVT::i32 || VT == MVT::f32)
18404         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
18405       if (VT == MVT::i16)
18406         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
18407       if (VT == MVT::i8 || VT == MVT::i1)
18408         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
18409       if (VT == MVT::i64)
18410         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
18411       break;
18412     case 'r':   // GENERAL_REGS
18413     case 'l':   // INDEX_REGS
18414       if (VT == MVT::i8 || VT == MVT::i1)
18415         return std::make_pair(0U, &X86::GR8RegClass);
18416       if (VT == MVT::i16)
18417         return std::make_pair(0U, &X86::GR16RegClass);
18418       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
18419         return std::make_pair(0U, &X86::GR32RegClass);
18420       return std::make_pair(0U, &X86::GR64RegClass);
18421     case 'R':   // LEGACY_REGS
18422       if (VT == MVT::i8 || VT == MVT::i1)
18423         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
18424       if (VT == MVT::i16)
18425         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
18426       if (VT == MVT::i32 || !Subtarget->is64Bit())
18427         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
18428       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
18429     case 'f':  // FP Stack registers.
18430       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
18431       // value to the correct fpstack register class.
18432       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
18433         return std::make_pair(0U, &X86::RFP32RegClass);
18434       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
18435         return std::make_pair(0U, &X86::RFP64RegClass);
18436       return std::make_pair(0U, &X86::RFP80RegClass);
18437     case 'y':   // MMX_REGS if MMX allowed.
18438       if (!Subtarget->hasMMX()) break;
18439       return std::make_pair(0U, &X86::VR64RegClass);
18440     case 'Y':   // SSE_REGS if SSE2 allowed
18441       if (!Subtarget->hasSSE2()) break;
18442       // FALL THROUGH.
18443     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
18444       if (!Subtarget->hasSSE1()) break;
18445
18446       switch (VT.getSimpleVT().SimpleTy) {
18447       default: break;
18448       // Scalar SSE types.
18449       case MVT::f32:
18450       case MVT::i32:
18451         return std::make_pair(0U, &X86::FR32RegClass);
18452       case MVT::f64:
18453       case MVT::i64:
18454         return std::make_pair(0U, &X86::FR64RegClass);
18455       // Vector types.
18456       case MVT::v16i8:
18457       case MVT::v8i16:
18458       case MVT::v4i32:
18459       case MVT::v2i64:
18460       case MVT::v4f32:
18461       case MVT::v2f64:
18462         return std::make_pair(0U, &X86::VR128RegClass);
18463       // AVX types.
18464       case MVT::v32i8:
18465       case MVT::v16i16:
18466       case MVT::v8i32:
18467       case MVT::v4i64:
18468       case MVT::v8f32:
18469       case MVT::v4f64:
18470         return std::make_pair(0U, &X86::VR256RegClass);
18471       }
18472       break;
18473     }
18474   }
18475
18476   // Use the default implementation in TargetLowering to convert the register
18477   // constraint into a member of a register class.
18478   std::pair<unsigned, const TargetRegisterClass*> Res;
18479   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
18480
18481   // Not found as a standard register?
18482   if (Res.second == 0) {
18483     // Map st(0) -> st(7) -> ST0
18484     if (Constraint.size() == 7 && Constraint[0] == '{' &&
18485         tolower(Constraint[1]) == 's' &&
18486         tolower(Constraint[2]) == 't' &&
18487         Constraint[3] == '(' &&
18488         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
18489         Constraint[5] == ')' &&
18490         Constraint[6] == '}') {
18491
18492       Res.first = X86::ST0+Constraint[4]-'0';
18493       Res.second = &X86::RFP80RegClass;
18494       return Res;
18495     }
18496
18497     // GCC allows "st(0)" to be called just plain "st".
18498     if (StringRef("{st}").equals_lower(Constraint)) {
18499       Res.first = X86::ST0;
18500       Res.second = &X86::RFP80RegClass;
18501       return Res;
18502     }
18503
18504     // flags -> EFLAGS
18505     if (StringRef("{flags}").equals_lower(Constraint)) {
18506       Res.first = X86::EFLAGS;
18507       Res.second = &X86::CCRRegClass;
18508       return Res;
18509     }
18510
18511     // 'A' means EAX + EDX.
18512     if (Constraint == "A") {
18513       Res.first = X86::EAX;
18514       Res.second = &X86::GR32_ADRegClass;
18515       return Res;
18516     }
18517     return Res;
18518   }
18519
18520   // Otherwise, check to see if this is a register class of the wrong value
18521   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
18522   // turn into {ax},{dx}.
18523   if (Res.second->hasType(VT))
18524     return Res;   // Correct type already, nothing to do.
18525
18526   // All of the single-register GCC register classes map their values onto
18527   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
18528   // really want an 8-bit or 32-bit register, map to the appropriate register
18529   // class and return the appropriate register.
18530   if (Res.second == &X86::GR16RegClass) {
18531     if (VT == MVT::i8 || VT == MVT::i1) {
18532       unsigned DestReg = 0;
18533       switch (Res.first) {
18534       default: break;
18535       case X86::AX: DestReg = X86::AL; break;
18536       case X86::DX: DestReg = X86::DL; break;
18537       case X86::CX: DestReg = X86::CL; break;
18538       case X86::BX: DestReg = X86::BL; break;
18539       }
18540       if (DestReg) {
18541         Res.first = DestReg;
18542         Res.second = &X86::GR8RegClass;
18543       }
18544     } else if (VT == MVT::i32 || VT == MVT::f32) {
18545       unsigned DestReg = 0;
18546       switch (Res.first) {
18547       default: break;
18548       case X86::AX: DestReg = X86::EAX; break;
18549       case X86::DX: DestReg = X86::EDX; break;
18550       case X86::CX: DestReg = X86::ECX; break;
18551       case X86::BX: DestReg = X86::EBX; break;
18552       case X86::SI: DestReg = X86::ESI; break;
18553       case X86::DI: DestReg = X86::EDI; break;
18554       case X86::BP: DestReg = X86::EBP; break;
18555       case X86::SP: DestReg = X86::ESP; break;
18556       }
18557       if (DestReg) {
18558         Res.first = DestReg;
18559         Res.second = &X86::GR32RegClass;
18560       }
18561     } else if (VT == MVT::i64 || VT == MVT::f64) {
18562       unsigned DestReg = 0;
18563       switch (Res.first) {
18564       default: break;
18565       case X86::AX: DestReg = X86::RAX; break;
18566       case X86::DX: DestReg = X86::RDX; break;
18567       case X86::CX: DestReg = X86::RCX; break;
18568       case X86::BX: DestReg = X86::RBX; break;
18569       case X86::SI: DestReg = X86::RSI; break;
18570       case X86::DI: DestReg = X86::RDI; break;
18571       case X86::BP: DestReg = X86::RBP; break;
18572       case X86::SP: DestReg = X86::RSP; break;
18573       }
18574       if (DestReg) {
18575         Res.first = DestReg;
18576         Res.second = &X86::GR64RegClass;
18577       }
18578     }
18579   } else if (Res.second == &X86::FR32RegClass ||
18580              Res.second == &X86::FR64RegClass ||
18581              Res.second == &X86::VR128RegClass) {
18582     // Handle references to XMM physical registers that got mapped into the
18583     // wrong class.  This can happen with constraints like {xmm0} where the
18584     // target independent register mapper will just pick the first match it can
18585     // find, ignoring the required type.
18586
18587     if (VT == MVT::f32 || VT == MVT::i32)
18588       Res.second = &X86::FR32RegClass;
18589     else if (VT == MVT::f64 || VT == MVT::i64)
18590       Res.second = &X86::FR64RegClass;
18591     else if (X86::VR128RegClass.hasType(VT))
18592       Res.second = &X86::VR128RegClass;
18593     else if (X86::VR256RegClass.hasType(VT))
18594       Res.second = &X86::VR256RegClass;
18595   }
18596
18597   return Res;
18598 }