Optimize vector select from all 0s or all 1s
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "x86-isel"
16 #include "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::MEMBARRIER    , MVT::Other, Custom);
530   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
531
532   // On X86 and X86-64, atomic operations are lowered to locked instructions.
533   // Locked instructions, in turn, have implicit fence semantics (all memory
534   // operations are flushed before issuing the locked instruction, and they
535   // are not buffered), so we can fold away the common pattern of
536   // fence-atomic-fence.
537   setShouldFoldAtomicFences(true);
538
539   // Expand certain atomics
540   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
541     MVT VT = IntVTs[i];
542     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
543     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
544     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
545   }
546
547   if (!Subtarget->is64Bit()) {
548     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
549     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
550     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
551     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
552     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
553     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
554     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
555     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
556     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
557     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
558     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
559     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
560   }
561
562   if (Subtarget->hasCmpxchg16b()) {
563     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
564   }
565
566   // FIXME - use subtarget debug flags
567   if (!Subtarget->isTargetDarwin() &&
568       !Subtarget->isTargetELF() &&
569       !Subtarget->isTargetCygMing()) {
570     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
571   }
572
573   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
574   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
575   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
576   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
577   if (Subtarget->is64Bit()) {
578     setExceptionPointerRegister(X86::RAX);
579     setExceptionSelectorRegister(X86::RDX);
580   } else {
581     setExceptionPointerRegister(X86::EAX);
582     setExceptionSelectorRegister(X86::EDX);
583   }
584   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
585   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
586
587   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
588   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
589
590   setOperationAction(ISD::TRAP, MVT::Other, Legal);
591   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
592
593   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
594   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
595   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
596   if (Subtarget->is64Bit()) {
597     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
598     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
599   } else {
600     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
601     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
602   }
603
604   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
605   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
606
607   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
608     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
609                        MVT::i64 : MVT::i32, Custom);
610   else if (TM.Options.EnableSegmentedStacks)
611     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
612                        MVT::i64 : MVT::i32, Custom);
613   else
614     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
615                        MVT::i64 : MVT::i32, Expand);
616
617   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
618     // f32 and f64 use SSE.
619     // Set up the FP register classes.
620     addRegisterClass(MVT::f32, &X86::FR32RegClass);
621     addRegisterClass(MVT::f64, &X86::FR64RegClass);
622
623     // Use ANDPD to simulate FABS.
624     setOperationAction(ISD::FABS , MVT::f64, Custom);
625     setOperationAction(ISD::FABS , MVT::f32, Custom);
626
627     // Use XORP to simulate FNEG.
628     setOperationAction(ISD::FNEG , MVT::f64, Custom);
629     setOperationAction(ISD::FNEG , MVT::f32, Custom);
630
631     // Use ANDPD and ORPD to simulate FCOPYSIGN.
632     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
633     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
634
635     // Lower this to FGETSIGNx86 plus an AND.
636     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
637     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
638
639     // We don't support sin/cos/fmod
640     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
641     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
642     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
643     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
644     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
645     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
646
647     // Expand FP immediates into loads from the stack, except for the special
648     // cases we handle.
649     addLegalFPImmediate(APFloat(+0.0)); // xorpd
650     addLegalFPImmediate(APFloat(+0.0f)); // xorps
651   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
652     // Use SSE for f32, x87 for f64.
653     // Set up the FP register classes.
654     addRegisterClass(MVT::f32, &X86::FR32RegClass);
655     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
656
657     // Use ANDPS to simulate FABS.
658     setOperationAction(ISD::FABS , MVT::f32, Custom);
659
660     // Use XORP to simulate FNEG.
661     setOperationAction(ISD::FNEG , MVT::f32, Custom);
662
663     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
664
665     // Use ANDPS and ORPS to simulate FCOPYSIGN.
666     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
667     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
668
669     // We don't support sin/cos/fmod
670     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
671     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
672     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
673
674     // Special cases we handle for FP constants.
675     addLegalFPImmediate(APFloat(+0.0f)); // xorps
676     addLegalFPImmediate(APFloat(+0.0)); // FLD0
677     addLegalFPImmediate(APFloat(+1.0)); // FLD1
678     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
679     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
680
681     if (!TM.Options.UnsafeFPMath) {
682       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
683       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
684       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
685     }
686   } else if (!TM.Options.UseSoftFloat) {
687     // f32 and f64 in x87.
688     // Set up the FP register classes.
689     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
690     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
691
692     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
693     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
694     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
695     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
696
697     if (!TM.Options.UnsafeFPMath) {
698       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
699       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
700       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
701       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
702       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
703       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
704     }
705     addLegalFPImmediate(APFloat(+0.0)); // FLD0
706     addLegalFPImmediate(APFloat(+1.0)); // FLD1
707     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
708     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
709     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
710     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
711     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
712     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
713   }
714
715   // We don't support FMA.
716   setOperationAction(ISD::FMA, MVT::f64, Expand);
717   setOperationAction(ISD::FMA, MVT::f32, Expand);
718
719   // Long double always uses X87.
720   if (!TM.Options.UseSoftFloat) {
721     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
722     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
723     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
724     {
725       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
726       addLegalFPImmediate(TmpFlt);  // FLD0
727       TmpFlt.changeSign();
728       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
729
730       bool ignored;
731       APFloat TmpFlt2(+1.0);
732       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
733                       &ignored);
734       addLegalFPImmediate(TmpFlt2);  // FLD1
735       TmpFlt2.changeSign();
736       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
737     }
738
739     if (!TM.Options.UnsafeFPMath) {
740       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
741       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
742       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
743     }
744
745     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
746     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
747     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
748     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
749     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
750     setOperationAction(ISD::FMA, MVT::f80, Expand);
751   }
752
753   // Always use a library call for pow.
754   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
755   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
756   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
757
758   setOperationAction(ISD::FLOG, MVT::f80, Expand);
759   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
760   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
761   setOperationAction(ISD::FEXP, MVT::f80, Expand);
762   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
763
764   // First set operation action for all vector types to either promote
765   // (for widening) or expand (for scalarization). Then we will selectively
766   // turn on ones that can be effectively codegen'd.
767   for (int i = MVT::FIRST_VECTOR_VALUETYPE;
768            i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
769     MVT VT = (MVT::SimpleValueType)i;
770     setOperationAction(ISD::ADD , VT, Expand);
771     setOperationAction(ISD::SUB , VT, Expand);
772     setOperationAction(ISD::FADD, VT, Expand);
773     setOperationAction(ISD::FNEG, VT, Expand);
774     setOperationAction(ISD::FSUB, VT, Expand);
775     setOperationAction(ISD::MUL , VT, Expand);
776     setOperationAction(ISD::FMUL, VT, Expand);
777     setOperationAction(ISD::SDIV, VT, Expand);
778     setOperationAction(ISD::UDIV, VT, Expand);
779     setOperationAction(ISD::FDIV, VT, Expand);
780     setOperationAction(ISD::SREM, VT, Expand);
781     setOperationAction(ISD::UREM, VT, Expand);
782     setOperationAction(ISD::LOAD, VT, Expand);
783     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
784     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
785     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
786     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
787     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
788     setOperationAction(ISD::FABS, VT, Expand);
789     setOperationAction(ISD::FSIN, VT, Expand);
790     setOperationAction(ISD::FSINCOS, VT, Expand);
791     setOperationAction(ISD::FCOS, VT, Expand);
792     setOperationAction(ISD::FSINCOS, VT, Expand);
793     setOperationAction(ISD::FREM, VT, Expand);
794     setOperationAction(ISD::FMA,  VT, Expand);
795     setOperationAction(ISD::FPOWI, VT, Expand);
796     setOperationAction(ISD::FSQRT, VT, Expand);
797     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
798     setOperationAction(ISD::FFLOOR, VT, Expand);
799     setOperationAction(ISD::FCEIL, VT, Expand);
800     setOperationAction(ISD::FTRUNC, VT, Expand);
801     setOperationAction(ISD::FRINT, VT, Expand);
802     setOperationAction(ISD::FNEARBYINT, VT, Expand);
803     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
804     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
805     setOperationAction(ISD::SDIVREM, VT, Expand);
806     setOperationAction(ISD::UDIVREM, VT, Expand);
807     setOperationAction(ISD::FPOW, VT, Expand);
808     setOperationAction(ISD::CTPOP, VT, Expand);
809     setOperationAction(ISD::CTTZ, VT, Expand);
810     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
811     setOperationAction(ISD::CTLZ, VT, Expand);
812     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
813     setOperationAction(ISD::SHL, VT, Expand);
814     setOperationAction(ISD::SRA, VT, Expand);
815     setOperationAction(ISD::SRL, VT, Expand);
816     setOperationAction(ISD::ROTL, VT, Expand);
817     setOperationAction(ISD::ROTR, VT, Expand);
818     setOperationAction(ISD::BSWAP, VT, Expand);
819     setOperationAction(ISD::SETCC, VT, Expand);
820     setOperationAction(ISD::FLOG, VT, Expand);
821     setOperationAction(ISD::FLOG2, VT, Expand);
822     setOperationAction(ISD::FLOG10, VT, Expand);
823     setOperationAction(ISD::FEXP, VT, Expand);
824     setOperationAction(ISD::FEXP2, VT, Expand);
825     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
826     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
827     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
828     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
829     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
830     setOperationAction(ISD::TRUNCATE, VT, Expand);
831     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
832     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
833     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
834     setOperationAction(ISD::VSELECT, VT, Expand);
835     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
836              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
837       setTruncStoreAction(VT,
838                           (MVT::SimpleValueType)InnerVT, Expand);
839     setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
840     setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
841     setLoadExtAction(ISD::EXTLOAD, VT, Expand);
842   }
843
844   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
845   // with -msoft-float, disable use of MMX as well.
846   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
847     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
848     // No operations on x86mmx supported, everything uses intrinsics.
849   }
850
851   // MMX-sized vectors (other than x86mmx) are expected to be expanded
852   // into smaller operations.
853   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
854   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
855   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
856   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
857   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
858   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
859   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
860   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
861   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
862   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
863   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
864   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
865   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
866   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
867   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
868   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
869   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
870   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
871   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
872   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
873   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
874   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
875   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
876   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
877   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
878   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
879   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
880   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
881   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
882
883   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
884     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
885
886     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
887     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
888     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
889     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
890     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
891     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
892     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
893     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
894     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
895     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
896     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
897     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
898   }
899
900   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
901     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
902
903     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
904     // registers cannot be used even for integer operations.
905     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
906     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
907     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
908     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
909
910     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
911     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
912     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
913     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
914     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
915     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
916     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
917     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
918     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
919     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
920     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
921     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
922     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
923     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
924     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
925     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
926     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
927     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
928
929     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
930     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
931     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
932     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
933
934     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
935     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
936     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
937     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
938     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
939
940     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
941     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
942       MVT VT = (MVT::SimpleValueType)i;
943       // Do not attempt to custom lower non-power-of-2 vectors
944       if (!isPowerOf2_32(VT.getVectorNumElements()))
945         continue;
946       // Do not attempt to custom lower non-128-bit vectors
947       if (!VT.is128BitVector())
948         continue;
949       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
950       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
951       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
952     }
953
954     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
955     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
956     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
957     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
958     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
959     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
960
961     if (Subtarget->is64Bit()) {
962       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
963       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
964     }
965
966     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
967     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
968       MVT VT = (MVT::SimpleValueType)i;
969
970       // Do not attempt to promote non-128-bit vectors
971       if (!VT.is128BitVector())
972         continue;
973
974       setOperationAction(ISD::AND,    VT, Promote);
975       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
976       setOperationAction(ISD::OR,     VT, Promote);
977       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
978       setOperationAction(ISD::XOR,    VT, Promote);
979       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
980       setOperationAction(ISD::LOAD,   VT, Promote);
981       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
982       setOperationAction(ISD::SELECT, VT, Promote);
983       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
984     }
985
986     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
987
988     // Custom lower v2i64 and v2f64 selects.
989     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
990     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
991     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
992     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
993
994     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
995     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
996
997     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
998     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
999     // As there is no 64-bit GPR available, we need build a special custom
1000     // sequence to convert from v2i32 to v2f32.
1001     if (!Subtarget->is64Bit())
1002       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
1003
1004     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1005     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1006
1007     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
1008   }
1009
1010   if (Subtarget->hasSSE41()) {
1011     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1012     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1013     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1014     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1015     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1016     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1017     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1018     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1019     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1020     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1021
1022     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1023     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1024     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1025     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1026     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1027     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1028     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1029     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1030     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1031     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1032
1033     // FIXME: Do we need to handle scalar-to-vector here?
1034     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1035
1036     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
1037     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
1038     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1039     setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
1040     setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
1041
1042     // i8 and i16 vectors are custom , because the source register and source
1043     // source memory operand types are not the same width.  f32 vectors are
1044     // custom since the immediate controlling the insert encodes additional
1045     // information.
1046     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1047     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1048     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1049     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1050
1051     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1052     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1053     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1054     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1055
1056     // FIXME: these should be Legal but thats only for the case where
1057     // the index is constant.  For now custom expand to deal with that.
1058     if (Subtarget->is64Bit()) {
1059       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1060       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1061     }
1062   }
1063
1064   if (Subtarget->hasSSE2()) {
1065     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1066     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1067
1068     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1069     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1070
1071     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1072     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1073
1074     // In the customized shift lowering, the legal cases in AVX2 will be
1075     // recognized.
1076     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1077     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1078
1079     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1080     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1081
1082     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1083
1084     setOperationAction(ISD::SDIV,              MVT::v8i16, Custom);
1085     setOperationAction(ISD::SDIV,              MVT::v4i32, Custom);
1086   }
1087
1088   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1089     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1090     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1091     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1092     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1093     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1094     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1095
1096     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1097     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1098     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1099
1100     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1101     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1102     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1103     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1104     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1105     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1106     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1107     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1108     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1109     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1110     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1111     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1112
1113     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1114     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1115     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1116     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1117     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1118     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1119     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1120     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1121     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1122     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1123     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1124     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1125
1126     setOperationAction(ISD::TRUNCATE,           MVT::v8i16, Custom);
1127     setOperationAction(ISD::TRUNCATE,           MVT::v4i32, Custom);
1128
1129     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Custom);
1130
1131     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1132     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1133     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1134     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1135
1136     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i32, Custom);
1137     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1138     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1139
1140     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1141
1142     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1143     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1144
1145     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1146     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1147
1148     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1149     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1150
1151     setOperationAction(ISD::SDIV,              MVT::v16i16, Custom);
1152
1153     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1154     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1155     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1156     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1157
1158     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1159     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1160     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1161
1162     setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1163     setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1164     setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1165     setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1166
1167     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1168     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1169     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1170     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1171     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1172     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1173
1174     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1175       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1176       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1177       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1178       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1179       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1180       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1181     }
1182
1183     if (Subtarget->hasInt256()) {
1184       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1185       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1186       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1187       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1188
1189       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1190       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1191       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1192       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1193
1194       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1195       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1196       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1197       // Don't lower v32i8 because there is no 128-bit byte mul
1198
1199       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1200
1201       setOperationAction(ISD::SDIV,            MVT::v8i32, Custom);
1202     } else {
1203       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1204       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1205       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1206       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1207
1208       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1209       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1210       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1211       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1212
1213       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1214       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1215       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1216       // Don't lower v32i8 because there is no 128-bit byte mul
1217     }
1218
1219     // In the customized shift lowering, the legal cases in AVX2 will be
1220     // recognized.
1221     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1222     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1223
1224     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1225     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1226
1227     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1228
1229     // Custom lower several nodes for 256-bit types.
1230     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1231              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1232       MVT VT = (MVT::SimpleValueType)i;
1233
1234       // Extract subvector is special because the value type
1235       // (result) is 128-bit but the source is 256-bit wide.
1236       if (VT.is128BitVector())
1237         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1238
1239       // Do not attempt to custom lower other non-256-bit vectors
1240       if (!VT.is256BitVector())
1241         continue;
1242
1243       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1244       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1245       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1246       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1247       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1248       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1249       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1250     }
1251
1252     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1253     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1254       MVT VT = (MVT::SimpleValueType)i;
1255
1256       // Do not attempt to promote non-256-bit vectors
1257       if (!VT.is256BitVector())
1258         continue;
1259
1260       setOperationAction(ISD::AND,    VT, Promote);
1261       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1262       setOperationAction(ISD::OR,     VT, Promote);
1263       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1264       setOperationAction(ISD::XOR,    VT, Promote);
1265       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1266       setOperationAction(ISD::LOAD,   VT, Promote);
1267       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1268       setOperationAction(ISD::SELECT, VT, Promote);
1269       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1270     }
1271   }
1272
1273   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1274   // of this type with custom code.
1275   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1276            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1277     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1278                        Custom);
1279   }
1280
1281   // We want to custom lower some of our intrinsics.
1282   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1283   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1284
1285   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1286   // handle type legalization for these operations here.
1287   //
1288   // FIXME: We really should do custom legalization for addition and
1289   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1290   // than generic legalization for 64-bit multiplication-with-overflow, though.
1291   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1292     // Add/Sub/Mul with overflow operations are custom lowered.
1293     MVT VT = IntVTs[i];
1294     setOperationAction(ISD::SADDO, VT, Custom);
1295     setOperationAction(ISD::UADDO, VT, Custom);
1296     setOperationAction(ISD::SSUBO, VT, Custom);
1297     setOperationAction(ISD::USUBO, VT, Custom);
1298     setOperationAction(ISD::SMULO, VT, Custom);
1299     setOperationAction(ISD::UMULO, VT, Custom);
1300   }
1301
1302   // There are no 8-bit 3-address imul/mul instructions
1303   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1304   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1305
1306   if (!Subtarget->is64Bit()) {
1307     // These libcalls are not available in 32-bit.
1308     setLibcallName(RTLIB::SHL_I128, 0);
1309     setLibcallName(RTLIB::SRL_I128, 0);
1310     setLibcallName(RTLIB::SRA_I128, 0);
1311   }
1312
1313   // Combine sin / cos into one node or libcall if possible.
1314   if (Subtarget->hasSinCos()) {
1315     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1316     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1317     if (Subtarget->isTargetDarwin()) {
1318       // For MacOSX, we don't want to the normal expansion of a libcall to
1319       // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1320       // traffic.
1321       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1322       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1323     }
1324   }
1325
1326   // We have target-specific dag combine patterns for the following nodes:
1327   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1328   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1329   setTargetDAGCombine(ISD::VSELECT);
1330   setTargetDAGCombine(ISD::SELECT);
1331   setTargetDAGCombine(ISD::SHL);
1332   setTargetDAGCombine(ISD::SRA);
1333   setTargetDAGCombine(ISD::SRL);
1334   setTargetDAGCombine(ISD::OR);
1335   setTargetDAGCombine(ISD::AND);
1336   setTargetDAGCombine(ISD::ADD);
1337   setTargetDAGCombine(ISD::FADD);
1338   setTargetDAGCombine(ISD::FSUB);
1339   setTargetDAGCombine(ISD::FMA);
1340   setTargetDAGCombine(ISD::SUB);
1341   setTargetDAGCombine(ISD::LOAD);
1342   setTargetDAGCombine(ISD::STORE);
1343   setTargetDAGCombine(ISD::ZERO_EXTEND);
1344   setTargetDAGCombine(ISD::ANY_EXTEND);
1345   setTargetDAGCombine(ISD::SIGN_EXTEND);
1346   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1347   setTargetDAGCombine(ISD::TRUNCATE);
1348   setTargetDAGCombine(ISD::SINT_TO_FP);
1349   setTargetDAGCombine(ISD::SETCC);
1350   if (Subtarget->is64Bit())
1351     setTargetDAGCombine(ISD::MUL);
1352   setTargetDAGCombine(ISD::XOR);
1353
1354   computeRegisterProperties();
1355
1356   // On Darwin, -Os means optimize for size without hurting performance,
1357   // do not reduce the limit.
1358   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1359   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1360   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1361   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1362   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1363   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1364   setPrefLoopAlignment(4); // 2^4 bytes.
1365
1366   // Predictable cmov don't hurt on atom because it's in-order.
1367   PredictableSelectIsExpensive = !Subtarget->isAtom();
1368
1369   setPrefFunctionAlignment(4); // 2^4 bytes.
1370 }
1371
1372 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1373   if (!VT.isVector()) return MVT::i8;
1374   return VT.changeVectorElementTypeToInteger();
1375 }
1376
1377 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1378 /// the desired ByVal argument alignment.
1379 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1380   if (MaxAlign == 16)
1381     return;
1382   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1383     if (VTy->getBitWidth() == 128)
1384       MaxAlign = 16;
1385   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1386     unsigned EltAlign = 0;
1387     getMaxByValAlign(ATy->getElementType(), EltAlign);
1388     if (EltAlign > MaxAlign)
1389       MaxAlign = EltAlign;
1390   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1391     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1392       unsigned EltAlign = 0;
1393       getMaxByValAlign(STy->getElementType(i), EltAlign);
1394       if (EltAlign > MaxAlign)
1395         MaxAlign = EltAlign;
1396       if (MaxAlign == 16)
1397         break;
1398     }
1399   }
1400 }
1401
1402 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1403 /// function arguments in the caller parameter area. For X86, aggregates
1404 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1405 /// are at 4-byte boundaries.
1406 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1407   if (Subtarget->is64Bit()) {
1408     // Max of 8 and alignment of type.
1409     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1410     if (TyAlign > 8)
1411       return TyAlign;
1412     return 8;
1413   }
1414
1415   unsigned Align = 4;
1416   if (Subtarget->hasSSE1())
1417     getMaxByValAlign(Ty, Align);
1418   return Align;
1419 }
1420
1421 /// getOptimalMemOpType - Returns the target specific optimal type for load
1422 /// and store operations as a result of memset, memcpy, and memmove
1423 /// lowering. If DstAlign is zero that means it's safe to destination
1424 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1425 /// means there isn't a need to check it against alignment requirement,
1426 /// probably because the source does not need to be loaded. If 'IsMemset' is
1427 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1428 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1429 /// source is constant so it does not need to be loaded.
1430 /// It returns EVT::Other if the type should be determined using generic
1431 /// target-independent logic.
1432 EVT
1433 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1434                                        unsigned DstAlign, unsigned SrcAlign,
1435                                        bool IsMemset, bool ZeroMemset,
1436                                        bool MemcpyStrSrc,
1437                                        MachineFunction &MF) const {
1438   const Function *F = MF.getFunction();
1439   if ((!IsMemset || ZeroMemset) &&
1440       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1441                                        Attribute::NoImplicitFloat)) {
1442     if (Size >= 16 &&
1443         (Subtarget->isUnalignedMemAccessFast() ||
1444          ((DstAlign == 0 || DstAlign >= 16) &&
1445           (SrcAlign == 0 || SrcAlign >= 16)))) {
1446       if (Size >= 32) {
1447         if (Subtarget->hasInt256())
1448           return MVT::v8i32;
1449         if (Subtarget->hasFp256())
1450           return MVT::v8f32;
1451       }
1452       if (Subtarget->hasSSE2())
1453         return MVT::v4i32;
1454       if (Subtarget->hasSSE1())
1455         return MVT::v4f32;
1456     } else if (!MemcpyStrSrc && Size >= 8 &&
1457                !Subtarget->is64Bit() &&
1458                Subtarget->hasSSE2()) {
1459       // Do not use f64 to lower memcpy if source is string constant. It's
1460       // better to use i32 to avoid the loads.
1461       return MVT::f64;
1462     }
1463   }
1464   if (Subtarget->is64Bit() && Size >= 8)
1465     return MVT::i64;
1466   return MVT::i32;
1467 }
1468
1469 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1470   if (VT == MVT::f32)
1471     return X86ScalarSSEf32;
1472   else if (VT == MVT::f64)
1473     return X86ScalarSSEf64;
1474   return true;
1475 }
1476
1477 bool
1478 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
1479   if (Fast)
1480     *Fast = Subtarget->isUnalignedMemAccessFast();
1481   return true;
1482 }
1483
1484 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1485 /// current function.  The returned value is a member of the
1486 /// MachineJumpTableInfo::JTEntryKind enum.
1487 unsigned X86TargetLowering::getJumpTableEncoding() const {
1488   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1489   // symbol.
1490   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1491       Subtarget->isPICStyleGOT())
1492     return MachineJumpTableInfo::EK_Custom32;
1493
1494   // Otherwise, use the normal jump table encoding heuristics.
1495   return TargetLowering::getJumpTableEncoding();
1496 }
1497
1498 const MCExpr *
1499 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1500                                              const MachineBasicBlock *MBB,
1501                                              unsigned uid,MCContext &Ctx) const{
1502   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1503          Subtarget->isPICStyleGOT());
1504   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1505   // entries.
1506   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1507                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1508 }
1509
1510 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1511 /// jumptable.
1512 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1513                                                     SelectionDAG &DAG) const {
1514   if (!Subtarget->is64Bit())
1515     // This doesn't have DebugLoc associated with it, but is not really the
1516     // same as a Register.
1517     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1518   return Table;
1519 }
1520
1521 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1522 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1523 /// MCExpr.
1524 const MCExpr *X86TargetLowering::
1525 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1526                              MCContext &Ctx) const {
1527   // X86-64 uses RIP relative addressing based on the jump table label.
1528   if (Subtarget->isPICStyleRIPRel())
1529     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1530
1531   // Otherwise, the reference is relative to the PIC base.
1532   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1533 }
1534
1535 // FIXME: Why this routine is here? Move to RegInfo!
1536 std::pair<const TargetRegisterClass*, uint8_t>
1537 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1538   const TargetRegisterClass *RRC = 0;
1539   uint8_t Cost = 1;
1540   switch (VT.SimpleTy) {
1541   default:
1542     return TargetLowering::findRepresentativeClass(VT);
1543   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1544     RRC = Subtarget->is64Bit() ?
1545       (const TargetRegisterClass*)&X86::GR64RegClass :
1546       (const TargetRegisterClass*)&X86::GR32RegClass;
1547     break;
1548   case MVT::x86mmx:
1549     RRC = &X86::VR64RegClass;
1550     break;
1551   case MVT::f32: case MVT::f64:
1552   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1553   case MVT::v4f32: case MVT::v2f64:
1554   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1555   case MVT::v4f64:
1556     RRC = &X86::VR128RegClass;
1557     break;
1558   }
1559   return std::make_pair(RRC, Cost);
1560 }
1561
1562 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1563                                                unsigned &Offset) const {
1564   if (!Subtarget->isTargetLinux())
1565     return false;
1566
1567   if (Subtarget->is64Bit()) {
1568     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1569     Offset = 0x28;
1570     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1571       AddressSpace = 256;
1572     else
1573       AddressSpace = 257;
1574   } else {
1575     // %gs:0x14 on i386
1576     Offset = 0x14;
1577     AddressSpace = 256;
1578   }
1579   return true;
1580 }
1581
1582 //===----------------------------------------------------------------------===//
1583 //               Return Value Calling Convention Implementation
1584 //===----------------------------------------------------------------------===//
1585
1586 #include "X86GenCallingConv.inc"
1587
1588 bool
1589 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1590                                   MachineFunction &MF, bool isVarArg,
1591                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1592                         LLVMContext &Context) const {
1593   SmallVector<CCValAssign, 16> RVLocs;
1594   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1595                  RVLocs, Context);
1596   return CCInfo.CheckReturn(Outs, RetCC_X86);
1597 }
1598
1599 SDValue
1600 X86TargetLowering::LowerReturn(SDValue Chain,
1601                                CallingConv::ID CallConv, bool isVarArg,
1602                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1603                                const SmallVectorImpl<SDValue> &OutVals,
1604                                DebugLoc dl, SelectionDAG &DAG) const {
1605   MachineFunction &MF = DAG.getMachineFunction();
1606   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1607
1608   SmallVector<CCValAssign, 16> RVLocs;
1609   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1610                  RVLocs, *DAG.getContext());
1611   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1612
1613   SDValue Flag;
1614   SmallVector<SDValue, 6> RetOps;
1615   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1616   // Operand #1 = Bytes To Pop
1617   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1618                    MVT::i16));
1619
1620   // Copy the result values into the output registers.
1621   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1622     CCValAssign &VA = RVLocs[i];
1623     assert(VA.isRegLoc() && "Can only return in registers!");
1624     SDValue ValToCopy = OutVals[i];
1625     EVT ValVT = ValToCopy.getValueType();
1626
1627     // Promote values to the appropriate types
1628     if (VA.getLocInfo() == CCValAssign::SExt)
1629       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1630     else if (VA.getLocInfo() == CCValAssign::ZExt)
1631       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1632     else if (VA.getLocInfo() == CCValAssign::AExt)
1633       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1634     else if (VA.getLocInfo() == CCValAssign::BCvt)
1635       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1636
1637     // If this is x86-64, and we disabled SSE, we can't return FP values,
1638     // or SSE or MMX vectors.
1639     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1640          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1641           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1642       report_fatal_error("SSE register return with SSE disabled");
1643     }
1644     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1645     // llvm-gcc has never done it right and no one has noticed, so this
1646     // should be OK for now.
1647     if (ValVT == MVT::f64 &&
1648         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1649       report_fatal_error("SSE2 register return with SSE2 disabled");
1650
1651     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1652     // the RET instruction and handled by the FP Stackifier.
1653     if (VA.getLocReg() == X86::ST0 ||
1654         VA.getLocReg() == X86::ST1) {
1655       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1656       // change the value to the FP stack register class.
1657       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1658         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1659       RetOps.push_back(ValToCopy);
1660       // Don't emit a copytoreg.
1661       continue;
1662     }
1663
1664     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1665     // which is returned in RAX / RDX.
1666     if (Subtarget->is64Bit()) {
1667       if (ValVT == MVT::x86mmx) {
1668         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1669           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1670           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1671                                   ValToCopy);
1672           // If we don't have SSE2 available, convert to v4f32 so the generated
1673           // register is legal.
1674           if (!Subtarget->hasSSE2())
1675             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1676         }
1677       }
1678     }
1679
1680     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1681     Flag = Chain.getValue(1);
1682     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1683   }
1684
1685   // The x86-64 ABIs require that for returning structs by value we copy
1686   // the sret argument into %rax/%eax (depending on ABI) for the return.
1687   // Win32 requires us to put the sret argument to %eax as well.
1688   // We saved the argument into a virtual register in the entry block,
1689   // so now we copy the value out and into %rax/%eax.
1690   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1691       (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
1692     MachineFunction &MF = DAG.getMachineFunction();
1693     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1694     unsigned Reg = FuncInfo->getSRetReturnReg();
1695     assert(Reg &&
1696            "SRetReturnReg should have been set in LowerFormalArguments().");
1697     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1698
1699     unsigned RetValReg
1700         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1701           X86::RAX : X86::EAX;
1702     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1703     Flag = Chain.getValue(1);
1704
1705     // RAX/EAX now acts like a return value.
1706     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1707   }
1708
1709   RetOps[0] = Chain;  // Update chain.
1710
1711   // Add the flag if we have it.
1712   if (Flag.getNode())
1713     RetOps.push_back(Flag);
1714
1715   return DAG.getNode(X86ISD::RET_FLAG, dl,
1716                      MVT::Other, &RetOps[0], RetOps.size());
1717 }
1718
1719 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1720   if (N->getNumValues() != 1)
1721     return false;
1722   if (!N->hasNUsesOfValue(1, 0))
1723     return false;
1724
1725   SDValue TCChain = Chain;
1726   SDNode *Copy = *N->use_begin();
1727   if (Copy->getOpcode() == ISD::CopyToReg) {
1728     // If the copy has a glue operand, we conservatively assume it isn't safe to
1729     // perform a tail call.
1730     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1731       return false;
1732     TCChain = Copy->getOperand(0);
1733   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1734     return false;
1735
1736   bool HasRet = false;
1737   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1738        UI != UE; ++UI) {
1739     if (UI->getOpcode() != X86ISD::RET_FLAG)
1740       return false;
1741     HasRet = true;
1742   }
1743
1744   if (!HasRet)
1745     return false;
1746
1747   Chain = TCChain;
1748   return true;
1749 }
1750
1751 MVT
1752 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1753                                             ISD::NodeType ExtendKind) const {
1754   MVT ReturnMVT;
1755   // TODO: Is this also valid on 32-bit?
1756   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1757     ReturnMVT = MVT::i8;
1758   else
1759     ReturnMVT = MVT::i32;
1760
1761   MVT MinVT = getRegisterType(ReturnMVT);
1762   return VT.bitsLT(MinVT) ? MinVT : VT;
1763 }
1764
1765 /// LowerCallResult - Lower the result values of a call into the
1766 /// appropriate copies out of appropriate physical registers.
1767 ///
1768 SDValue
1769 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1770                                    CallingConv::ID CallConv, bool isVarArg,
1771                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1772                                    DebugLoc dl, SelectionDAG &DAG,
1773                                    SmallVectorImpl<SDValue> &InVals) const {
1774
1775   // Assign locations to each value returned by this call.
1776   SmallVector<CCValAssign, 16> RVLocs;
1777   bool Is64Bit = Subtarget->is64Bit();
1778   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1779                  getTargetMachine(), RVLocs, *DAG.getContext());
1780   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1781
1782   // Copy all of the result registers out of their specified physreg.
1783   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1784     CCValAssign &VA = RVLocs[i];
1785     EVT CopyVT = VA.getValVT();
1786
1787     // If this is x86-64, and we disabled SSE, we can't return FP values
1788     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1789         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1790       report_fatal_error("SSE register return with SSE disabled");
1791     }
1792
1793     SDValue Val;
1794
1795     // If this is a call to a function that returns an fp value on the floating
1796     // point stack, we must guarantee the value is popped from the stack, so
1797     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1798     // if the return value is not used. We use the FpPOP_RETVAL instruction
1799     // instead.
1800     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1801       // If we prefer to use the value in xmm registers, copy it out as f80 and
1802       // use a truncate to move it from fp stack reg to xmm reg.
1803       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1804       SDValue Ops[] = { Chain, InFlag };
1805       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1806                                          MVT::Other, MVT::Glue, Ops, 2), 1);
1807       Val = Chain.getValue(0);
1808
1809       // Round the f80 to the right size, which also moves it to the appropriate
1810       // xmm register.
1811       if (CopyVT != VA.getValVT())
1812         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1813                           // This truncation won't change the value.
1814                           DAG.getIntPtrConstant(1));
1815     } else {
1816       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1817                                  CopyVT, InFlag).getValue(1);
1818       Val = Chain.getValue(0);
1819     }
1820     InFlag = Chain.getValue(2);
1821     InVals.push_back(Val);
1822   }
1823
1824   return Chain;
1825 }
1826
1827 //===----------------------------------------------------------------------===//
1828 //                C & StdCall & Fast Calling Convention implementation
1829 //===----------------------------------------------------------------------===//
1830 //  StdCall calling convention seems to be standard for many Windows' API
1831 //  routines and around. It differs from C calling convention just a little:
1832 //  callee should clean up the stack, not caller. Symbols should be also
1833 //  decorated in some fancy way :) It doesn't support any vector arguments.
1834 //  For info on fast calling convention see Fast Calling Convention (tail call)
1835 //  implementation LowerX86_32FastCCCallTo.
1836
1837 /// CallIsStructReturn - Determines whether a call uses struct return
1838 /// semantics.
1839 enum StructReturnType {
1840   NotStructReturn,
1841   RegStructReturn,
1842   StackStructReturn
1843 };
1844 static StructReturnType
1845 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1846   if (Outs.empty())
1847     return NotStructReturn;
1848
1849   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
1850   if (!Flags.isSRet())
1851     return NotStructReturn;
1852   if (Flags.isInReg())
1853     return RegStructReturn;
1854   return StackStructReturn;
1855 }
1856
1857 /// ArgsAreStructReturn - Determines whether a function uses struct
1858 /// return semantics.
1859 static StructReturnType
1860 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1861   if (Ins.empty())
1862     return NotStructReturn;
1863
1864   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
1865   if (!Flags.isSRet())
1866     return NotStructReturn;
1867   if (Flags.isInReg())
1868     return RegStructReturn;
1869   return StackStructReturn;
1870 }
1871
1872 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1873 /// by "Src" to address "Dst" with size and alignment information specified by
1874 /// the specific parameter attribute. The copy will be passed as a byval
1875 /// function parameter.
1876 static SDValue
1877 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1878                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1879                           DebugLoc dl) {
1880   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1881
1882   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1883                        /*isVolatile*/false, /*AlwaysInline=*/true,
1884                        MachinePointerInfo(), MachinePointerInfo());
1885 }
1886
1887 /// IsTailCallConvention - Return true if the calling convention is one that
1888 /// supports tail call optimization.
1889 static bool IsTailCallConvention(CallingConv::ID CC) {
1890   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
1891           CC == CallingConv::HiPE);
1892 }
1893
1894 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1895   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1896     return false;
1897
1898   CallSite CS(CI);
1899   CallingConv::ID CalleeCC = CS.getCallingConv();
1900   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1901     return false;
1902
1903   return true;
1904 }
1905
1906 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1907 /// a tailcall target by changing its ABI.
1908 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1909                                    bool GuaranteedTailCallOpt) {
1910   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1911 }
1912
1913 SDValue
1914 X86TargetLowering::LowerMemArgument(SDValue Chain,
1915                                     CallingConv::ID CallConv,
1916                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1917                                     DebugLoc dl, SelectionDAG &DAG,
1918                                     const CCValAssign &VA,
1919                                     MachineFrameInfo *MFI,
1920                                     unsigned i) const {
1921   // Create the nodes corresponding to a load from this parameter slot.
1922   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1923   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1924                               getTargetMachine().Options.GuaranteedTailCallOpt);
1925   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1926   EVT ValVT;
1927
1928   // If value is passed by pointer we have address passed instead of the value
1929   // itself.
1930   if (VA.getLocInfo() == CCValAssign::Indirect)
1931     ValVT = VA.getLocVT();
1932   else
1933     ValVT = VA.getValVT();
1934
1935   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1936   // changed with more analysis.
1937   // In case of tail call optimization mark all arguments mutable. Since they
1938   // could be overwritten by lowering of arguments in case of a tail call.
1939   if (Flags.isByVal()) {
1940     unsigned Bytes = Flags.getByValSize();
1941     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1942     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1943     return DAG.getFrameIndex(FI, getPointerTy());
1944   } else {
1945     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1946                                     VA.getLocMemOffset(), isImmutable);
1947     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1948     return DAG.getLoad(ValVT, dl, Chain, FIN,
1949                        MachinePointerInfo::getFixedStack(FI),
1950                        false, false, false, 0);
1951   }
1952 }
1953
1954 SDValue
1955 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1956                                         CallingConv::ID CallConv,
1957                                         bool isVarArg,
1958                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1959                                         DebugLoc dl,
1960                                         SelectionDAG &DAG,
1961                                         SmallVectorImpl<SDValue> &InVals)
1962                                           const {
1963   MachineFunction &MF = DAG.getMachineFunction();
1964   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1965
1966   const Function* Fn = MF.getFunction();
1967   if (Fn->hasExternalLinkage() &&
1968       Subtarget->isTargetCygMing() &&
1969       Fn->getName() == "main")
1970     FuncInfo->setForceFramePointer(true);
1971
1972   MachineFrameInfo *MFI = MF.getFrameInfo();
1973   bool Is64Bit = Subtarget->is64Bit();
1974   bool IsWindows = Subtarget->isTargetWindows();
1975   bool IsWin64 = Subtarget->isTargetWin64();
1976
1977   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1978          "Var args not supported with calling convention fastcc, ghc or hipe");
1979
1980   // Assign locations to all of the incoming arguments.
1981   SmallVector<CCValAssign, 16> ArgLocs;
1982   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1983                  ArgLocs, *DAG.getContext());
1984
1985   // Allocate shadow area for Win64
1986   if (IsWin64) {
1987     CCInfo.AllocateStack(32, 8);
1988   }
1989
1990   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1991
1992   unsigned LastVal = ~0U;
1993   SDValue ArgValue;
1994   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1995     CCValAssign &VA = ArgLocs[i];
1996     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1997     // places.
1998     assert(VA.getValNo() != LastVal &&
1999            "Don't support value assigned to multiple locs yet");
2000     (void)LastVal;
2001     LastVal = VA.getValNo();
2002
2003     if (VA.isRegLoc()) {
2004       EVT RegVT = VA.getLocVT();
2005       const TargetRegisterClass *RC;
2006       if (RegVT == MVT::i32)
2007         RC = &X86::GR32RegClass;
2008       else if (Is64Bit && RegVT == MVT::i64)
2009         RC = &X86::GR64RegClass;
2010       else if (RegVT == MVT::f32)
2011         RC = &X86::FR32RegClass;
2012       else if (RegVT == MVT::f64)
2013         RC = &X86::FR64RegClass;
2014       else if (RegVT.is256BitVector())
2015         RC = &X86::VR256RegClass;
2016       else if (RegVT.is128BitVector())
2017         RC = &X86::VR128RegClass;
2018       else if (RegVT == MVT::x86mmx)
2019         RC = &X86::VR64RegClass;
2020       else
2021         llvm_unreachable("Unknown argument type!");
2022
2023       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2024       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2025
2026       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2027       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2028       // right size.
2029       if (VA.getLocInfo() == CCValAssign::SExt)
2030         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2031                                DAG.getValueType(VA.getValVT()));
2032       else if (VA.getLocInfo() == CCValAssign::ZExt)
2033         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2034                                DAG.getValueType(VA.getValVT()));
2035       else if (VA.getLocInfo() == CCValAssign::BCvt)
2036         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2037
2038       if (VA.isExtInLoc()) {
2039         // Handle MMX values passed in XMM regs.
2040         if (RegVT.isVector())
2041           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2042         else
2043           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2044       }
2045     } else {
2046       assert(VA.isMemLoc());
2047       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2048     }
2049
2050     // If value is passed via pointer - do a load.
2051     if (VA.getLocInfo() == CCValAssign::Indirect)
2052       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2053                              MachinePointerInfo(), false, false, false, 0);
2054
2055     InVals.push_back(ArgValue);
2056   }
2057
2058   // The x86-64 ABIs require that for returning structs by value we copy
2059   // the sret argument into %rax/%eax (depending on ABI) for the return.
2060   // Win32 requires us to put the sret argument to %eax as well.
2061   // Save the argument into a virtual register so that we can access it
2062   // from the return points.
2063   if (MF.getFunction()->hasStructRetAttr() &&
2064       (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
2065     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2066     unsigned Reg = FuncInfo->getSRetReturnReg();
2067     if (!Reg) {
2068       MVT PtrTy = getPointerTy();
2069       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2070       FuncInfo->setSRetReturnReg(Reg);
2071     }
2072     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2073     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2074   }
2075
2076   unsigned StackSize = CCInfo.getNextStackOffset();
2077   // Align stack specially for tail calls.
2078   if (FuncIsMadeTailCallSafe(CallConv,
2079                              MF.getTarget().Options.GuaranteedTailCallOpt))
2080     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2081
2082   // If the function takes variable number of arguments, make a frame index for
2083   // the start of the first vararg value... for expansion of llvm.va_start.
2084   if (isVarArg) {
2085     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2086                     CallConv != CallingConv::X86_ThisCall)) {
2087       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2088     }
2089     if (Is64Bit) {
2090       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2091
2092       // FIXME: We should really autogenerate these arrays
2093       static const uint16_t GPR64ArgRegsWin64[] = {
2094         X86::RCX, X86::RDX, X86::R8,  X86::R9
2095       };
2096       static const uint16_t GPR64ArgRegs64Bit[] = {
2097         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2098       };
2099       static const uint16_t XMMArgRegs64Bit[] = {
2100         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2101         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2102       };
2103       const uint16_t *GPR64ArgRegs;
2104       unsigned NumXMMRegs = 0;
2105
2106       if (IsWin64) {
2107         // The XMM registers which might contain var arg parameters are shadowed
2108         // in their paired GPR.  So we only need to save the GPR to their home
2109         // slots.
2110         TotalNumIntRegs = 4;
2111         GPR64ArgRegs = GPR64ArgRegsWin64;
2112       } else {
2113         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2114         GPR64ArgRegs = GPR64ArgRegs64Bit;
2115
2116         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2117                                                 TotalNumXMMRegs);
2118       }
2119       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2120                                                        TotalNumIntRegs);
2121
2122       bool NoImplicitFloatOps = Fn->getAttributes().
2123         hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2124       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2125              "SSE register cannot be used when SSE is disabled!");
2126       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2127                NoImplicitFloatOps) &&
2128              "SSE register cannot be used when SSE is disabled!");
2129       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2130           !Subtarget->hasSSE1())
2131         // Kernel mode asks for SSE to be disabled, so don't push them
2132         // on the stack.
2133         TotalNumXMMRegs = 0;
2134
2135       if (IsWin64) {
2136         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2137         // Get to the caller-allocated home save location.  Add 8 to account
2138         // for the return address.
2139         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2140         FuncInfo->setRegSaveFrameIndex(
2141           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2142         // Fixup to set vararg frame on shadow area (4 x i64).
2143         if (NumIntRegs < 4)
2144           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2145       } else {
2146         // For X86-64, if there are vararg parameters that are passed via
2147         // registers, then we must store them to their spots on the stack so
2148         // they may be loaded by deferencing the result of va_next.
2149         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2150         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2151         FuncInfo->setRegSaveFrameIndex(
2152           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2153                                false));
2154       }
2155
2156       // Store the integer parameter registers.
2157       SmallVector<SDValue, 8> MemOps;
2158       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2159                                         getPointerTy());
2160       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2161       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2162         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2163                                   DAG.getIntPtrConstant(Offset));
2164         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2165                                      &X86::GR64RegClass);
2166         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2167         SDValue Store =
2168           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2169                        MachinePointerInfo::getFixedStack(
2170                          FuncInfo->getRegSaveFrameIndex(), Offset),
2171                        false, false, 0);
2172         MemOps.push_back(Store);
2173         Offset += 8;
2174       }
2175
2176       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2177         // Now store the XMM (fp + vector) parameter registers.
2178         SmallVector<SDValue, 11> SaveXMMOps;
2179         SaveXMMOps.push_back(Chain);
2180
2181         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2182         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2183         SaveXMMOps.push_back(ALVal);
2184
2185         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2186                                FuncInfo->getRegSaveFrameIndex()));
2187         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2188                                FuncInfo->getVarArgsFPOffset()));
2189
2190         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2191           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2192                                        &X86::VR128RegClass);
2193           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2194           SaveXMMOps.push_back(Val);
2195         }
2196         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2197                                      MVT::Other,
2198                                      &SaveXMMOps[0], SaveXMMOps.size()));
2199       }
2200
2201       if (!MemOps.empty())
2202         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2203                             &MemOps[0], MemOps.size());
2204     }
2205   }
2206
2207   // Some CCs need callee pop.
2208   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2209                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2210     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2211   } else {
2212     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2213     // If this is an sret function, the return should pop the hidden pointer.
2214     if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2215         argsAreStructReturn(Ins) == StackStructReturn)
2216       FuncInfo->setBytesToPopOnReturn(4);
2217   }
2218
2219   if (!Is64Bit) {
2220     // RegSaveFrameIndex is X86-64 only.
2221     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2222     if (CallConv == CallingConv::X86_FastCall ||
2223         CallConv == CallingConv::X86_ThisCall)
2224       // fastcc functions can't have varargs.
2225       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2226   }
2227
2228   FuncInfo->setArgumentStackSize(StackSize);
2229
2230   return Chain;
2231 }
2232
2233 SDValue
2234 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2235                                     SDValue StackPtr, SDValue Arg,
2236                                     DebugLoc dl, SelectionDAG &DAG,
2237                                     const CCValAssign &VA,
2238                                     ISD::ArgFlagsTy Flags) const {
2239   unsigned LocMemOffset = VA.getLocMemOffset();
2240   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2241   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2242   if (Flags.isByVal())
2243     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2244
2245   return DAG.getStore(Chain, dl, Arg, PtrOff,
2246                       MachinePointerInfo::getStack(LocMemOffset),
2247                       false, false, 0);
2248 }
2249
2250 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2251 /// optimization is performed and it is required.
2252 SDValue
2253 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2254                                            SDValue &OutRetAddr, SDValue Chain,
2255                                            bool IsTailCall, bool Is64Bit,
2256                                            int FPDiff, DebugLoc dl) const {
2257   // Adjust the Return address stack slot.
2258   EVT VT = getPointerTy();
2259   OutRetAddr = getReturnAddressFrameIndex(DAG);
2260
2261   // Load the "old" Return address.
2262   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2263                            false, false, false, 0);
2264   return SDValue(OutRetAddr.getNode(), 1);
2265 }
2266
2267 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2268 /// optimization is performed and it is required (FPDiff!=0).
2269 static SDValue
2270 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2271                          SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2272                          unsigned SlotSize, int FPDiff, DebugLoc dl) {
2273   // Store the return address to the appropriate stack slot.
2274   if (!FPDiff) return Chain;
2275   // Calculate the new stack slot for the return address.
2276   int NewReturnAddrFI =
2277     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2278   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2279   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2280                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2281                        false, false, 0);
2282   return Chain;
2283 }
2284
2285 SDValue
2286 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2287                              SmallVectorImpl<SDValue> &InVals) const {
2288   SelectionDAG &DAG                     = CLI.DAG;
2289   DebugLoc &dl                          = CLI.DL;
2290   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2291   SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
2292   SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
2293   SDValue Chain                         = CLI.Chain;
2294   SDValue Callee                        = CLI.Callee;
2295   CallingConv::ID CallConv              = CLI.CallConv;
2296   bool &isTailCall                      = CLI.IsTailCall;
2297   bool isVarArg                         = CLI.IsVarArg;
2298
2299   MachineFunction &MF = DAG.getMachineFunction();
2300   bool Is64Bit        = Subtarget->is64Bit();
2301   bool IsWin64        = Subtarget->isTargetWin64();
2302   bool IsWindows      = Subtarget->isTargetWindows();
2303   StructReturnType SR = callIsStructReturn(Outs);
2304   bool IsSibcall      = false;
2305
2306   if (MF.getTarget().Options.DisableTailCalls)
2307     isTailCall = false;
2308
2309   if (isTailCall) {
2310     // Check if it's really possible to do a tail call.
2311     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2312                     isVarArg, SR != NotStructReturn,
2313                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2314                     Outs, OutVals, Ins, DAG);
2315
2316     // Sibcalls are automatically detected tailcalls which do not require
2317     // ABI changes.
2318     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2319       IsSibcall = true;
2320
2321     if (isTailCall)
2322       ++NumTailCalls;
2323   }
2324
2325   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2326          "Var args not supported with calling convention fastcc, ghc or hipe");
2327
2328   // Analyze operands of the call, assigning locations to each operand.
2329   SmallVector<CCValAssign, 16> ArgLocs;
2330   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2331                  ArgLocs, *DAG.getContext());
2332
2333   // Allocate shadow area for Win64
2334   if (IsWin64) {
2335     CCInfo.AllocateStack(32, 8);
2336   }
2337
2338   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2339
2340   // Get a count of how many bytes are to be pushed on the stack.
2341   unsigned NumBytes = CCInfo.getNextStackOffset();
2342   if (IsSibcall)
2343     // This is a sibcall. The memory operands are available in caller's
2344     // own caller's stack.
2345     NumBytes = 0;
2346   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2347            IsTailCallConvention(CallConv))
2348     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2349
2350   int FPDiff = 0;
2351   if (isTailCall && !IsSibcall) {
2352     // Lower arguments at fp - stackoffset + fpdiff.
2353     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2354     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2355
2356     FPDiff = NumBytesCallerPushed - NumBytes;
2357
2358     // Set the delta of movement of the returnaddr stackslot.
2359     // But only set if delta is greater than previous delta.
2360     if (FPDiff < X86Info->getTCReturnAddrDelta())
2361       X86Info->setTCReturnAddrDelta(FPDiff);
2362   }
2363
2364   if (!IsSibcall)
2365     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2366
2367   SDValue RetAddrFrIdx;
2368   // Load return address for tail calls.
2369   if (isTailCall && FPDiff)
2370     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2371                                     Is64Bit, FPDiff, dl);
2372
2373   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2374   SmallVector<SDValue, 8> MemOpChains;
2375   SDValue StackPtr;
2376
2377   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2378   // of tail call optimization arguments are handle later.
2379   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2380     CCValAssign &VA = ArgLocs[i];
2381     EVT RegVT = VA.getLocVT();
2382     SDValue Arg = OutVals[i];
2383     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2384     bool isByVal = Flags.isByVal();
2385
2386     // Promote the value if needed.
2387     switch (VA.getLocInfo()) {
2388     default: llvm_unreachable("Unknown loc info!");
2389     case CCValAssign::Full: break;
2390     case CCValAssign::SExt:
2391       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2392       break;
2393     case CCValAssign::ZExt:
2394       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2395       break;
2396     case CCValAssign::AExt:
2397       if (RegVT.is128BitVector()) {
2398         // Special case: passing MMX values in XMM registers.
2399         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2400         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2401         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2402       } else
2403         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2404       break;
2405     case CCValAssign::BCvt:
2406       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2407       break;
2408     case CCValAssign::Indirect: {
2409       // Store the argument.
2410       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2411       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2412       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2413                            MachinePointerInfo::getFixedStack(FI),
2414                            false, false, 0);
2415       Arg = SpillSlot;
2416       break;
2417     }
2418     }
2419
2420     if (VA.isRegLoc()) {
2421       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2422       if (isVarArg && IsWin64) {
2423         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2424         // shadow reg if callee is a varargs function.
2425         unsigned ShadowReg = 0;
2426         switch (VA.getLocReg()) {
2427         case X86::XMM0: ShadowReg = X86::RCX; break;
2428         case X86::XMM1: ShadowReg = X86::RDX; break;
2429         case X86::XMM2: ShadowReg = X86::R8; break;
2430         case X86::XMM3: ShadowReg = X86::R9; break;
2431         }
2432         if (ShadowReg)
2433           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2434       }
2435     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2436       assert(VA.isMemLoc());
2437       if (StackPtr.getNode() == 0)
2438         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2439                                       getPointerTy());
2440       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2441                                              dl, DAG, VA, Flags));
2442     }
2443   }
2444
2445   if (!MemOpChains.empty())
2446     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2447                         &MemOpChains[0], MemOpChains.size());
2448
2449   if (Subtarget->isPICStyleGOT()) {
2450     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2451     // GOT pointer.
2452     if (!isTailCall) {
2453       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2454                DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy())));
2455     } else {
2456       // If we are tail calling and generating PIC/GOT style code load the
2457       // address of the callee into ECX. The value in ecx is used as target of
2458       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2459       // for tail calls on PIC/GOT architectures. Normally we would just put the
2460       // address of GOT into ebx and then call target@PLT. But for tail calls
2461       // ebx would be restored (since ebx is callee saved) before jumping to the
2462       // target@PLT.
2463
2464       // Note: The actual moving to ECX is done further down.
2465       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2466       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2467           !G->getGlobal()->hasProtectedVisibility())
2468         Callee = LowerGlobalAddress(Callee, DAG);
2469       else if (isa<ExternalSymbolSDNode>(Callee))
2470         Callee = LowerExternalSymbol(Callee, DAG);
2471     }
2472   }
2473
2474   if (Is64Bit && isVarArg && !IsWin64) {
2475     // From AMD64 ABI document:
2476     // For calls that may call functions that use varargs or stdargs
2477     // (prototype-less calls or calls to functions containing ellipsis (...) in
2478     // the declaration) %al is used as hidden argument to specify the number
2479     // of SSE registers used. The contents of %al do not need to match exactly
2480     // the number of registers, but must be an ubound on the number of SSE
2481     // registers used and is in the range 0 - 8 inclusive.
2482
2483     // Count the number of XMM registers allocated.
2484     static const uint16_t XMMArgRegs[] = {
2485       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2486       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2487     };
2488     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2489     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2490            && "SSE registers cannot be used when SSE is disabled");
2491
2492     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2493                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2494   }
2495
2496   // For tail calls lower the arguments to the 'real' stack slot.
2497   if (isTailCall) {
2498     // Force all the incoming stack arguments to be loaded from the stack
2499     // before any new outgoing arguments are stored to the stack, because the
2500     // outgoing stack slots may alias the incoming argument stack slots, and
2501     // the alias isn't otherwise explicit. This is slightly more conservative
2502     // than necessary, because it means that each store effectively depends
2503     // on every argument instead of just those arguments it would clobber.
2504     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2505
2506     SmallVector<SDValue, 8> MemOpChains2;
2507     SDValue FIN;
2508     int FI = 0;
2509     if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2510       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2511         CCValAssign &VA = ArgLocs[i];
2512         if (VA.isRegLoc())
2513           continue;
2514         assert(VA.isMemLoc());
2515         SDValue Arg = OutVals[i];
2516         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2517         // Create frame index.
2518         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2519         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2520         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2521         FIN = DAG.getFrameIndex(FI, getPointerTy());
2522
2523         if (Flags.isByVal()) {
2524           // Copy relative to framepointer.
2525           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2526           if (StackPtr.getNode() == 0)
2527             StackPtr = DAG.getCopyFromReg(Chain, dl,
2528                                           RegInfo->getStackRegister(),
2529                                           getPointerTy());
2530           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2531
2532           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2533                                                            ArgChain,
2534                                                            Flags, DAG, dl));
2535         } else {
2536           // Store relative to framepointer.
2537           MemOpChains2.push_back(
2538             DAG.getStore(ArgChain, dl, Arg, FIN,
2539                          MachinePointerInfo::getFixedStack(FI),
2540                          false, false, 0));
2541         }
2542       }
2543     }
2544
2545     if (!MemOpChains2.empty())
2546       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2547                           &MemOpChains2[0], MemOpChains2.size());
2548
2549     // Store the return address to the appropriate stack slot.
2550     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2551                                      getPointerTy(), RegInfo->getSlotSize(),
2552                                      FPDiff, dl);
2553   }
2554
2555   // Build a sequence of copy-to-reg nodes chained together with token chain
2556   // and flag operands which copy the outgoing args into registers.
2557   SDValue InFlag;
2558   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2559     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2560                              RegsToPass[i].second, InFlag);
2561     InFlag = Chain.getValue(1);
2562   }
2563
2564   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2565     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2566     // In the 64-bit large code model, we have to make all calls
2567     // through a register, since the call instruction's 32-bit
2568     // pc-relative offset may not be large enough to hold the whole
2569     // address.
2570   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2571     // If the callee is a GlobalAddress node (quite common, every direct call
2572     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2573     // it.
2574
2575     // We should use extra load for direct calls to dllimported functions in
2576     // non-JIT mode.
2577     const GlobalValue *GV = G->getGlobal();
2578     if (!GV->hasDLLImportLinkage()) {
2579       unsigned char OpFlags = 0;
2580       bool ExtraLoad = false;
2581       unsigned WrapperKind = ISD::DELETED_NODE;
2582
2583       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2584       // external symbols most go through the PLT in PIC mode.  If the symbol
2585       // has hidden or protected visibility, or if it is static or local, then
2586       // we don't need to use the PLT - we can directly call it.
2587       if (Subtarget->isTargetELF() &&
2588           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2589           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2590         OpFlags = X86II::MO_PLT;
2591       } else if (Subtarget->isPICStyleStubAny() &&
2592                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2593                  (!Subtarget->getTargetTriple().isMacOSX() ||
2594                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2595         // PC-relative references to external symbols should go through $stub,
2596         // unless we're building with the leopard linker or later, which
2597         // automatically synthesizes these stubs.
2598         OpFlags = X86II::MO_DARWIN_STUB;
2599       } else if (Subtarget->isPICStyleRIPRel() &&
2600                  isa<Function>(GV) &&
2601                  cast<Function>(GV)->getAttributes().
2602                    hasAttribute(AttributeSet::FunctionIndex,
2603                                 Attribute::NonLazyBind)) {
2604         // If the function is marked as non-lazy, generate an indirect call
2605         // which loads from the GOT directly. This avoids runtime overhead
2606         // at the cost of eager binding (and one extra byte of encoding).
2607         OpFlags = X86II::MO_GOTPCREL;
2608         WrapperKind = X86ISD::WrapperRIP;
2609         ExtraLoad = true;
2610       }
2611
2612       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2613                                           G->getOffset(), OpFlags);
2614
2615       // Add a wrapper if needed.
2616       if (WrapperKind != ISD::DELETED_NODE)
2617         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2618       // Add extra indirection if needed.
2619       if (ExtraLoad)
2620         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2621                              MachinePointerInfo::getGOT(),
2622                              false, false, false, 0);
2623     }
2624   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2625     unsigned char OpFlags = 0;
2626
2627     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2628     // external symbols should go through the PLT.
2629     if (Subtarget->isTargetELF() &&
2630         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2631       OpFlags = X86II::MO_PLT;
2632     } else if (Subtarget->isPICStyleStubAny() &&
2633                (!Subtarget->getTargetTriple().isMacOSX() ||
2634                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2635       // PC-relative references to external symbols should go through $stub,
2636       // unless we're building with the leopard linker or later, which
2637       // automatically synthesizes these stubs.
2638       OpFlags = X86II::MO_DARWIN_STUB;
2639     }
2640
2641     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2642                                          OpFlags);
2643   }
2644
2645   // Returns a chain & a flag for retval copy to use.
2646   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2647   SmallVector<SDValue, 8> Ops;
2648
2649   if (!IsSibcall && isTailCall) {
2650     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2651                            DAG.getIntPtrConstant(0, true), InFlag);
2652     InFlag = Chain.getValue(1);
2653   }
2654
2655   Ops.push_back(Chain);
2656   Ops.push_back(Callee);
2657
2658   if (isTailCall)
2659     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2660
2661   // Add argument registers to the end of the list so that they are known live
2662   // into the call.
2663   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2664     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2665                                   RegsToPass[i].second.getValueType()));
2666
2667   // Add a register mask operand representing the call-preserved registers.
2668   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2669   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2670   assert(Mask && "Missing call preserved mask for calling convention");
2671   Ops.push_back(DAG.getRegisterMask(Mask));
2672
2673   if (InFlag.getNode())
2674     Ops.push_back(InFlag);
2675
2676   if (isTailCall) {
2677     // We used to do:
2678     //// If this is the first return lowered for this function, add the regs
2679     //// to the liveout set for the function.
2680     // This isn't right, although it's probably harmless on x86; liveouts
2681     // should be computed from returns not tail calls.  Consider a void
2682     // function making a tail call to a function returning int.
2683     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
2684   }
2685
2686   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2687   InFlag = Chain.getValue(1);
2688
2689   // Create the CALLSEQ_END node.
2690   unsigned NumBytesForCalleeToPush;
2691   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2692                        getTargetMachine().Options.GuaranteedTailCallOpt))
2693     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2694   else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2695            SR == StackStructReturn)
2696     // If this is a call to a struct-return function, the callee
2697     // pops the hidden struct pointer, so we have to push it back.
2698     // This is common for Darwin/X86, Linux & Mingw32 targets.
2699     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2700     NumBytesForCalleeToPush = 4;
2701   else
2702     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2703
2704   // Returns a flag for retval copy to use.
2705   if (!IsSibcall) {
2706     Chain = DAG.getCALLSEQ_END(Chain,
2707                                DAG.getIntPtrConstant(NumBytes, true),
2708                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2709                                                      true),
2710                                InFlag);
2711     InFlag = Chain.getValue(1);
2712   }
2713
2714   // Handle result values, copying them out of physregs into vregs that we
2715   // return.
2716   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2717                          Ins, dl, DAG, InVals);
2718 }
2719
2720 //===----------------------------------------------------------------------===//
2721 //                Fast Calling Convention (tail call) implementation
2722 //===----------------------------------------------------------------------===//
2723
2724 //  Like std call, callee cleans arguments, convention except that ECX is
2725 //  reserved for storing the tail called function address. Only 2 registers are
2726 //  free for argument passing (inreg). Tail call optimization is performed
2727 //  provided:
2728 //                * tailcallopt is enabled
2729 //                * caller/callee are fastcc
2730 //  On X86_64 architecture with GOT-style position independent code only local
2731 //  (within module) calls are supported at the moment.
2732 //  To keep the stack aligned according to platform abi the function
2733 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2734 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2735 //  If a tail called function callee has more arguments than the caller the
2736 //  caller needs to make sure that there is room to move the RETADDR to. This is
2737 //  achieved by reserving an area the size of the argument delta right after the
2738 //  original REtADDR, but before the saved framepointer or the spilled registers
2739 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2740 //  stack layout:
2741 //    arg1
2742 //    arg2
2743 //    RETADDR
2744 //    [ new RETADDR
2745 //      move area ]
2746 //    (possible EBP)
2747 //    ESI
2748 //    EDI
2749 //    local1 ..
2750
2751 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2752 /// for a 16 byte align requirement.
2753 unsigned
2754 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2755                                                SelectionDAG& DAG) const {
2756   MachineFunction &MF = DAG.getMachineFunction();
2757   const TargetMachine &TM = MF.getTarget();
2758   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2759   unsigned StackAlignment = TFI.getStackAlignment();
2760   uint64_t AlignMask = StackAlignment - 1;
2761   int64_t Offset = StackSize;
2762   unsigned SlotSize = RegInfo->getSlotSize();
2763   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2764     // Number smaller than 12 so just add the difference.
2765     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2766   } else {
2767     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2768     Offset = ((~AlignMask) & Offset) + StackAlignment +
2769       (StackAlignment-SlotSize);
2770   }
2771   return Offset;
2772 }
2773
2774 /// MatchingStackOffset - Return true if the given stack call argument is
2775 /// already available in the same position (relatively) of the caller's
2776 /// incoming argument stack.
2777 static
2778 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2779                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2780                          const X86InstrInfo *TII) {
2781   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2782   int FI = INT_MAX;
2783   if (Arg.getOpcode() == ISD::CopyFromReg) {
2784     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2785     if (!TargetRegisterInfo::isVirtualRegister(VR))
2786       return false;
2787     MachineInstr *Def = MRI->getVRegDef(VR);
2788     if (!Def)
2789       return false;
2790     if (!Flags.isByVal()) {
2791       if (!TII->isLoadFromStackSlot(Def, FI))
2792         return false;
2793     } else {
2794       unsigned Opcode = Def->getOpcode();
2795       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2796           Def->getOperand(1).isFI()) {
2797         FI = Def->getOperand(1).getIndex();
2798         Bytes = Flags.getByValSize();
2799       } else
2800         return false;
2801     }
2802   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2803     if (Flags.isByVal())
2804       // ByVal argument is passed in as a pointer but it's now being
2805       // dereferenced. e.g.
2806       // define @foo(%struct.X* %A) {
2807       //   tail call @bar(%struct.X* byval %A)
2808       // }
2809       return false;
2810     SDValue Ptr = Ld->getBasePtr();
2811     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2812     if (!FINode)
2813       return false;
2814     FI = FINode->getIndex();
2815   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2816     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2817     FI = FINode->getIndex();
2818     Bytes = Flags.getByValSize();
2819   } else
2820     return false;
2821
2822   assert(FI != INT_MAX);
2823   if (!MFI->isFixedObjectIndex(FI))
2824     return false;
2825   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2826 }
2827
2828 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2829 /// for tail call optimization. Targets which want to do tail call
2830 /// optimization should implement this function.
2831 bool
2832 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2833                                                      CallingConv::ID CalleeCC,
2834                                                      bool isVarArg,
2835                                                      bool isCalleeStructRet,
2836                                                      bool isCallerStructRet,
2837                                                      Type *RetTy,
2838                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2839                                     const SmallVectorImpl<SDValue> &OutVals,
2840                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2841                                                      SelectionDAG &DAG) const {
2842   if (!IsTailCallConvention(CalleeCC) &&
2843       CalleeCC != CallingConv::C)
2844     return false;
2845
2846   // If -tailcallopt is specified, make fastcc functions tail-callable.
2847   const MachineFunction &MF = DAG.getMachineFunction();
2848   const Function *CallerF = DAG.getMachineFunction().getFunction();
2849
2850   // If the function return type is x86_fp80 and the callee return type is not,
2851   // then the FP_EXTEND of the call result is not a nop. It's not safe to
2852   // perform a tailcall optimization here.
2853   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
2854     return false;
2855
2856   CallingConv::ID CallerCC = CallerF->getCallingConv();
2857   bool CCMatch = CallerCC == CalleeCC;
2858
2859   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2860     if (IsTailCallConvention(CalleeCC) && CCMatch)
2861       return true;
2862     return false;
2863   }
2864
2865   // Look for obvious safe cases to perform tail call optimization that do not
2866   // require ABI changes. This is what gcc calls sibcall.
2867
2868   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2869   // emit a special epilogue.
2870   if (RegInfo->needsStackRealignment(MF))
2871     return false;
2872
2873   // Also avoid sibcall optimization if either caller or callee uses struct
2874   // return semantics.
2875   if (isCalleeStructRet || isCallerStructRet)
2876     return false;
2877
2878   // An stdcall caller is expected to clean up its arguments; the callee
2879   // isn't going to do that.
2880   if (!CCMatch && CallerCC == CallingConv::X86_StdCall)
2881     return false;
2882
2883   // Do not sibcall optimize vararg calls unless all arguments are passed via
2884   // registers.
2885   if (isVarArg && !Outs.empty()) {
2886
2887     // Optimizing for varargs on Win64 is unlikely to be safe without
2888     // additional testing.
2889     if (Subtarget->isTargetWin64())
2890       return false;
2891
2892     SmallVector<CCValAssign, 16> ArgLocs;
2893     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2894                    getTargetMachine(), ArgLocs, *DAG.getContext());
2895
2896     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2897     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2898       if (!ArgLocs[i].isRegLoc())
2899         return false;
2900   }
2901
2902   // If the call result is in ST0 / ST1, it needs to be popped off the x87
2903   // stack.  Therefore, if it's not used by the call it is not safe to optimize
2904   // this into a sibcall.
2905   bool Unused = false;
2906   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2907     if (!Ins[i].Used) {
2908       Unused = true;
2909       break;
2910     }
2911   }
2912   if (Unused) {
2913     SmallVector<CCValAssign, 16> RVLocs;
2914     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2915                    getTargetMachine(), RVLocs, *DAG.getContext());
2916     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2917     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2918       CCValAssign &VA = RVLocs[i];
2919       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2920         return false;
2921     }
2922   }
2923
2924   // If the calling conventions do not match, then we'd better make sure the
2925   // results are returned in the same way as what the caller expects.
2926   if (!CCMatch) {
2927     SmallVector<CCValAssign, 16> RVLocs1;
2928     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2929                     getTargetMachine(), RVLocs1, *DAG.getContext());
2930     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2931
2932     SmallVector<CCValAssign, 16> RVLocs2;
2933     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2934                     getTargetMachine(), RVLocs2, *DAG.getContext());
2935     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2936
2937     if (RVLocs1.size() != RVLocs2.size())
2938       return false;
2939     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2940       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2941         return false;
2942       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2943         return false;
2944       if (RVLocs1[i].isRegLoc()) {
2945         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2946           return false;
2947       } else {
2948         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2949           return false;
2950       }
2951     }
2952   }
2953
2954   // If the callee takes no arguments then go on to check the results of the
2955   // call.
2956   if (!Outs.empty()) {
2957     // Check if stack adjustment is needed. For now, do not do this if any
2958     // argument is passed on the stack.
2959     SmallVector<CCValAssign, 16> ArgLocs;
2960     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2961                    getTargetMachine(), ArgLocs, *DAG.getContext());
2962
2963     // Allocate shadow area for Win64
2964     if (Subtarget->isTargetWin64()) {
2965       CCInfo.AllocateStack(32, 8);
2966     }
2967
2968     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2969     if (CCInfo.getNextStackOffset()) {
2970       MachineFunction &MF = DAG.getMachineFunction();
2971       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2972         return false;
2973
2974       // Check if the arguments are already laid out in the right way as
2975       // the caller's fixed stack objects.
2976       MachineFrameInfo *MFI = MF.getFrameInfo();
2977       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2978       const X86InstrInfo *TII =
2979         ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
2980       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2981         CCValAssign &VA = ArgLocs[i];
2982         SDValue Arg = OutVals[i];
2983         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2984         if (VA.getLocInfo() == CCValAssign::Indirect)
2985           return false;
2986         if (!VA.isRegLoc()) {
2987           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2988                                    MFI, MRI, TII))
2989             return false;
2990         }
2991       }
2992     }
2993
2994     // If the tailcall address may be in a register, then make sure it's
2995     // possible to register allocate for it. In 32-bit, the call address can
2996     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2997     // callee-saved registers are restored. These happen to be the same
2998     // registers used to pass 'inreg' arguments so watch out for those.
2999     if (!Subtarget->is64Bit() &&
3000         ((!isa<GlobalAddressSDNode>(Callee) &&
3001           !isa<ExternalSymbolSDNode>(Callee)) ||
3002          getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
3003       unsigned NumInRegs = 0;
3004       // In PIC we need an extra register to formulate the address computation
3005       // for the callee.
3006       unsigned MaxInRegs =
3007           (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3008
3009       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3010         CCValAssign &VA = ArgLocs[i];
3011         if (!VA.isRegLoc())
3012           continue;
3013         unsigned Reg = VA.getLocReg();
3014         switch (Reg) {
3015         default: break;
3016         case X86::EAX: case X86::EDX: case X86::ECX:
3017           if (++NumInRegs == MaxInRegs)
3018             return false;
3019           break;
3020         }
3021       }
3022     }
3023   }
3024
3025   return true;
3026 }
3027
3028 FastISel *
3029 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3030                                   const TargetLibraryInfo *libInfo) const {
3031   return X86::createFastISel(funcInfo, libInfo);
3032 }
3033
3034 //===----------------------------------------------------------------------===//
3035 //                           Other Lowering Hooks
3036 //===----------------------------------------------------------------------===//
3037
3038 static bool MayFoldLoad(SDValue Op) {
3039   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3040 }
3041
3042 static bool MayFoldIntoStore(SDValue Op) {
3043   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3044 }
3045
3046 static bool isTargetShuffle(unsigned Opcode) {
3047   switch(Opcode) {
3048   default: return false;
3049   case X86ISD::PSHUFD:
3050   case X86ISD::PSHUFHW:
3051   case X86ISD::PSHUFLW:
3052   case X86ISD::SHUFP:
3053   case X86ISD::PALIGNR:
3054   case X86ISD::MOVLHPS:
3055   case X86ISD::MOVLHPD:
3056   case X86ISD::MOVHLPS:
3057   case X86ISD::MOVLPS:
3058   case X86ISD::MOVLPD:
3059   case X86ISD::MOVSHDUP:
3060   case X86ISD::MOVSLDUP:
3061   case X86ISD::MOVDDUP:
3062   case X86ISD::MOVSS:
3063   case X86ISD::MOVSD:
3064   case X86ISD::UNPCKL:
3065   case X86ISD::UNPCKH:
3066   case X86ISD::VPERMILP:
3067   case X86ISD::VPERM2X128:
3068   case X86ISD::VPERMI:
3069     return true;
3070   }
3071 }
3072
3073 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3074                                     SDValue V1, SelectionDAG &DAG) {
3075   switch(Opc) {
3076   default: llvm_unreachable("Unknown x86 shuffle node");
3077   case X86ISD::MOVSHDUP:
3078   case X86ISD::MOVSLDUP:
3079   case X86ISD::MOVDDUP:
3080     return DAG.getNode(Opc, dl, VT, V1);
3081   }
3082 }
3083
3084 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3085                                     SDValue V1, unsigned TargetMask,
3086                                     SelectionDAG &DAG) {
3087   switch(Opc) {
3088   default: llvm_unreachable("Unknown x86 shuffle node");
3089   case X86ISD::PSHUFD:
3090   case X86ISD::PSHUFHW:
3091   case X86ISD::PSHUFLW:
3092   case X86ISD::VPERMILP:
3093   case X86ISD::VPERMI:
3094     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3095   }
3096 }
3097
3098 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3099                                     SDValue V1, SDValue V2, unsigned TargetMask,
3100                                     SelectionDAG &DAG) {
3101   switch(Opc) {
3102   default: llvm_unreachable("Unknown x86 shuffle node");
3103   case X86ISD::PALIGNR:
3104   case X86ISD::SHUFP:
3105   case X86ISD::VPERM2X128:
3106     return DAG.getNode(Opc, dl, VT, V1, V2,
3107                        DAG.getConstant(TargetMask, MVT::i8));
3108   }
3109 }
3110
3111 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3112                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3113   switch(Opc) {
3114   default: llvm_unreachable("Unknown x86 shuffle node");
3115   case X86ISD::MOVLHPS:
3116   case X86ISD::MOVLHPD:
3117   case X86ISD::MOVHLPS:
3118   case X86ISD::MOVLPS:
3119   case X86ISD::MOVLPD:
3120   case X86ISD::MOVSS:
3121   case X86ISD::MOVSD:
3122   case X86ISD::UNPCKL:
3123   case X86ISD::UNPCKH:
3124     return DAG.getNode(Opc, dl, VT, V1, V2);
3125   }
3126 }
3127
3128 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3129   MachineFunction &MF = DAG.getMachineFunction();
3130   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3131   int ReturnAddrIndex = FuncInfo->getRAIndex();
3132
3133   if (ReturnAddrIndex == 0) {
3134     // Set up a frame object for the return address.
3135     unsigned SlotSize = RegInfo->getSlotSize();
3136     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
3137                                                            false);
3138     FuncInfo->setRAIndex(ReturnAddrIndex);
3139   }
3140
3141   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3142 }
3143
3144 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3145                                        bool hasSymbolicDisplacement) {
3146   // Offset should fit into 32 bit immediate field.
3147   if (!isInt<32>(Offset))
3148     return false;
3149
3150   // If we don't have a symbolic displacement - we don't have any extra
3151   // restrictions.
3152   if (!hasSymbolicDisplacement)
3153     return true;
3154
3155   // FIXME: Some tweaks might be needed for medium code model.
3156   if (M != CodeModel::Small && M != CodeModel::Kernel)
3157     return false;
3158
3159   // For small code model we assume that latest object is 16MB before end of 31
3160   // bits boundary. We may also accept pretty large negative constants knowing
3161   // that all objects are in the positive half of address space.
3162   if (M == CodeModel::Small && Offset < 16*1024*1024)
3163     return true;
3164
3165   // For kernel code model we know that all object resist in the negative half
3166   // of 32bits address space. We may not accept negative offsets, since they may
3167   // be just off and we may accept pretty large positive ones.
3168   if (M == CodeModel::Kernel && Offset > 0)
3169     return true;
3170
3171   return false;
3172 }
3173
3174 /// isCalleePop - Determines whether the callee is required to pop its
3175 /// own arguments. Callee pop is necessary to support tail calls.
3176 bool X86::isCalleePop(CallingConv::ID CallingConv,
3177                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3178   if (IsVarArg)
3179     return false;
3180
3181   switch (CallingConv) {
3182   default:
3183     return false;
3184   case CallingConv::X86_StdCall:
3185     return !is64Bit;
3186   case CallingConv::X86_FastCall:
3187     return !is64Bit;
3188   case CallingConv::X86_ThisCall:
3189     return !is64Bit;
3190   case CallingConv::Fast:
3191     return TailCallOpt;
3192   case CallingConv::GHC:
3193     return TailCallOpt;
3194   case CallingConv::HiPE:
3195     return TailCallOpt;
3196   }
3197 }
3198
3199 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3200 /// specific condition code, returning the condition code and the LHS/RHS of the
3201 /// comparison to make.
3202 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3203                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3204   if (!isFP) {
3205     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3206       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3207         // X > -1   -> X == 0, jump !sign.
3208         RHS = DAG.getConstant(0, RHS.getValueType());
3209         return X86::COND_NS;
3210       }
3211       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3212         // X < 0   -> X == 0, jump on sign.
3213         return X86::COND_S;
3214       }
3215       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3216         // X < 1   -> X <= 0
3217         RHS = DAG.getConstant(0, RHS.getValueType());
3218         return X86::COND_LE;
3219       }
3220     }
3221
3222     switch (SetCCOpcode) {
3223     default: llvm_unreachable("Invalid integer condition!");
3224     case ISD::SETEQ:  return X86::COND_E;
3225     case ISD::SETGT:  return X86::COND_G;
3226     case ISD::SETGE:  return X86::COND_GE;
3227     case ISD::SETLT:  return X86::COND_L;
3228     case ISD::SETLE:  return X86::COND_LE;
3229     case ISD::SETNE:  return X86::COND_NE;
3230     case ISD::SETULT: return X86::COND_B;
3231     case ISD::SETUGT: return X86::COND_A;
3232     case ISD::SETULE: return X86::COND_BE;
3233     case ISD::SETUGE: return X86::COND_AE;
3234     }
3235   }
3236
3237   // First determine if it is required or is profitable to flip the operands.
3238
3239   // If LHS is a foldable load, but RHS is not, flip the condition.
3240   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3241       !ISD::isNON_EXTLoad(RHS.getNode())) {
3242     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3243     std::swap(LHS, RHS);
3244   }
3245
3246   switch (SetCCOpcode) {
3247   default: break;
3248   case ISD::SETOLT:
3249   case ISD::SETOLE:
3250   case ISD::SETUGT:
3251   case ISD::SETUGE:
3252     std::swap(LHS, RHS);
3253     break;
3254   }
3255
3256   // On a floating point condition, the flags are set as follows:
3257   // ZF  PF  CF   op
3258   //  0 | 0 | 0 | X > Y
3259   //  0 | 0 | 1 | X < Y
3260   //  1 | 0 | 0 | X == Y
3261   //  1 | 1 | 1 | unordered
3262   switch (SetCCOpcode) {
3263   default: llvm_unreachable("Condcode should be pre-legalized away");
3264   case ISD::SETUEQ:
3265   case ISD::SETEQ:   return X86::COND_E;
3266   case ISD::SETOLT:              // flipped
3267   case ISD::SETOGT:
3268   case ISD::SETGT:   return X86::COND_A;
3269   case ISD::SETOLE:              // flipped
3270   case ISD::SETOGE:
3271   case ISD::SETGE:   return X86::COND_AE;
3272   case ISD::SETUGT:              // flipped
3273   case ISD::SETULT:
3274   case ISD::SETLT:   return X86::COND_B;
3275   case ISD::SETUGE:              // flipped
3276   case ISD::SETULE:
3277   case ISD::SETLE:   return X86::COND_BE;
3278   case ISD::SETONE:
3279   case ISD::SETNE:   return X86::COND_NE;
3280   case ISD::SETUO:   return X86::COND_P;
3281   case ISD::SETO:    return X86::COND_NP;
3282   case ISD::SETOEQ:
3283   case ISD::SETUNE:  return X86::COND_INVALID;
3284   }
3285 }
3286
3287 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3288 /// code. Current x86 isa includes the following FP cmov instructions:
3289 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3290 static bool hasFPCMov(unsigned X86CC) {
3291   switch (X86CC) {
3292   default:
3293     return false;
3294   case X86::COND_B:
3295   case X86::COND_BE:
3296   case X86::COND_E:
3297   case X86::COND_P:
3298   case X86::COND_A:
3299   case X86::COND_AE:
3300   case X86::COND_NE:
3301   case X86::COND_NP:
3302     return true;
3303   }
3304 }
3305
3306 /// isFPImmLegal - Returns true if the target can instruction select the
3307 /// specified FP immediate natively. If false, the legalizer will
3308 /// materialize the FP immediate as a load from a constant pool.
3309 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3310   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3311     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3312       return true;
3313   }
3314   return false;
3315 }
3316
3317 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3318 /// the specified range (L, H].
3319 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3320   return (Val < 0) || (Val >= Low && Val < Hi);
3321 }
3322
3323 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3324 /// specified value.
3325 static bool isUndefOrEqual(int Val, int CmpVal) {
3326   return (Val < 0 || Val == CmpVal);
3327 }
3328
3329 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3330 /// from position Pos and ending in Pos+Size, falls within the specified
3331 /// sequential range (L, L+Pos]. or is undef.
3332 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3333                                        unsigned Pos, unsigned Size, int Low) {
3334   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3335     if (!isUndefOrEqual(Mask[i], Low))
3336       return false;
3337   return true;
3338 }
3339
3340 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3341 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3342 /// the second operand.
3343 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3344   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3345     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3346   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3347     return (Mask[0] < 2 && Mask[1] < 2);
3348   return false;
3349 }
3350
3351 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3352 /// is suitable for input to PSHUFHW.
3353 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3354   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3355     return false;
3356
3357   // Lower quadword copied in order or undef.
3358   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3359     return false;
3360
3361   // Upper quadword shuffled.
3362   for (unsigned i = 4; i != 8; ++i)
3363     if (!isUndefOrInRange(Mask[i], 4, 8))
3364       return false;
3365
3366   if (VT == MVT::v16i16) {
3367     // Lower quadword copied in order or undef.
3368     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3369       return false;
3370
3371     // Upper quadword shuffled.
3372     for (unsigned i = 12; i != 16; ++i)
3373       if (!isUndefOrInRange(Mask[i], 12, 16))
3374         return false;
3375   }
3376
3377   return true;
3378 }
3379
3380 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3381 /// is suitable for input to PSHUFLW.
3382 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3383   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3384     return false;
3385
3386   // Upper quadword copied in order.
3387   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3388     return false;
3389
3390   // Lower quadword shuffled.
3391   for (unsigned i = 0; i != 4; ++i)
3392     if (!isUndefOrInRange(Mask[i], 0, 4))
3393       return false;
3394
3395   if (VT == MVT::v16i16) {
3396     // Upper quadword copied in order.
3397     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3398       return false;
3399
3400     // Lower quadword shuffled.
3401     for (unsigned i = 8; i != 12; ++i)
3402       if (!isUndefOrInRange(Mask[i], 8, 12))
3403         return false;
3404   }
3405
3406   return true;
3407 }
3408
3409 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3410 /// is suitable for input to PALIGNR.
3411 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3412                           const X86Subtarget *Subtarget) {
3413   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3414       (VT.is256BitVector() && !Subtarget->hasInt256()))
3415     return false;
3416
3417   unsigned NumElts = VT.getVectorNumElements();
3418   unsigned NumLanes = VT.getSizeInBits()/128;
3419   unsigned NumLaneElts = NumElts/NumLanes;
3420
3421   // Do not handle 64-bit element shuffles with palignr.
3422   if (NumLaneElts == 2)
3423     return false;
3424
3425   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3426     unsigned i;
3427     for (i = 0; i != NumLaneElts; ++i) {
3428       if (Mask[i+l] >= 0)
3429         break;
3430     }
3431
3432     // Lane is all undef, go to next lane
3433     if (i == NumLaneElts)
3434       continue;
3435
3436     int Start = Mask[i+l];
3437
3438     // Make sure its in this lane in one of the sources
3439     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3440         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3441       return false;
3442
3443     // If not lane 0, then we must match lane 0
3444     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3445       return false;
3446
3447     // Correct second source to be contiguous with first source
3448     if (Start >= (int)NumElts)
3449       Start -= NumElts - NumLaneElts;
3450
3451     // Make sure we're shifting in the right direction.
3452     if (Start <= (int)(i+l))
3453       return false;
3454
3455     Start -= i;
3456
3457     // Check the rest of the elements to see if they are consecutive.
3458     for (++i; i != NumLaneElts; ++i) {
3459       int Idx = Mask[i+l];
3460
3461       // Make sure its in this lane
3462       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3463           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3464         return false;
3465
3466       // If not lane 0, then we must match lane 0
3467       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3468         return false;
3469
3470       if (Idx >= (int)NumElts)
3471         Idx -= NumElts - NumLaneElts;
3472
3473       if (!isUndefOrEqual(Idx, Start+i))
3474         return false;
3475
3476     }
3477   }
3478
3479   return true;
3480 }
3481
3482 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3483 /// the two vector operands have swapped position.
3484 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3485                                      unsigned NumElems) {
3486   for (unsigned i = 0; i != NumElems; ++i) {
3487     int idx = Mask[i];
3488     if (idx < 0)
3489       continue;
3490     else if (idx < (int)NumElems)
3491       Mask[i] = idx + NumElems;
3492     else
3493       Mask[i] = idx - NumElems;
3494   }
3495 }
3496
3497 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3498 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3499 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3500 /// reverse of what x86 shuffles want.
3501 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256,
3502                         bool Commuted = false) {
3503   if (!HasFp256 && VT.is256BitVector())
3504     return false;
3505
3506   unsigned NumElems = VT.getVectorNumElements();
3507   unsigned NumLanes = VT.getSizeInBits()/128;
3508   unsigned NumLaneElems = NumElems/NumLanes;
3509
3510   if (NumLaneElems != 2 && NumLaneElems != 4)
3511     return false;
3512
3513   // VSHUFPSY divides the resulting vector into 4 chunks.
3514   // The sources are also splitted into 4 chunks, and each destination
3515   // chunk must come from a different source chunk.
3516   //
3517   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3518   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3519   //
3520   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3521   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3522   //
3523   // VSHUFPDY divides the resulting vector into 4 chunks.
3524   // The sources are also splitted into 4 chunks, and each destination
3525   // chunk must come from a different source chunk.
3526   //
3527   //  SRC1 =>      X3       X2       X1       X0
3528   //  SRC2 =>      Y3       Y2       Y1       Y0
3529   //
3530   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3531   //
3532   unsigned HalfLaneElems = NumLaneElems/2;
3533   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3534     for (unsigned i = 0; i != NumLaneElems; ++i) {
3535       int Idx = Mask[i+l];
3536       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3537       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3538         return false;
3539       // For VSHUFPSY, the mask of the second half must be the same as the
3540       // first but with the appropriate offsets. This works in the same way as
3541       // VPERMILPS works with masks.
3542       if (NumElems != 8 || l == 0 || Mask[i] < 0)
3543         continue;
3544       if (!isUndefOrEqual(Idx, Mask[i]+l))
3545         return false;
3546     }
3547   }
3548
3549   return true;
3550 }
3551
3552 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3553 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3554 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3555   if (!VT.is128BitVector())
3556     return false;
3557
3558   unsigned NumElems = VT.getVectorNumElements();
3559
3560   if (NumElems != 4)
3561     return false;
3562
3563   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3564   return isUndefOrEqual(Mask[0], 6) &&
3565          isUndefOrEqual(Mask[1], 7) &&
3566          isUndefOrEqual(Mask[2], 2) &&
3567          isUndefOrEqual(Mask[3], 3);
3568 }
3569
3570 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3571 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3572 /// <2, 3, 2, 3>
3573 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3574   if (!VT.is128BitVector())
3575     return false;
3576
3577   unsigned NumElems = VT.getVectorNumElements();
3578
3579   if (NumElems != 4)
3580     return false;
3581
3582   return isUndefOrEqual(Mask[0], 2) &&
3583          isUndefOrEqual(Mask[1], 3) &&
3584          isUndefOrEqual(Mask[2], 2) &&
3585          isUndefOrEqual(Mask[3], 3);
3586 }
3587
3588 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3589 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3590 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3591   if (!VT.is128BitVector())
3592     return false;
3593
3594   unsigned NumElems = VT.getVectorNumElements();
3595
3596   if (NumElems != 2 && NumElems != 4)
3597     return false;
3598
3599   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3600     if (!isUndefOrEqual(Mask[i], i + NumElems))
3601       return false;
3602
3603   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3604     if (!isUndefOrEqual(Mask[i], i))
3605       return false;
3606
3607   return true;
3608 }
3609
3610 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3611 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3612 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3613   if (!VT.is128BitVector())
3614     return false;
3615
3616   unsigned NumElems = VT.getVectorNumElements();
3617
3618   if (NumElems != 2 && NumElems != 4)
3619     return false;
3620
3621   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3622     if (!isUndefOrEqual(Mask[i], i))
3623       return false;
3624
3625   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3626     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3627       return false;
3628
3629   return true;
3630 }
3631
3632 //
3633 // Some special combinations that can be optimized.
3634 //
3635 static
3636 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3637                                SelectionDAG &DAG) {
3638   MVT VT = SVOp->getValueType(0).getSimpleVT();
3639   DebugLoc dl = SVOp->getDebugLoc();
3640
3641   if (VT != MVT::v8i32 && VT != MVT::v8f32)
3642     return SDValue();
3643
3644   ArrayRef<int> Mask = SVOp->getMask();
3645
3646   // These are the special masks that may be optimized.
3647   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3648   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
3649   bool MatchEvenMask = true;
3650   bool MatchOddMask  = true;
3651   for (int i=0; i<8; ++i) {
3652     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3653       MatchEvenMask = false;
3654     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3655       MatchOddMask = false;
3656   }
3657
3658   if (!MatchEvenMask && !MatchOddMask)
3659     return SDValue();
3660
3661   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3662
3663   SDValue Op0 = SVOp->getOperand(0);
3664   SDValue Op1 = SVOp->getOperand(1);
3665
3666   if (MatchEvenMask) {
3667     // Shift the second operand right to 32 bits.
3668     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3669     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3670   } else {
3671     // Shift the first operand left to 32 bits.
3672     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3673     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3674   }
3675   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3676   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3677 }
3678
3679 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3680 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3681 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3682                          bool HasInt256, bool V2IsSplat = false) {
3683   unsigned NumElts = VT.getVectorNumElements();
3684
3685   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3686          "Unsupported vector type for unpckh");
3687
3688   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3689       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3690     return false;
3691
3692   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3693   // independently on 128-bit lanes.
3694   unsigned NumLanes = VT.getSizeInBits()/128;
3695   unsigned NumLaneElts = NumElts/NumLanes;
3696
3697   for (unsigned l = 0; l != NumLanes; ++l) {
3698     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3699          i != (l+1)*NumLaneElts;
3700          i += 2, ++j) {
3701       int BitI  = Mask[i];
3702       int BitI1 = Mask[i+1];
3703       if (!isUndefOrEqual(BitI, j))
3704         return false;
3705       if (V2IsSplat) {
3706         if (!isUndefOrEqual(BitI1, NumElts))
3707           return false;
3708       } else {
3709         if (!isUndefOrEqual(BitI1, j + NumElts))
3710           return false;
3711       }
3712     }
3713   }
3714
3715   return true;
3716 }
3717
3718 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3719 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3720 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3721                          bool HasInt256, bool V2IsSplat = false) {
3722   unsigned NumElts = VT.getVectorNumElements();
3723
3724   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3725          "Unsupported vector type for unpckh");
3726
3727   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3728       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3729     return false;
3730
3731   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3732   // independently on 128-bit lanes.
3733   unsigned NumLanes = VT.getSizeInBits()/128;
3734   unsigned NumLaneElts = NumElts/NumLanes;
3735
3736   for (unsigned l = 0; l != NumLanes; ++l) {
3737     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3738          i != (l+1)*NumLaneElts; i += 2, ++j) {
3739       int BitI  = Mask[i];
3740       int BitI1 = Mask[i+1];
3741       if (!isUndefOrEqual(BitI, j))
3742         return false;
3743       if (V2IsSplat) {
3744         if (isUndefOrEqual(BitI1, NumElts))
3745           return false;
3746       } else {
3747         if (!isUndefOrEqual(BitI1, j+NumElts))
3748           return false;
3749       }
3750     }
3751   }
3752   return true;
3753 }
3754
3755 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3756 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3757 /// <0, 0, 1, 1>
3758 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3759   unsigned NumElts = VT.getVectorNumElements();
3760   bool Is256BitVec = VT.is256BitVector();
3761
3762   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3763          "Unsupported vector type for unpckh");
3764
3765   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
3766       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3767     return false;
3768
3769   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3770   // FIXME: Need a better way to get rid of this, there's no latency difference
3771   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3772   // the former later. We should also remove the "_undef" special mask.
3773   if (NumElts == 4 && Is256BitVec)
3774     return false;
3775
3776   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3777   // independently on 128-bit lanes.
3778   unsigned NumLanes = VT.getSizeInBits()/128;
3779   unsigned NumLaneElts = NumElts/NumLanes;
3780
3781   for (unsigned l = 0; l != NumLanes; ++l) {
3782     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3783          i != (l+1)*NumLaneElts;
3784          i += 2, ++j) {
3785       int BitI  = Mask[i];
3786       int BitI1 = Mask[i+1];
3787
3788       if (!isUndefOrEqual(BitI, j))
3789         return false;
3790       if (!isUndefOrEqual(BitI1, j))
3791         return false;
3792     }
3793   }
3794
3795   return true;
3796 }
3797
3798 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3799 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3800 /// <2, 2, 3, 3>
3801 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3802   unsigned NumElts = VT.getVectorNumElements();
3803
3804   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3805          "Unsupported vector type for unpckh");
3806
3807   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3808       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3809     return false;
3810
3811   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3812   // independently on 128-bit lanes.
3813   unsigned NumLanes = VT.getSizeInBits()/128;
3814   unsigned NumLaneElts = NumElts/NumLanes;
3815
3816   for (unsigned l = 0; l != NumLanes; ++l) {
3817     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3818          i != (l+1)*NumLaneElts; i += 2, ++j) {
3819       int BitI  = Mask[i];
3820       int BitI1 = Mask[i+1];
3821       if (!isUndefOrEqual(BitI, j))
3822         return false;
3823       if (!isUndefOrEqual(BitI1, j))
3824         return false;
3825     }
3826   }
3827   return true;
3828 }
3829
3830 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3831 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3832 /// MOVSD, and MOVD, i.e. setting the lowest element.
3833 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3834   if (VT.getVectorElementType().getSizeInBits() < 32)
3835     return false;
3836   if (!VT.is128BitVector())
3837     return false;
3838
3839   unsigned NumElts = VT.getVectorNumElements();
3840
3841   if (!isUndefOrEqual(Mask[0], NumElts))
3842     return false;
3843
3844   for (unsigned i = 1; i != NumElts; ++i)
3845     if (!isUndefOrEqual(Mask[i], i))
3846       return false;
3847
3848   return true;
3849 }
3850
3851 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3852 /// as permutations between 128-bit chunks or halves. As an example: this
3853 /// shuffle bellow:
3854 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3855 /// The first half comes from the second half of V1 and the second half from the
3856 /// the second half of V2.
3857 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3858   if (!HasFp256 || !VT.is256BitVector())
3859     return false;
3860
3861   // The shuffle result is divided into half A and half B. In total the two
3862   // sources have 4 halves, namely: C, D, E, F. The final values of A and
3863   // B must come from C, D, E or F.
3864   unsigned HalfSize = VT.getVectorNumElements()/2;
3865   bool MatchA = false, MatchB = false;
3866
3867   // Check if A comes from one of C, D, E, F.
3868   for (unsigned Half = 0; Half != 4; ++Half) {
3869     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3870       MatchA = true;
3871       break;
3872     }
3873   }
3874
3875   // Check if B comes from one of C, D, E, F.
3876   for (unsigned Half = 0; Half != 4; ++Half) {
3877     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3878       MatchB = true;
3879       break;
3880     }
3881   }
3882
3883   return MatchA && MatchB;
3884 }
3885
3886 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3887 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3888 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3889   MVT VT = SVOp->getValueType(0).getSimpleVT();
3890
3891   unsigned HalfSize = VT.getVectorNumElements()/2;
3892
3893   unsigned FstHalf = 0, SndHalf = 0;
3894   for (unsigned i = 0; i < HalfSize; ++i) {
3895     if (SVOp->getMaskElt(i) > 0) {
3896       FstHalf = SVOp->getMaskElt(i)/HalfSize;
3897       break;
3898     }
3899   }
3900   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3901     if (SVOp->getMaskElt(i) > 0) {
3902       SndHalf = SVOp->getMaskElt(i)/HalfSize;
3903       break;
3904     }
3905   }
3906
3907   return (FstHalf | (SndHalf << 4));
3908 }
3909
3910 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3911 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3912 /// Note that VPERMIL mask matching is different depending whether theunderlying
3913 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3914 /// to the same elements of the low, but to the higher half of the source.
3915 /// In VPERMILPD the two lanes could be shuffled independently of each other
3916 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
3917 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3918   if (!HasFp256)
3919     return false;
3920
3921   unsigned NumElts = VT.getVectorNumElements();
3922   // Only match 256-bit with 32/64-bit types
3923   if (!VT.is256BitVector() || (NumElts != 4 && NumElts != 8))
3924     return false;
3925
3926   unsigned NumLanes = VT.getSizeInBits()/128;
3927   unsigned LaneSize = NumElts/NumLanes;
3928   for (unsigned l = 0; l != NumElts; l += LaneSize) {
3929     for (unsigned i = 0; i != LaneSize; ++i) {
3930       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3931         return false;
3932       if (NumElts != 8 || l == 0)
3933         continue;
3934       // VPERMILPS handling
3935       if (Mask[i] < 0)
3936         continue;
3937       if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3938         return false;
3939     }
3940   }
3941
3942   return true;
3943 }
3944
3945 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
3946 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3947 /// element of vector 2 and the other elements to come from vector 1 in order.
3948 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3949                                bool V2IsSplat = false, bool V2IsUndef = false) {
3950   if (!VT.is128BitVector())
3951     return false;
3952
3953   unsigned NumOps = VT.getVectorNumElements();
3954   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3955     return false;
3956
3957   if (!isUndefOrEqual(Mask[0], 0))
3958     return false;
3959
3960   for (unsigned i = 1; i != NumOps; ++i)
3961     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3962           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3963           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3964       return false;
3965
3966   return true;
3967 }
3968
3969 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3970 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3971 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3972 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
3973                            const X86Subtarget *Subtarget) {
3974   if (!Subtarget->hasSSE3())
3975     return false;
3976
3977   unsigned NumElems = VT.getVectorNumElements();
3978
3979   if ((VT.is128BitVector() && NumElems != 4) ||
3980       (VT.is256BitVector() && NumElems != 8))
3981     return false;
3982
3983   // "i+1" is the value the indexed mask element must have
3984   for (unsigned i = 0; i != NumElems; i += 2)
3985     if (!isUndefOrEqual(Mask[i], i+1) ||
3986         !isUndefOrEqual(Mask[i+1], i+1))
3987       return false;
3988
3989   return true;
3990 }
3991
3992 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3993 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3994 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3995 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3996                            const X86Subtarget *Subtarget) {
3997   if (!Subtarget->hasSSE3())
3998     return false;
3999
4000   unsigned NumElems = VT.getVectorNumElements();
4001
4002   if ((VT.is128BitVector() && NumElems != 4) ||
4003       (VT.is256BitVector() && NumElems != 8))
4004     return false;
4005
4006   // "i" is the value the indexed mask element must have
4007   for (unsigned i = 0; i != NumElems; i += 2)
4008     if (!isUndefOrEqual(Mask[i], i) ||
4009         !isUndefOrEqual(Mask[i+1], i))
4010       return false;
4011
4012   return true;
4013 }
4014
4015 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4016 /// specifies a shuffle of elements that is suitable for input to 256-bit
4017 /// version of MOVDDUP.
4018 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
4019   if (!HasFp256 || !VT.is256BitVector())
4020     return false;
4021
4022   unsigned NumElts = VT.getVectorNumElements();
4023   if (NumElts != 4)
4024     return false;
4025
4026   for (unsigned i = 0; i != NumElts/2; ++i)
4027     if (!isUndefOrEqual(Mask[i], 0))
4028       return false;
4029   for (unsigned i = NumElts/2; i != NumElts; ++i)
4030     if (!isUndefOrEqual(Mask[i], NumElts/2))
4031       return false;
4032   return true;
4033 }
4034
4035 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4036 /// specifies a shuffle of elements that is suitable for input to 128-bit
4037 /// version of MOVDDUP.
4038 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
4039   if (!VT.is128BitVector())
4040     return false;
4041
4042   unsigned e = VT.getVectorNumElements() / 2;
4043   for (unsigned i = 0; i != e; ++i)
4044     if (!isUndefOrEqual(Mask[i], i))
4045       return false;
4046   for (unsigned i = 0; i != e; ++i)
4047     if (!isUndefOrEqual(Mask[e+i], i))
4048       return false;
4049   return true;
4050 }
4051
4052 /// isVEXTRACTF128Index - Return true if the specified
4053 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4054 /// suitable for input to VEXTRACTF128.
4055 bool X86::isVEXTRACTF128Index(SDNode *N) {
4056   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4057     return false;
4058
4059   // The index should be aligned on a 128-bit boundary.
4060   uint64_t Index =
4061     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4062
4063   MVT VT = N->getValueType(0).getSimpleVT();
4064   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4065   bool Result = (Index * ElSize) % 128 == 0;
4066
4067   return Result;
4068 }
4069
4070 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
4071 /// operand specifies a subvector insert that is suitable for input to
4072 /// VINSERTF128.
4073 bool X86::isVINSERTF128Index(SDNode *N) {
4074   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4075     return false;
4076
4077   // The index should be aligned on a 128-bit boundary.
4078   uint64_t Index =
4079     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4080
4081   MVT VT = N->getValueType(0).getSimpleVT();
4082   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4083   bool Result = (Index * ElSize) % 128 == 0;
4084
4085   return Result;
4086 }
4087
4088 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4089 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4090 /// Handles 128-bit and 256-bit.
4091 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4092   MVT VT = N->getValueType(0).getSimpleVT();
4093
4094   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4095          "Unsupported vector type for PSHUF/SHUFP");
4096
4097   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4098   // independently on 128-bit lanes.
4099   unsigned NumElts = VT.getVectorNumElements();
4100   unsigned NumLanes = VT.getSizeInBits()/128;
4101   unsigned NumLaneElts = NumElts/NumLanes;
4102
4103   assert((NumLaneElts == 2 || NumLaneElts == 4) &&
4104          "Only supports 2 or 4 elements per lane");
4105
4106   unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
4107   unsigned Mask = 0;
4108   for (unsigned i = 0; i != NumElts; ++i) {
4109     int Elt = N->getMaskElt(i);
4110     if (Elt < 0) continue;
4111     Elt &= NumLaneElts - 1;
4112     unsigned ShAmt = (i << Shift) % 8;
4113     Mask |= Elt << ShAmt;
4114   }
4115
4116   return Mask;
4117 }
4118
4119 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4120 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4121 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4122   MVT VT = N->getValueType(0).getSimpleVT();
4123
4124   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4125          "Unsupported vector type for PSHUFHW");
4126
4127   unsigned NumElts = VT.getVectorNumElements();
4128
4129   unsigned Mask = 0;
4130   for (unsigned l = 0; l != NumElts; l += 8) {
4131     // 8 nodes per lane, but we only care about the last 4.
4132     for (unsigned i = 0; i < 4; ++i) {
4133       int Elt = N->getMaskElt(l+i+4);
4134       if (Elt < 0) continue;
4135       Elt &= 0x3; // only 2-bits.
4136       Mask |= Elt << (i * 2);
4137     }
4138   }
4139
4140   return Mask;
4141 }
4142
4143 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4144 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4145 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4146   MVT VT = N->getValueType(0).getSimpleVT();
4147
4148   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4149          "Unsupported vector type for PSHUFHW");
4150
4151   unsigned NumElts = VT.getVectorNumElements();
4152
4153   unsigned Mask = 0;
4154   for (unsigned l = 0; l != NumElts; l += 8) {
4155     // 8 nodes per lane, but we only care about the first 4.
4156     for (unsigned i = 0; i < 4; ++i) {
4157       int Elt = N->getMaskElt(l+i);
4158       if (Elt < 0) continue;
4159       Elt &= 0x3; // only 2-bits
4160       Mask |= Elt << (i * 2);
4161     }
4162   }
4163
4164   return Mask;
4165 }
4166
4167 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4168 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4169 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4170   MVT VT = SVOp->getValueType(0).getSimpleVT();
4171   unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4172
4173   unsigned NumElts = VT.getVectorNumElements();
4174   unsigned NumLanes = VT.getSizeInBits()/128;
4175   unsigned NumLaneElts = NumElts/NumLanes;
4176
4177   int Val = 0;
4178   unsigned i;
4179   for (i = 0; i != NumElts; ++i) {
4180     Val = SVOp->getMaskElt(i);
4181     if (Val >= 0)
4182       break;
4183   }
4184   if (Val >= (int)NumElts)
4185     Val -= NumElts - NumLaneElts;
4186
4187   assert(Val - i > 0 && "PALIGNR imm should be positive");
4188   return (Val - i) * EltSize;
4189 }
4190
4191 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4192 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4193 /// instructions.
4194 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4195   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4196     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4197
4198   uint64_t Index =
4199     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4200
4201   MVT VecVT = N->getOperand(0).getValueType().getSimpleVT();
4202   MVT ElVT = VecVT.getVectorElementType();
4203
4204   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4205   return Index / NumElemsPerChunk;
4206 }
4207
4208 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4209 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4210 /// instructions.
4211 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4212   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4213     llvm_unreachable("Illegal insert subvector for VINSERTF128");
4214
4215   uint64_t Index =
4216     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4217
4218   MVT VecVT = N->getValueType(0).getSimpleVT();
4219   MVT ElVT = VecVT.getVectorElementType();
4220
4221   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4222   return Index / NumElemsPerChunk;
4223 }
4224
4225 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4226 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4227 /// Handles 256-bit.
4228 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4229   MVT VT = N->getValueType(0).getSimpleVT();
4230
4231   unsigned NumElts = VT.getVectorNumElements();
4232
4233   assert((VT.is256BitVector() && NumElts == 4) &&
4234          "Unsupported vector type for VPERMQ/VPERMPD");
4235
4236   unsigned Mask = 0;
4237   for (unsigned i = 0; i != NumElts; ++i) {
4238     int Elt = N->getMaskElt(i);
4239     if (Elt < 0)
4240       continue;
4241     Mask |= Elt << (i*2);
4242   }
4243
4244   return Mask;
4245 }
4246 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4247 /// constant +0.0.
4248 bool X86::isZeroNode(SDValue Elt) {
4249   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Elt))
4250     return CN->isNullValue();
4251   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4252     return CFP->getValueAPF().isPosZero();
4253   return false;
4254 }
4255
4256 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4257 /// their permute mask.
4258 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4259                                     SelectionDAG &DAG) {
4260   MVT VT = SVOp->getValueType(0).getSimpleVT();
4261   unsigned NumElems = VT.getVectorNumElements();
4262   SmallVector<int, 8> MaskVec;
4263
4264   for (unsigned i = 0; i != NumElems; ++i) {
4265     int Idx = SVOp->getMaskElt(i);
4266     if (Idx >= 0) {
4267       if (Idx < (int)NumElems)
4268         Idx += NumElems;
4269       else
4270         Idx -= NumElems;
4271     }
4272     MaskVec.push_back(Idx);
4273   }
4274   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4275                               SVOp->getOperand(0), &MaskVec[0]);
4276 }
4277
4278 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4279 /// match movhlps. The lower half elements should come from upper half of
4280 /// V1 (and in order), and the upper half elements should come from the upper
4281 /// half of V2 (and in order).
4282 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4283   if (!VT.is128BitVector())
4284     return false;
4285   if (VT.getVectorNumElements() != 4)
4286     return false;
4287   for (unsigned i = 0, e = 2; i != e; ++i)
4288     if (!isUndefOrEqual(Mask[i], i+2))
4289       return false;
4290   for (unsigned i = 2; i != 4; ++i)
4291     if (!isUndefOrEqual(Mask[i], i+4))
4292       return false;
4293   return true;
4294 }
4295
4296 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4297 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4298 /// required.
4299 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4300   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4301     return false;
4302   N = N->getOperand(0).getNode();
4303   if (!ISD::isNON_EXTLoad(N))
4304     return false;
4305   if (LD)
4306     *LD = cast<LoadSDNode>(N);
4307   return true;
4308 }
4309
4310 // Test whether the given value is a vector value which will be legalized
4311 // into a load.
4312 static bool WillBeConstantPoolLoad(SDNode *N) {
4313   if (N->getOpcode() != ISD::BUILD_VECTOR)
4314     return false;
4315
4316   // Check for any non-constant elements.
4317   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4318     switch (N->getOperand(i).getNode()->getOpcode()) {
4319     case ISD::UNDEF:
4320     case ISD::ConstantFP:
4321     case ISD::Constant:
4322       break;
4323     default:
4324       return false;
4325     }
4326
4327   // Vectors of all-zeros and all-ones are materialized with special
4328   // instructions rather than being loaded.
4329   return !ISD::isBuildVectorAllZeros(N) &&
4330          !ISD::isBuildVectorAllOnes(N);
4331 }
4332
4333 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4334 /// match movlp{s|d}. The lower half elements should come from lower half of
4335 /// V1 (and in order), and the upper half elements should come from the upper
4336 /// half of V2 (and in order). And since V1 will become the source of the
4337 /// MOVLP, it must be either a vector load or a scalar load to vector.
4338 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4339                                ArrayRef<int> Mask, EVT VT) {
4340   if (!VT.is128BitVector())
4341     return false;
4342
4343   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4344     return false;
4345   // Is V2 is a vector load, don't do this transformation. We will try to use
4346   // load folding shufps op.
4347   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4348     return false;
4349
4350   unsigned NumElems = VT.getVectorNumElements();
4351
4352   if (NumElems != 2 && NumElems != 4)
4353     return false;
4354   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4355     if (!isUndefOrEqual(Mask[i], i))
4356       return false;
4357   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4358     if (!isUndefOrEqual(Mask[i], i+NumElems))
4359       return false;
4360   return true;
4361 }
4362
4363 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4364 /// all the same.
4365 static bool isSplatVector(SDNode *N) {
4366   if (N->getOpcode() != ISD::BUILD_VECTOR)
4367     return false;
4368
4369   SDValue SplatValue = N->getOperand(0);
4370   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4371     if (N->getOperand(i) != SplatValue)
4372       return false;
4373   return true;
4374 }
4375
4376 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4377 /// to an zero vector.
4378 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4379 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4380   SDValue V1 = N->getOperand(0);
4381   SDValue V2 = N->getOperand(1);
4382   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4383   for (unsigned i = 0; i != NumElems; ++i) {
4384     int Idx = N->getMaskElt(i);
4385     if (Idx >= (int)NumElems) {
4386       unsigned Opc = V2.getOpcode();
4387       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4388         continue;
4389       if (Opc != ISD::BUILD_VECTOR ||
4390           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4391         return false;
4392     } else if (Idx >= 0) {
4393       unsigned Opc = V1.getOpcode();
4394       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4395         continue;
4396       if (Opc != ISD::BUILD_VECTOR ||
4397           !X86::isZeroNode(V1.getOperand(Idx)))
4398         return false;
4399     }
4400   }
4401   return true;
4402 }
4403
4404 /// getZeroVector - Returns a vector of specified type with all zero elements.
4405 ///
4406 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4407                              SelectionDAG &DAG, DebugLoc dl) {
4408   assert(VT.isVector() && "Expected a vector type");
4409
4410   // Always build SSE zero vectors as <4 x i32> bitcasted
4411   // to their dest type. This ensures they get CSE'd.
4412   SDValue Vec;
4413   if (VT.is128BitVector()) {  // SSE
4414     if (Subtarget->hasSSE2()) {  // SSE2
4415       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4416       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4417     } else { // SSE1
4418       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4419       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4420     }
4421   } else if (VT.is256BitVector()) { // AVX
4422     if (Subtarget->hasInt256()) { // AVX2
4423       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4424       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4425       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4426     } else {
4427       // 256-bit logic and arithmetic instructions in AVX are all
4428       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4429       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4430       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4431       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4432     }
4433   } else
4434     llvm_unreachable("Unexpected vector type");
4435
4436   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4437 }
4438
4439 /// getOnesVector - Returns a vector of specified type with all bits set.
4440 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4441 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4442 /// Then bitcast to their original type, ensuring they get CSE'd.
4443 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4444                              DebugLoc dl) {
4445   assert(VT.isVector() && "Expected a vector type");
4446
4447   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4448   SDValue Vec;
4449   if (VT.is256BitVector()) {
4450     if (HasInt256) { // AVX2
4451       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4452       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4453     } else { // AVX
4454       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4455       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4456     }
4457   } else if (VT.is128BitVector()) {
4458     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4459   } else
4460     llvm_unreachable("Unexpected vector type");
4461
4462   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4463 }
4464
4465 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4466 /// that point to V2 points to its first element.
4467 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4468   for (unsigned i = 0; i != NumElems; ++i) {
4469     if (Mask[i] > (int)NumElems) {
4470       Mask[i] = NumElems;
4471     }
4472   }
4473 }
4474
4475 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4476 /// operation of specified width.
4477 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4478                        SDValue V2) {
4479   unsigned NumElems = VT.getVectorNumElements();
4480   SmallVector<int, 8> Mask;
4481   Mask.push_back(NumElems);
4482   for (unsigned i = 1; i != NumElems; ++i)
4483     Mask.push_back(i);
4484   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4485 }
4486
4487 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4488 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4489                           SDValue V2) {
4490   unsigned NumElems = VT.getVectorNumElements();
4491   SmallVector<int, 8> Mask;
4492   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4493     Mask.push_back(i);
4494     Mask.push_back(i + NumElems);
4495   }
4496   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4497 }
4498
4499 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4500 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4501                           SDValue V2) {
4502   unsigned NumElems = VT.getVectorNumElements();
4503   SmallVector<int, 8> Mask;
4504   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4505     Mask.push_back(i + Half);
4506     Mask.push_back(i + NumElems + Half);
4507   }
4508   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4509 }
4510
4511 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4512 // a generic shuffle instruction because the target has no such instructions.
4513 // Generate shuffles which repeat i16 and i8 several times until they can be
4514 // represented by v4f32 and then be manipulated by target suported shuffles.
4515 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4516   EVT VT = V.getValueType();
4517   int NumElems = VT.getVectorNumElements();
4518   DebugLoc dl = V.getDebugLoc();
4519
4520   while (NumElems > 4) {
4521     if (EltNo < NumElems/2) {
4522       V = getUnpackl(DAG, dl, VT, V, V);
4523     } else {
4524       V = getUnpackh(DAG, dl, VT, V, V);
4525       EltNo -= NumElems/2;
4526     }
4527     NumElems >>= 1;
4528   }
4529   return V;
4530 }
4531
4532 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4533 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4534   EVT VT = V.getValueType();
4535   DebugLoc dl = V.getDebugLoc();
4536
4537   if (VT.is128BitVector()) {
4538     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4539     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4540     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4541                              &SplatMask[0]);
4542   } else if (VT.is256BitVector()) {
4543     // To use VPERMILPS to splat scalars, the second half of indicies must
4544     // refer to the higher part, which is a duplication of the lower one,
4545     // because VPERMILPS can only handle in-lane permutations.
4546     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4547                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4548
4549     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4550     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4551                              &SplatMask[0]);
4552   } else
4553     llvm_unreachable("Vector size not supported");
4554
4555   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4556 }
4557
4558 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4559 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4560   EVT SrcVT = SV->getValueType(0);
4561   SDValue V1 = SV->getOperand(0);
4562   DebugLoc dl = SV->getDebugLoc();
4563
4564   int EltNo = SV->getSplatIndex();
4565   int NumElems = SrcVT.getVectorNumElements();
4566   bool Is256BitVec = SrcVT.is256BitVector();
4567
4568   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
4569          "Unknown how to promote splat for type");
4570
4571   // Extract the 128-bit part containing the splat element and update
4572   // the splat element index when it refers to the higher register.
4573   if (Is256BitVec) {
4574     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4575     if (EltNo >= NumElems/2)
4576       EltNo -= NumElems/2;
4577   }
4578
4579   // All i16 and i8 vector types can't be used directly by a generic shuffle
4580   // instruction because the target has no such instruction. Generate shuffles
4581   // which repeat i16 and i8 several times until they fit in i32, and then can
4582   // be manipulated by target suported shuffles.
4583   EVT EltVT = SrcVT.getVectorElementType();
4584   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4585     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4586
4587   // Recreate the 256-bit vector and place the same 128-bit vector
4588   // into the low and high part. This is necessary because we want
4589   // to use VPERM* to shuffle the vectors
4590   if (Is256BitVec) {
4591     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4592   }
4593
4594   return getLegalSplat(DAG, V1, EltNo);
4595 }
4596
4597 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4598 /// vector of zero or undef vector.  This produces a shuffle where the low
4599 /// element of V2 is swizzled into the zero/undef vector, landing at element
4600 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4601 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4602                                            bool IsZero,
4603                                            const X86Subtarget *Subtarget,
4604                                            SelectionDAG &DAG) {
4605   EVT VT = V2.getValueType();
4606   SDValue V1 = IsZero
4607     ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4608   unsigned NumElems = VT.getVectorNumElements();
4609   SmallVector<int, 16> MaskVec;
4610   for (unsigned i = 0; i != NumElems; ++i)
4611     // If this is the insertion idx, put the low elt of V2 here.
4612     MaskVec.push_back(i == Idx ? NumElems : i);
4613   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4614 }
4615
4616 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4617 /// target specific opcode. Returns true if the Mask could be calculated.
4618 /// Sets IsUnary to true if only uses one source.
4619 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4620                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4621   unsigned NumElems = VT.getVectorNumElements();
4622   SDValue ImmN;
4623
4624   IsUnary = false;
4625   switch(N->getOpcode()) {
4626   case X86ISD::SHUFP:
4627     ImmN = N->getOperand(N->getNumOperands()-1);
4628     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4629     break;
4630   case X86ISD::UNPCKH:
4631     DecodeUNPCKHMask(VT, Mask);
4632     break;
4633   case X86ISD::UNPCKL:
4634     DecodeUNPCKLMask(VT, Mask);
4635     break;
4636   case X86ISD::MOVHLPS:
4637     DecodeMOVHLPSMask(NumElems, Mask);
4638     break;
4639   case X86ISD::MOVLHPS:
4640     DecodeMOVLHPSMask(NumElems, Mask);
4641     break;
4642   case X86ISD::PALIGNR:
4643     ImmN = N->getOperand(N->getNumOperands()-1);
4644     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4645     break;
4646   case X86ISD::PSHUFD:
4647   case X86ISD::VPERMILP:
4648     ImmN = N->getOperand(N->getNumOperands()-1);
4649     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4650     IsUnary = true;
4651     break;
4652   case X86ISD::PSHUFHW:
4653     ImmN = N->getOperand(N->getNumOperands()-1);
4654     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4655     IsUnary = true;
4656     break;
4657   case X86ISD::PSHUFLW:
4658     ImmN = N->getOperand(N->getNumOperands()-1);
4659     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4660     IsUnary = true;
4661     break;
4662   case X86ISD::VPERMI:
4663     ImmN = N->getOperand(N->getNumOperands()-1);
4664     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4665     IsUnary = true;
4666     break;
4667   case X86ISD::MOVSS:
4668   case X86ISD::MOVSD: {
4669     // The index 0 always comes from the first element of the second source,
4670     // this is why MOVSS and MOVSD are used in the first place. The other
4671     // elements come from the other positions of the first source vector
4672     Mask.push_back(NumElems);
4673     for (unsigned i = 1; i != NumElems; ++i) {
4674       Mask.push_back(i);
4675     }
4676     break;
4677   }
4678   case X86ISD::VPERM2X128:
4679     ImmN = N->getOperand(N->getNumOperands()-1);
4680     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4681     if (Mask.empty()) return false;
4682     break;
4683   case X86ISD::MOVDDUP:
4684   case X86ISD::MOVLHPD:
4685   case X86ISD::MOVLPD:
4686   case X86ISD::MOVLPS:
4687   case X86ISD::MOVSHDUP:
4688   case X86ISD::MOVSLDUP:
4689     // Not yet implemented
4690     return false;
4691   default: llvm_unreachable("unknown target shuffle node");
4692   }
4693
4694   return true;
4695 }
4696
4697 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4698 /// element of the result of the vector shuffle.
4699 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4700                                    unsigned Depth) {
4701   if (Depth == 6)
4702     return SDValue();  // Limit search depth.
4703
4704   SDValue V = SDValue(N, 0);
4705   EVT VT = V.getValueType();
4706   unsigned Opcode = V.getOpcode();
4707
4708   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4709   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4710     int Elt = SV->getMaskElt(Index);
4711
4712     if (Elt < 0)
4713       return DAG.getUNDEF(VT.getVectorElementType());
4714
4715     unsigned NumElems = VT.getVectorNumElements();
4716     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4717                                          : SV->getOperand(1);
4718     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4719   }
4720
4721   // Recurse into target specific vector shuffles to find scalars.
4722   if (isTargetShuffle(Opcode)) {
4723     MVT ShufVT = V.getValueType().getSimpleVT();
4724     unsigned NumElems = ShufVT.getVectorNumElements();
4725     SmallVector<int, 16> ShuffleMask;
4726     bool IsUnary;
4727
4728     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4729       return SDValue();
4730
4731     int Elt = ShuffleMask[Index];
4732     if (Elt < 0)
4733       return DAG.getUNDEF(ShufVT.getVectorElementType());
4734
4735     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4736                                          : N->getOperand(1);
4737     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4738                                Depth+1);
4739   }
4740
4741   // Actual nodes that may contain scalar elements
4742   if (Opcode == ISD::BITCAST) {
4743     V = V.getOperand(0);
4744     EVT SrcVT = V.getValueType();
4745     unsigned NumElems = VT.getVectorNumElements();
4746
4747     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4748       return SDValue();
4749   }
4750
4751   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4752     return (Index == 0) ? V.getOperand(0)
4753                         : DAG.getUNDEF(VT.getVectorElementType());
4754
4755   if (V.getOpcode() == ISD::BUILD_VECTOR)
4756     return V.getOperand(Index);
4757
4758   return SDValue();
4759 }
4760
4761 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4762 /// shuffle operation which come from a consecutively from a zero. The
4763 /// search can start in two different directions, from left or right.
4764 static
4765 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, unsigned NumElems,
4766                                   bool ZerosFromLeft, SelectionDAG &DAG) {
4767   unsigned i;
4768   for (i = 0; i != NumElems; ++i) {
4769     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4770     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4771     if (!(Elt.getNode() &&
4772          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4773       break;
4774   }
4775
4776   return i;
4777 }
4778
4779 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4780 /// correspond consecutively to elements from one of the vector operands,
4781 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4782 static
4783 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4784                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4785                               unsigned NumElems, unsigned &OpNum) {
4786   bool SeenV1 = false;
4787   bool SeenV2 = false;
4788
4789   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4790     int Idx = SVOp->getMaskElt(i);
4791     // Ignore undef indicies
4792     if (Idx < 0)
4793       continue;
4794
4795     if (Idx < (int)NumElems)
4796       SeenV1 = true;
4797     else
4798       SeenV2 = true;
4799
4800     // Only accept consecutive elements from the same vector
4801     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4802       return false;
4803   }
4804
4805   OpNum = SeenV1 ? 0 : 1;
4806   return true;
4807 }
4808
4809 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4810 /// logical left shift of a vector.
4811 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4812                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4813   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4814   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4815               false /* check zeros from right */, DAG);
4816   unsigned OpSrc;
4817
4818   if (!NumZeros)
4819     return false;
4820
4821   // Considering the elements in the mask that are not consecutive zeros,
4822   // check if they consecutively come from only one of the source vectors.
4823   //
4824   //               V1 = {X, A, B, C}     0
4825   //                         \  \  \    /
4826   //   vector_shuffle V1, V2 <1, 2, 3, X>
4827   //
4828   if (!isShuffleMaskConsecutive(SVOp,
4829             0,                   // Mask Start Index
4830             NumElems-NumZeros,   // Mask End Index(exclusive)
4831             NumZeros,            // Where to start looking in the src vector
4832             NumElems,            // Number of elements in vector
4833             OpSrc))              // Which source operand ?
4834     return false;
4835
4836   isLeft = false;
4837   ShAmt = NumZeros;
4838   ShVal = SVOp->getOperand(OpSrc);
4839   return true;
4840 }
4841
4842 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4843 /// logical left shift of a vector.
4844 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4845                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4846   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4847   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4848               true /* check zeros from left */, DAG);
4849   unsigned OpSrc;
4850
4851   if (!NumZeros)
4852     return false;
4853
4854   // Considering the elements in the mask that are not consecutive zeros,
4855   // check if they consecutively come from only one of the source vectors.
4856   //
4857   //                           0    { A, B, X, X } = V2
4858   //                          / \    /  /
4859   //   vector_shuffle V1, V2 <X, X, 4, 5>
4860   //
4861   if (!isShuffleMaskConsecutive(SVOp,
4862             NumZeros,     // Mask Start Index
4863             NumElems,     // Mask End Index(exclusive)
4864             0,            // Where to start looking in the src vector
4865             NumElems,     // Number of elements in vector
4866             OpSrc))       // Which source operand ?
4867     return false;
4868
4869   isLeft = true;
4870   ShAmt = NumZeros;
4871   ShVal = SVOp->getOperand(OpSrc);
4872   return true;
4873 }
4874
4875 /// isVectorShift - Returns true if the shuffle can be implemented as a
4876 /// logical left or right shift of a vector.
4877 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4878                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4879   // Although the logic below support any bitwidth size, there are no
4880   // shift instructions which handle more than 128-bit vectors.
4881   if (!SVOp->getValueType(0).is128BitVector())
4882     return false;
4883
4884   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4885       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4886     return true;
4887
4888   return false;
4889 }
4890
4891 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4892 ///
4893 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4894                                        unsigned NumNonZero, unsigned NumZero,
4895                                        SelectionDAG &DAG,
4896                                        const X86Subtarget* Subtarget,
4897                                        const TargetLowering &TLI) {
4898   if (NumNonZero > 8)
4899     return SDValue();
4900
4901   DebugLoc dl = Op.getDebugLoc();
4902   SDValue V(0, 0);
4903   bool First = true;
4904   for (unsigned i = 0; i < 16; ++i) {
4905     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4906     if (ThisIsNonZero && First) {
4907       if (NumZero)
4908         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4909       else
4910         V = DAG.getUNDEF(MVT::v8i16);
4911       First = false;
4912     }
4913
4914     if ((i & 1) != 0) {
4915       SDValue ThisElt(0, 0), LastElt(0, 0);
4916       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4917       if (LastIsNonZero) {
4918         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4919                               MVT::i16, Op.getOperand(i-1));
4920       }
4921       if (ThisIsNonZero) {
4922         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4923         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4924                               ThisElt, DAG.getConstant(8, MVT::i8));
4925         if (LastIsNonZero)
4926           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4927       } else
4928         ThisElt = LastElt;
4929
4930       if (ThisElt.getNode())
4931         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4932                         DAG.getIntPtrConstant(i/2));
4933     }
4934   }
4935
4936   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4937 }
4938
4939 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4940 ///
4941 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4942                                      unsigned NumNonZero, unsigned NumZero,
4943                                      SelectionDAG &DAG,
4944                                      const X86Subtarget* Subtarget,
4945                                      const TargetLowering &TLI) {
4946   if (NumNonZero > 4)
4947     return SDValue();
4948
4949   DebugLoc dl = Op.getDebugLoc();
4950   SDValue V(0, 0);
4951   bool First = true;
4952   for (unsigned i = 0; i < 8; ++i) {
4953     bool isNonZero = (NonZeros & (1 << i)) != 0;
4954     if (isNonZero) {
4955       if (First) {
4956         if (NumZero)
4957           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4958         else
4959           V = DAG.getUNDEF(MVT::v8i16);
4960         First = false;
4961       }
4962       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4963                       MVT::v8i16, V, Op.getOperand(i),
4964                       DAG.getIntPtrConstant(i));
4965     }
4966   }
4967
4968   return V;
4969 }
4970
4971 /// getVShift - Return a vector logical shift node.
4972 ///
4973 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4974                          unsigned NumBits, SelectionDAG &DAG,
4975                          const TargetLowering &TLI, DebugLoc dl) {
4976   assert(VT.is128BitVector() && "Unknown type for VShift");
4977   EVT ShVT = MVT::v2i64;
4978   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4979   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4980   return DAG.getNode(ISD::BITCAST, dl, VT,
4981                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4982                              DAG.getConstant(NumBits,
4983                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
4984 }
4985
4986 SDValue
4987 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4988                                           SelectionDAG &DAG) const {
4989
4990   // Check if the scalar load can be widened into a vector load. And if
4991   // the address is "base + cst" see if the cst can be "absorbed" into
4992   // the shuffle mask.
4993   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4994     SDValue Ptr = LD->getBasePtr();
4995     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4996       return SDValue();
4997     EVT PVT = LD->getValueType(0);
4998     if (PVT != MVT::i32 && PVT != MVT::f32)
4999       return SDValue();
5000
5001     int FI = -1;
5002     int64_t Offset = 0;
5003     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5004       FI = FINode->getIndex();
5005       Offset = 0;
5006     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5007                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5008       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5009       Offset = Ptr.getConstantOperandVal(1);
5010       Ptr = Ptr.getOperand(0);
5011     } else {
5012       return SDValue();
5013     }
5014
5015     // FIXME: 256-bit vector instructions don't require a strict alignment,
5016     // improve this code to support it better.
5017     unsigned RequiredAlign = VT.getSizeInBits()/8;
5018     SDValue Chain = LD->getChain();
5019     // Make sure the stack object alignment is at least 16 or 32.
5020     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5021     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5022       if (MFI->isFixedObjectIndex(FI)) {
5023         // Can't change the alignment. FIXME: It's possible to compute
5024         // the exact stack offset and reference FI + adjust offset instead.
5025         // If someone *really* cares about this. That's the way to implement it.
5026         return SDValue();
5027       } else {
5028         MFI->setObjectAlignment(FI, RequiredAlign);
5029       }
5030     }
5031
5032     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5033     // Ptr + (Offset & ~15).
5034     if (Offset < 0)
5035       return SDValue();
5036     if ((Offset % RequiredAlign) & 3)
5037       return SDValue();
5038     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5039     if (StartOffset)
5040       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
5041                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5042
5043     int EltNo = (Offset - StartOffset) >> 2;
5044     unsigned NumElems = VT.getVectorNumElements();
5045
5046     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5047     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5048                              LD->getPointerInfo().getWithOffset(StartOffset),
5049                              false, false, false, 0);
5050
5051     SmallVector<int, 8> Mask;
5052     for (unsigned i = 0; i != NumElems; ++i)
5053       Mask.push_back(EltNo);
5054
5055     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5056   }
5057
5058   return SDValue();
5059 }
5060
5061 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5062 /// vector of type 'VT', see if the elements can be replaced by a single large
5063 /// load which has the same value as a build_vector whose operands are 'elts'.
5064 ///
5065 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5066 ///
5067 /// FIXME: we'd also like to handle the case where the last elements are zero
5068 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5069 /// There's even a handy isZeroNode for that purpose.
5070 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5071                                         DebugLoc &DL, SelectionDAG &DAG) {
5072   EVT EltVT = VT.getVectorElementType();
5073   unsigned NumElems = Elts.size();
5074
5075   LoadSDNode *LDBase = NULL;
5076   unsigned LastLoadedElt = -1U;
5077
5078   // For each element in the initializer, see if we've found a load or an undef.
5079   // If we don't find an initial load element, or later load elements are
5080   // non-consecutive, bail out.
5081   for (unsigned i = 0; i < NumElems; ++i) {
5082     SDValue Elt = Elts[i];
5083
5084     if (!Elt.getNode() ||
5085         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5086       return SDValue();
5087     if (!LDBase) {
5088       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5089         return SDValue();
5090       LDBase = cast<LoadSDNode>(Elt.getNode());
5091       LastLoadedElt = i;
5092       continue;
5093     }
5094     if (Elt.getOpcode() == ISD::UNDEF)
5095       continue;
5096
5097     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5098     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5099       return SDValue();
5100     LastLoadedElt = i;
5101   }
5102
5103   // If we have found an entire vector of loads and undefs, then return a large
5104   // load of the entire vector width starting at the base pointer.  If we found
5105   // consecutive loads for the low half, generate a vzext_load node.
5106   if (LastLoadedElt == NumElems - 1) {
5107     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5108       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5109                          LDBase->getPointerInfo(),
5110                          LDBase->isVolatile(), LDBase->isNonTemporal(),
5111                          LDBase->isInvariant(), 0);
5112     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5113                        LDBase->getPointerInfo(),
5114                        LDBase->isVolatile(), LDBase->isNonTemporal(),
5115                        LDBase->isInvariant(), LDBase->getAlignment());
5116   }
5117   if (NumElems == 4 && LastLoadedElt == 1 &&
5118       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5119     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5120     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5121     SDValue ResNode =
5122         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
5123                                 LDBase->getPointerInfo(),
5124                                 LDBase->getAlignment(),
5125                                 false/*isVolatile*/, true/*ReadMem*/,
5126                                 false/*WriteMem*/);
5127
5128     // Make sure the newly-created LOAD is in the same position as LDBase in
5129     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5130     // update uses of LDBase's output chain to use the TokenFactor.
5131     if (LDBase->hasAnyUseOfValue(1)) {
5132       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5133                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5134       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5135       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5136                              SDValue(ResNode.getNode(), 1));
5137     }
5138
5139     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5140   }
5141   return SDValue();
5142 }
5143
5144 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5145 /// to generate a splat value for the following cases:
5146 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5147 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5148 /// a scalar load, or a constant.
5149 /// The VBROADCAST node is returned when a pattern is found,
5150 /// or SDValue() otherwise.
5151 SDValue
5152 X86TargetLowering::LowerVectorBroadcast(SDValue Op, SelectionDAG &DAG) const {
5153   if (!Subtarget->hasFp256())
5154     return SDValue();
5155
5156   MVT VT = Op.getValueType().getSimpleVT();
5157   DebugLoc dl = Op.getDebugLoc();
5158
5159   assert((VT.is128BitVector() || VT.is256BitVector()) &&
5160          "Unsupported vector type for broadcast.");
5161
5162   SDValue Ld;
5163   bool ConstSplatVal;
5164
5165   switch (Op.getOpcode()) {
5166     default:
5167       // Unknown pattern found.
5168       return SDValue();
5169
5170     case ISD::BUILD_VECTOR: {
5171       // The BUILD_VECTOR node must be a splat.
5172       if (!isSplatVector(Op.getNode()))
5173         return SDValue();
5174
5175       Ld = Op.getOperand(0);
5176       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5177                      Ld.getOpcode() == ISD::ConstantFP);
5178
5179       // The suspected load node has several users. Make sure that all
5180       // of its users are from the BUILD_VECTOR node.
5181       // Constants may have multiple users.
5182       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5183         return SDValue();
5184       break;
5185     }
5186
5187     case ISD::VECTOR_SHUFFLE: {
5188       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5189
5190       // Shuffles must have a splat mask where the first element is
5191       // broadcasted.
5192       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5193         return SDValue();
5194
5195       SDValue Sc = Op.getOperand(0);
5196       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5197           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5198
5199         if (!Subtarget->hasInt256())
5200           return SDValue();
5201
5202         // Use the register form of the broadcast instruction available on AVX2.
5203         if (VT.is256BitVector())
5204           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5205         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5206       }
5207
5208       Ld = Sc.getOperand(0);
5209       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5210                        Ld.getOpcode() == ISD::ConstantFP);
5211
5212       // The scalar_to_vector node and the suspected
5213       // load node must have exactly one user.
5214       // Constants may have multiple users.
5215       if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5216         return SDValue();
5217       break;
5218     }
5219   }
5220
5221   bool Is256 = VT.is256BitVector();
5222
5223   // Handle the broadcasting a single constant scalar from the constant pool
5224   // into a vector. On Sandybridge it is still better to load a constant vector
5225   // from the constant pool and not to broadcast it from a scalar.
5226   if (ConstSplatVal && Subtarget->hasInt256()) {
5227     EVT CVT = Ld.getValueType();
5228     assert(!CVT.isVector() && "Must not broadcast a vector type");
5229     unsigned ScalarSize = CVT.getSizeInBits();
5230
5231     if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5232       const Constant *C = 0;
5233       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5234         C = CI->getConstantIntValue();
5235       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5236         C = CF->getConstantFPValue();
5237
5238       assert(C && "Invalid constant type");
5239
5240       SDValue CP = DAG.getConstantPool(C, getPointerTy());
5241       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5242       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5243                        MachinePointerInfo::getConstantPool(),
5244                        false, false, false, Alignment);
5245
5246       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5247     }
5248   }
5249
5250   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5251   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5252
5253   // Handle AVX2 in-register broadcasts.
5254   if (!IsLoad && Subtarget->hasInt256() &&
5255       (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5256     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5257
5258   // The scalar source must be a normal load.
5259   if (!IsLoad)
5260     return SDValue();
5261
5262   if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5263     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5264
5265   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5266   // double since there is no vbroadcastsd xmm
5267   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5268     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5269       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5270   }
5271
5272   // Unsupported broadcast.
5273   return SDValue();
5274 }
5275
5276 SDValue
5277 X86TargetLowering::buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) const {
5278   EVT VT = Op.getValueType();
5279
5280   // Skip if insert_vec_elt is not supported.
5281   if (!isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5282     return SDValue();
5283
5284   DebugLoc DL = Op.getDebugLoc();
5285   unsigned NumElems = Op.getNumOperands();
5286
5287   SDValue VecIn1;
5288   SDValue VecIn2;
5289   SmallVector<unsigned, 4> InsertIndices;
5290   SmallVector<int, 8> Mask(NumElems, -1);
5291
5292   for (unsigned i = 0; i != NumElems; ++i) {
5293     unsigned Opc = Op.getOperand(i).getOpcode();
5294
5295     if (Opc == ISD::UNDEF)
5296       continue;
5297
5298     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5299       // Quit if more than 1 elements need inserting.
5300       if (InsertIndices.size() > 1)
5301         return SDValue();
5302
5303       InsertIndices.push_back(i);
5304       continue;
5305     }
5306
5307     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5308     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5309
5310     // Quit if extracted from vector of different type.
5311     if (ExtractedFromVec.getValueType() != VT)
5312       return SDValue();
5313
5314     // Quit if non-constant index.
5315     if (!isa<ConstantSDNode>(ExtIdx))
5316       return SDValue();
5317
5318     if (VecIn1.getNode() == 0)
5319       VecIn1 = ExtractedFromVec;
5320     else if (VecIn1 != ExtractedFromVec) {
5321       if (VecIn2.getNode() == 0)
5322         VecIn2 = ExtractedFromVec;
5323       else if (VecIn2 != ExtractedFromVec)
5324         // Quit if more than 2 vectors to shuffle
5325         return SDValue();
5326     }
5327
5328     unsigned Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5329
5330     if (ExtractedFromVec == VecIn1)
5331       Mask[i] = Idx;
5332     else if (ExtractedFromVec == VecIn2)
5333       Mask[i] = Idx + NumElems;
5334   }
5335
5336   if (VecIn1.getNode() == 0)
5337     return SDValue();
5338
5339   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5340   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5341   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5342     unsigned Idx = InsertIndices[i];
5343     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5344                      DAG.getIntPtrConstant(Idx));
5345   }
5346
5347   return NV;
5348 }
5349
5350 SDValue
5351 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5352   DebugLoc dl = Op.getDebugLoc();
5353
5354   MVT VT = Op.getValueType().getSimpleVT();
5355   MVT ExtVT = VT.getVectorElementType();
5356   unsigned NumElems = Op.getNumOperands();
5357
5358   // Vectors containing all zeros can be matched by pxor and xorps later
5359   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5360     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5361     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5362     if (VT == MVT::v4i32 || VT == MVT::v8i32)
5363       return Op;
5364
5365     return getZeroVector(VT, Subtarget, DAG, dl);
5366   }
5367
5368   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5369   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5370   // vpcmpeqd on 256-bit vectors.
5371   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5372     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5373       return Op;
5374
5375     return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5376   }
5377
5378   SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5379   if (Broadcast.getNode())
5380     return Broadcast;
5381
5382   unsigned EVTBits = ExtVT.getSizeInBits();
5383
5384   unsigned NumZero  = 0;
5385   unsigned NumNonZero = 0;
5386   unsigned NonZeros = 0;
5387   bool IsAllConstants = true;
5388   SmallSet<SDValue, 8> Values;
5389   for (unsigned i = 0; i < NumElems; ++i) {
5390     SDValue Elt = Op.getOperand(i);
5391     if (Elt.getOpcode() == ISD::UNDEF)
5392       continue;
5393     Values.insert(Elt);
5394     if (Elt.getOpcode() != ISD::Constant &&
5395         Elt.getOpcode() != ISD::ConstantFP)
5396       IsAllConstants = false;
5397     if (X86::isZeroNode(Elt))
5398       NumZero++;
5399     else {
5400       NonZeros |= (1 << i);
5401       NumNonZero++;
5402     }
5403   }
5404
5405   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5406   if (NumNonZero == 0)
5407     return DAG.getUNDEF(VT);
5408
5409   // Special case for single non-zero, non-undef, element.
5410   if (NumNonZero == 1) {
5411     unsigned Idx = CountTrailingZeros_32(NonZeros);
5412     SDValue Item = Op.getOperand(Idx);
5413
5414     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5415     // the value are obviously zero, truncate the value to i32 and do the
5416     // insertion that way.  Only do this if the value is non-constant or if the
5417     // value is a constant being inserted into element 0.  It is cheaper to do
5418     // a constant pool load than it is to do a movd + shuffle.
5419     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5420         (!IsAllConstants || Idx == 0)) {
5421       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5422         // Handle SSE only.
5423         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5424         EVT VecVT = MVT::v4i32;
5425         unsigned VecElts = 4;
5426
5427         // Truncate the value (which may itself be a constant) to i32, and
5428         // convert it to a vector with movd (S2V+shuffle to zero extend).
5429         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5430         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5431         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5432
5433         // Now we have our 32-bit value zero extended in the low element of
5434         // a vector.  If Idx != 0, swizzle it into place.
5435         if (Idx != 0) {
5436           SmallVector<int, 4> Mask;
5437           Mask.push_back(Idx);
5438           for (unsigned i = 1; i != VecElts; ++i)
5439             Mask.push_back(i);
5440           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5441                                       &Mask[0]);
5442         }
5443         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5444       }
5445     }
5446
5447     // If we have a constant or non-constant insertion into the low element of
5448     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5449     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5450     // depending on what the source datatype is.
5451     if (Idx == 0) {
5452       if (NumZero == 0)
5453         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5454
5455       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5456           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5457         if (VT.is256BitVector()) {
5458           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5459           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5460                              Item, DAG.getIntPtrConstant(0));
5461         }
5462         assert(VT.is128BitVector() && "Expected an SSE value type!");
5463         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5464         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5465         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5466       }
5467
5468       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5469         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5470         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5471         if (VT.is256BitVector()) {
5472           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5473           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5474         } else {
5475           assert(VT.is128BitVector() && "Expected an SSE value type!");
5476           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5477         }
5478         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5479       }
5480     }
5481
5482     // Is it a vector logical left shift?
5483     if (NumElems == 2 && Idx == 1 &&
5484         X86::isZeroNode(Op.getOperand(0)) &&
5485         !X86::isZeroNode(Op.getOperand(1))) {
5486       unsigned NumBits = VT.getSizeInBits();
5487       return getVShift(true, VT,
5488                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5489                                    VT, Op.getOperand(1)),
5490                        NumBits/2, DAG, *this, dl);
5491     }
5492
5493     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5494       return SDValue();
5495
5496     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5497     // is a non-constant being inserted into an element other than the low one,
5498     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5499     // movd/movss) to move this into the low element, then shuffle it into
5500     // place.
5501     if (EVTBits == 32) {
5502       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5503
5504       // Turn it into a shuffle of zero and zero-extended scalar to vector.
5505       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5506       SmallVector<int, 8> MaskVec;
5507       for (unsigned i = 0; i != NumElems; ++i)
5508         MaskVec.push_back(i == Idx ? 0 : 1);
5509       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5510     }
5511   }
5512
5513   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5514   if (Values.size() == 1) {
5515     if (EVTBits == 32) {
5516       // Instead of a shuffle like this:
5517       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5518       // Check if it's possible to issue this instead.
5519       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5520       unsigned Idx = CountTrailingZeros_32(NonZeros);
5521       SDValue Item = Op.getOperand(Idx);
5522       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5523         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5524     }
5525     return SDValue();
5526   }
5527
5528   // A vector full of immediates; various special cases are already
5529   // handled, so this is best done with a single constant-pool load.
5530   if (IsAllConstants)
5531     return SDValue();
5532
5533   // For AVX-length vectors, build the individual 128-bit pieces and use
5534   // shuffles to put them in place.
5535   if (VT.is256BitVector()) {
5536     SmallVector<SDValue, 32> V;
5537     for (unsigned i = 0; i != NumElems; ++i)
5538       V.push_back(Op.getOperand(i));
5539
5540     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5541
5542     // Build both the lower and upper subvector.
5543     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5544     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5545                                 NumElems/2);
5546
5547     // Recreate the wider vector with the lower and upper part.
5548     return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5549   }
5550
5551   // Let legalizer expand 2-wide build_vectors.
5552   if (EVTBits == 64) {
5553     if (NumNonZero == 1) {
5554       // One half is zero or undef.
5555       unsigned Idx = CountTrailingZeros_32(NonZeros);
5556       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5557                                  Op.getOperand(Idx));
5558       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5559     }
5560     return SDValue();
5561   }
5562
5563   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5564   if (EVTBits == 8 && NumElems == 16) {
5565     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5566                                         Subtarget, *this);
5567     if (V.getNode()) return V;
5568   }
5569
5570   if (EVTBits == 16 && NumElems == 8) {
5571     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5572                                       Subtarget, *this);
5573     if (V.getNode()) return V;
5574   }
5575
5576   // If element VT is == 32 bits, turn it into a number of shuffles.
5577   SmallVector<SDValue, 8> V(NumElems);
5578   if (NumElems == 4 && NumZero > 0) {
5579     for (unsigned i = 0; i < 4; ++i) {
5580       bool isZero = !(NonZeros & (1 << i));
5581       if (isZero)
5582         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5583       else
5584         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5585     }
5586
5587     for (unsigned i = 0; i < 2; ++i) {
5588       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5589         default: break;
5590         case 0:
5591           V[i] = V[i*2];  // Must be a zero vector.
5592           break;
5593         case 1:
5594           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5595           break;
5596         case 2:
5597           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5598           break;
5599         case 3:
5600           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5601           break;
5602       }
5603     }
5604
5605     bool Reverse1 = (NonZeros & 0x3) == 2;
5606     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5607     int MaskVec[] = {
5608       Reverse1 ? 1 : 0,
5609       Reverse1 ? 0 : 1,
5610       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5611       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5612     };
5613     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5614   }
5615
5616   if (Values.size() > 1 && VT.is128BitVector()) {
5617     // Check for a build vector of consecutive loads.
5618     for (unsigned i = 0; i < NumElems; ++i)
5619       V[i] = Op.getOperand(i);
5620
5621     // Check for elements which are consecutive loads.
5622     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5623     if (LD.getNode())
5624       return LD;
5625
5626     // Check for a build vector from mostly shuffle plus few inserting.
5627     SDValue Sh = buildFromShuffleMostly(Op, DAG);
5628     if (Sh.getNode())
5629       return Sh;
5630
5631     // For SSE 4.1, use insertps to put the high elements into the low element.
5632     if (getSubtarget()->hasSSE41()) {
5633       SDValue Result;
5634       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5635         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5636       else
5637         Result = DAG.getUNDEF(VT);
5638
5639       for (unsigned i = 1; i < NumElems; ++i) {
5640         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5641         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5642                              Op.getOperand(i), DAG.getIntPtrConstant(i));
5643       }
5644       return Result;
5645     }
5646
5647     // Otherwise, expand into a number of unpckl*, start by extending each of
5648     // our (non-undef) elements to the full vector width with the element in the
5649     // bottom slot of the vector (which generates no code for SSE).
5650     for (unsigned i = 0; i < NumElems; ++i) {
5651       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5652         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5653       else
5654         V[i] = DAG.getUNDEF(VT);
5655     }
5656
5657     // Next, we iteratively mix elements, e.g. for v4f32:
5658     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5659     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5660     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5661     unsigned EltStride = NumElems >> 1;
5662     while (EltStride != 0) {
5663       for (unsigned i = 0; i < EltStride; ++i) {
5664         // If V[i+EltStride] is undef and this is the first round of mixing,
5665         // then it is safe to just drop this shuffle: V[i] is already in the
5666         // right place, the one element (since it's the first round) being
5667         // inserted as undef can be dropped.  This isn't safe for successive
5668         // rounds because they will permute elements within both vectors.
5669         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5670             EltStride == NumElems/2)
5671           continue;
5672
5673         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5674       }
5675       EltStride >>= 1;
5676     }
5677     return V[0];
5678   }
5679   return SDValue();
5680 }
5681
5682 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5683 // to create 256-bit vectors from two other 128-bit ones.
5684 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5685   DebugLoc dl = Op.getDebugLoc();
5686   MVT ResVT = Op.getValueType().getSimpleVT();
5687
5688   assert(ResVT.is256BitVector() && "Value type must be 256-bit wide");
5689
5690   SDValue V1 = Op.getOperand(0);
5691   SDValue V2 = Op.getOperand(1);
5692   unsigned NumElems = ResVT.getVectorNumElements();
5693
5694   return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5695 }
5696
5697 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5698   assert(Op.getNumOperands() == 2);
5699
5700   // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5701   // from two other 128-bit ones.
5702   return LowerAVXCONCAT_VECTORS(Op, DAG);
5703 }
5704
5705 // Try to lower a shuffle node into a simple blend instruction.
5706 static SDValue
5707 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5708                            const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5709   SDValue V1 = SVOp->getOperand(0);
5710   SDValue V2 = SVOp->getOperand(1);
5711   DebugLoc dl = SVOp->getDebugLoc();
5712   MVT VT = SVOp->getValueType(0).getSimpleVT();
5713   MVT EltVT = VT.getVectorElementType();
5714   unsigned NumElems = VT.getVectorNumElements();
5715
5716   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
5717     return SDValue();
5718   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
5719     return SDValue();
5720
5721   // Check the mask for BLEND and build the value.
5722   unsigned MaskValue = 0;
5723   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
5724   unsigned NumLanes = (NumElems-1)/8 + 1;
5725   unsigned NumElemsInLane = NumElems / NumLanes;
5726
5727   // Blend for v16i16 should be symetric for the both lanes.
5728   for (unsigned i = 0; i < NumElemsInLane; ++i) {
5729
5730     int SndLaneEltIdx = (NumLanes == 2) ?
5731       SVOp->getMaskElt(i + NumElemsInLane) : -1;
5732     int EltIdx = SVOp->getMaskElt(i);
5733
5734     if ((EltIdx < 0 || EltIdx == (int)i) &&
5735         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
5736       continue;
5737
5738     if (((unsigned)EltIdx == (i + NumElems)) &&
5739         (SndLaneEltIdx < 0 ||
5740          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
5741       MaskValue |= (1<<i);
5742     else
5743       return SDValue();
5744   }
5745
5746   // Convert i32 vectors to floating point if it is not AVX2.
5747   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
5748   MVT BlendVT = VT;
5749   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
5750     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
5751                                NumElems);
5752     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
5753     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
5754   }
5755
5756   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
5757                             DAG.getConstant(MaskValue, MVT::i32));
5758   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5759 }
5760
5761 // v8i16 shuffles - Prefer shuffles in the following order:
5762 // 1. [all]   pshuflw, pshufhw, optional move
5763 // 2. [ssse3] 1 x pshufb
5764 // 3. [ssse3] 2 x pshufb + 1 x por
5765 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5766 static SDValue
5767 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
5768                          SelectionDAG &DAG) {
5769   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5770   SDValue V1 = SVOp->getOperand(0);
5771   SDValue V2 = SVOp->getOperand(1);
5772   DebugLoc dl = SVOp->getDebugLoc();
5773   SmallVector<int, 8> MaskVals;
5774
5775   // Determine if more than 1 of the words in each of the low and high quadwords
5776   // of the result come from the same quadword of one of the two inputs.  Undef
5777   // mask values count as coming from any quadword, for better codegen.
5778   unsigned LoQuad[] = { 0, 0, 0, 0 };
5779   unsigned HiQuad[] = { 0, 0, 0, 0 };
5780   std::bitset<4> InputQuads;
5781   for (unsigned i = 0; i < 8; ++i) {
5782     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5783     int EltIdx = SVOp->getMaskElt(i);
5784     MaskVals.push_back(EltIdx);
5785     if (EltIdx < 0) {
5786       ++Quad[0];
5787       ++Quad[1];
5788       ++Quad[2];
5789       ++Quad[3];
5790       continue;
5791     }
5792     ++Quad[EltIdx / 4];
5793     InputQuads.set(EltIdx / 4);
5794   }
5795
5796   int BestLoQuad = -1;
5797   unsigned MaxQuad = 1;
5798   for (unsigned i = 0; i < 4; ++i) {
5799     if (LoQuad[i] > MaxQuad) {
5800       BestLoQuad = i;
5801       MaxQuad = LoQuad[i];
5802     }
5803   }
5804
5805   int BestHiQuad = -1;
5806   MaxQuad = 1;
5807   for (unsigned i = 0; i < 4; ++i) {
5808     if (HiQuad[i] > MaxQuad) {
5809       BestHiQuad = i;
5810       MaxQuad = HiQuad[i];
5811     }
5812   }
5813
5814   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5815   // of the two input vectors, shuffle them into one input vector so only a
5816   // single pshufb instruction is necessary. If There are more than 2 input
5817   // quads, disable the next transformation since it does not help SSSE3.
5818   bool V1Used = InputQuads[0] || InputQuads[1];
5819   bool V2Used = InputQuads[2] || InputQuads[3];
5820   if (Subtarget->hasSSSE3()) {
5821     if (InputQuads.count() == 2 && V1Used && V2Used) {
5822       BestLoQuad = InputQuads[0] ? 0 : 1;
5823       BestHiQuad = InputQuads[2] ? 2 : 3;
5824     }
5825     if (InputQuads.count() > 2) {
5826       BestLoQuad = -1;
5827       BestHiQuad = -1;
5828     }
5829   }
5830
5831   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5832   // the shuffle mask.  If a quad is scored as -1, that means that it contains
5833   // words from all 4 input quadwords.
5834   SDValue NewV;
5835   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5836     int MaskV[] = {
5837       BestLoQuad < 0 ? 0 : BestLoQuad,
5838       BestHiQuad < 0 ? 1 : BestHiQuad
5839     };
5840     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5841                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5842                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5843     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5844
5845     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5846     // source words for the shuffle, to aid later transformations.
5847     bool AllWordsInNewV = true;
5848     bool InOrder[2] = { true, true };
5849     for (unsigned i = 0; i != 8; ++i) {
5850       int idx = MaskVals[i];
5851       if (idx != (int)i)
5852         InOrder[i/4] = false;
5853       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5854         continue;
5855       AllWordsInNewV = false;
5856       break;
5857     }
5858
5859     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5860     if (AllWordsInNewV) {
5861       for (int i = 0; i != 8; ++i) {
5862         int idx = MaskVals[i];
5863         if (idx < 0)
5864           continue;
5865         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5866         if ((idx != i) && idx < 4)
5867           pshufhw = false;
5868         if ((idx != i) && idx > 3)
5869           pshuflw = false;
5870       }
5871       V1 = NewV;
5872       V2Used = false;
5873       BestLoQuad = 0;
5874       BestHiQuad = 1;
5875     }
5876
5877     // If we've eliminated the use of V2, and the new mask is a pshuflw or
5878     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
5879     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5880       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5881       unsigned TargetMask = 0;
5882       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5883                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5884       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5885       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5886                              getShufflePSHUFLWImmediate(SVOp);
5887       V1 = NewV.getOperand(0);
5888       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5889     }
5890   }
5891
5892   // Promote splats to a larger type which usually leads to more efficient code.
5893   // FIXME: Is this true if pshufb is available?
5894   if (SVOp->isSplat())
5895     return PromoteSplat(SVOp, DAG);
5896
5897   // If we have SSSE3, and all words of the result are from 1 input vector,
5898   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5899   // is present, fall back to case 4.
5900   if (Subtarget->hasSSSE3()) {
5901     SmallVector<SDValue,16> pshufbMask;
5902
5903     // If we have elements from both input vectors, set the high bit of the
5904     // shuffle mask element to zero out elements that come from V2 in the V1
5905     // mask, and elements that come from V1 in the V2 mask, so that the two
5906     // results can be OR'd together.
5907     bool TwoInputs = V1Used && V2Used;
5908     for (unsigned i = 0; i != 8; ++i) {
5909       int EltIdx = MaskVals[i] * 2;
5910       int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
5911       int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
5912       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5913       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5914     }
5915     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5916     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5917                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5918                                  MVT::v16i8, &pshufbMask[0], 16));
5919     if (!TwoInputs)
5920       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5921
5922     // Calculate the shuffle mask for the second input, shuffle it, and
5923     // OR it with the first shuffled input.
5924     pshufbMask.clear();
5925     for (unsigned i = 0; i != 8; ++i) {
5926       int EltIdx = MaskVals[i] * 2;
5927       int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5928       int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
5929       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5930       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5931     }
5932     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5933     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5934                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5935                                  MVT::v16i8, &pshufbMask[0], 16));
5936     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5937     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5938   }
5939
5940   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5941   // and update MaskVals with new element order.
5942   std::bitset<8> InOrder;
5943   if (BestLoQuad >= 0) {
5944     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5945     for (int i = 0; i != 4; ++i) {
5946       int idx = MaskVals[i];
5947       if (idx < 0) {
5948         InOrder.set(i);
5949       } else if ((idx / 4) == BestLoQuad) {
5950         MaskV[i] = idx & 3;
5951         InOrder.set(i);
5952       }
5953     }
5954     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5955                                 &MaskV[0]);
5956
5957     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5958       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5959       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5960                                   NewV.getOperand(0),
5961                                   getShufflePSHUFLWImmediate(SVOp), DAG);
5962     }
5963   }
5964
5965   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5966   // and update MaskVals with the new element order.
5967   if (BestHiQuad >= 0) {
5968     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5969     for (unsigned i = 4; i != 8; ++i) {
5970       int idx = MaskVals[i];
5971       if (idx < 0) {
5972         InOrder.set(i);
5973       } else if ((idx / 4) == BestHiQuad) {
5974         MaskV[i] = (idx & 3) + 4;
5975         InOrder.set(i);
5976       }
5977     }
5978     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5979                                 &MaskV[0]);
5980
5981     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5982       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5983       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5984                                   NewV.getOperand(0),
5985                                   getShufflePSHUFHWImmediate(SVOp), DAG);
5986     }
5987   }
5988
5989   // In case BestHi & BestLo were both -1, which means each quadword has a word
5990   // from each of the four input quadwords, calculate the InOrder bitvector now
5991   // before falling through to the insert/extract cleanup.
5992   if (BestLoQuad == -1 && BestHiQuad == -1) {
5993     NewV = V1;
5994     for (int i = 0; i != 8; ++i)
5995       if (MaskVals[i] < 0 || MaskVals[i] == i)
5996         InOrder.set(i);
5997   }
5998
5999   // The other elements are put in the right place using pextrw and pinsrw.
6000   for (unsigned i = 0; i != 8; ++i) {
6001     if (InOrder[i])
6002       continue;
6003     int EltIdx = MaskVals[i];
6004     if (EltIdx < 0)
6005       continue;
6006     SDValue ExtOp = (EltIdx < 8) ?
6007       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6008                   DAG.getIntPtrConstant(EltIdx)) :
6009       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6010                   DAG.getIntPtrConstant(EltIdx - 8));
6011     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6012                        DAG.getIntPtrConstant(i));
6013   }
6014   return NewV;
6015 }
6016
6017 // v16i8 shuffles - Prefer shuffles in the following order:
6018 // 1. [ssse3] 1 x pshufb
6019 // 2. [ssse3] 2 x pshufb + 1 x por
6020 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
6021 static
6022 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6023                                  SelectionDAG &DAG,
6024                                  const X86TargetLowering &TLI) {
6025   SDValue V1 = SVOp->getOperand(0);
6026   SDValue V2 = SVOp->getOperand(1);
6027   DebugLoc dl = SVOp->getDebugLoc();
6028   ArrayRef<int> MaskVals = SVOp->getMask();
6029
6030   // Promote splats to a larger type which usually leads to more efficient code.
6031   // FIXME: Is this true if pshufb is available?
6032   if (SVOp->isSplat())
6033     return PromoteSplat(SVOp, DAG);
6034
6035   // If we have SSSE3, case 1 is generated when all result bytes come from
6036   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
6037   // present, fall back to case 3.
6038
6039   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6040   if (TLI.getSubtarget()->hasSSSE3()) {
6041     SmallVector<SDValue,16> pshufbMask;
6042
6043     // If all result elements are from one input vector, then only translate
6044     // undef mask values to 0x80 (zero out result) in the pshufb mask.
6045     //
6046     // Otherwise, we have elements from both input vectors, and must zero out
6047     // elements that come from V2 in the first mask, and V1 in the second mask
6048     // so that we can OR them together.
6049     for (unsigned i = 0; i != 16; ++i) {
6050       int EltIdx = MaskVals[i];
6051       if (EltIdx < 0 || EltIdx >= 16)
6052         EltIdx = 0x80;
6053       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6054     }
6055     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6056                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6057                                  MVT::v16i8, &pshufbMask[0], 16));
6058
6059     // As PSHUFB will zero elements with negative indices, it's safe to ignore
6060     // the 2nd operand if it's undefined or zero.
6061     if (V2.getOpcode() == ISD::UNDEF ||
6062         ISD::isBuildVectorAllZeros(V2.getNode()))
6063       return V1;
6064
6065     // Calculate the shuffle mask for the second input, shuffle it, and
6066     // OR it with the first shuffled input.
6067     pshufbMask.clear();
6068     for (unsigned i = 0; i != 16; ++i) {
6069       int EltIdx = MaskVals[i];
6070       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6071       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6072     }
6073     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6074                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6075                                  MVT::v16i8, &pshufbMask[0], 16));
6076     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6077   }
6078
6079   // No SSSE3 - Calculate in place words and then fix all out of place words
6080   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
6081   // the 16 different words that comprise the two doublequadword input vectors.
6082   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6083   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6084   SDValue NewV = V1;
6085   for (int i = 0; i != 8; ++i) {
6086     int Elt0 = MaskVals[i*2];
6087     int Elt1 = MaskVals[i*2+1];
6088
6089     // This word of the result is all undef, skip it.
6090     if (Elt0 < 0 && Elt1 < 0)
6091       continue;
6092
6093     // This word of the result is already in the correct place, skip it.
6094     if ((Elt0 == i*2) && (Elt1 == i*2+1))
6095       continue;
6096
6097     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6098     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6099     SDValue InsElt;
6100
6101     // If Elt0 and Elt1 are defined, are consecutive, and can be load
6102     // using a single extract together, load it and store it.
6103     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6104       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6105                            DAG.getIntPtrConstant(Elt1 / 2));
6106       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6107                         DAG.getIntPtrConstant(i));
6108       continue;
6109     }
6110
6111     // If Elt1 is defined, extract it from the appropriate source.  If the
6112     // source byte is not also odd, shift the extracted word left 8 bits
6113     // otherwise clear the bottom 8 bits if we need to do an or.
6114     if (Elt1 >= 0) {
6115       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6116                            DAG.getIntPtrConstant(Elt1 / 2));
6117       if ((Elt1 & 1) == 0)
6118         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6119                              DAG.getConstant(8,
6120                                   TLI.getShiftAmountTy(InsElt.getValueType())));
6121       else if (Elt0 >= 0)
6122         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6123                              DAG.getConstant(0xFF00, MVT::i16));
6124     }
6125     // If Elt0 is defined, extract it from the appropriate source.  If the
6126     // source byte is not also even, shift the extracted word right 8 bits. If
6127     // Elt1 was also defined, OR the extracted values together before
6128     // inserting them in the result.
6129     if (Elt0 >= 0) {
6130       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6131                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6132       if ((Elt0 & 1) != 0)
6133         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6134                               DAG.getConstant(8,
6135                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
6136       else if (Elt1 >= 0)
6137         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6138                              DAG.getConstant(0x00FF, MVT::i16));
6139       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6140                          : InsElt0;
6141     }
6142     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6143                        DAG.getIntPtrConstant(i));
6144   }
6145   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6146 }
6147
6148 // v32i8 shuffles - Translate to VPSHUFB if possible.
6149 static
6150 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6151                                  const X86Subtarget *Subtarget,
6152                                  SelectionDAG &DAG) {
6153   MVT VT = SVOp->getValueType(0).getSimpleVT();
6154   SDValue V1 = SVOp->getOperand(0);
6155   SDValue V2 = SVOp->getOperand(1);
6156   DebugLoc dl = SVOp->getDebugLoc();
6157   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6158
6159   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6160   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6161   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6162
6163   // VPSHUFB may be generated if
6164   // (1) one of input vector is undefined or zeroinitializer.
6165   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6166   // And (2) the mask indexes don't cross the 128-bit lane.
6167   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6168       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6169     return SDValue();
6170
6171   if (V1IsAllZero && !V2IsAllZero) {
6172     CommuteVectorShuffleMask(MaskVals, 32);
6173     V1 = V2;
6174   }
6175   SmallVector<SDValue, 32> pshufbMask;
6176   for (unsigned i = 0; i != 32; i++) {
6177     int EltIdx = MaskVals[i];
6178     if (EltIdx < 0 || EltIdx >= 32)
6179       EltIdx = 0x80;
6180     else {
6181       if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6182         // Cross lane is not allowed.
6183         return SDValue();
6184       EltIdx &= 0xf;
6185     }
6186     pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6187   }
6188   return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6189                       DAG.getNode(ISD::BUILD_VECTOR, dl,
6190                                   MVT::v32i8, &pshufbMask[0], 32));
6191 }
6192
6193 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6194 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6195 /// done when every pair / quad of shuffle mask elements point to elements in
6196 /// the right sequence. e.g.
6197 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6198 static
6199 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6200                                  SelectionDAG &DAG) {
6201   MVT VT = SVOp->getValueType(0).getSimpleVT();
6202   DebugLoc dl = SVOp->getDebugLoc();
6203   unsigned NumElems = VT.getVectorNumElements();
6204   MVT NewVT;
6205   unsigned Scale;
6206   switch (VT.SimpleTy) {
6207   default: llvm_unreachable("Unexpected!");
6208   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
6209   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
6210   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
6211   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
6212   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6213   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
6214   }
6215
6216   SmallVector<int, 8> MaskVec;
6217   for (unsigned i = 0; i != NumElems; i += Scale) {
6218     int StartIdx = -1;
6219     for (unsigned j = 0; j != Scale; ++j) {
6220       int EltIdx = SVOp->getMaskElt(i+j);
6221       if (EltIdx < 0)
6222         continue;
6223       if (StartIdx < 0)
6224         StartIdx = (EltIdx / Scale);
6225       if (EltIdx != (int)(StartIdx*Scale + j))
6226         return SDValue();
6227     }
6228     MaskVec.push_back(StartIdx);
6229   }
6230
6231   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6232   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6233   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6234 }
6235
6236 /// getVZextMovL - Return a zero-extending vector move low node.
6237 ///
6238 static SDValue getVZextMovL(MVT VT, EVT OpVT,
6239                             SDValue SrcOp, SelectionDAG &DAG,
6240                             const X86Subtarget *Subtarget, DebugLoc dl) {
6241   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6242     LoadSDNode *LD = NULL;
6243     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6244       LD = dyn_cast<LoadSDNode>(SrcOp);
6245     if (!LD) {
6246       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6247       // instead.
6248       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6249       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6250           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6251           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6252           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6253         // PR2108
6254         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6255         return DAG.getNode(ISD::BITCAST, dl, VT,
6256                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6257                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6258                                                    OpVT,
6259                                                    SrcOp.getOperand(0)
6260                                                           .getOperand(0))));
6261       }
6262     }
6263   }
6264
6265   return DAG.getNode(ISD::BITCAST, dl, VT,
6266                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6267                                  DAG.getNode(ISD::BITCAST, dl,
6268                                              OpVT, SrcOp)));
6269 }
6270
6271 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6272 /// which could not be matched by any known target speficic shuffle
6273 static SDValue
6274 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6275
6276   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6277   if (NewOp.getNode())
6278     return NewOp;
6279
6280   MVT VT = SVOp->getValueType(0).getSimpleVT();
6281
6282   unsigned NumElems = VT.getVectorNumElements();
6283   unsigned NumLaneElems = NumElems / 2;
6284
6285   DebugLoc dl = SVOp->getDebugLoc();
6286   MVT EltVT = VT.getVectorElementType();
6287   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6288   SDValue Output[2];
6289
6290   SmallVector<int, 16> Mask;
6291   for (unsigned l = 0; l < 2; ++l) {
6292     // Build a shuffle mask for the output, discovering on the fly which
6293     // input vectors to use as shuffle operands (recorded in InputUsed).
6294     // If building a suitable shuffle vector proves too hard, then bail
6295     // out with UseBuildVector set.
6296     bool UseBuildVector = false;
6297     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6298     unsigned LaneStart = l * NumLaneElems;
6299     for (unsigned i = 0; i != NumLaneElems; ++i) {
6300       // The mask element.  This indexes into the input.
6301       int Idx = SVOp->getMaskElt(i+LaneStart);
6302       if (Idx < 0) {
6303         // the mask element does not index into any input vector.
6304         Mask.push_back(-1);
6305         continue;
6306       }
6307
6308       // The input vector this mask element indexes into.
6309       int Input = Idx / NumLaneElems;
6310
6311       // Turn the index into an offset from the start of the input vector.
6312       Idx -= Input * NumLaneElems;
6313
6314       // Find or create a shuffle vector operand to hold this input.
6315       unsigned OpNo;
6316       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6317         if (InputUsed[OpNo] == Input)
6318           // This input vector is already an operand.
6319           break;
6320         if (InputUsed[OpNo] < 0) {
6321           // Create a new operand for this input vector.
6322           InputUsed[OpNo] = Input;
6323           break;
6324         }
6325       }
6326
6327       if (OpNo >= array_lengthof(InputUsed)) {
6328         // More than two input vectors used!  Give up on trying to create a
6329         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6330         UseBuildVector = true;
6331         break;
6332       }
6333
6334       // Add the mask index for the new shuffle vector.
6335       Mask.push_back(Idx + OpNo * NumLaneElems);
6336     }
6337
6338     if (UseBuildVector) {
6339       SmallVector<SDValue, 16> SVOps;
6340       for (unsigned i = 0; i != NumLaneElems; ++i) {
6341         // The mask element.  This indexes into the input.
6342         int Idx = SVOp->getMaskElt(i+LaneStart);
6343         if (Idx < 0) {
6344           SVOps.push_back(DAG.getUNDEF(EltVT));
6345           continue;
6346         }
6347
6348         // The input vector this mask element indexes into.
6349         int Input = Idx / NumElems;
6350
6351         // Turn the index into an offset from the start of the input vector.
6352         Idx -= Input * NumElems;
6353
6354         // Extract the vector element by hand.
6355         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6356                                     SVOp->getOperand(Input),
6357                                     DAG.getIntPtrConstant(Idx)));
6358       }
6359
6360       // Construct the output using a BUILD_VECTOR.
6361       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6362                               SVOps.size());
6363     } else if (InputUsed[0] < 0) {
6364       // No input vectors were used! The result is undefined.
6365       Output[l] = DAG.getUNDEF(NVT);
6366     } else {
6367       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6368                                         (InputUsed[0] % 2) * NumLaneElems,
6369                                         DAG, dl);
6370       // If only one input was used, use an undefined vector for the other.
6371       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6372         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6373                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6374       // At least one input vector was used. Create a new shuffle vector.
6375       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6376     }
6377
6378     Mask.clear();
6379   }
6380
6381   // Concatenate the result back
6382   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6383 }
6384
6385 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6386 /// 4 elements, and match them with several different shuffle types.
6387 static SDValue
6388 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6389   SDValue V1 = SVOp->getOperand(0);
6390   SDValue V2 = SVOp->getOperand(1);
6391   DebugLoc dl = SVOp->getDebugLoc();
6392   MVT VT = SVOp->getValueType(0).getSimpleVT();
6393
6394   assert(VT.is128BitVector() && "Unsupported vector size");
6395
6396   std::pair<int, int> Locs[4];
6397   int Mask1[] = { -1, -1, -1, -1 };
6398   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6399
6400   unsigned NumHi = 0;
6401   unsigned NumLo = 0;
6402   for (unsigned i = 0; i != 4; ++i) {
6403     int Idx = PermMask[i];
6404     if (Idx < 0) {
6405       Locs[i] = std::make_pair(-1, -1);
6406     } else {
6407       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6408       if (Idx < 4) {
6409         Locs[i] = std::make_pair(0, NumLo);
6410         Mask1[NumLo] = Idx;
6411         NumLo++;
6412       } else {
6413         Locs[i] = std::make_pair(1, NumHi);
6414         if (2+NumHi < 4)
6415           Mask1[2+NumHi] = Idx;
6416         NumHi++;
6417       }
6418     }
6419   }
6420
6421   if (NumLo <= 2 && NumHi <= 2) {
6422     // If no more than two elements come from either vector. This can be
6423     // implemented with two shuffles. First shuffle gather the elements.
6424     // The second shuffle, which takes the first shuffle as both of its
6425     // vector operands, put the elements into the right order.
6426     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6427
6428     int Mask2[] = { -1, -1, -1, -1 };
6429
6430     for (unsigned i = 0; i != 4; ++i)
6431       if (Locs[i].first != -1) {
6432         unsigned Idx = (i < 2) ? 0 : 4;
6433         Idx += Locs[i].first * 2 + Locs[i].second;
6434         Mask2[i] = Idx;
6435       }
6436
6437     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6438   }
6439
6440   if (NumLo == 3 || NumHi == 3) {
6441     // Otherwise, we must have three elements from one vector, call it X, and
6442     // one element from the other, call it Y.  First, use a shufps to build an
6443     // intermediate vector with the one element from Y and the element from X
6444     // that will be in the same half in the final destination (the indexes don't
6445     // matter). Then, use a shufps to build the final vector, taking the half
6446     // containing the element from Y from the intermediate, and the other half
6447     // from X.
6448     if (NumHi == 3) {
6449       // Normalize it so the 3 elements come from V1.
6450       CommuteVectorShuffleMask(PermMask, 4);
6451       std::swap(V1, V2);
6452     }
6453
6454     // Find the element from V2.
6455     unsigned HiIndex;
6456     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6457       int Val = PermMask[HiIndex];
6458       if (Val < 0)
6459         continue;
6460       if (Val >= 4)
6461         break;
6462     }
6463
6464     Mask1[0] = PermMask[HiIndex];
6465     Mask1[1] = -1;
6466     Mask1[2] = PermMask[HiIndex^1];
6467     Mask1[3] = -1;
6468     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6469
6470     if (HiIndex >= 2) {
6471       Mask1[0] = PermMask[0];
6472       Mask1[1] = PermMask[1];
6473       Mask1[2] = HiIndex & 1 ? 6 : 4;
6474       Mask1[3] = HiIndex & 1 ? 4 : 6;
6475       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6476     }
6477
6478     Mask1[0] = HiIndex & 1 ? 2 : 0;
6479     Mask1[1] = HiIndex & 1 ? 0 : 2;
6480     Mask1[2] = PermMask[2];
6481     Mask1[3] = PermMask[3];
6482     if (Mask1[2] >= 0)
6483       Mask1[2] += 4;
6484     if (Mask1[3] >= 0)
6485       Mask1[3] += 4;
6486     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6487   }
6488
6489   // Break it into (shuffle shuffle_hi, shuffle_lo).
6490   int LoMask[] = { -1, -1, -1, -1 };
6491   int HiMask[] = { -1, -1, -1, -1 };
6492
6493   int *MaskPtr = LoMask;
6494   unsigned MaskIdx = 0;
6495   unsigned LoIdx = 0;
6496   unsigned HiIdx = 2;
6497   for (unsigned i = 0; i != 4; ++i) {
6498     if (i == 2) {
6499       MaskPtr = HiMask;
6500       MaskIdx = 1;
6501       LoIdx = 0;
6502       HiIdx = 2;
6503     }
6504     int Idx = PermMask[i];
6505     if (Idx < 0) {
6506       Locs[i] = std::make_pair(-1, -1);
6507     } else if (Idx < 4) {
6508       Locs[i] = std::make_pair(MaskIdx, LoIdx);
6509       MaskPtr[LoIdx] = Idx;
6510       LoIdx++;
6511     } else {
6512       Locs[i] = std::make_pair(MaskIdx, HiIdx);
6513       MaskPtr[HiIdx] = Idx;
6514       HiIdx++;
6515     }
6516   }
6517
6518   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6519   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6520   int MaskOps[] = { -1, -1, -1, -1 };
6521   for (unsigned i = 0; i != 4; ++i)
6522     if (Locs[i].first != -1)
6523       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6524   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6525 }
6526
6527 static bool MayFoldVectorLoad(SDValue V) {
6528   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6529     V = V.getOperand(0);
6530
6531   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6532     V = V.getOperand(0);
6533   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6534       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6535     // BUILD_VECTOR (load), undef
6536     V = V.getOperand(0);
6537
6538   return MayFoldLoad(V);
6539 }
6540
6541 static
6542 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6543   EVT VT = Op.getValueType();
6544
6545   // Canonizalize to v2f64.
6546   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6547   return DAG.getNode(ISD::BITCAST, dl, VT,
6548                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6549                                           V1, DAG));
6550 }
6551
6552 static
6553 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6554                         bool HasSSE2) {
6555   SDValue V1 = Op.getOperand(0);
6556   SDValue V2 = Op.getOperand(1);
6557   EVT VT = Op.getValueType();
6558
6559   assert(VT != MVT::v2i64 && "unsupported shuffle type");
6560
6561   if (HasSSE2 && VT == MVT::v2f64)
6562     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6563
6564   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6565   return DAG.getNode(ISD::BITCAST, dl, VT,
6566                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6567                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6568                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6569 }
6570
6571 static
6572 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6573   SDValue V1 = Op.getOperand(0);
6574   SDValue V2 = Op.getOperand(1);
6575   EVT VT = Op.getValueType();
6576
6577   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6578          "unsupported shuffle type");
6579
6580   if (V2.getOpcode() == ISD::UNDEF)
6581     V2 = V1;
6582
6583   // v4i32 or v4f32
6584   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6585 }
6586
6587 static
6588 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6589   SDValue V1 = Op.getOperand(0);
6590   SDValue V2 = Op.getOperand(1);
6591   EVT VT = Op.getValueType();
6592   unsigned NumElems = VT.getVectorNumElements();
6593
6594   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6595   // operand of these instructions is only memory, so check if there's a
6596   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6597   // same masks.
6598   bool CanFoldLoad = false;
6599
6600   // Trivial case, when V2 comes from a load.
6601   if (MayFoldVectorLoad(V2))
6602     CanFoldLoad = true;
6603
6604   // When V1 is a load, it can be folded later into a store in isel, example:
6605   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6606   //    turns into:
6607   //  (MOVLPSmr addr:$src1, VR128:$src2)
6608   // So, recognize this potential and also use MOVLPS or MOVLPD
6609   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6610     CanFoldLoad = true;
6611
6612   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6613   if (CanFoldLoad) {
6614     if (HasSSE2 && NumElems == 2)
6615       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6616
6617     if (NumElems == 4)
6618       // If we don't care about the second element, proceed to use movss.
6619       if (SVOp->getMaskElt(1) != -1)
6620         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6621   }
6622
6623   // movl and movlp will both match v2i64, but v2i64 is never matched by
6624   // movl earlier because we make it strict to avoid messing with the movlp load
6625   // folding logic (see the code above getMOVLP call). Match it here then,
6626   // this is horrible, but will stay like this until we move all shuffle
6627   // matching to x86 specific nodes. Note that for the 1st condition all
6628   // types are matched with movsd.
6629   if (HasSSE2) {
6630     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6631     // as to remove this logic from here, as much as possible
6632     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6633       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6634     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6635   }
6636
6637   assert(VT != MVT::v4i32 && "unsupported shuffle type");
6638
6639   // Invert the operand order and use SHUFPS to match it.
6640   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6641                               getShuffleSHUFImmediate(SVOp), DAG);
6642 }
6643
6644 // Reduce a vector shuffle to zext.
6645 SDValue
6646 X86TargetLowering::LowerVectorIntExtend(SDValue Op, SelectionDAG &DAG) const {
6647   // PMOVZX is only available from SSE41.
6648   if (!Subtarget->hasSSE41())
6649     return SDValue();
6650
6651   EVT VT = Op.getValueType();
6652
6653   // Only AVX2 support 256-bit vector integer extending.
6654   if (!Subtarget->hasInt256() && VT.is256BitVector())
6655     return SDValue();
6656
6657   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6658   DebugLoc DL = Op.getDebugLoc();
6659   SDValue V1 = Op.getOperand(0);
6660   SDValue V2 = Op.getOperand(1);
6661   unsigned NumElems = VT.getVectorNumElements();
6662
6663   // Extending is an unary operation and the element type of the source vector
6664   // won't be equal to or larger than i64.
6665   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
6666       VT.getVectorElementType() == MVT::i64)
6667     return SDValue();
6668
6669   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
6670   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
6671   while ((1U << Shift) < NumElems) {
6672     if (SVOp->getMaskElt(1U << Shift) == 1)
6673       break;
6674     Shift += 1;
6675     // The maximal ratio is 8, i.e. from i8 to i64.
6676     if (Shift > 3)
6677       return SDValue();
6678   }
6679
6680   // Check the shuffle mask.
6681   unsigned Mask = (1U << Shift) - 1;
6682   for (unsigned i = 0; i != NumElems; ++i) {
6683     int EltIdx = SVOp->getMaskElt(i);
6684     if ((i & Mask) != 0 && EltIdx != -1)
6685       return SDValue();
6686     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
6687       return SDValue();
6688   }
6689
6690   LLVMContext *Context = DAG.getContext();
6691   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
6692   EVT NeVT = EVT::getIntegerVT(*Context, NBits);
6693   EVT NVT = EVT::getVectorVT(*Context, NeVT, NumElems >> Shift);
6694
6695   if (!isTypeLegal(NVT))
6696     return SDValue();
6697
6698   // Simplify the operand as it's prepared to be fed into shuffle.
6699   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
6700   if (V1.getOpcode() == ISD::BITCAST &&
6701       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
6702       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6703       V1.getOperand(0)
6704         .getOperand(0).getValueType().getSizeInBits() == SignificantBits) {
6705     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
6706     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
6707     ConstantSDNode *CIdx =
6708       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
6709     // If it's foldable, i.e. normal load with single use, we will let code
6710     // selection to fold it. Otherwise, we will short the conversion sequence.
6711     if (CIdx && CIdx->getZExtValue() == 0 &&
6712         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
6713       if (V.getValueSizeInBits() > V1.getValueSizeInBits()) {
6714         // The "ext_vec_elt" node is wider than the result node.
6715         // In this case we should extract subvector from V.
6716         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
6717         unsigned Ratio = V.getValueSizeInBits() / V1.getValueSizeInBits();
6718         EVT FullVT = V.getValueType();
6719         EVT SubVecVT = EVT::getVectorVT(*Context, 
6720                                         FullVT.getVectorElementType(),
6721                                         FullVT.getVectorNumElements()/Ratio);
6722         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V, 
6723                         DAG.getIntPtrConstant(0));
6724       }
6725       V1 = DAG.getNode(ISD::BITCAST, DL, V1.getValueType(), V);
6726     }
6727   }
6728
6729   return DAG.getNode(ISD::BITCAST, DL, VT,
6730                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
6731 }
6732
6733 SDValue
6734 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6735   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6736   MVT VT = Op.getValueType().getSimpleVT();
6737   DebugLoc dl = Op.getDebugLoc();
6738   SDValue V1 = Op.getOperand(0);
6739   SDValue V2 = Op.getOperand(1);
6740
6741   if (isZeroShuffle(SVOp))
6742     return getZeroVector(VT, Subtarget, DAG, dl);
6743
6744   // Handle splat operations
6745   if (SVOp->isSplat()) {
6746     // Use vbroadcast whenever the splat comes from a foldable load
6747     SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6748     if (Broadcast.getNode())
6749       return Broadcast;
6750   }
6751
6752   // Check integer expanding shuffles.
6753   SDValue NewOp = LowerVectorIntExtend(Op, DAG);
6754   if (NewOp.getNode())
6755     return NewOp;
6756
6757   // If the shuffle can be profitably rewritten as a narrower shuffle, then
6758   // do it!
6759   if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
6760       VT == MVT::v16i16 || VT == MVT::v32i8) {
6761     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
6762     if (NewOp.getNode())
6763       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6764   } else if ((VT == MVT::v4i32 ||
6765              (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6766     // FIXME: Figure out a cleaner way to do this.
6767     // Try to make use of movq to zero out the top part.
6768     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6769       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
6770       if (NewOp.getNode()) {
6771         MVT NewVT = NewOp.getValueType().getSimpleVT();
6772         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6773                                NewVT, true, false))
6774           return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6775                               DAG, Subtarget, dl);
6776       }
6777     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6778       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
6779       if (NewOp.getNode()) {
6780         MVT NewVT = NewOp.getValueType().getSimpleVT();
6781         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6782           return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6783                               DAG, Subtarget, dl);
6784       }
6785     }
6786   }
6787   return SDValue();
6788 }
6789
6790 SDValue
6791 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6792   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6793   SDValue V1 = Op.getOperand(0);
6794   SDValue V2 = Op.getOperand(1);
6795   MVT VT = Op.getValueType().getSimpleVT();
6796   DebugLoc dl = Op.getDebugLoc();
6797   unsigned NumElems = VT.getVectorNumElements();
6798   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6799   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6800   bool V1IsSplat = false;
6801   bool V2IsSplat = false;
6802   bool HasSSE2 = Subtarget->hasSSE2();
6803   bool HasFp256    = Subtarget->hasFp256();
6804   bool HasInt256   = Subtarget->hasInt256();
6805   MachineFunction &MF = DAG.getMachineFunction();
6806   bool OptForSize = MF.getFunction()->getAttributes().
6807     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
6808
6809   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6810
6811   if (V1IsUndef && V2IsUndef)
6812     return DAG.getUNDEF(VT);
6813
6814   assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6815
6816   // Vector shuffle lowering takes 3 steps:
6817   //
6818   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6819   //    narrowing and commutation of operands should be handled.
6820   // 2) Matching of shuffles with known shuffle masks to x86 target specific
6821   //    shuffle nodes.
6822   // 3) Rewriting of unmatched masks into new generic shuffle operations,
6823   //    so the shuffle can be broken into other shuffles and the legalizer can
6824   //    try the lowering again.
6825   //
6826   // The general idea is that no vector_shuffle operation should be left to
6827   // be matched during isel, all of them must be converted to a target specific
6828   // node here.
6829
6830   // Normalize the input vectors. Here splats, zeroed vectors, profitable
6831   // narrowing and commutation of operands should be handled. The actual code
6832   // doesn't include all of those, work in progress...
6833   SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6834   if (NewOp.getNode())
6835     return NewOp;
6836
6837   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6838
6839   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6840   // unpckh_undef). Only use pshufd if speed is more important than size.
6841   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
6842     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6843   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
6844     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6845
6846   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6847       V2IsUndef && MayFoldVectorLoad(V1))
6848     return getMOVDDup(Op, dl, V1, DAG);
6849
6850   if (isMOVHLPS_v_undef_Mask(M, VT))
6851     return getMOVHighToLow(Op, dl, DAG);
6852
6853   // Use to match splats
6854   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
6855       (VT == MVT::v2f64 || VT == MVT::v2i64))
6856     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6857
6858   if (isPSHUFDMask(M, VT)) {
6859     // The actual implementation will match the mask in the if above and then
6860     // during isel it can match several different instructions, not only pshufd
6861     // as its name says, sad but true, emulate the behavior for now...
6862     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6863       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6864
6865     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6866
6867     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6868       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6869
6870     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
6871       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
6872                                   DAG);
6873
6874     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6875                                 TargetMask, DAG);
6876   }
6877
6878   // Check if this can be converted into a logical shift.
6879   bool isLeft = false;
6880   unsigned ShAmt = 0;
6881   SDValue ShVal;
6882   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6883   if (isShift && ShVal.hasOneUse()) {
6884     // If the shifted value has multiple uses, it may be cheaper to use
6885     // v_set0 + movlhps or movhlps, etc.
6886     MVT EltVT = VT.getVectorElementType();
6887     ShAmt *= EltVT.getSizeInBits();
6888     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6889   }
6890
6891   if (isMOVLMask(M, VT)) {
6892     if (ISD::isBuildVectorAllZeros(V1.getNode()))
6893       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6894     if (!isMOVLPMask(M, VT)) {
6895       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6896         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6897
6898       if (VT == MVT::v4i32 || VT == MVT::v4f32)
6899         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6900     }
6901   }
6902
6903   // FIXME: fold these into legal mask.
6904   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
6905     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6906
6907   if (isMOVHLPSMask(M, VT))
6908     return getMOVHighToLow(Op, dl, DAG);
6909
6910   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6911     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6912
6913   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6914     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6915
6916   if (isMOVLPMask(M, VT))
6917     return getMOVLP(Op, dl, DAG, HasSSE2);
6918
6919   if (ShouldXformToMOVHLPS(M, VT) ||
6920       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6921     return CommuteVectorShuffle(SVOp, DAG);
6922
6923   if (isShift) {
6924     // No better options. Use a vshldq / vsrldq.
6925     MVT EltVT = VT.getVectorElementType();
6926     ShAmt *= EltVT.getSizeInBits();
6927     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6928   }
6929
6930   bool Commuted = false;
6931   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
6932   // 1,1,1,1 -> v8i16 though.
6933   V1IsSplat = isSplatVector(V1.getNode());
6934   V2IsSplat = isSplatVector(V2.getNode());
6935
6936   // Canonicalize the splat or undef, if present, to be on the RHS.
6937   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6938     CommuteVectorShuffleMask(M, NumElems);
6939     std::swap(V1, V2);
6940     std::swap(V1IsSplat, V2IsSplat);
6941     Commuted = true;
6942   }
6943
6944   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6945     // Shuffling low element of v1 into undef, just return v1.
6946     if (V2IsUndef)
6947       return V1;
6948     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6949     // the instruction selector will not match, so get a canonical MOVL with
6950     // swapped operands to undo the commute.
6951     return getMOVL(DAG, dl, VT, V2, V1);
6952   }
6953
6954   if (isUNPCKLMask(M, VT, HasInt256))
6955     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6956
6957   if (isUNPCKHMask(M, VT, HasInt256))
6958     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6959
6960   if (V2IsSplat) {
6961     // Normalize mask so all entries that point to V2 points to its first
6962     // element then try to match unpck{h|l} again. If match, return a
6963     // new vector_shuffle with the corrected mask.p
6964     SmallVector<int, 8> NewMask(M.begin(), M.end());
6965     NormalizeMask(NewMask, NumElems);
6966     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
6967       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6968     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
6969       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6970   }
6971
6972   if (Commuted) {
6973     // Commute is back and try unpck* again.
6974     // FIXME: this seems wrong.
6975     CommuteVectorShuffleMask(M, NumElems);
6976     std::swap(V1, V2);
6977     std::swap(V1IsSplat, V2IsSplat);
6978     Commuted = false;
6979
6980     if (isUNPCKLMask(M, VT, HasInt256))
6981       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6982
6983     if (isUNPCKHMask(M, VT, HasInt256))
6984       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6985   }
6986
6987   // Normalize the node to match x86 shuffle ops if needed
6988   if (!V2IsUndef && (isSHUFPMask(M, VT, HasFp256, /* Commuted */ true)))
6989     return CommuteVectorShuffle(SVOp, DAG);
6990
6991   // The checks below are all present in isShuffleMaskLegal, but they are
6992   // inlined here right now to enable us to directly emit target specific
6993   // nodes, and remove one by one until they don't return Op anymore.
6994
6995   if (isPALIGNRMask(M, VT, Subtarget))
6996     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
6997                                 getShufflePALIGNRImmediate(SVOp),
6998                                 DAG);
6999
7000   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7001       SVOp->getSplatIndex() == 0 && V2IsUndef) {
7002     if (VT == MVT::v2f64 || VT == MVT::v2i64)
7003       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7004   }
7005
7006   if (isPSHUFHWMask(M, VT, HasInt256))
7007     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7008                                 getShufflePSHUFHWImmediate(SVOp),
7009                                 DAG);
7010
7011   if (isPSHUFLWMask(M, VT, HasInt256))
7012     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7013                                 getShufflePSHUFLWImmediate(SVOp),
7014                                 DAG);
7015
7016   if (isSHUFPMask(M, VT, HasFp256))
7017     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7018                                 getShuffleSHUFImmediate(SVOp), DAG);
7019
7020   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7021     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7022   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7023     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7024
7025   //===--------------------------------------------------------------------===//
7026   // Generate target specific nodes for 128 or 256-bit shuffles only
7027   // supported in the AVX instruction set.
7028   //
7029
7030   // Handle VMOVDDUPY permutations
7031   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7032     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7033
7034   // Handle VPERMILPS/D* permutations
7035   if (isVPERMILPMask(M, VT, HasFp256)) {
7036     if (HasInt256 && VT == MVT::v8i32)
7037       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7038                                   getShuffleSHUFImmediate(SVOp), DAG);
7039     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7040                                 getShuffleSHUFImmediate(SVOp), DAG);
7041   }
7042
7043   // Handle VPERM2F128/VPERM2I128 permutations
7044   if (isVPERM2X128Mask(M, VT, HasFp256))
7045     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7046                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7047
7048   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7049   if (BlendOp.getNode())
7050     return BlendOp;
7051
7052   if (V2IsUndef && HasInt256 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
7053     SmallVector<SDValue, 8> permclMask;
7054     for (unsigned i = 0; i != 8; ++i) {
7055       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
7056     }
7057     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
7058                                &permclMask[0], 8);
7059     // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7060     return DAG.getNode(X86ISD::VPERMV, dl, VT,
7061                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7062   }
7063
7064   if (V2IsUndef && HasInt256 && (VT == MVT::v4i64 || VT == MVT::v4f64))
7065     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
7066                                 getShuffleCLImmediate(SVOp), DAG);
7067
7068   //===--------------------------------------------------------------------===//
7069   // Since no target specific shuffle was selected for this generic one,
7070   // lower it into other known shuffles. FIXME: this isn't true yet, but
7071   // this is the plan.
7072   //
7073
7074   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7075   if (VT == MVT::v8i16) {
7076     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7077     if (NewOp.getNode())
7078       return NewOp;
7079   }
7080
7081   if (VT == MVT::v16i8) {
7082     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
7083     if (NewOp.getNode())
7084       return NewOp;
7085   }
7086
7087   if (VT == MVT::v32i8) {
7088     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7089     if (NewOp.getNode())
7090       return NewOp;
7091   }
7092
7093   // Handle all 128-bit wide vectors with 4 elements, and match them with
7094   // several different shuffle types.
7095   if (NumElems == 4 && VT.is128BitVector())
7096     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7097
7098   // Handle general 256-bit shuffles
7099   if (VT.is256BitVector())
7100     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7101
7102   return SDValue();
7103 }
7104
7105 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7106   MVT VT = Op.getValueType().getSimpleVT();
7107   DebugLoc dl = Op.getDebugLoc();
7108
7109   if (!Op.getOperand(0).getValueType().getSimpleVT().is128BitVector())
7110     return SDValue();
7111
7112   if (VT.getSizeInBits() == 8) {
7113     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7114                                   Op.getOperand(0), Op.getOperand(1));
7115     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7116                                   DAG.getValueType(VT));
7117     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7118   }
7119
7120   if (VT.getSizeInBits() == 16) {
7121     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7122     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7123     if (Idx == 0)
7124       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7125                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7126                                      DAG.getNode(ISD::BITCAST, dl,
7127                                                  MVT::v4i32,
7128                                                  Op.getOperand(0)),
7129                                      Op.getOperand(1)));
7130     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7131                                   Op.getOperand(0), Op.getOperand(1));
7132     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7133                                   DAG.getValueType(VT));
7134     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7135   }
7136
7137   if (VT == MVT::f32) {
7138     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7139     // the result back to FR32 register. It's only worth matching if the
7140     // result has a single use which is a store or a bitcast to i32.  And in
7141     // the case of a store, it's not worth it if the index is a constant 0,
7142     // because a MOVSSmr can be used instead, which is smaller and faster.
7143     if (!Op.hasOneUse())
7144       return SDValue();
7145     SDNode *User = *Op.getNode()->use_begin();
7146     if ((User->getOpcode() != ISD::STORE ||
7147          (isa<ConstantSDNode>(Op.getOperand(1)) &&
7148           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7149         (User->getOpcode() != ISD::BITCAST ||
7150          User->getValueType(0) != MVT::i32))
7151       return SDValue();
7152     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7153                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7154                                               Op.getOperand(0)),
7155                                               Op.getOperand(1));
7156     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7157   }
7158
7159   if (VT == MVT::i32 || VT == MVT::i64) {
7160     // ExtractPS/pextrq works with constant index.
7161     if (isa<ConstantSDNode>(Op.getOperand(1)))
7162       return Op;
7163   }
7164   return SDValue();
7165 }
7166
7167 SDValue
7168 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7169                                            SelectionDAG &DAG) const {
7170   if (!isa<ConstantSDNode>(Op.getOperand(1)))
7171     return SDValue();
7172
7173   SDValue Vec = Op.getOperand(0);
7174   MVT VecVT = Vec.getValueType().getSimpleVT();
7175
7176   // If this is a 256-bit vector result, first extract the 128-bit vector and
7177   // then extract the element from the 128-bit vector.
7178   if (VecVT.is256BitVector()) {
7179     DebugLoc dl = Op.getNode()->getDebugLoc();
7180     unsigned NumElems = VecVT.getVectorNumElements();
7181     SDValue Idx = Op.getOperand(1);
7182     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7183
7184     // Get the 128-bit vector.
7185     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7186
7187     if (IdxVal >= NumElems/2)
7188       IdxVal -= NumElems/2;
7189     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7190                        DAG.getConstant(IdxVal, MVT::i32));
7191   }
7192
7193   assert(VecVT.is128BitVector() && "Unexpected vector length");
7194
7195   if (Subtarget->hasSSE41()) {
7196     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7197     if (Res.getNode())
7198       return Res;
7199   }
7200
7201   MVT VT = Op.getValueType().getSimpleVT();
7202   DebugLoc dl = Op.getDebugLoc();
7203   // TODO: handle v16i8.
7204   if (VT.getSizeInBits() == 16) {
7205     SDValue Vec = Op.getOperand(0);
7206     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7207     if (Idx == 0)
7208       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7209                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7210                                      DAG.getNode(ISD::BITCAST, dl,
7211                                                  MVT::v4i32, Vec),
7212                                      Op.getOperand(1)));
7213     // Transform it so it match pextrw which produces a 32-bit result.
7214     MVT EltVT = MVT::i32;
7215     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7216                                   Op.getOperand(0), Op.getOperand(1));
7217     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7218                                   DAG.getValueType(VT));
7219     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7220   }
7221
7222   if (VT.getSizeInBits() == 32) {
7223     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7224     if (Idx == 0)
7225       return Op;
7226
7227     // SHUFPS the element to the lowest double word, then movss.
7228     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7229     MVT VVT = Op.getOperand(0).getValueType().getSimpleVT();
7230     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7231                                        DAG.getUNDEF(VVT), Mask);
7232     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7233                        DAG.getIntPtrConstant(0));
7234   }
7235
7236   if (VT.getSizeInBits() == 64) {
7237     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7238     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7239     //        to match extract_elt for f64.
7240     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7241     if (Idx == 0)
7242       return Op;
7243
7244     // UNPCKHPD the element to the lowest double word, then movsd.
7245     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7246     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7247     int Mask[2] = { 1, -1 };
7248     MVT VVT = Op.getOperand(0).getValueType().getSimpleVT();
7249     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7250                                        DAG.getUNDEF(VVT), Mask);
7251     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7252                        DAG.getIntPtrConstant(0));
7253   }
7254
7255   return SDValue();
7256 }
7257
7258 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7259   MVT VT = Op.getValueType().getSimpleVT();
7260   MVT EltVT = VT.getVectorElementType();
7261   DebugLoc dl = Op.getDebugLoc();
7262
7263   SDValue N0 = Op.getOperand(0);
7264   SDValue N1 = Op.getOperand(1);
7265   SDValue N2 = Op.getOperand(2);
7266
7267   if (!VT.is128BitVector())
7268     return SDValue();
7269
7270   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7271       isa<ConstantSDNode>(N2)) {
7272     unsigned Opc;
7273     if (VT == MVT::v8i16)
7274       Opc = X86ISD::PINSRW;
7275     else if (VT == MVT::v16i8)
7276       Opc = X86ISD::PINSRB;
7277     else
7278       Opc = X86ISD::PINSRB;
7279
7280     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7281     // argument.
7282     if (N1.getValueType() != MVT::i32)
7283       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7284     if (N2.getValueType() != MVT::i32)
7285       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7286     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7287   }
7288
7289   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7290     // Bits [7:6] of the constant are the source select.  This will always be
7291     //  zero here.  The DAG Combiner may combine an extract_elt index into these
7292     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
7293     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
7294     // Bits [5:4] of the constant are the destination select.  This is the
7295     //  value of the incoming immediate.
7296     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
7297     //   combine either bitwise AND or insert of float 0.0 to set these bits.
7298     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7299     // Create this as a scalar to vector..
7300     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7301     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7302   }
7303
7304   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7305     // PINSR* works with constant index.
7306     return Op;
7307   }
7308   return SDValue();
7309 }
7310
7311 SDValue
7312 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7313   MVT VT = Op.getValueType().getSimpleVT();
7314   MVT EltVT = VT.getVectorElementType();
7315
7316   DebugLoc dl = Op.getDebugLoc();
7317   SDValue N0 = Op.getOperand(0);
7318   SDValue N1 = Op.getOperand(1);
7319   SDValue N2 = Op.getOperand(2);
7320
7321   // If this is a 256-bit vector result, first extract the 128-bit vector,
7322   // insert the element into the extracted half and then place it back.
7323   if (VT.is256BitVector()) {
7324     if (!isa<ConstantSDNode>(N2))
7325       return SDValue();
7326
7327     // Get the desired 128-bit vector half.
7328     unsigned NumElems = VT.getVectorNumElements();
7329     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7330     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7331
7332     // Insert the element into the desired half.
7333     bool Upper = IdxVal >= NumElems/2;
7334     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7335                  DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
7336
7337     // Insert the changed part back to the 256-bit vector
7338     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7339   }
7340
7341   if (Subtarget->hasSSE41())
7342     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7343
7344   if (EltVT == MVT::i8)
7345     return SDValue();
7346
7347   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7348     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7349     // as its second argument.
7350     if (N1.getValueType() != MVT::i32)
7351       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7352     if (N2.getValueType() != MVT::i32)
7353       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7354     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7355   }
7356   return SDValue();
7357 }
7358
7359 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7360   LLVMContext *Context = DAG.getContext();
7361   DebugLoc dl = Op.getDebugLoc();
7362   MVT OpVT = Op.getValueType().getSimpleVT();
7363
7364   // If this is a 256-bit vector result, first insert into a 128-bit
7365   // vector and then insert into the 256-bit vector.
7366   if (!OpVT.is128BitVector()) {
7367     // Insert into a 128-bit vector.
7368     EVT VT128 = EVT::getVectorVT(*Context,
7369                                  OpVT.getVectorElementType(),
7370                                  OpVT.getVectorNumElements() / 2);
7371
7372     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7373
7374     // Insert the 128-bit vector.
7375     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7376   }
7377
7378   if (OpVT == MVT::v1i64 &&
7379       Op.getOperand(0).getValueType() == MVT::i64)
7380     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7381
7382   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7383   assert(OpVT.is128BitVector() && "Expected an SSE type!");
7384   return DAG.getNode(ISD::BITCAST, dl, OpVT,
7385                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7386 }
7387
7388 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7389 // a simple subregister reference or explicit instructions to grab
7390 // upper bits of a vector.
7391 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7392                                       SelectionDAG &DAG) {
7393   if (Subtarget->hasFp256()) {
7394     DebugLoc dl = Op.getNode()->getDebugLoc();
7395     SDValue Vec = Op.getNode()->getOperand(0);
7396     SDValue Idx = Op.getNode()->getOperand(1);
7397
7398     if (Op.getNode()->getValueType(0).is128BitVector() &&
7399         Vec.getNode()->getValueType(0).is256BitVector() &&
7400         isa<ConstantSDNode>(Idx)) {
7401       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7402       return Extract128BitVector(Vec, IdxVal, DAG, dl);
7403     }
7404   }
7405   return SDValue();
7406 }
7407
7408 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7409 // simple superregister reference or explicit instructions to insert
7410 // the upper bits of a vector.
7411 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7412                                      SelectionDAG &DAG) {
7413   if (Subtarget->hasFp256()) {
7414     DebugLoc dl = Op.getNode()->getDebugLoc();
7415     SDValue Vec = Op.getNode()->getOperand(0);
7416     SDValue SubVec = Op.getNode()->getOperand(1);
7417     SDValue Idx = Op.getNode()->getOperand(2);
7418
7419     if (Op.getNode()->getValueType(0).is256BitVector() &&
7420         SubVec.getNode()->getValueType(0).is128BitVector() &&
7421         isa<ConstantSDNode>(Idx)) {
7422       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7423       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7424     }
7425   }
7426   return SDValue();
7427 }
7428
7429 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7430 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7431 // one of the above mentioned nodes. It has to be wrapped because otherwise
7432 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7433 // be used to form addressing mode. These wrapped nodes will be selected
7434 // into MOV32ri.
7435 SDValue
7436 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7437   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7438
7439   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7440   // global base reg.
7441   unsigned char OpFlag = 0;
7442   unsigned WrapperKind = X86ISD::Wrapper;
7443   CodeModel::Model M = getTargetMachine().getCodeModel();
7444
7445   if (Subtarget->isPICStyleRIPRel() &&
7446       (M == CodeModel::Small || M == CodeModel::Kernel))
7447     WrapperKind = X86ISD::WrapperRIP;
7448   else if (Subtarget->isPICStyleGOT())
7449     OpFlag = X86II::MO_GOTOFF;
7450   else if (Subtarget->isPICStyleStubPIC())
7451     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7452
7453   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7454                                              CP->getAlignment(),
7455                                              CP->getOffset(), OpFlag);
7456   DebugLoc DL = CP->getDebugLoc();
7457   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7458   // With PIC, the address is actually $g + Offset.
7459   if (OpFlag) {
7460     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7461                          DAG.getNode(X86ISD::GlobalBaseReg,
7462                                      DebugLoc(), getPointerTy()),
7463                          Result);
7464   }
7465
7466   return Result;
7467 }
7468
7469 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7470   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7471
7472   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7473   // global base reg.
7474   unsigned char OpFlag = 0;
7475   unsigned WrapperKind = X86ISD::Wrapper;
7476   CodeModel::Model M = getTargetMachine().getCodeModel();
7477
7478   if (Subtarget->isPICStyleRIPRel() &&
7479       (M == CodeModel::Small || M == CodeModel::Kernel))
7480     WrapperKind = X86ISD::WrapperRIP;
7481   else if (Subtarget->isPICStyleGOT())
7482     OpFlag = X86II::MO_GOTOFF;
7483   else if (Subtarget->isPICStyleStubPIC())
7484     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7485
7486   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7487                                           OpFlag);
7488   DebugLoc DL = JT->getDebugLoc();
7489   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7490
7491   // With PIC, the address is actually $g + Offset.
7492   if (OpFlag)
7493     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7494                          DAG.getNode(X86ISD::GlobalBaseReg,
7495                                      DebugLoc(), getPointerTy()),
7496                          Result);
7497
7498   return Result;
7499 }
7500
7501 SDValue
7502 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7503   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7504
7505   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7506   // global base reg.
7507   unsigned char OpFlag = 0;
7508   unsigned WrapperKind = X86ISD::Wrapper;
7509   CodeModel::Model M = getTargetMachine().getCodeModel();
7510
7511   if (Subtarget->isPICStyleRIPRel() &&
7512       (M == CodeModel::Small || M == CodeModel::Kernel)) {
7513     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7514       OpFlag = X86II::MO_GOTPCREL;
7515     WrapperKind = X86ISD::WrapperRIP;
7516   } else if (Subtarget->isPICStyleGOT()) {
7517     OpFlag = X86II::MO_GOT;
7518   } else if (Subtarget->isPICStyleStubPIC()) {
7519     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7520   } else if (Subtarget->isPICStyleStubNoDynamic()) {
7521     OpFlag = X86II::MO_DARWIN_NONLAZY;
7522   }
7523
7524   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7525
7526   DebugLoc DL = Op.getDebugLoc();
7527   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7528
7529   // With PIC, the address is actually $g + Offset.
7530   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7531       !Subtarget->is64Bit()) {
7532     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7533                          DAG.getNode(X86ISD::GlobalBaseReg,
7534                                      DebugLoc(), getPointerTy()),
7535                          Result);
7536   }
7537
7538   // For symbols that require a load from a stub to get the address, emit the
7539   // load.
7540   if (isGlobalStubReference(OpFlag))
7541     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7542                          MachinePointerInfo::getGOT(), false, false, false, 0);
7543
7544   return Result;
7545 }
7546
7547 SDValue
7548 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7549   // Create the TargetBlockAddressAddress node.
7550   unsigned char OpFlags =
7551     Subtarget->ClassifyBlockAddressReference();
7552   CodeModel::Model M = getTargetMachine().getCodeModel();
7553   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7554   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
7555   DebugLoc dl = Op.getDebugLoc();
7556   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
7557                                              OpFlags);
7558
7559   if (Subtarget->isPICStyleRIPRel() &&
7560       (M == CodeModel::Small || M == CodeModel::Kernel))
7561     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7562   else
7563     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7564
7565   // With PIC, the address is actually $g + Offset.
7566   if (isGlobalRelativeToPICBase(OpFlags)) {
7567     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7568                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7569                          Result);
7570   }
7571
7572   return Result;
7573 }
7574
7575 SDValue
7576 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7577                                       int64_t Offset, SelectionDAG &DAG) const {
7578   // Create the TargetGlobalAddress node, folding in the constant
7579   // offset if it is legal.
7580   unsigned char OpFlags =
7581     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7582   CodeModel::Model M = getTargetMachine().getCodeModel();
7583   SDValue Result;
7584   if (OpFlags == X86II::MO_NO_FLAG &&
7585       X86::isOffsetSuitableForCodeModel(Offset, M)) {
7586     // A direct static reference to a global.
7587     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7588     Offset = 0;
7589   } else {
7590     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7591   }
7592
7593   if (Subtarget->isPICStyleRIPRel() &&
7594       (M == CodeModel::Small || M == CodeModel::Kernel))
7595     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7596   else
7597     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7598
7599   // With PIC, the address is actually $g + Offset.
7600   if (isGlobalRelativeToPICBase(OpFlags)) {
7601     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7602                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7603                          Result);
7604   }
7605
7606   // For globals that require a load from a stub to get the address, emit the
7607   // load.
7608   if (isGlobalStubReference(OpFlags))
7609     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7610                          MachinePointerInfo::getGOT(), false, false, false, 0);
7611
7612   // If there was a non-zero offset that we didn't fold, create an explicit
7613   // addition for it.
7614   if (Offset != 0)
7615     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7616                          DAG.getConstant(Offset, getPointerTy()));
7617
7618   return Result;
7619 }
7620
7621 SDValue
7622 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7623   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7624   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7625   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7626 }
7627
7628 static SDValue
7629 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7630            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7631            unsigned char OperandFlags, bool LocalDynamic = false) {
7632   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7633   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7634   DebugLoc dl = GA->getDebugLoc();
7635   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7636                                            GA->getValueType(0),
7637                                            GA->getOffset(),
7638                                            OperandFlags);
7639
7640   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7641                                            : X86ISD::TLSADDR;
7642
7643   if (InFlag) {
7644     SDValue Ops[] = { Chain,  TGA, *InFlag };
7645     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 3);
7646   } else {
7647     SDValue Ops[]  = { Chain, TGA };
7648     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 2);
7649   }
7650
7651   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7652   MFI->setAdjustsStack(true);
7653
7654   SDValue Flag = Chain.getValue(1);
7655   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7656 }
7657
7658 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7659 static SDValue
7660 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7661                                 const EVT PtrVT) {
7662   SDValue InFlag;
7663   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
7664   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7665                                    DAG.getNode(X86ISD::GlobalBaseReg,
7666                                                DebugLoc(), PtrVT), InFlag);
7667   InFlag = Chain.getValue(1);
7668
7669   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7670 }
7671
7672 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7673 static SDValue
7674 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7675                                 const EVT PtrVT) {
7676   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7677                     X86::RAX, X86II::MO_TLSGD);
7678 }
7679
7680 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7681                                            SelectionDAG &DAG,
7682                                            const EVT PtrVT,
7683                                            bool is64Bit) {
7684   DebugLoc dl = GA->getDebugLoc();
7685
7686   // Get the start address of the TLS block for this module.
7687   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7688       .getInfo<X86MachineFunctionInfo>();
7689   MFI->incNumLocalDynamicTLSAccesses();
7690
7691   SDValue Base;
7692   if (is64Bit) {
7693     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7694                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
7695   } else {
7696     SDValue InFlag;
7697     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7698         DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), InFlag);
7699     InFlag = Chain.getValue(1);
7700     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7701                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7702   }
7703
7704   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7705   // of Base.
7706
7707   // Build x@dtpoff.
7708   unsigned char OperandFlags = X86II::MO_DTPOFF;
7709   unsigned WrapperKind = X86ISD::Wrapper;
7710   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7711                                            GA->getValueType(0),
7712                                            GA->getOffset(), OperandFlags);
7713   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7714
7715   // Add x@dtpoff with the base.
7716   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7717 }
7718
7719 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7720 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7721                                    const EVT PtrVT, TLSModel::Model model,
7722                                    bool is64Bit, bool isPIC) {
7723   DebugLoc dl = GA->getDebugLoc();
7724
7725   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7726   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7727                                                          is64Bit ? 257 : 256));
7728
7729   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7730                                       DAG.getIntPtrConstant(0),
7731                                       MachinePointerInfo(Ptr),
7732                                       false, false, false, 0);
7733
7734   unsigned char OperandFlags = 0;
7735   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
7736   // initialexec.
7737   unsigned WrapperKind = X86ISD::Wrapper;
7738   if (model == TLSModel::LocalExec) {
7739     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7740   } else if (model == TLSModel::InitialExec) {
7741     if (is64Bit) {
7742       OperandFlags = X86II::MO_GOTTPOFF;
7743       WrapperKind = X86ISD::WrapperRIP;
7744     } else {
7745       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7746     }
7747   } else {
7748     llvm_unreachable("Unexpected model");
7749   }
7750
7751   // emit "addl x@ntpoff,%eax" (local exec)
7752   // or "addl x@indntpoff,%eax" (initial exec)
7753   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7754   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7755                                            GA->getValueType(0),
7756                                            GA->getOffset(), OperandFlags);
7757   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7758
7759   if (model == TLSModel::InitialExec) {
7760     if (isPIC && !is64Bit) {
7761       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7762                           DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT),
7763                            Offset);
7764     }
7765
7766     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7767                          MachinePointerInfo::getGOT(), false, false, false,
7768                          0);
7769   }
7770
7771   // The address of the thread local variable is the add of the thread
7772   // pointer with the offset of the variable.
7773   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7774 }
7775
7776 SDValue
7777 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7778
7779   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7780   const GlobalValue *GV = GA->getGlobal();
7781
7782   if (Subtarget->isTargetELF()) {
7783     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7784
7785     switch (model) {
7786       case TLSModel::GeneralDynamic:
7787         if (Subtarget->is64Bit())
7788           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7789         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7790       case TLSModel::LocalDynamic:
7791         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7792                                            Subtarget->is64Bit());
7793       case TLSModel::InitialExec:
7794       case TLSModel::LocalExec:
7795         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7796                                    Subtarget->is64Bit(),
7797                         getTargetMachine().getRelocationModel() == Reloc::PIC_);
7798     }
7799     llvm_unreachable("Unknown TLS model.");
7800   }
7801
7802   if (Subtarget->isTargetDarwin()) {
7803     // Darwin only has one model of TLS.  Lower to that.
7804     unsigned char OpFlag = 0;
7805     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7806                            X86ISD::WrapperRIP : X86ISD::Wrapper;
7807
7808     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7809     // global base reg.
7810     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7811                   !Subtarget->is64Bit();
7812     if (PIC32)
7813       OpFlag = X86II::MO_TLVP_PIC_BASE;
7814     else
7815       OpFlag = X86II::MO_TLVP;
7816     DebugLoc DL = Op.getDebugLoc();
7817     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7818                                                 GA->getValueType(0),
7819                                                 GA->getOffset(), OpFlag);
7820     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7821
7822     // With PIC32, the address is actually $g + Offset.
7823     if (PIC32)
7824       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7825                            DAG.getNode(X86ISD::GlobalBaseReg,
7826                                        DebugLoc(), getPointerTy()),
7827                            Offset);
7828
7829     // Lowering the machine isd will make sure everything is in the right
7830     // location.
7831     SDValue Chain = DAG.getEntryNode();
7832     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7833     SDValue Args[] = { Chain, Offset };
7834     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7835
7836     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7837     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7838     MFI->setAdjustsStack(true);
7839
7840     // And our return value (tls address) is in the standard call return value
7841     // location.
7842     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7843     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7844                               Chain.getValue(1));
7845   }
7846
7847   if (Subtarget->isTargetWindows() || Subtarget->isTargetMingw()) {
7848     // Just use the implicit TLS architecture
7849     // Need to generate someting similar to:
7850     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7851     //                                  ; from TEB
7852     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
7853     //   mov     rcx, qword [rdx+rcx*8]
7854     //   mov     eax, .tls$:tlsvar
7855     //   [rax+rcx] contains the address
7856     // Windows 64bit: gs:0x58
7857     // Windows 32bit: fs:__tls_array
7858
7859     // If GV is an alias then use the aliasee for determining
7860     // thread-localness.
7861     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7862       GV = GA->resolveAliasedGlobal(false);
7863     DebugLoc dl = GA->getDebugLoc();
7864     SDValue Chain = DAG.getEntryNode();
7865
7866     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7867     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
7868     // use its literal value of 0x2C.
7869     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7870                                         ? Type::getInt8PtrTy(*DAG.getContext(),
7871                                                              256)
7872                                         : Type::getInt32PtrTy(*DAG.getContext(),
7873                                                               257));
7874
7875     SDValue TlsArray = Subtarget->is64Bit() ? DAG.getIntPtrConstant(0x58) :
7876       (Subtarget->isTargetMingw() ? DAG.getIntPtrConstant(0x2C) :
7877         DAG.getExternalSymbol("_tls_array", getPointerTy()));
7878
7879     SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
7880                                         MachinePointerInfo(Ptr),
7881                                         false, false, false, 0);
7882
7883     // Load the _tls_index variable
7884     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7885     if (Subtarget->is64Bit())
7886       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7887                            IDX, MachinePointerInfo(), MVT::i32,
7888                            false, false, 0);
7889     else
7890       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7891                         false, false, false, 0);
7892
7893     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
7894                                     getPointerTy());
7895     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7896
7897     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7898     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7899                       false, false, false, 0);
7900
7901     // Get the offset of start of .tls section
7902     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7903                                              GA->getValueType(0),
7904                                              GA->getOffset(), X86II::MO_SECREL);
7905     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7906
7907     // The address of the thread local variable is the add of the thread
7908     // pointer with the offset of the variable.
7909     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7910   }
7911
7912   llvm_unreachable("TLS not implemented for this target.");
7913 }
7914
7915 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7916 /// and take a 2 x i32 value to shift plus a shift amount.
7917 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7918   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7919   EVT VT = Op.getValueType();
7920   unsigned VTBits = VT.getSizeInBits();
7921   DebugLoc dl = Op.getDebugLoc();
7922   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7923   SDValue ShOpLo = Op.getOperand(0);
7924   SDValue ShOpHi = Op.getOperand(1);
7925   SDValue ShAmt  = Op.getOperand(2);
7926   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7927                                      DAG.getConstant(VTBits - 1, MVT::i8))
7928                        : DAG.getConstant(0, VT);
7929
7930   SDValue Tmp2, Tmp3;
7931   if (Op.getOpcode() == ISD::SHL_PARTS) {
7932     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7933     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7934   } else {
7935     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7936     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7937   }
7938
7939   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7940                                 DAG.getConstant(VTBits, MVT::i8));
7941   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7942                              AndNode, DAG.getConstant(0, MVT::i8));
7943
7944   SDValue Hi, Lo;
7945   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7946   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7947   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7948
7949   if (Op.getOpcode() == ISD::SHL_PARTS) {
7950     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7951     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7952   } else {
7953     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7954     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7955   }
7956
7957   SDValue Ops[2] = { Lo, Hi };
7958   return DAG.getMergeValues(Ops, 2, dl);
7959 }
7960
7961 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7962                                            SelectionDAG &DAG) const {
7963   EVT SrcVT = Op.getOperand(0).getValueType();
7964
7965   if (SrcVT.isVector())
7966     return SDValue();
7967
7968   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7969          "Unknown SINT_TO_FP to lower!");
7970
7971   // These are really Legal; return the operand so the caller accepts it as
7972   // Legal.
7973   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7974     return Op;
7975   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7976       Subtarget->is64Bit()) {
7977     return Op;
7978   }
7979
7980   DebugLoc dl = Op.getDebugLoc();
7981   unsigned Size = SrcVT.getSizeInBits()/8;
7982   MachineFunction &MF = DAG.getMachineFunction();
7983   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7984   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7985   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7986                                StackSlot,
7987                                MachinePointerInfo::getFixedStack(SSFI),
7988                                false, false, 0);
7989   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7990 }
7991
7992 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7993                                      SDValue StackSlot,
7994                                      SelectionDAG &DAG) const {
7995   // Build the FILD
7996   DebugLoc DL = Op.getDebugLoc();
7997   SDVTList Tys;
7998   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7999   if (useSSE)
8000     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
8001   else
8002     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
8003
8004   unsigned ByteSize = SrcVT.getSizeInBits()/8;
8005
8006   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
8007   MachineMemOperand *MMO;
8008   if (FI) {
8009     int SSFI = FI->getIndex();
8010     MMO =
8011       DAG.getMachineFunction()
8012       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8013                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
8014   } else {
8015     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
8016     StackSlot = StackSlot.getOperand(1);
8017   }
8018   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
8019   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
8020                                            X86ISD::FILD, DL,
8021                                            Tys, Ops, array_lengthof(Ops),
8022                                            SrcVT, MMO);
8023
8024   if (useSSE) {
8025     Chain = Result.getValue(1);
8026     SDValue InFlag = Result.getValue(2);
8027
8028     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
8029     // shouldn't be necessary except that RFP cannot be live across
8030     // multiple blocks. When stackifier is fixed, they can be uncoupled.
8031     MachineFunction &MF = DAG.getMachineFunction();
8032     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
8033     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
8034     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8035     Tys = DAG.getVTList(MVT::Other);
8036     SDValue Ops[] = {
8037       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
8038     };
8039     MachineMemOperand *MMO =
8040       DAG.getMachineFunction()
8041       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8042                             MachineMemOperand::MOStore, SSFISize, SSFISize);
8043
8044     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
8045                                     Ops, array_lengthof(Ops),
8046                                     Op.getValueType(), MMO);
8047     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
8048                          MachinePointerInfo::getFixedStack(SSFI),
8049                          false, false, false, 0);
8050   }
8051
8052   return Result;
8053 }
8054
8055 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
8056 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
8057                                                SelectionDAG &DAG) const {
8058   // This algorithm is not obvious. Here it is what we're trying to output:
8059   /*
8060      movq       %rax,  %xmm0
8061      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
8062      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8063      #ifdef __SSE3__
8064        haddpd   %xmm0, %xmm0
8065      #else
8066        pshufd   $0x4e, %xmm0, %xmm1
8067        addpd    %xmm1, %xmm0
8068      #endif
8069   */
8070
8071   DebugLoc dl = Op.getDebugLoc();
8072   LLVMContext *Context = DAG.getContext();
8073
8074   // Build some magic constants.
8075   const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8076   Constant *C0 = ConstantDataVector::get(*Context, CV0);
8077   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8078
8079   SmallVector<Constant*,2> CV1;
8080   CV1.push_back(
8081     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8082                                       APInt(64, 0x4330000000000000ULL))));
8083   CV1.push_back(
8084     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8085                                       APInt(64, 0x4530000000000000ULL))));
8086   Constant *C1 = ConstantVector::get(CV1);
8087   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8088
8089   // Load the 64-bit value into an XMM register.
8090   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8091                             Op.getOperand(0));
8092   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8093                               MachinePointerInfo::getConstantPool(),
8094                               false, false, false, 16);
8095   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8096                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8097                               CLod0);
8098
8099   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8100                               MachinePointerInfo::getConstantPool(),
8101                               false, false, false, 16);
8102   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8103   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8104   SDValue Result;
8105
8106   if (Subtarget->hasSSE3()) {
8107     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8108     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8109   } else {
8110     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8111     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8112                                            S2F, 0x4E, DAG);
8113     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8114                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8115                          Sub);
8116   }
8117
8118   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8119                      DAG.getIntPtrConstant(0));
8120 }
8121
8122 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8123 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8124                                                SelectionDAG &DAG) const {
8125   DebugLoc dl = Op.getDebugLoc();
8126   // FP constant to bias correct the final result.
8127   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8128                                    MVT::f64);
8129
8130   // Load the 32-bit value into an XMM register.
8131   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8132                              Op.getOperand(0));
8133
8134   // Zero out the upper parts of the register.
8135   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8136
8137   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8138                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8139                      DAG.getIntPtrConstant(0));
8140
8141   // Or the load with the bias.
8142   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8143                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8144                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8145                                                    MVT::v2f64, Load)),
8146                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8147                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8148                                                    MVT::v2f64, Bias)));
8149   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8150                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8151                    DAG.getIntPtrConstant(0));
8152
8153   // Subtract the bias.
8154   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
8155
8156   // Handle final rounding.
8157   EVT DestVT = Op.getValueType();
8158
8159   if (DestVT.bitsLT(MVT::f64))
8160     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
8161                        DAG.getIntPtrConstant(0));
8162   if (DestVT.bitsGT(MVT::f64))
8163     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
8164
8165   // Handle final rounding.
8166   return Sub;
8167 }
8168
8169 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
8170                                                SelectionDAG &DAG) const {
8171   SDValue N0 = Op.getOperand(0);
8172   EVT SVT = N0.getValueType();
8173   DebugLoc dl = Op.getDebugLoc();
8174
8175   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
8176           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
8177          "Custom UINT_TO_FP is not supported!");
8178
8179   EVT NVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
8180                              SVT.getVectorNumElements());
8181   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
8182                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
8183 }
8184
8185 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8186                                            SelectionDAG &DAG) const {
8187   SDValue N0 = Op.getOperand(0);
8188   DebugLoc dl = Op.getDebugLoc();
8189
8190   if (Op.getValueType().isVector())
8191     return lowerUINT_TO_FP_vec(Op, DAG);
8192
8193   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8194   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8195   // the optimization here.
8196   if (DAG.SignBitIsZero(N0))
8197     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8198
8199   EVT SrcVT = N0.getValueType();
8200   EVT DstVT = Op.getValueType();
8201   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8202     return LowerUINT_TO_FP_i64(Op, DAG);
8203   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8204     return LowerUINT_TO_FP_i32(Op, DAG);
8205   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8206     return SDValue();
8207
8208   // Make a 64-bit buffer, and use it to build an FILD.
8209   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8210   if (SrcVT == MVT::i32) {
8211     SDValue WordOff = DAG.getConstant(4, getPointerTy());
8212     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8213                                      getPointerTy(), StackSlot, WordOff);
8214     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8215                                   StackSlot, MachinePointerInfo(),
8216                                   false, false, 0);
8217     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8218                                   OffsetSlot, MachinePointerInfo(),
8219                                   false, false, 0);
8220     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8221     return Fild;
8222   }
8223
8224   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8225   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8226                                StackSlot, MachinePointerInfo(),
8227                                false, false, 0);
8228   // For i64 source, we need to add the appropriate power of 2 if the input
8229   // was negative.  This is the same as the optimization in
8230   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8231   // we must be careful to do the computation in x87 extended precision, not
8232   // in SSE. (The generic code can't know it's OK to do this, or how to.)
8233   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8234   MachineMemOperand *MMO =
8235     DAG.getMachineFunction()
8236     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8237                           MachineMemOperand::MOLoad, 8, 8);
8238
8239   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8240   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8241   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
8242                                          MVT::i64, MMO);
8243
8244   APInt FF(32, 0x5F800000ULL);
8245
8246   // Check whether the sign bit is set.
8247   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
8248                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8249                                  ISD::SETLT);
8250
8251   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8252   SDValue FudgePtr = DAG.getConstantPool(
8253                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8254                                          getPointerTy());
8255
8256   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8257   SDValue Zero = DAG.getIntPtrConstant(0);
8258   SDValue Four = DAG.getIntPtrConstant(4);
8259   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8260                                Zero, Four);
8261   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8262
8263   // Load the value out, extending it from f32 to f80.
8264   // FIXME: Avoid the extend by constructing the right constant pool?
8265   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8266                                  FudgePtr, MachinePointerInfo::getConstantPool(),
8267                                  MVT::f32, false, false, 4);
8268   // Extend everything to 80 bits to force it to be done on x87.
8269   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8270   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8271 }
8272
8273 std::pair<SDValue,SDValue>
8274 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
8275                                     bool IsSigned, bool IsReplace) const {
8276   DebugLoc DL = Op.getDebugLoc();
8277
8278   EVT DstTy = Op.getValueType();
8279
8280   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8281     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8282     DstTy = MVT::i64;
8283   }
8284
8285   assert(DstTy.getSimpleVT() <= MVT::i64 &&
8286          DstTy.getSimpleVT() >= MVT::i16 &&
8287          "Unknown FP_TO_INT to lower!");
8288
8289   // These are really Legal.
8290   if (DstTy == MVT::i32 &&
8291       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8292     return std::make_pair(SDValue(), SDValue());
8293   if (Subtarget->is64Bit() &&
8294       DstTy == MVT::i64 &&
8295       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8296     return std::make_pair(SDValue(), SDValue());
8297
8298   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8299   // stack slot, or into the FTOL runtime function.
8300   MachineFunction &MF = DAG.getMachineFunction();
8301   unsigned MemSize = DstTy.getSizeInBits()/8;
8302   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8303   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8304
8305   unsigned Opc;
8306   if (!IsSigned && isIntegerTypeFTOL(DstTy))
8307     Opc = X86ISD::WIN_FTOL;
8308   else
8309     switch (DstTy.getSimpleVT().SimpleTy) {
8310     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8311     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8312     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8313     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8314     }
8315
8316   SDValue Chain = DAG.getEntryNode();
8317   SDValue Value = Op.getOperand(0);
8318   EVT TheVT = Op.getOperand(0).getValueType();
8319   // FIXME This causes a redundant load/store if the SSE-class value is already
8320   // in memory, such as if it is on the callstack.
8321   if (isScalarFPTypeInSSEReg(TheVT)) {
8322     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8323     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8324                          MachinePointerInfo::getFixedStack(SSFI),
8325                          false, false, 0);
8326     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8327     SDValue Ops[] = {
8328       Chain, StackSlot, DAG.getValueType(TheVT)
8329     };
8330
8331     MachineMemOperand *MMO =
8332       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8333                               MachineMemOperand::MOLoad, MemSize, MemSize);
8334     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
8335                                     DstTy, MMO);
8336     Chain = Value.getValue(1);
8337     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8338     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8339   }
8340
8341   MachineMemOperand *MMO =
8342     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8343                             MachineMemOperand::MOStore, MemSize, MemSize);
8344
8345   if (Opc != X86ISD::WIN_FTOL) {
8346     // Build the FP_TO_INT*_IN_MEM
8347     SDValue Ops[] = { Chain, Value, StackSlot };
8348     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8349                                            Ops, 3, DstTy, MMO);
8350     return std::make_pair(FIST, StackSlot);
8351   } else {
8352     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8353       DAG.getVTList(MVT::Other, MVT::Glue),
8354       Chain, Value);
8355     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8356       MVT::i32, ftol.getValue(1));
8357     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8358       MVT::i32, eax.getValue(2));
8359     SDValue Ops[] = { eax, edx };
8360     SDValue pair = IsReplace
8361       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, 2)
8362       : DAG.getMergeValues(Ops, 2, DL);
8363     return std::make_pair(pair, SDValue());
8364   }
8365 }
8366
8367 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
8368                               const X86Subtarget *Subtarget) {
8369   MVT VT = Op->getValueType(0).getSimpleVT();
8370   SDValue In = Op->getOperand(0);
8371   MVT InVT = In.getValueType().getSimpleVT();
8372   DebugLoc dl = Op->getDebugLoc();
8373
8374   // Optimize vectors in AVX mode:
8375   //
8376   //   v8i16 -> v8i32
8377   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
8378   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
8379   //   Concat upper and lower parts.
8380   //
8381   //   v4i32 -> v4i64
8382   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
8383   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
8384   //   Concat upper and lower parts.
8385   //
8386
8387   if (((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
8388       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
8389     return SDValue();
8390
8391   if (Subtarget->hasInt256())
8392     return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, In);
8393
8394   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
8395   SDValue Undef = DAG.getUNDEF(InVT);
8396   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
8397   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8398   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8399
8400   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
8401                              VT.getVectorNumElements()/2);
8402
8403   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
8404   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
8405
8406   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
8407 }
8408
8409 SDValue X86TargetLowering::LowerANY_EXTEND(SDValue Op,
8410                                            SelectionDAG &DAG) const {
8411   if (Subtarget->hasFp256()) {
8412     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8413     if (Res.getNode())
8414       return Res;
8415   }
8416
8417   return SDValue();
8418 }
8419 SDValue X86TargetLowering::LowerZERO_EXTEND(SDValue Op,
8420                                             SelectionDAG &DAG) const {
8421   DebugLoc DL = Op.getDebugLoc();
8422   MVT VT = Op.getValueType().getSimpleVT();
8423   SDValue In = Op.getOperand(0);
8424   MVT SVT = In.getValueType().getSimpleVT();
8425
8426   if (Subtarget->hasFp256()) {
8427     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8428     if (Res.getNode())
8429       return Res;
8430   }
8431
8432   if (!VT.is256BitVector() || !SVT.is128BitVector() ||
8433       VT.getVectorNumElements() != SVT.getVectorNumElements())
8434     return SDValue();
8435
8436   assert(Subtarget->hasFp256() && "256-bit vector is observed without AVX!");
8437
8438   // AVX2 has better support of integer extending.
8439   if (Subtarget->hasInt256())
8440     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
8441
8442   SDValue Lo = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32, In);
8443   static const int Mask[] = {4, 5, 6, 7, -1, -1, -1, -1};
8444   SDValue Hi = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32,
8445                            DAG.getVectorShuffle(MVT::v8i16, DL, In,
8446                                                 DAG.getUNDEF(MVT::v8i16),
8447                                                 &Mask[0]));
8448
8449   return DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i32, Lo, Hi);
8450 }
8451
8452 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
8453   DebugLoc DL = Op.getDebugLoc();
8454   MVT VT = Op.getValueType().getSimpleVT();
8455   SDValue In = Op.getOperand(0);
8456   MVT SVT = In.getValueType().getSimpleVT();
8457
8458   if ((VT == MVT::v4i32) && (SVT == MVT::v4i64)) {
8459     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
8460     if (Subtarget->hasInt256()) {
8461       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
8462       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
8463       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
8464                                 ShufMask);
8465       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
8466                          DAG.getIntPtrConstant(0));
8467     }
8468
8469     // On AVX, v4i64 -> v4i32 becomes a sequence that uses PSHUFD and MOVLHPS.
8470     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8471                                DAG.getIntPtrConstant(0));
8472     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8473                                DAG.getIntPtrConstant(2));
8474
8475     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
8476     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
8477
8478     // The PSHUFD mask:
8479     static const int ShufMask1[] = {0, 2, 0, 0};
8480     SDValue Undef = DAG.getUNDEF(VT);
8481     OpLo = DAG.getVectorShuffle(VT, DL, OpLo, Undef, ShufMask1);
8482     OpHi = DAG.getVectorShuffle(VT, DL, OpHi, Undef, ShufMask1);
8483
8484     // The MOVLHPS mask:
8485     static const int ShufMask2[] = {0, 1, 4, 5};
8486     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask2);
8487   }
8488
8489   if ((VT == MVT::v8i16) && (SVT == MVT::v8i32)) {
8490     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
8491     if (Subtarget->hasInt256()) {
8492       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
8493
8494       SmallVector<SDValue,32> pshufbMask;
8495       for (unsigned i = 0; i < 2; ++i) {
8496         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
8497         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
8498         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
8499         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
8500         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
8501         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
8502         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
8503         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
8504         for (unsigned j = 0; j < 8; ++j)
8505           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
8506       }
8507       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8,
8508                                &pshufbMask[0], 32);
8509       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
8510       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
8511
8512       static const int ShufMask[] = {0,  2,  -1,  -1};
8513       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
8514                                 &ShufMask[0]);
8515       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8516                        DAG.getIntPtrConstant(0));
8517       return DAG.getNode(ISD::BITCAST, DL, VT, In);
8518     }
8519
8520     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
8521                                DAG.getIntPtrConstant(0));
8522
8523     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
8524                                DAG.getIntPtrConstant(4));
8525
8526     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
8527     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
8528
8529     // The PSHUFB mask:
8530     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
8531                                    -1, -1, -1, -1, -1, -1, -1, -1};
8532
8533     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
8534     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
8535     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
8536
8537     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
8538     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
8539
8540     // The MOVLHPS Mask:
8541     static const int ShufMask2[] = {0, 1, 4, 5};
8542     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
8543     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
8544   }
8545
8546   // Handle truncation of V256 to V128 using shuffles.
8547   if (!VT.is128BitVector() || !SVT.is256BitVector())
8548     return SDValue();
8549
8550   assert(VT.getVectorNumElements() != SVT.getVectorNumElements() &&
8551          "Invalid op");
8552   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
8553
8554   unsigned NumElems = VT.getVectorNumElements();
8555   EVT NVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
8556                              NumElems * 2);
8557
8558   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
8559   // Prepare truncation shuffle mask
8560   for (unsigned i = 0; i != NumElems; ++i)
8561     MaskVec[i] = i * 2;
8562   SDValue V = DAG.getVectorShuffle(NVT, DL,
8563                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
8564                                    DAG.getUNDEF(NVT), &MaskVec[0]);
8565   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
8566                      DAG.getIntPtrConstant(0));
8567 }
8568
8569 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8570                                            SelectionDAG &DAG) const {
8571   MVT VT = Op.getValueType().getSimpleVT();
8572   if (VT.isVector()) {
8573     if (VT == MVT::v8i16)
8574       return DAG.getNode(ISD::TRUNCATE, Op.getDebugLoc(), VT,
8575                          DAG.getNode(ISD::FP_TO_SINT, Op.getDebugLoc(),
8576                                      MVT::v8i32, Op.getOperand(0)));
8577     return SDValue();
8578   }
8579
8580   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8581     /*IsSigned=*/ true, /*IsReplace=*/ false);
8582   SDValue FIST = Vals.first, StackSlot = Vals.second;
8583   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8584   if (FIST.getNode() == 0) return Op;
8585
8586   if (StackSlot.getNode())
8587     // Load the result.
8588     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8589                        FIST, StackSlot, MachinePointerInfo(),
8590                        false, false, false, 0);
8591
8592   // The node is the result.
8593   return FIST;
8594 }
8595
8596 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8597                                            SelectionDAG &DAG) const {
8598   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8599     /*IsSigned=*/ false, /*IsReplace=*/ false);
8600   SDValue FIST = Vals.first, StackSlot = Vals.second;
8601   assert(FIST.getNode() && "Unexpected failure");
8602
8603   if (StackSlot.getNode())
8604     // Load the result.
8605     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8606                        FIST, StackSlot, MachinePointerInfo(),
8607                        false, false, false, 0);
8608
8609   // The node is the result.
8610   return FIST;
8611 }
8612
8613 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
8614   DebugLoc DL = Op.getDebugLoc();
8615   MVT VT = Op.getValueType().getSimpleVT();
8616   SDValue In = Op.getOperand(0);
8617   MVT SVT = In.getValueType().getSimpleVT();
8618
8619   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
8620
8621   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
8622                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
8623                                  In, DAG.getUNDEF(SVT)));
8624 }
8625
8626 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
8627   LLVMContext *Context = DAG.getContext();
8628   DebugLoc dl = Op.getDebugLoc();
8629   MVT VT = Op.getValueType().getSimpleVT();
8630   MVT EltVT = VT;
8631   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8632   if (VT.isVector()) {
8633     EltVT = VT.getVectorElementType();
8634     NumElts = VT.getVectorNumElements();
8635   }
8636   Constant *C;
8637   if (EltVT == MVT::f64)
8638     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8639                                           APInt(64, ~(1ULL << 63))));
8640   else
8641     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
8642                                           APInt(32, ~(1U << 31))));
8643   C = ConstantVector::getSplat(NumElts, C);
8644   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8645   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8646   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8647                              MachinePointerInfo::getConstantPool(),
8648                              false, false, false, Alignment);
8649   if (VT.isVector()) {
8650     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8651     return DAG.getNode(ISD::BITCAST, dl, VT,
8652                        DAG.getNode(ISD::AND, dl, ANDVT,
8653                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
8654                                                Op.getOperand(0)),
8655                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
8656   }
8657   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8658 }
8659
8660 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8661   LLVMContext *Context = DAG.getContext();
8662   DebugLoc dl = Op.getDebugLoc();
8663   MVT VT = Op.getValueType().getSimpleVT();
8664   MVT EltVT = VT;
8665   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8666   if (VT.isVector()) {
8667     EltVT = VT.getVectorElementType();
8668     NumElts = VT.getVectorNumElements();
8669   }
8670   Constant *C;
8671   if (EltVT == MVT::f64)
8672     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8673                                           APInt(64, 1ULL << 63)));
8674   else
8675     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
8676                                           APInt(32, 1U << 31)));
8677   C = ConstantVector::getSplat(NumElts, C);
8678   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8679   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8680   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8681                              MachinePointerInfo::getConstantPool(),
8682                              false, false, false, Alignment);
8683   if (VT.isVector()) {
8684     MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8685     return DAG.getNode(ISD::BITCAST, dl, VT,
8686                        DAG.getNode(ISD::XOR, dl, XORVT,
8687                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
8688                                                Op.getOperand(0)),
8689                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8690   }
8691
8692   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8693 }
8694
8695 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8696   LLVMContext *Context = DAG.getContext();
8697   SDValue Op0 = Op.getOperand(0);
8698   SDValue Op1 = Op.getOperand(1);
8699   DebugLoc dl = Op.getDebugLoc();
8700   MVT VT = Op.getValueType().getSimpleVT();
8701   MVT SrcVT = Op1.getValueType().getSimpleVT();
8702
8703   // If second operand is smaller, extend it first.
8704   if (SrcVT.bitsLT(VT)) {
8705     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8706     SrcVT = VT;
8707   }
8708   // And if it is bigger, shrink it first.
8709   if (SrcVT.bitsGT(VT)) {
8710     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8711     SrcVT = VT;
8712   }
8713
8714   // At this point the operands and the result should have the same
8715   // type, and that won't be f80 since that is not custom lowered.
8716
8717   // First get the sign bit of second operand.
8718   SmallVector<Constant*,4> CV;
8719   if (SrcVT == MVT::f64) {
8720     const fltSemantics &Sem = APFloat::IEEEdouble;
8721     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
8722     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
8723   } else {
8724     const fltSemantics &Sem = APFloat::IEEEsingle;
8725     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
8726     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8727     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8728     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8729   }
8730   Constant *C = ConstantVector::get(CV);
8731   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8732   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8733                               MachinePointerInfo::getConstantPool(),
8734                               false, false, false, 16);
8735   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8736
8737   // Shift sign bit right or left if the two operands have different types.
8738   if (SrcVT.bitsGT(VT)) {
8739     // Op0 is MVT::f32, Op1 is MVT::f64.
8740     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8741     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8742                           DAG.getConstant(32, MVT::i32));
8743     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8744     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8745                           DAG.getIntPtrConstant(0));
8746   }
8747
8748   // Clear first operand sign bit.
8749   CV.clear();
8750   if (VT == MVT::f64) {
8751     const fltSemantics &Sem = APFloat::IEEEdouble;
8752     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
8753                                                    APInt(64, ~(1ULL << 63)))));
8754     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
8755   } else {
8756     const fltSemantics &Sem = APFloat::IEEEsingle;
8757     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
8758                                                    APInt(32, ~(1U << 31)))));
8759     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8760     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8761     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8762   }
8763   C = ConstantVector::get(CV);
8764   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8765   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8766                               MachinePointerInfo::getConstantPool(),
8767                               false, false, false, 16);
8768   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8769
8770   // Or the value with the sign bit.
8771   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8772 }
8773
8774 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
8775   SDValue N0 = Op.getOperand(0);
8776   DebugLoc dl = Op.getDebugLoc();
8777   MVT VT = Op.getValueType().getSimpleVT();
8778
8779   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8780   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8781                                   DAG.getConstant(1, VT));
8782   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8783 }
8784
8785 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
8786 //
8787 SDValue X86TargetLowering::LowerVectorAllZeroTest(SDValue Op,
8788                                                   SelectionDAG &DAG) const {
8789   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
8790
8791   if (!Subtarget->hasSSE41())
8792     return SDValue();
8793
8794   if (!Op->hasOneUse())
8795     return SDValue();
8796
8797   SDNode *N = Op.getNode();
8798   DebugLoc DL = N->getDebugLoc();
8799
8800   SmallVector<SDValue, 8> Opnds;
8801   DenseMap<SDValue, unsigned> VecInMap;
8802   EVT VT = MVT::Other;
8803
8804   // Recognize a special case where a vector is casted into wide integer to
8805   // test all 0s.
8806   Opnds.push_back(N->getOperand(0));
8807   Opnds.push_back(N->getOperand(1));
8808
8809   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
8810     SmallVector<SDValue, 8>::const_iterator I = Opnds.begin() + Slot;
8811     // BFS traverse all OR'd operands.
8812     if (I->getOpcode() == ISD::OR) {
8813       Opnds.push_back(I->getOperand(0));
8814       Opnds.push_back(I->getOperand(1));
8815       // Re-evaluate the number of nodes to be traversed.
8816       e += 2; // 2 more nodes (LHS and RHS) are pushed.
8817       continue;
8818     }
8819
8820     // Quit if a non-EXTRACT_VECTOR_ELT
8821     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8822       return SDValue();
8823
8824     // Quit if without a constant index.
8825     SDValue Idx = I->getOperand(1);
8826     if (!isa<ConstantSDNode>(Idx))
8827       return SDValue();
8828
8829     SDValue ExtractedFromVec = I->getOperand(0);
8830     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
8831     if (M == VecInMap.end()) {
8832       VT = ExtractedFromVec.getValueType();
8833       // Quit if not 128/256-bit vector.
8834       if (!VT.is128BitVector() && !VT.is256BitVector())
8835         return SDValue();
8836       // Quit if not the same type.
8837       if (VecInMap.begin() != VecInMap.end() &&
8838           VT != VecInMap.begin()->first.getValueType())
8839         return SDValue();
8840       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
8841     }
8842     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
8843   }
8844
8845   assert((VT.is128BitVector() || VT.is256BitVector()) &&
8846          "Not extracted from 128-/256-bit vector.");
8847
8848   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
8849   SmallVector<SDValue, 8> VecIns;
8850
8851   for (DenseMap<SDValue, unsigned>::const_iterator
8852         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
8853     // Quit if not all elements are used.
8854     if (I->second != FullMask)
8855       return SDValue();
8856     VecIns.push_back(I->first);
8857   }
8858
8859   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8860
8861   // Cast all vectors into TestVT for PTEST.
8862   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
8863     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
8864
8865   // If more than one full vectors are evaluated, OR them first before PTEST.
8866   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
8867     // Each iteration will OR 2 nodes and append the result until there is only
8868     // 1 node left, i.e. the final OR'd value of all vectors.
8869     SDValue LHS = VecIns[Slot];
8870     SDValue RHS = VecIns[Slot + 1];
8871     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
8872   }
8873
8874   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
8875                      VecIns.back(), VecIns.back());
8876 }
8877
8878 /// Emit nodes that will be selected as "test Op0,Op0", or something
8879 /// equivalent.
8880 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8881                                     SelectionDAG &DAG) const {
8882   DebugLoc dl = Op.getDebugLoc();
8883
8884   // CF and OF aren't always set the way we want. Determine which
8885   // of these we need.
8886   bool NeedCF = false;
8887   bool NeedOF = false;
8888   switch (X86CC) {
8889   default: break;
8890   case X86::COND_A: case X86::COND_AE:
8891   case X86::COND_B: case X86::COND_BE:
8892     NeedCF = true;
8893     break;
8894   case X86::COND_G: case X86::COND_GE:
8895   case X86::COND_L: case X86::COND_LE:
8896   case X86::COND_O: case X86::COND_NO:
8897     NeedOF = true;
8898     break;
8899   }
8900
8901   // See if we can use the EFLAGS value from the operand instead of
8902   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8903   // we prove that the arithmetic won't overflow, we can't use OF or CF.
8904   if (Op.getResNo() != 0 || NeedOF || NeedCF)
8905     // Emit a CMP with 0, which is the TEST pattern.
8906     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8907                        DAG.getConstant(0, Op.getValueType()));
8908
8909   unsigned Opcode = 0;
8910   unsigned NumOperands = 0;
8911
8912   // Truncate operations may prevent the merge of the SETCC instruction
8913   // and the arithmetic intruction before it. Attempt to truncate the operands
8914   // of the arithmetic instruction and use a reduced bit-width instruction.
8915   bool NeedTruncation = false;
8916   SDValue ArithOp = Op;
8917   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
8918     SDValue Arith = Op->getOperand(0);
8919     // Both the trunc and the arithmetic op need to have one user each.
8920     if (Arith->hasOneUse())
8921       switch (Arith.getOpcode()) {
8922         default: break;
8923         case ISD::ADD:
8924         case ISD::SUB:
8925         case ISD::AND:
8926         case ISD::OR:
8927         case ISD::XOR: {
8928           NeedTruncation = true;
8929           ArithOp = Arith;
8930         }
8931       }
8932   }
8933
8934   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
8935   // which may be the result of a CAST.  We use the variable 'Op', which is the
8936   // non-casted variable when we check for possible users.
8937   switch (ArithOp.getOpcode()) {
8938   case ISD::ADD:
8939     // Due to an isel shortcoming, be conservative if this add is likely to be
8940     // selected as part of a load-modify-store instruction. When the root node
8941     // in a match is a store, isel doesn't know how to remap non-chain non-flag
8942     // uses of other nodes in the match, such as the ADD in this case. This
8943     // leads to the ADD being left around and reselected, with the result being
8944     // two adds in the output.  Alas, even if none our users are stores, that
8945     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
8946     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
8947     // climbing the DAG back to the root, and it doesn't seem to be worth the
8948     // effort.
8949     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8950          UE = Op.getNode()->use_end(); UI != UE; ++UI)
8951       if (UI->getOpcode() != ISD::CopyToReg &&
8952           UI->getOpcode() != ISD::SETCC &&
8953           UI->getOpcode() != ISD::STORE)
8954         goto default_case;
8955
8956     if (ConstantSDNode *C =
8957         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
8958       // An add of one will be selected as an INC.
8959       if (C->getAPIntValue() == 1) {
8960         Opcode = X86ISD::INC;
8961         NumOperands = 1;
8962         break;
8963       }
8964
8965       // An add of negative one (subtract of one) will be selected as a DEC.
8966       if (C->getAPIntValue().isAllOnesValue()) {
8967         Opcode = X86ISD::DEC;
8968         NumOperands = 1;
8969         break;
8970       }
8971     }
8972
8973     // Otherwise use a regular EFLAGS-setting add.
8974     Opcode = X86ISD::ADD;
8975     NumOperands = 2;
8976     break;
8977   case ISD::AND: {
8978     // If the primary and result isn't used, don't bother using X86ISD::AND,
8979     // because a TEST instruction will be better.
8980     bool NonFlagUse = false;
8981     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8982            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8983       SDNode *User = *UI;
8984       unsigned UOpNo = UI.getOperandNo();
8985       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8986         // Look pass truncate.
8987         UOpNo = User->use_begin().getOperandNo();
8988         User = *User->use_begin();
8989       }
8990
8991       if (User->getOpcode() != ISD::BRCOND &&
8992           User->getOpcode() != ISD::SETCC &&
8993           !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
8994         NonFlagUse = true;
8995         break;
8996       }
8997     }
8998
8999     if (!NonFlagUse)
9000       break;
9001   }
9002     // FALL THROUGH
9003   case ISD::SUB:
9004   case ISD::OR:
9005   case ISD::XOR:
9006     // Due to the ISEL shortcoming noted above, be conservative if this op is
9007     // likely to be selected as part of a load-modify-store instruction.
9008     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9009            UE = Op.getNode()->use_end(); UI != UE; ++UI)
9010       if (UI->getOpcode() == ISD::STORE)
9011         goto default_case;
9012
9013     // Otherwise use a regular EFLAGS-setting instruction.
9014     switch (ArithOp.getOpcode()) {
9015     default: llvm_unreachable("unexpected operator!");
9016     case ISD::SUB: Opcode = X86ISD::SUB; break;
9017     case ISD::XOR: Opcode = X86ISD::XOR; break;
9018     case ISD::AND: Opcode = X86ISD::AND; break;
9019     case ISD::OR: {
9020       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
9021         SDValue EFLAGS = LowerVectorAllZeroTest(Op, DAG);
9022         if (EFLAGS.getNode())
9023           return EFLAGS;
9024       }
9025       Opcode = X86ISD::OR;
9026       break;
9027     }
9028     }
9029
9030     NumOperands = 2;
9031     break;
9032   case X86ISD::ADD:
9033   case X86ISD::SUB:
9034   case X86ISD::INC:
9035   case X86ISD::DEC:
9036   case X86ISD::OR:
9037   case X86ISD::XOR:
9038   case X86ISD::AND:
9039     return SDValue(Op.getNode(), 1);
9040   default:
9041   default_case:
9042     break;
9043   }
9044
9045   // If we found that truncation is beneficial, perform the truncation and
9046   // update 'Op'.
9047   if (NeedTruncation) {
9048     EVT VT = Op.getValueType();
9049     SDValue WideVal = Op->getOperand(0);
9050     EVT WideVT = WideVal.getValueType();
9051     unsigned ConvertedOp = 0;
9052     // Use a target machine opcode to prevent further DAGCombine
9053     // optimizations that may separate the arithmetic operations
9054     // from the setcc node.
9055     switch (WideVal.getOpcode()) {
9056       default: break;
9057       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
9058       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
9059       case ISD::AND: ConvertedOp = X86ISD::AND; break;
9060       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
9061       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
9062     }
9063
9064     if (ConvertedOp) {
9065       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9066       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
9067         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
9068         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
9069         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
9070       }
9071     }
9072   }
9073
9074   if (Opcode == 0)
9075     // Emit a CMP with 0, which is the TEST pattern.
9076     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9077                        DAG.getConstant(0, Op.getValueType()));
9078
9079   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
9080   SmallVector<SDValue, 4> Ops;
9081   for (unsigned i = 0; i != NumOperands; ++i)
9082     Ops.push_back(Op.getOperand(i));
9083
9084   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
9085   DAG.ReplaceAllUsesWith(Op, New);
9086   return SDValue(New.getNode(), 1);
9087 }
9088
9089 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
9090 /// equivalent.
9091 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
9092                                    SelectionDAG &DAG) const {
9093   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
9094     if (C->getAPIntValue() == 0)
9095       return EmitTest(Op0, X86CC, DAG);
9096
9097   DebugLoc dl = Op0.getDebugLoc();
9098   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
9099        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
9100     // Use SUB instead of CMP to enable CSE between SUB and CMP.
9101     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
9102     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
9103                               Op0, Op1);
9104     return SDValue(Sub.getNode(), 1);
9105   }
9106   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
9107 }
9108
9109 /// Convert a comparison if required by the subtarget.
9110 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
9111                                                  SelectionDAG &DAG) const {
9112   // If the subtarget does not support the FUCOMI instruction, floating-point
9113   // comparisons have to be converted.
9114   if (Subtarget->hasCMov() ||
9115       Cmp.getOpcode() != X86ISD::CMP ||
9116       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
9117       !Cmp.getOperand(1).getValueType().isFloatingPoint())
9118     return Cmp;
9119
9120   // The instruction selector will select an FUCOM instruction instead of
9121   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
9122   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
9123   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
9124   DebugLoc dl = Cmp.getDebugLoc();
9125   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
9126   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
9127   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
9128                             DAG.getConstant(8, MVT::i8));
9129   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
9130   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
9131 }
9132
9133 static bool isAllOnes(SDValue V) {
9134   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9135   return C && C->isAllOnesValue();
9136 }
9137
9138 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
9139 /// if it's possible.
9140 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
9141                                      DebugLoc dl, SelectionDAG &DAG) const {
9142   SDValue Op0 = And.getOperand(0);
9143   SDValue Op1 = And.getOperand(1);
9144   if (Op0.getOpcode() == ISD::TRUNCATE)
9145     Op0 = Op0.getOperand(0);
9146   if (Op1.getOpcode() == ISD::TRUNCATE)
9147     Op1 = Op1.getOperand(0);
9148
9149   SDValue LHS, RHS;
9150   if (Op1.getOpcode() == ISD::SHL)
9151     std::swap(Op0, Op1);
9152   if (Op0.getOpcode() == ISD::SHL) {
9153     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
9154       if (And00C->getZExtValue() == 1) {
9155         // If we looked past a truncate, check that it's only truncating away
9156         // known zeros.
9157         unsigned BitWidth = Op0.getValueSizeInBits();
9158         unsigned AndBitWidth = And.getValueSizeInBits();
9159         if (BitWidth > AndBitWidth) {
9160           APInt Zeros, Ones;
9161           DAG.ComputeMaskedBits(Op0, Zeros, Ones);
9162           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
9163             return SDValue();
9164         }
9165         LHS = Op1;
9166         RHS = Op0.getOperand(1);
9167       }
9168   } else if (Op1.getOpcode() == ISD::Constant) {
9169     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
9170     uint64_t AndRHSVal = AndRHS->getZExtValue();
9171     SDValue AndLHS = Op0;
9172
9173     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
9174       LHS = AndLHS.getOperand(0);
9175       RHS = AndLHS.getOperand(1);
9176     }
9177
9178     // Use BT if the immediate can't be encoded in a TEST instruction.
9179     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
9180       LHS = AndLHS;
9181       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
9182     }
9183   }
9184
9185   if (LHS.getNode()) {
9186     // If the LHS is of the form (x ^ -1) then replace the LHS with x and flip
9187     // the condition code later.
9188     bool Invert = false;
9189     if (LHS.getOpcode() == ISD::XOR && isAllOnes(LHS.getOperand(1))) {
9190       Invert = true;
9191       LHS = LHS.getOperand(0);
9192     }
9193
9194     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
9195     // instruction.  Since the shift amount is in-range-or-undefined, we know
9196     // that doing a bittest on the i32 value is ok.  We extend to i32 because
9197     // the encoding for the i16 version is larger than the i32 version.
9198     // Also promote i16 to i32 for performance / code size reason.
9199     if (LHS.getValueType() == MVT::i8 ||
9200         LHS.getValueType() == MVT::i16)
9201       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
9202
9203     // If the operand types disagree, extend the shift amount to match.  Since
9204     // BT ignores high bits (like shifts) we can use anyextend.
9205     if (LHS.getValueType() != RHS.getValueType())
9206       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
9207
9208     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
9209     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
9210     // Flip the condition if the LHS was a not instruction
9211     if (Invert)
9212       Cond = X86::GetOppositeBranchCondition(Cond);
9213     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9214                        DAG.getConstant(Cond, MVT::i8), BT);
9215   }
9216
9217   return SDValue();
9218 }
9219
9220 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
9221 // ones, and then concatenate the result back.
9222 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
9223   MVT VT = Op.getValueType().getSimpleVT();
9224
9225   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
9226          "Unsupported value type for operation");
9227
9228   unsigned NumElems = VT.getVectorNumElements();
9229   DebugLoc dl = Op.getDebugLoc();
9230   SDValue CC = Op.getOperand(2);
9231
9232   // Extract the LHS vectors
9233   SDValue LHS = Op.getOperand(0);
9234   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
9235   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
9236
9237   // Extract the RHS vectors
9238   SDValue RHS = Op.getOperand(1);
9239   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
9240   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
9241
9242   // Issue the operation on the smaller types and concatenate the result back
9243   MVT EltVT = VT.getVectorElementType();
9244   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9245   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9246                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
9247                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
9248 }
9249
9250 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
9251                            SelectionDAG &DAG) {
9252   SDValue Cond;
9253   SDValue Op0 = Op.getOperand(0);
9254   SDValue Op1 = Op.getOperand(1);
9255   SDValue CC = Op.getOperand(2);
9256   MVT VT = Op.getValueType().getSimpleVT();
9257   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
9258   bool isFP = Op.getOperand(1).getValueType().getSimpleVT().isFloatingPoint();
9259   DebugLoc dl = Op.getDebugLoc();
9260
9261   if (isFP) {
9262 #ifndef NDEBUG
9263     MVT EltVT = Op0.getValueType().getVectorElementType().getSimpleVT();
9264     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
9265 #endif
9266
9267     unsigned SSECC;
9268     bool Swap = false;
9269
9270     // SSE Condition code mapping:
9271     //  0 - EQ
9272     //  1 - LT
9273     //  2 - LE
9274     //  3 - UNORD
9275     //  4 - NEQ
9276     //  5 - NLT
9277     //  6 - NLE
9278     //  7 - ORD
9279     switch (SetCCOpcode) {
9280     default: llvm_unreachable("Unexpected SETCC condition");
9281     case ISD::SETOEQ:
9282     case ISD::SETEQ:  SSECC = 0; break;
9283     case ISD::SETOGT:
9284     case ISD::SETGT: Swap = true; // Fallthrough
9285     case ISD::SETLT:
9286     case ISD::SETOLT: SSECC = 1; break;
9287     case ISD::SETOGE:
9288     case ISD::SETGE: Swap = true; // Fallthrough
9289     case ISD::SETLE:
9290     case ISD::SETOLE: SSECC = 2; break;
9291     case ISD::SETUO:  SSECC = 3; break;
9292     case ISD::SETUNE:
9293     case ISD::SETNE:  SSECC = 4; break;
9294     case ISD::SETULE: Swap = true; // Fallthrough
9295     case ISD::SETUGE: SSECC = 5; break;
9296     case ISD::SETULT: Swap = true; // Fallthrough
9297     case ISD::SETUGT: SSECC = 6; break;
9298     case ISD::SETO:   SSECC = 7; break;
9299     case ISD::SETUEQ:
9300     case ISD::SETONE: SSECC = 8; break;
9301     }
9302     if (Swap)
9303       std::swap(Op0, Op1);
9304
9305     // In the two special cases we can't handle, emit two comparisons.
9306     if (SSECC == 8) {
9307       unsigned CC0, CC1;
9308       unsigned CombineOpc;
9309       if (SetCCOpcode == ISD::SETUEQ) {
9310         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
9311       } else {
9312         assert(SetCCOpcode == ISD::SETONE);
9313         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
9314       }
9315
9316       SDValue Cmp0 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9317                                  DAG.getConstant(CC0, MVT::i8));
9318       SDValue Cmp1 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9319                                  DAG.getConstant(CC1, MVT::i8));
9320       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
9321     }
9322     // Handle all other FP comparisons here.
9323     return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9324                        DAG.getConstant(SSECC, MVT::i8));
9325   }
9326
9327   // Break 256-bit integer vector compare into smaller ones.
9328   if (VT.is256BitVector() && !Subtarget->hasInt256())
9329     return Lower256IntVSETCC(Op, DAG);
9330
9331   // We are handling one of the integer comparisons here.  Since SSE only has
9332   // GT and EQ comparisons for integer, swapping operands and multiple
9333   // operations may be required for some comparisons.
9334   unsigned Opc;
9335   bool Swap = false, Invert = false, FlipSigns = false;
9336
9337   switch (SetCCOpcode) {
9338   default: llvm_unreachable("Unexpected SETCC condition");
9339   case ISD::SETNE:  Invert = true;
9340   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
9341   case ISD::SETLT:  Swap = true;
9342   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
9343   case ISD::SETGE:  Swap = true;
9344   case ISD::SETLE:  Opc = X86ISD::PCMPGT; Invert = true; break;
9345   case ISD::SETULT: Swap = true;
9346   case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
9347   case ISD::SETUGE: Swap = true;
9348   case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
9349   }
9350   if (Swap)
9351     std::swap(Op0, Op1);
9352
9353   // Check that the operation in question is available (most are plain SSE2,
9354   // but PCMPGTQ and PCMPEQQ have different requirements).
9355   if (VT == MVT::v2i64) {
9356     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42())
9357       return SDValue();
9358     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
9359       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
9360       // pcmpeqd + pshufd + pand.
9361       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
9362
9363       // First cast everything to the right type,
9364       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
9365       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
9366
9367       // Do the compare.
9368       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
9369
9370       // Make sure the lower and upper halves are both all-ones.
9371       const int Mask[] = { 1, 0, 3, 2 };
9372       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
9373       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
9374
9375       if (Invert)
9376         Result = DAG.getNOT(dl, Result, MVT::v4i32);
9377
9378       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
9379     }
9380   }
9381
9382   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
9383   // bits of the inputs before performing those operations.
9384   if (FlipSigns) {
9385     EVT EltVT = VT.getVectorElementType();
9386     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
9387                                       EltVT);
9388     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
9389     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
9390                                     SignBits.size());
9391     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
9392     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
9393   }
9394
9395   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
9396
9397   // If the logical-not of the result is required, perform that now.
9398   if (Invert)
9399     Result = DAG.getNOT(dl, Result, VT);
9400
9401   return Result;
9402 }
9403
9404 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
9405
9406   MVT VT = Op.getValueType().getSimpleVT();
9407
9408   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
9409
9410   assert(VT == MVT::i8 && "SetCC type must be 8-bit integer");
9411   SDValue Op0 = Op.getOperand(0);
9412   SDValue Op1 = Op.getOperand(1);
9413   DebugLoc dl = Op.getDebugLoc();
9414   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
9415
9416   // Optimize to BT if possible.
9417   // Lower (X & (1 << N)) == 0 to BT(X, N).
9418   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
9419   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
9420   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
9421       Op1.getOpcode() == ISD::Constant &&
9422       cast<ConstantSDNode>(Op1)->isNullValue() &&
9423       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9424     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
9425     if (NewSetCC.getNode())
9426       return NewSetCC;
9427   }
9428
9429   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
9430   // these.
9431   if (Op1.getOpcode() == ISD::Constant &&
9432       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
9433        cast<ConstantSDNode>(Op1)->isNullValue()) &&
9434       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9435
9436     // If the input is a setcc, then reuse the input setcc or use a new one with
9437     // the inverted condition.
9438     if (Op0.getOpcode() == X86ISD::SETCC) {
9439       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
9440       bool Invert = (CC == ISD::SETNE) ^
9441         cast<ConstantSDNode>(Op1)->isNullValue();
9442       if (!Invert) return Op0;
9443
9444       CCode = X86::GetOppositeBranchCondition(CCode);
9445       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9446                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
9447     }
9448   }
9449
9450   bool isFP = Op1.getValueType().getSimpleVT().isFloatingPoint();
9451   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
9452   if (X86CC == X86::COND_INVALID)
9453     return SDValue();
9454
9455   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
9456   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
9457   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9458                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
9459 }
9460
9461 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
9462 static bool isX86LogicalCmp(SDValue Op) {
9463   unsigned Opc = Op.getNode()->getOpcode();
9464   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
9465       Opc == X86ISD::SAHF)
9466     return true;
9467   if (Op.getResNo() == 1 &&
9468       (Opc == X86ISD::ADD ||
9469        Opc == X86ISD::SUB ||
9470        Opc == X86ISD::ADC ||
9471        Opc == X86ISD::SBB ||
9472        Opc == X86ISD::SMUL ||
9473        Opc == X86ISD::UMUL ||
9474        Opc == X86ISD::INC ||
9475        Opc == X86ISD::DEC ||
9476        Opc == X86ISD::OR ||
9477        Opc == X86ISD::XOR ||
9478        Opc == X86ISD::AND))
9479     return true;
9480
9481   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
9482     return true;
9483
9484   return false;
9485 }
9486
9487 static bool isZero(SDValue V) {
9488   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9489   return C && C->isNullValue();
9490 }
9491
9492 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
9493   if (V.getOpcode() != ISD::TRUNCATE)
9494     return false;
9495
9496   SDValue VOp0 = V.getOperand(0);
9497   unsigned InBits = VOp0.getValueSizeInBits();
9498   unsigned Bits = V.getValueSizeInBits();
9499   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
9500 }
9501
9502 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
9503   bool addTest = true;
9504   SDValue Cond  = Op.getOperand(0);
9505   SDValue Op1 = Op.getOperand(1);
9506   SDValue Op2 = Op.getOperand(2);
9507   DebugLoc DL = Op.getDebugLoc();
9508   SDValue CC;
9509
9510   if (Cond.getOpcode() == ISD::SETCC) {
9511     SDValue NewCond = LowerSETCC(Cond, DAG);
9512     if (NewCond.getNode())
9513       Cond = NewCond;
9514   }
9515
9516   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
9517   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
9518   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
9519   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
9520   if (Cond.getOpcode() == X86ISD::SETCC &&
9521       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
9522       isZero(Cond.getOperand(1).getOperand(1))) {
9523     SDValue Cmp = Cond.getOperand(1);
9524
9525     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
9526
9527     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
9528         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
9529       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
9530
9531       SDValue CmpOp0 = Cmp.getOperand(0);
9532       // Apply further optimizations for special cases
9533       // (select (x != 0), -1, 0) -> neg & sbb
9534       // (select (x == 0), 0, -1) -> neg & sbb
9535       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
9536         if (YC->isNullValue() &&
9537             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
9538           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
9539           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
9540                                     DAG.getConstant(0, CmpOp0.getValueType()),
9541                                     CmpOp0);
9542           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9543                                     DAG.getConstant(X86::COND_B, MVT::i8),
9544                                     SDValue(Neg.getNode(), 1));
9545           return Res;
9546         }
9547
9548       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
9549                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
9550       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9551
9552       SDValue Res =   // Res = 0 or -1.
9553         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9554                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
9555
9556       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
9557         Res = DAG.getNOT(DL, Res, Res.getValueType());
9558
9559       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
9560       if (N2C == 0 || !N2C->isNullValue())
9561         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
9562       return Res;
9563     }
9564   }
9565
9566   // Look past (and (setcc_carry (cmp ...)), 1).
9567   if (Cond.getOpcode() == ISD::AND &&
9568       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9569     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9570     if (C && C->getAPIntValue() == 1)
9571       Cond = Cond.getOperand(0);
9572   }
9573
9574   // If condition flag is set by a X86ISD::CMP, then use it as the condition
9575   // setting operand in place of the X86ISD::SETCC.
9576   unsigned CondOpcode = Cond.getOpcode();
9577   if (CondOpcode == X86ISD::SETCC ||
9578       CondOpcode == X86ISD::SETCC_CARRY) {
9579     CC = Cond.getOperand(0);
9580
9581     SDValue Cmp = Cond.getOperand(1);
9582     unsigned Opc = Cmp.getOpcode();
9583     MVT VT = Op.getValueType().getSimpleVT();
9584
9585     bool IllegalFPCMov = false;
9586     if (VT.isFloatingPoint() && !VT.isVector() &&
9587         !isScalarFPTypeInSSEReg(VT))  // FPStack?
9588       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
9589
9590     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
9591         Opc == X86ISD::BT) { // FIXME
9592       Cond = Cmp;
9593       addTest = false;
9594     }
9595   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9596              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9597              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9598               Cond.getOperand(0).getValueType() != MVT::i8)) {
9599     SDValue LHS = Cond.getOperand(0);
9600     SDValue RHS = Cond.getOperand(1);
9601     unsigned X86Opcode;
9602     unsigned X86Cond;
9603     SDVTList VTs;
9604     switch (CondOpcode) {
9605     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9606     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9607     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9608     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9609     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9610     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9611     default: llvm_unreachable("unexpected overflowing operator");
9612     }
9613     if (CondOpcode == ISD::UMULO)
9614       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9615                           MVT::i32);
9616     else
9617       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9618
9619     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
9620
9621     if (CondOpcode == ISD::UMULO)
9622       Cond = X86Op.getValue(2);
9623     else
9624       Cond = X86Op.getValue(1);
9625
9626     CC = DAG.getConstant(X86Cond, MVT::i8);
9627     addTest = false;
9628   }
9629
9630   if (addTest) {
9631     // Look pass the truncate if the high bits are known zero.
9632     if (isTruncWithZeroHighBitsInput(Cond, DAG))
9633         Cond = Cond.getOperand(0);
9634
9635     // We know the result of AND is compared against zero. Try to match
9636     // it to BT.
9637     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9638       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
9639       if (NewSetCC.getNode()) {
9640         CC = NewSetCC.getOperand(0);
9641         Cond = NewSetCC.getOperand(1);
9642         addTest = false;
9643       }
9644     }
9645   }
9646
9647   if (addTest) {
9648     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9649     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9650   }
9651
9652   // a <  b ? -1 :  0 -> RES = ~setcc_carry
9653   // a <  b ?  0 : -1 -> RES = setcc_carry
9654   // a >= b ? -1 :  0 -> RES = setcc_carry
9655   // a >= b ?  0 : -1 -> RES = ~setcc_carry
9656   if (Cond.getOpcode() == X86ISD::SUB) {
9657     Cond = ConvertCmpIfNecessary(Cond, DAG);
9658     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
9659
9660     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
9661         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
9662       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9663                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
9664       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
9665         return DAG.getNOT(DL, Res, Res.getValueType());
9666       return Res;
9667     }
9668   }
9669
9670   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
9671   // widen the cmov and push the truncate through. This avoids introducing a new
9672   // branch during isel and doesn't add any extensions.
9673   if (Op.getValueType() == MVT::i8 &&
9674       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
9675     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
9676     if (T1.getValueType() == T2.getValueType() &&
9677         // Blacklist CopyFromReg to avoid partial register stalls.
9678         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
9679       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
9680       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
9681       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
9682     }
9683   }
9684
9685   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
9686   // condition is true.
9687   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
9688   SDValue Ops[] = { Op2, Op1, CC, Cond };
9689   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
9690 }
9691
9692 SDValue X86TargetLowering::LowerSIGN_EXTEND(SDValue Op,
9693                                             SelectionDAG &DAG) const {
9694   MVT VT = Op->getValueType(0).getSimpleVT();
9695   SDValue In = Op->getOperand(0);
9696   MVT InVT = In.getValueType().getSimpleVT();
9697   DebugLoc dl = Op->getDebugLoc();
9698
9699   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
9700       (VT != MVT::v8i32 || InVT != MVT::v8i16))
9701     return SDValue();
9702
9703   if (Subtarget->hasInt256())
9704     return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, In);
9705
9706   // Optimize vectors in AVX mode
9707   // Sign extend  v8i16 to v8i32 and
9708   //              v4i32 to v4i64
9709   //
9710   // Divide input vector into two parts
9711   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
9712   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
9713   // concat the vectors to original VT
9714
9715   unsigned NumElems = InVT.getVectorNumElements();
9716   SDValue Undef = DAG.getUNDEF(InVT);
9717
9718   SmallVector<int,8> ShufMask1(NumElems, -1);
9719   for (unsigned i = 0; i != NumElems/2; ++i)
9720     ShufMask1[i] = i;
9721
9722   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
9723
9724   SmallVector<int,8> ShufMask2(NumElems, -1);
9725   for (unsigned i = 0; i != NumElems/2; ++i)
9726     ShufMask2[i] = i + NumElems/2;
9727
9728   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
9729
9730   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
9731                                 VT.getVectorNumElements()/2);
9732
9733   OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
9734   OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
9735
9736   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9737 }
9738
9739 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
9740 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
9741 // from the AND / OR.
9742 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
9743   Opc = Op.getOpcode();
9744   if (Opc != ISD::OR && Opc != ISD::AND)
9745     return false;
9746   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9747           Op.getOperand(0).hasOneUse() &&
9748           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
9749           Op.getOperand(1).hasOneUse());
9750 }
9751
9752 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
9753 // 1 and that the SETCC node has a single use.
9754 static bool isXor1OfSetCC(SDValue Op) {
9755   if (Op.getOpcode() != ISD::XOR)
9756     return false;
9757   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9758   if (N1C && N1C->getAPIntValue() == 1) {
9759     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9760       Op.getOperand(0).hasOneUse();
9761   }
9762   return false;
9763 }
9764
9765 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
9766   bool addTest = true;
9767   SDValue Chain = Op.getOperand(0);
9768   SDValue Cond  = Op.getOperand(1);
9769   SDValue Dest  = Op.getOperand(2);
9770   DebugLoc dl = Op.getDebugLoc();
9771   SDValue CC;
9772   bool Inverted = false;
9773
9774   if (Cond.getOpcode() == ISD::SETCC) {
9775     // Check for setcc([su]{add,sub,mul}o == 0).
9776     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
9777         isa<ConstantSDNode>(Cond.getOperand(1)) &&
9778         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
9779         Cond.getOperand(0).getResNo() == 1 &&
9780         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
9781          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
9782          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
9783          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
9784          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
9785          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
9786       Inverted = true;
9787       Cond = Cond.getOperand(0);
9788     } else {
9789       SDValue NewCond = LowerSETCC(Cond, DAG);
9790       if (NewCond.getNode())
9791         Cond = NewCond;
9792     }
9793   }
9794 #if 0
9795   // FIXME: LowerXALUO doesn't handle these!!
9796   else if (Cond.getOpcode() == X86ISD::ADD  ||
9797            Cond.getOpcode() == X86ISD::SUB  ||
9798            Cond.getOpcode() == X86ISD::SMUL ||
9799            Cond.getOpcode() == X86ISD::UMUL)
9800     Cond = LowerXALUO(Cond, DAG);
9801 #endif
9802
9803   // Look pass (and (setcc_carry (cmp ...)), 1).
9804   if (Cond.getOpcode() == ISD::AND &&
9805       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9806     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9807     if (C && C->getAPIntValue() == 1)
9808       Cond = Cond.getOperand(0);
9809   }
9810
9811   // If condition flag is set by a X86ISD::CMP, then use it as the condition
9812   // setting operand in place of the X86ISD::SETCC.
9813   unsigned CondOpcode = Cond.getOpcode();
9814   if (CondOpcode == X86ISD::SETCC ||
9815       CondOpcode == X86ISD::SETCC_CARRY) {
9816     CC = Cond.getOperand(0);
9817
9818     SDValue Cmp = Cond.getOperand(1);
9819     unsigned Opc = Cmp.getOpcode();
9820     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9821     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9822       Cond = Cmp;
9823       addTest = false;
9824     } else {
9825       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9826       default: break;
9827       case X86::COND_O:
9828       case X86::COND_B:
9829         // These can only come from an arithmetic instruction with overflow,
9830         // e.g. SADDO, UADDO.
9831         Cond = Cond.getNode()->getOperand(1);
9832         addTest = false;
9833         break;
9834       }
9835     }
9836   }
9837   CondOpcode = Cond.getOpcode();
9838   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9839       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9840       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9841        Cond.getOperand(0).getValueType() != MVT::i8)) {
9842     SDValue LHS = Cond.getOperand(0);
9843     SDValue RHS = Cond.getOperand(1);
9844     unsigned X86Opcode;
9845     unsigned X86Cond;
9846     SDVTList VTs;
9847     switch (CondOpcode) {
9848     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9849     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9850     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9851     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9852     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9853     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9854     default: llvm_unreachable("unexpected overflowing operator");
9855     }
9856     if (Inverted)
9857       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9858     if (CondOpcode == ISD::UMULO)
9859       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9860                           MVT::i32);
9861     else
9862       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9863
9864     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9865
9866     if (CondOpcode == ISD::UMULO)
9867       Cond = X86Op.getValue(2);
9868     else
9869       Cond = X86Op.getValue(1);
9870
9871     CC = DAG.getConstant(X86Cond, MVT::i8);
9872     addTest = false;
9873   } else {
9874     unsigned CondOpc;
9875     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9876       SDValue Cmp = Cond.getOperand(0).getOperand(1);
9877       if (CondOpc == ISD::OR) {
9878         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9879         // two branches instead of an explicit OR instruction with a
9880         // separate test.
9881         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9882             isX86LogicalCmp(Cmp)) {
9883           CC = Cond.getOperand(0).getOperand(0);
9884           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9885                               Chain, Dest, CC, Cmp);
9886           CC = Cond.getOperand(1).getOperand(0);
9887           Cond = Cmp;
9888           addTest = false;
9889         }
9890       } else { // ISD::AND
9891         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9892         // two branches instead of an explicit AND instruction with a
9893         // separate test. However, we only do this if this block doesn't
9894         // have a fall-through edge, because this requires an explicit
9895         // jmp when the condition is false.
9896         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9897             isX86LogicalCmp(Cmp) &&
9898             Op.getNode()->hasOneUse()) {
9899           X86::CondCode CCode =
9900             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9901           CCode = X86::GetOppositeBranchCondition(CCode);
9902           CC = DAG.getConstant(CCode, MVT::i8);
9903           SDNode *User = *Op.getNode()->use_begin();
9904           // Look for an unconditional branch following this conditional branch.
9905           // We need this because we need to reverse the successors in order
9906           // to implement FCMP_OEQ.
9907           if (User->getOpcode() == ISD::BR) {
9908             SDValue FalseBB = User->getOperand(1);
9909             SDNode *NewBR =
9910               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9911             assert(NewBR == User);
9912             (void)NewBR;
9913             Dest = FalseBB;
9914
9915             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9916                                 Chain, Dest, CC, Cmp);
9917             X86::CondCode CCode =
9918               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9919             CCode = X86::GetOppositeBranchCondition(CCode);
9920             CC = DAG.getConstant(CCode, MVT::i8);
9921             Cond = Cmp;
9922             addTest = false;
9923           }
9924         }
9925       }
9926     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9927       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9928       // It should be transformed during dag combiner except when the condition
9929       // is set by a arithmetics with overflow node.
9930       X86::CondCode CCode =
9931         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9932       CCode = X86::GetOppositeBranchCondition(CCode);
9933       CC = DAG.getConstant(CCode, MVT::i8);
9934       Cond = Cond.getOperand(0).getOperand(1);
9935       addTest = false;
9936     } else if (Cond.getOpcode() == ISD::SETCC &&
9937                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9938       // For FCMP_OEQ, we can emit
9939       // two branches instead of an explicit AND instruction with a
9940       // separate test. However, we only do this if this block doesn't
9941       // have a fall-through edge, because this requires an explicit
9942       // jmp when the condition is false.
9943       if (Op.getNode()->hasOneUse()) {
9944         SDNode *User = *Op.getNode()->use_begin();
9945         // Look for an unconditional branch following this conditional branch.
9946         // We need this because we need to reverse the successors in order
9947         // to implement FCMP_OEQ.
9948         if (User->getOpcode() == ISD::BR) {
9949           SDValue FalseBB = User->getOperand(1);
9950           SDNode *NewBR =
9951             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9952           assert(NewBR == User);
9953           (void)NewBR;
9954           Dest = FalseBB;
9955
9956           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9957                                     Cond.getOperand(0), Cond.getOperand(1));
9958           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9959           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9960           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9961                               Chain, Dest, CC, Cmp);
9962           CC = DAG.getConstant(X86::COND_P, MVT::i8);
9963           Cond = Cmp;
9964           addTest = false;
9965         }
9966       }
9967     } else if (Cond.getOpcode() == ISD::SETCC &&
9968                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9969       // For FCMP_UNE, we can emit
9970       // two branches instead of an explicit AND instruction with a
9971       // separate test. However, we only do this if this block doesn't
9972       // have a fall-through edge, because this requires an explicit
9973       // jmp when the condition is false.
9974       if (Op.getNode()->hasOneUse()) {
9975         SDNode *User = *Op.getNode()->use_begin();
9976         // Look for an unconditional branch following this conditional branch.
9977         // We need this because we need to reverse the successors in order
9978         // to implement FCMP_UNE.
9979         if (User->getOpcode() == ISD::BR) {
9980           SDValue FalseBB = User->getOperand(1);
9981           SDNode *NewBR =
9982             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9983           assert(NewBR == User);
9984           (void)NewBR;
9985
9986           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9987                                     Cond.getOperand(0), Cond.getOperand(1));
9988           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9989           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9990           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9991                               Chain, Dest, CC, Cmp);
9992           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9993           Cond = Cmp;
9994           addTest = false;
9995           Dest = FalseBB;
9996         }
9997       }
9998     }
9999   }
10000
10001   if (addTest) {
10002     // Look pass the truncate if the high bits are known zero.
10003     if (isTruncWithZeroHighBitsInput(Cond, DAG))
10004         Cond = Cond.getOperand(0);
10005
10006     // We know the result of AND is compared against zero. Try to match
10007     // it to BT.
10008     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10009       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
10010       if (NewSetCC.getNode()) {
10011         CC = NewSetCC.getOperand(0);
10012         Cond = NewSetCC.getOperand(1);
10013         addTest = false;
10014       }
10015     }
10016   }
10017
10018   if (addTest) {
10019     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10020     Cond = EmitTest(Cond, X86::COND_NE, DAG);
10021   }
10022   Cond = ConvertCmpIfNecessary(Cond, DAG);
10023   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10024                      Chain, Dest, CC, Cond);
10025 }
10026
10027 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
10028 // Calls to _alloca is needed to probe the stack when allocating more than 4k
10029 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
10030 // that the guard pages used by the OS virtual memory manager are allocated in
10031 // correct sequence.
10032 SDValue
10033 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
10034                                            SelectionDAG &DAG) const {
10035   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
10036           getTargetMachine().Options.EnableSegmentedStacks) &&
10037          "This should be used only on Windows targets or when segmented stacks "
10038          "are being used");
10039   assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
10040   DebugLoc dl = Op.getDebugLoc();
10041
10042   // Get the inputs.
10043   SDValue Chain = Op.getOperand(0);
10044   SDValue Size  = Op.getOperand(1);
10045   // FIXME: Ensure alignment here
10046
10047   bool Is64Bit = Subtarget->is64Bit();
10048   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
10049
10050   if (getTargetMachine().Options.EnableSegmentedStacks) {
10051     MachineFunction &MF = DAG.getMachineFunction();
10052     MachineRegisterInfo &MRI = MF.getRegInfo();
10053
10054     if (Is64Bit) {
10055       // The 64 bit implementation of segmented stacks needs to clobber both r10
10056       // r11. This makes it impossible to use it along with nested parameters.
10057       const Function *F = MF.getFunction();
10058
10059       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
10060            I != E; ++I)
10061         if (I->hasNestAttr())
10062           report_fatal_error("Cannot use segmented stacks with functions that "
10063                              "have nested arguments.");
10064     }
10065
10066     const TargetRegisterClass *AddrRegClass =
10067       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
10068     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
10069     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
10070     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
10071                                 DAG.getRegister(Vreg, SPTy));
10072     SDValue Ops1[2] = { Value, Chain };
10073     return DAG.getMergeValues(Ops1, 2, dl);
10074   } else {
10075     SDValue Flag;
10076     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
10077
10078     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
10079     Flag = Chain.getValue(1);
10080     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10081
10082     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
10083     Flag = Chain.getValue(1);
10084
10085     Chain = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
10086                                SPTy).getValue(1);
10087
10088     SDValue Ops1[2] = { Chain.getValue(0), Chain };
10089     return DAG.getMergeValues(Ops1, 2, dl);
10090   }
10091 }
10092
10093 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
10094   MachineFunction &MF = DAG.getMachineFunction();
10095   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
10096
10097   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10098   DebugLoc DL = Op.getDebugLoc();
10099
10100   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
10101     // vastart just stores the address of the VarArgsFrameIndex slot into the
10102     // memory location argument.
10103     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10104                                    getPointerTy());
10105     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
10106                         MachinePointerInfo(SV), false, false, 0);
10107   }
10108
10109   // __va_list_tag:
10110   //   gp_offset         (0 - 6 * 8)
10111   //   fp_offset         (48 - 48 + 8 * 16)
10112   //   overflow_arg_area (point to parameters coming in memory).
10113   //   reg_save_area
10114   SmallVector<SDValue, 8> MemOps;
10115   SDValue FIN = Op.getOperand(1);
10116   // Store gp_offset
10117   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
10118                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
10119                                                MVT::i32),
10120                                FIN, MachinePointerInfo(SV), false, false, 0);
10121   MemOps.push_back(Store);
10122
10123   // Store fp_offset
10124   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10125                     FIN, DAG.getIntPtrConstant(4));
10126   Store = DAG.getStore(Op.getOperand(0), DL,
10127                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
10128                                        MVT::i32),
10129                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
10130   MemOps.push_back(Store);
10131
10132   // Store ptr to overflow_arg_area
10133   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10134                     FIN, DAG.getIntPtrConstant(4));
10135   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10136                                     getPointerTy());
10137   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
10138                        MachinePointerInfo(SV, 8),
10139                        false, false, 0);
10140   MemOps.push_back(Store);
10141
10142   // Store ptr to reg_save_area.
10143   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10144                     FIN, DAG.getIntPtrConstant(8));
10145   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
10146                                     getPointerTy());
10147   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
10148                        MachinePointerInfo(SV, 16), false, false, 0);
10149   MemOps.push_back(Store);
10150   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
10151                      &MemOps[0], MemOps.size());
10152 }
10153
10154 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
10155   assert(Subtarget->is64Bit() &&
10156          "LowerVAARG only handles 64-bit va_arg!");
10157   assert((Subtarget->isTargetLinux() ||
10158           Subtarget->isTargetDarwin()) &&
10159           "Unhandled target in LowerVAARG");
10160   assert(Op.getNode()->getNumOperands() == 4);
10161   SDValue Chain = Op.getOperand(0);
10162   SDValue SrcPtr = Op.getOperand(1);
10163   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10164   unsigned Align = Op.getConstantOperandVal(3);
10165   DebugLoc dl = Op.getDebugLoc();
10166
10167   EVT ArgVT = Op.getNode()->getValueType(0);
10168   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10169   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
10170   uint8_t ArgMode;
10171
10172   // Decide which area this value should be read from.
10173   // TODO: Implement the AMD64 ABI in its entirety. This simple
10174   // selection mechanism works only for the basic types.
10175   if (ArgVT == MVT::f80) {
10176     llvm_unreachable("va_arg for f80 not yet implemented");
10177   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
10178     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
10179   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
10180     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
10181   } else {
10182     llvm_unreachable("Unhandled argument type in LowerVAARG");
10183   }
10184
10185   if (ArgMode == 2) {
10186     // Sanity Check: Make sure using fp_offset makes sense.
10187     assert(!getTargetMachine().Options.UseSoftFloat &&
10188            !(DAG.getMachineFunction()
10189                 .getFunction()->getAttributes()
10190                 .hasAttribute(AttributeSet::FunctionIndex,
10191                               Attribute::NoImplicitFloat)) &&
10192            Subtarget->hasSSE1());
10193   }
10194
10195   // Insert VAARG_64 node into the DAG
10196   // VAARG_64 returns two values: Variable Argument Address, Chain
10197   SmallVector<SDValue, 11> InstOps;
10198   InstOps.push_back(Chain);
10199   InstOps.push_back(SrcPtr);
10200   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
10201   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
10202   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
10203   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
10204   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
10205                                           VTs, &InstOps[0], InstOps.size(),
10206                                           MVT::i64,
10207                                           MachinePointerInfo(SV),
10208                                           /*Align=*/0,
10209                                           /*Volatile=*/false,
10210                                           /*ReadMem=*/true,
10211                                           /*WriteMem=*/true);
10212   Chain = VAARG.getValue(1);
10213
10214   // Load the next argument and return it
10215   return DAG.getLoad(ArgVT, dl,
10216                      Chain,
10217                      VAARG,
10218                      MachinePointerInfo(),
10219                      false, false, false, 0);
10220 }
10221
10222 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
10223                            SelectionDAG &DAG) {
10224   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
10225   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
10226   SDValue Chain = Op.getOperand(0);
10227   SDValue DstPtr = Op.getOperand(1);
10228   SDValue SrcPtr = Op.getOperand(2);
10229   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
10230   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10231   DebugLoc DL = Op.getDebugLoc();
10232
10233   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
10234                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
10235                        false,
10236                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
10237 }
10238
10239 // getTargetVShiftNode - Handle vector element shifts where the shift amount
10240 // may or may not be a constant. Takes immediate version of shift as input.
10241 static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
10242                                    SDValue SrcOp, SDValue ShAmt,
10243                                    SelectionDAG &DAG) {
10244   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
10245
10246   if (isa<ConstantSDNode>(ShAmt)) {
10247     // Constant may be a TargetConstant. Use a regular constant.
10248     uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
10249     switch (Opc) {
10250       default: llvm_unreachable("Unknown target vector shift node");
10251       case X86ISD::VSHLI:
10252       case X86ISD::VSRLI:
10253       case X86ISD::VSRAI:
10254         return DAG.getNode(Opc, dl, VT, SrcOp,
10255                            DAG.getConstant(ShiftAmt, MVT::i32));
10256     }
10257   }
10258
10259   // Change opcode to non-immediate version
10260   switch (Opc) {
10261     default: llvm_unreachable("Unknown target vector shift node");
10262     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
10263     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
10264     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
10265   }
10266
10267   // Need to build a vector containing shift amount
10268   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
10269   SDValue ShOps[4];
10270   ShOps[0] = ShAmt;
10271   ShOps[1] = DAG.getConstant(0, MVT::i32);
10272   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
10273   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
10274
10275   // The return type has to be a 128-bit type with the same element
10276   // type as the input type.
10277   MVT EltVT = VT.getVectorElementType().getSimpleVT();
10278   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
10279
10280   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
10281   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
10282 }
10283
10284 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
10285   DebugLoc dl = Op.getDebugLoc();
10286   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10287   switch (IntNo) {
10288   default: return SDValue();    // Don't custom lower most intrinsics.
10289   // Comparison intrinsics.
10290   case Intrinsic::x86_sse_comieq_ss:
10291   case Intrinsic::x86_sse_comilt_ss:
10292   case Intrinsic::x86_sse_comile_ss:
10293   case Intrinsic::x86_sse_comigt_ss:
10294   case Intrinsic::x86_sse_comige_ss:
10295   case Intrinsic::x86_sse_comineq_ss:
10296   case Intrinsic::x86_sse_ucomieq_ss:
10297   case Intrinsic::x86_sse_ucomilt_ss:
10298   case Intrinsic::x86_sse_ucomile_ss:
10299   case Intrinsic::x86_sse_ucomigt_ss:
10300   case Intrinsic::x86_sse_ucomige_ss:
10301   case Intrinsic::x86_sse_ucomineq_ss:
10302   case Intrinsic::x86_sse2_comieq_sd:
10303   case Intrinsic::x86_sse2_comilt_sd:
10304   case Intrinsic::x86_sse2_comile_sd:
10305   case Intrinsic::x86_sse2_comigt_sd:
10306   case Intrinsic::x86_sse2_comige_sd:
10307   case Intrinsic::x86_sse2_comineq_sd:
10308   case Intrinsic::x86_sse2_ucomieq_sd:
10309   case Intrinsic::x86_sse2_ucomilt_sd:
10310   case Intrinsic::x86_sse2_ucomile_sd:
10311   case Intrinsic::x86_sse2_ucomigt_sd:
10312   case Intrinsic::x86_sse2_ucomige_sd:
10313   case Intrinsic::x86_sse2_ucomineq_sd: {
10314     unsigned Opc;
10315     ISD::CondCode CC;
10316     switch (IntNo) {
10317     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10318     case Intrinsic::x86_sse_comieq_ss:
10319     case Intrinsic::x86_sse2_comieq_sd:
10320       Opc = X86ISD::COMI;
10321       CC = ISD::SETEQ;
10322       break;
10323     case Intrinsic::x86_sse_comilt_ss:
10324     case Intrinsic::x86_sse2_comilt_sd:
10325       Opc = X86ISD::COMI;
10326       CC = ISD::SETLT;
10327       break;
10328     case Intrinsic::x86_sse_comile_ss:
10329     case Intrinsic::x86_sse2_comile_sd:
10330       Opc = X86ISD::COMI;
10331       CC = ISD::SETLE;
10332       break;
10333     case Intrinsic::x86_sse_comigt_ss:
10334     case Intrinsic::x86_sse2_comigt_sd:
10335       Opc = X86ISD::COMI;
10336       CC = ISD::SETGT;
10337       break;
10338     case Intrinsic::x86_sse_comige_ss:
10339     case Intrinsic::x86_sse2_comige_sd:
10340       Opc = X86ISD::COMI;
10341       CC = ISD::SETGE;
10342       break;
10343     case Intrinsic::x86_sse_comineq_ss:
10344     case Intrinsic::x86_sse2_comineq_sd:
10345       Opc = X86ISD::COMI;
10346       CC = ISD::SETNE;
10347       break;
10348     case Intrinsic::x86_sse_ucomieq_ss:
10349     case Intrinsic::x86_sse2_ucomieq_sd:
10350       Opc = X86ISD::UCOMI;
10351       CC = ISD::SETEQ;
10352       break;
10353     case Intrinsic::x86_sse_ucomilt_ss:
10354     case Intrinsic::x86_sse2_ucomilt_sd:
10355       Opc = X86ISD::UCOMI;
10356       CC = ISD::SETLT;
10357       break;
10358     case Intrinsic::x86_sse_ucomile_ss:
10359     case Intrinsic::x86_sse2_ucomile_sd:
10360       Opc = X86ISD::UCOMI;
10361       CC = ISD::SETLE;
10362       break;
10363     case Intrinsic::x86_sse_ucomigt_ss:
10364     case Intrinsic::x86_sse2_ucomigt_sd:
10365       Opc = X86ISD::UCOMI;
10366       CC = ISD::SETGT;
10367       break;
10368     case Intrinsic::x86_sse_ucomige_ss:
10369     case Intrinsic::x86_sse2_ucomige_sd:
10370       Opc = X86ISD::UCOMI;
10371       CC = ISD::SETGE;
10372       break;
10373     case Intrinsic::x86_sse_ucomineq_ss:
10374     case Intrinsic::x86_sse2_ucomineq_sd:
10375       Opc = X86ISD::UCOMI;
10376       CC = ISD::SETNE;
10377       break;
10378     }
10379
10380     SDValue LHS = Op.getOperand(1);
10381     SDValue RHS = Op.getOperand(2);
10382     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
10383     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
10384     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
10385     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10386                                 DAG.getConstant(X86CC, MVT::i8), Cond);
10387     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10388   }
10389
10390   // Arithmetic intrinsics.
10391   case Intrinsic::x86_sse2_pmulu_dq:
10392   case Intrinsic::x86_avx2_pmulu_dq:
10393     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
10394                        Op.getOperand(1), Op.getOperand(2));
10395
10396   // SSE2/AVX2 sub with unsigned saturation intrinsics
10397   case Intrinsic::x86_sse2_psubus_b:
10398   case Intrinsic::x86_sse2_psubus_w:
10399   case Intrinsic::x86_avx2_psubus_b:
10400   case Intrinsic::x86_avx2_psubus_w:
10401     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
10402                        Op.getOperand(1), Op.getOperand(2));
10403
10404   // SSE3/AVX horizontal add/sub intrinsics
10405   case Intrinsic::x86_sse3_hadd_ps:
10406   case Intrinsic::x86_sse3_hadd_pd:
10407   case Intrinsic::x86_avx_hadd_ps_256:
10408   case Intrinsic::x86_avx_hadd_pd_256:
10409   case Intrinsic::x86_sse3_hsub_ps:
10410   case Intrinsic::x86_sse3_hsub_pd:
10411   case Intrinsic::x86_avx_hsub_ps_256:
10412   case Intrinsic::x86_avx_hsub_pd_256:
10413   case Intrinsic::x86_ssse3_phadd_w_128:
10414   case Intrinsic::x86_ssse3_phadd_d_128:
10415   case Intrinsic::x86_avx2_phadd_w:
10416   case Intrinsic::x86_avx2_phadd_d:
10417   case Intrinsic::x86_ssse3_phsub_w_128:
10418   case Intrinsic::x86_ssse3_phsub_d_128:
10419   case Intrinsic::x86_avx2_phsub_w:
10420   case Intrinsic::x86_avx2_phsub_d: {
10421     unsigned Opcode;
10422     switch (IntNo) {
10423     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10424     case Intrinsic::x86_sse3_hadd_ps:
10425     case Intrinsic::x86_sse3_hadd_pd:
10426     case Intrinsic::x86_avx_hadd_ps_256:
10427     case Intrinsic::x86_avx_hadd_pd_256:
10428       Opcode = X86ISD::FHADD;
10429       break;
10430     case Intrinsic::x86_sse3_hsub_ps:
10431     case Intrinsic::x86_sse3_hsub_pd:
10432     case Intrinsic::x86_avx_hsub_ps_256:
10433     case Intrinsic::x86_avx_hsub_pd_256:
10434       Opcode = X86ISD::FHSUB;
10435       break;
10436     case Intrinsic::x86_ssse3_phadd_w_128:
10437     case Intrinsic::x86_ssse3_phadd_d_128:
10438     case Intrinsic::x86_avx2_phadd_w:
10439     case Intrinsic::x86_avx2_phadd_d:
10440       Opcode = X86ISD::HADD;
10441       break;
10442     case Intrinsic::x86_ssse3_phsub_w_128:
10443     case Intrinsic::x86_ssse3_phsub_d_128:
10444     case Intrinsic::x86_avx2_phsub_w:
10445     case Intrinsic::x86_avx2_phsub_d:
10446       Opcode = X86ISD::HSUB;
10447       break;
10448     }
10449     return DAG.getNode(Opcode, dl, Op.getValueType(),
10450                        Op.getOperand(1), Op.getOperand(2));
10451   }
10452
10453   // SSE2/SSE41/AVX2 integer max/min intrinsics.
10454   case Intrinsic::x86_sse2_pmaxu_b:
10455   case Intrinsic::x86_sse41_pmaxuw:
10456   case Intrinsic::x86_sse41_pmaxud:
10457   case Intrinsic::x86_avx2_pmaxu_b:
10458   case Intrinsic::x86_avx2_pmaxu_w:
10459   case Intrinsic::x86_avx2_pmaxu_d:
10460   case Intrinsic::x86_sse2_pminu_b:
10461   case Intrinsic::x86_sse41_pminuw:
10462   case Intrinsic::x86_sse41_pminud:
10463   case Intrinsic::x86_avx2_pminu_b:
10464   case Intrinsic::x86_avx2_pminu_w:
10465   case Intrinsic::x86_avx2_pminu_d:
10466   case Intrinsic::x86_sse41_pmaxsb:
10467   case Intrinsic::x86_sse2_pmaxs_w:
10468   case Intrinsic::x86_sse41_pmaxsd:
10469   case Intrinsic::x86_avx2_pmaxs_b:
10470   case Intrinsic::x86_avx2_pmaxs_w:
10471   case Intrinsic::x86_avx2_pmaxs_d:
10472   case Intrinsic::x86_sse41_pminsb:
10473   case Intrinsic::x86_sse2_pmins_w:
10474   case Intrinsic::x86_sse41_pminsd:
10475   case Intrinsic::x86_avx2_pmins_b:
10476   case Intrinsic::x86_avx2_pmins_w:
10477   case Intrinsic::x86_avx2_pmins_d: {
10478     unsigned Opcode;
10479     switch (IntNo) {
10480     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10481     case Intrinsic::x86_sse2_pmaxu_b:
10482     case Intrinsic::x86_sse41_pmaxuw:
10483     case Intrinsic::x86_sse41_pmaxud:
10484     case Intrinsic::x86_avx2_pmaxu_b:
10485     case Intrinsic::x86_avx2_pmaxu_w:
10486     case Intrinsic::x86_avx2_pmaxu_d:
10487       Opcode = X86ISD::UMAX;
10488       break;
10489     case Intrinsic::x86_sse2_pminu_b:
10490     case Intrinsic::x86_sse41_pminuw:
10491     case Intrinsic::x86_sse41_pminud:
10492     case Intrinsic::x86_avx2_pminu_b:
10493     case Intrinsic::x86_avx2_pminu_w:
10494     case Intrinsic::x86_avx2_pminu_d:
10495       Opcode = X86ISD::UMIN;
10496       break;
10497     case Intrinsic::x86_sse41_pmaxsb:
10498     case Intrinsic::x86_sse2_pmaxs_w:
10499     case Intrinsic::x86_sse41_pmaxsd:
10500     case Intrinsic::x86_avx2_pmaxs_b:
10501     case Intrinsic::x86_avx2_pmaxs_w:
10502     case Intrinsic::x86_avx2_pmaxs_d:
10503       Opcode = X86ISD::SMAX;
10504       break;
10505     case Intrinsic::x86_sse41_pminsb:
10506     case Intrinsic::x86_sse2_pmins_w:
10507     case Intrinsic::x86_sse41_pminsd:
10508     case Intrinsic::x86_avx2_pmins_b:
10509     case Intrinsic::x86_avx2_pmins_w:
10510     case Intrinsic::x86_avx2_pmins_d:
10511       Opcode = X86ISD::SMIN;
10512       break;
10513     }
10514     return DAG.getNode(Opcode, dl, Op.getValueType(),
10515                        Op.getOperand(1), Op.getOperand(2));
10516   }
10517
10518   // SSE/SSE2/AVX floating point max/min intrinsics.
10519   case Intrinsic::x86_sse_max_ps:
10520   case Intrinsic::x86_sse2_max_pd:
10521   case Intrinsic::x86_avx_max_ps_256:
10522   case Intrinsic::x86_avx_max_pd_256:
10523   case Intrinsic::x86_sse_min_ps:
10524   case Intrinsic::x86_sse2_min_pd:
10525   case Intrinsic::x86_avx_min_ps_256:
10526   case Intrinsic::x86_avx_min_pd_256: {
10527     unsigned Opcode;
10528     switch (IntNo) {
10529     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10530     case Intrinsic::x86_sse_max_ps:
10531     case Intrinsic::x86_sse2_max_pd:
10532     case Intrinsic::x86_avx_max_ps_256:
10533     case Intrinsic::x86_avx_max_pd_256:
10534       Opcode = X86ISD::FMAX;
10535       break;
10536     case Intrinsic::x86_sse_min_ps:
10537     case Intrinsic::x86_sse2_min_pd:
10538     case Intrinsic::x86_avx_min_ps_256:
10539     case Intrinsic::x86_avx_min_pd_256:
10540       Opcode = X86ISD::FMIN;
10541       break;
10542     }
10543     return DAG.getNode(Opcode, dl, Op.getValueType(),
10544                        Op.getOperand(1), Op.getOperand(2));
10545   }
10546
10547   // AVX2 variable shift intrinsics
10548   case Intrinsic::x86_avx2_psllv_d:
10549   case Intrinsic::x86_avx2_psllv_q:
10550   case Intrinsic::x86_avx2_psllv_d_256:
10551   case Intrinsic::x86_avx2_psllv_q_256:
10552   case Intrinsic::x86_avx2_psrlv_d:
10553   case Intrinsic::x86_avx2_psrlv_q:
10554   case Intrinsic::x86_avx2_psrlv_d_256:
10555   case Intrinsic::x86_avx2_psrlv_q_256:
10556   case Intrinsic::x86_avx2_psrav_d:
10557   case Intrinsic::x86_avx2_psrav_d_256: {
10558     unsigned Opcode;
10559     switch (IntNo) {
10560     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10561     case Intrinsic::x86_avx2_psllv_d:
10562     case Intrinsic::x86_avx2_psllv_q:
10563     case Intrinsic::x86_avx2_psllv_d_256:
10564     case Intrinsic::x86_avx2_psllv_q_256:
10565       Opcode = ISD::SHL;
10566       break;
10567     case Intrinsic::x86_avx2_psrlv_d:
10568     case Intrinsic::x86_avx2_psrlv_q:
10569     case Intrinsic::x86_avx2_psrlv_d_256:
10570     case Intrinsic::x86_avx2_psrlv_q_256:
10571       Opcode = ISD::SRL;
10572       break;
10573     case Intrinsic::x86_avx2_psrav_d:
10574     case Intrinsic::x86_avx2_psrav_d_256:
10575       Opcode = ISD::SRA;
10576       break;
10577     }
10578     return DAG.getNode(Opcode, dl, Op.getValueType(),
10579                        Op.getOperand(1), Op.getOperand(2));
10580   }
10581
10582   case Intrinsic::x86_ssse3_pshuf_b_128:
10583   case Intrinsic::x86_avx2_pshuf_b:
10584     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
10585                        Op.getOperand(1), Op.getOperand(2));
10586
10587   case Intrinsic::x86_ssse3_psign_b_128:
10588   case Intrinsic::x86_ssse3_psign_w_128:
10589   case Intrinsic::x86_ssse3_psign_d_128:
10590   case Intrinsic::x86_avx2_psign_b:
10591   case Intrinsic::x86_avx2_psign_w:
10592   case Intrinsic::x86_avx2_psign_d:
10593     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
10594                        Op.getOperand(1), Op.getOperand(2));
10595
10596   case Intrinsic::x86_sse41_insertps:
10597     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
10598                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10599
10600   case Intrinsic::x86_avx_vperm2f128_ps_256:
10601   case Intrinsic::x86_avx_vperm2f128_pd_256:
10602   case Intrinsic::x86_avx_vperm2f128_si_256:
10603   case Intrinsic::x86_avx2_vperm2i128:
10604     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
10605                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10606
10607   case Intrinsic::x86_avx2_permd:
10608   case Intrinsic::x86_avx2_permps:
10609     // Operands intentionally swapped. Mask is last operand to intrinsic,
10610     // but second operand for node/intruction.
10611     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
10612                        Op.getOperand(2), Op.getOperand(1));
10613
10614   case Intrinsic::x86_sse_sqrt_ps:
10615   case Intrinsic::x86_sse2_sqrt_pd:
10616   case Intrinsic::x86_avx_sqrt_ps_256:
10617   case Intrinsic::x86_avx_sqrt_pd_256:
10618     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
10619
10620   // ptest and testp intrinsics. The intrinsic these come from are designed to
10621   // return an integer value, not just an instruction so lower it to the ptest
10622   // or testp pattern and a setcc for the result.
10623   case Intrinsic::x86_sse41_ptestz:
10624   case Intrinsic::x86_sse41_ptestc:
10625   case Intrinsic::x86_sse41_ptestnzc:
10626   case Intrinsic::x86_avx_ptestz_256:
10627   case Intrinsic::x86_avx_ptestc_256:
10628   case Intrinsic::x86_avx_ptestnzc_256:
10629   case Intrinsic::x86_avx_vtestz_ps:
10630   case Intrinsic::x86_avx_vtestc_ps:
10631   case Intrinsic::x86_avx_vtestnzc_ps:
10632   case Intrinsic::x86_avx_vtestz_pd:
10633   case Intrinsic::x86_avx_vtestc_pd:
10634   case Intrinsic::x86_avx_vtestnzc_pd:
10635   case Intrinsic::x86_avx_vtestz_ps_256:
10636   case Intrinsic::x86_avx_vtestc_ps_256:
10637   case Intrinsic::x86_avx_vtestnzc_ps_256:
10638   case Intrinsic::x86_avx_vtestz_pd_256:
10639   case Intrinsic::x86_avx_vtestc_pd_256:
10640   case Intrinsic::x86_avx_vtestnzc_pd_256: {
10641     bool IsTestPacked = false;
10642     unsigned X86CC;
10643     switch (IntNo) {
10644     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
10645     case Intrinsic::x86_avx_vtestz_ps:
10646     case Intrinsic::x86_avx_vtestz_pd:
10647     case Intrinsic::x86_avx_vtestz_ps_256:
10648     case Intrinsic::x86_avx_vtestz_pd_256:
10649       IsTestPacked = true; // Fallthrough
10650     case Intrinsic::x86_sse41_ptestz:
10651     case Intrinsic::x86_avx_ptestz_256:
10652       // ZF = 1
10653       X86CC = X86::COND_E;
10654       break;
10655     case Intrinsic::x86_avx_vtestc_ps:
10656     case Intrinsic::x86_avx_vtestc_pd:
10657     case Intrinsic::x86_avx_vtestc_ps_256:
10658     case Intrinsic::x86_avx_vtestc_pd_256:
10659       IsTestPacked = true; // Fallthrough
10660     case Intrinsic::x86_sse41_ptestc:
10661     case Intrinsic::x86_avx_ptestc_256:
10662       // CF = 1
10663       X86CC = X86::COND_B;
10664       break;
10665     case Intrinsic::x86_avx_vtestnzc_ps:
10666     case Intrinsic::x86_avx_vtestnzc_pd:
10667     case Intrinsic::x86_avx_vtestnzc_ps_256:
10668     case Intrinsic::x86_avx_vtestnzc_pd_256:
10669       IsTestPacked = true; // Fallthrough
10670     case Intrinsic::x86_sse41_ptestnzc:
10671     case Intrinsic::x86_avx_ptestnzc_256:
10672       // ZF and CF = 0
10673       X86CC = X86::COND_A;
10674       break;
10675     }
10676
10677     SDValue LHS = Op.getOperand(1);
10678     SDValue RHS = Op.getOperand(2);
10679     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
10680     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
10681     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
10682     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
10683     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10684   }
10685
10686   // SSE/AVX shift intrinsics
10687   case Intrinsic::x86_sse2_psll_w:
10688   case Intrinsic::x86_sse2_psll_d:
10689   case Intrinsic::x86_sse2_psll_q:
10690   case Intrinsic::x86_avx2_psll_w:
10691   case Intrinsic::x86_avx2_psll_d:
10692   case Intrinsic::x86_avx2_psll_q:
10693   case Intrinsic::x86_sse2_psrl_w:
10694   case Intrinsic::x86_sse2_psrl_d:
10695   case Intrinsic::x86_sse2_psrl_q:
10696   case Intrinsic::x86_avx2_psrl_w:
10697   case Intrinsic::x86_avx2_psrl_d:
10698   case Intrinsic::x86_avx2_psrl_q:
10699   case Intrinsic::x86_sse2_psra_w:
10700   case Intrinsic::x86_sse2_psra_d:
10701   case Intrinsic::x86_avx2_psra_w:
10702   case Intrinsic::x86_avx2_psra_d: {
10703     unsigned Opcode;
10704     switch (IntNo) {
10705     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10706     case Intrinsic::x86_sse2_psll_w:
10707     case Intrinsic::x86_sse2_psll_d:
10708     case Intrinsic::x86_sse2_psll_q:
10709     case Intrinsic::x86_avx2_psll_w:
10710     case Intrinsic::x86_avx2_psll_d:
10711     case Intrinsic::x86_avx2_psll_q:
10712       Opcode = X86ISD::VSHL;
10713       break;
10714     case Intrinsic::x86_sse2_psrl_w:
10715     case Intrinsic::x86_sse2_psrl_d:
10716     case Intrinsic::x86_sse2_psrl_q:
10717     case Intrinsic::x86_avx2_psrl_w:
10718     case Intrinsic::x86_avx2_psrl_d:
10719     case Intrinsic::x86_avx2_psrl_q:
10720       Opcode = X86ISD::VSRL;
10721       break;
10722     case Intrinsic::x86_sse2_psra_w:
10723     case Intrinsic::x86_sse2_psra_d:
10724     case Intrinsic::x86_avx2_psra_w:
10725     case Intrinsic::x86_avx2_psra_d:
10726       Opcode = X86ISD::VSRA;
10727       break;
10728     }
10729     return DAG.getNode(Opcode, dl, Op.getValueType(),
10730                        Op.getOperand(1), Op.getOperand(2));
10731   }
10732
10733   // SSE/AVX immediate shift intrinsics
10734   case Intrinsic::x86_sse2_pslli_w:
10735   case Intrinsic::x86_sse2_pslli_d:
10736   case Intrinsic::x86_sse2_pslli_q:
10737   case Intrinsic::x86_avx2_pslli_w:
10738   case Intrinsic::x86_avx2_pslli_d:
10739   case Intrinsic::x86_avx2_pslli_q:
10740   case Intrinsic::x86_sse2_psrli_w:
10741   case Intrinsic::x86_sse2_psrli_d:
10742   case Intrinsic::x86_sse2_psrli_q:
10743   case Intrinsic::x86_avx2_psrli_w:
10744   case Intrinsic::x86_avx2_psrli_d:
10745   case Intrinsic::x86_avx2_psrli_q:
10746   case Intrinsic::x86_sse2_psrai_w:
10747   case Intrinsic::x86_sse2_psrai_d:
10748   case Intrinsic::x86_avx2_psrai_w:
10749   case Intrinsic::x86_avx2_psrai_d: {
10750     unsigned Opcode;
10751     switch (IntNo) {
10752     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10753     case Intrinsic::x86_sse2_pslli_w:
10754     case Intrinsic::x86_sse2_pslli_d:
10755     case Intrinsic::x86_sse2_pslli_q:
10756     case Intrinsic::x86_avx2_pslli_w:
10757     case Intrinsic::x86_avx2_pslli_d:
10758     case Intrinsic::x86_avx2_pslli_q:
10759       Opcode = X86ISD::VSHLI;
10760       break;
10761     case Intrinsic::x86_sse2_psrli_w:
10762     case Intrinsic::x86_sse2_psrli_d:
10763     case Intrinsic::x86_sse2_psrli_q:
10764     case Intrinsic::x86_avx2_psrli_w:
10765     case Intrinsic::x86_avx2_psrli_d:
10766     case Intrinsic::x86_avx2_psrli_q:
10767       Opcode = X86ISD::VSRLI;
10768       break;
10769     case Intrinsic::x86_sse2_psrai_w:
10770     case Intrinsic::x86_sse2_psrai_d:
10771     case Intrinsic::x86_avx2_psrai_w:
10772     case Intrinsic::x86_avx2_psrai_d:
10773       Opcode = X86ISD::VSRAI;
10774       break;
10775     }
10776     return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
10777                                Op.getOperand(1), Op.getOperand(2), DAG);
10778   }
10779
10780   case Intrinsic::x86_sse42_pcmpistria128:
10781   case Intrinsic::x86_sse42_pcmpestria128:
10782   case Intrinsic::x86_sse42_pcmpistric128:
10783   case Intrinsic::x86_sse42_pcmpestric128:
10784   case Intrinsic::x86_sse42_pcmpistrio128:
10785   case Intrinsic::x86_sse42_pcmpestrio128:
10786   case Intrinsic::x86_sse42_pcmpistris128:
10787   case Intrinsic::x86_sse42_pcmpestris128:
10788   case Intrinsic::x86_sse42_pcmpistriz128:
10789   case Intrinsic::x86_sse42_pcmpestriz128: {
10790     unsigned Opcode;
10791     unsigned X86CC;
10792     switch (IntNo) {
10793     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10794     case Intrinsic::x86_sse42_pcmpistria128:
10795       Opcode = X86ISD::PCMPISTRI;
10796       X86CC = X86::COND_A;
10797       break;
10798     case Intrinsic::x86_sse42_pcmpestria128:
10799       Opcode = X86ISD::PCMPESTRI;
10800       X86CC = X86::COND_A;
10801       break;
10802     case Intrinsic::x86_sse42_pcmpistric128:
10803       Opcode = X86ISD::PCMPISTRI;
10804       X86CC = X86::COND_B;
10805       break;
10806     case Intrinsic::x86_sse42_pcmpestric128:
10807       Opcode = X86ISD::PCMPESTRI;
10808       X86CC = X86::COND_B;
10809       break;
10810     case Intrinsic::x86_sse42_pcmpistrio128:
10811       Opcode = X86ISD::PCMPISTRI;
10812       X86CC = X86::COND_O;
10813       break;
10814     case Intrinsic::x86_sse42_pcmpestrio128:
10815       Opcode = X86ISD::PCMPESTRI;
10816       X86CC = X86::COND_O;
10817       break;
10818     case Intrinsic::x86_sse42_pcmpistris128:
10819       Opcode = X86ISD::PCMPISTRI;
10820       X86CC = X86::COND_S;
10821       break;
10822     case Intrinsic::x86_sse42_pcmpestris128:
10823       Opcode = X86ISD::PCMPESTRI;
10824       X86CC = X86::COND_S;
10825       break;
10826     case Intrinsic::x86_sse42_pcmpistriz128:
10827       Opcode = X86ISD::PCMPISTRI;
10828       X86CC = X86::COND_E;
10829       break;
10830     case Intrinsic::x86_sse42_pcmpestriz128:
10831       Opcode = X86ISD::PCMPESTRI;
10832       X86CC = X86::COND_E;
10833       break;
10834     }
10835     SmallVector<SDValue, 5> NewOps;
10836     NewOps.append(Op->op_begin()+1, Op->op_end());
10837     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10838     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10839     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10840                                 DAG.getConstant(X86CC, MVT::i8),
10841                                 SDValue(PCMP.getNode(), 1));
10842     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10843   }
10844
10845   case Intrinsic::x86_sse42_pcmpistri128:
10846   case Intrinsic::x86_sse42_pcmpestri128: {
10847     unsigned Opcode;
10848     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
10849       Opcode = X86ISD::PCMPISTRI;
10850     else
10851       Opcode = X86ISD::PCMPESTRI;
10852
10853     SmallVector<SDValue, 5> NewOps;
10854     NewOps.append(Op->op_begin()+1, Op->op_end());
10855     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10856     return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10857   }
10858   case Intrinsic::x86_fma_vfmadd_ps:
10859   case Intrinsic::x86_fma_vfmadd_pd:
10860   case Intrinsic::x86_fma_vfmsub_ps:
10861   case Intrinsic::x86_fma_vfmsub_pd:
10862   case Intrinsic::x86_fma_vfnmadd_ps:
10863   case Intrinsic::x86_fma_vfnmadd_pd:
10864   case Intrinsic::x86_fma_vfnmsub_ps:
10865   case Intrinsic::x86_fma_vfnmsub_pd:
10866   case Intrinsic::x86_fma_vfmaddsub_ps:
10867   case Intrinsic::x86_fma_vfmaddsub_pd:
10868   case Intrinsic::x86_fma_vfmsubadd_ps:
10869   case Intrinsic::x86_fma_vfmsubadd_pd:
10870   case Intrinsic::x86_fma_vfmadd_ps_256:
10871   case Intrinsic::x86_fma_vfmadd_pd_256:
10872   case Intrinsic::x86_fma_vfmsub_ps_256:
10873   case Intrinsic::x86_fma_vfmsub_pd_256:
10874   case Intrinsic::x86_fma_vfnmadd_ps_256:
10875   case Intrinsic::x86_fma_vfnmadd_pd_256:
10876   case Intrinsic::x86_fma_vfnmsub_ps_256:
10877   case Intrinsic::x86_fma_vfnmsub_pd_256:
10878   case Intrinsic::x86_fma_vfmaddsub_ps_256:
10879   case Intrinsic::x86_fma_vfmaddsub_pd_256:
10880   case Intrinsic::x86_fma_vfmsubadd_ps_256:
10881   case Intrinsic::x86_fma_vfmsubadd_pd_256: {
10882     unsigned Opc;
10883     switch (IntNo) {
10884     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10885     case Intrinsic::x86_fma_vfmadd_ps:
10886     case Intrinsic::x86_fma_vfmadd_pd:
10887     case Intrinsic::x86_fma_vfmadd_ps_256:
10888     case Intrinsic::x86_fma_vfmadd_pd_256:
10889       Opc = X86ISD::FMADD;
10890       break;
10891     case Intrinsic::x86_fma_vfmsub_ps:
10892     case Intrinsic::x86_fma_vfmsub_pd:
10893     case Intrinsic::x86_fma_vfmsub_ps_256:
10894     case Intrinsic::x86_fma_vfmsub_pd_256:
10895       Opc = X86ISD::FMSUB;
10896       break;
10897     case Intrinsic::x86_fma_vfnmadd_ps:
10898     case Intrinsic::x86_fma_vfnmadd_pd:
10899     case Intrinsic::x86_fma_vfnmadd_ps_256:
10900     case Intrinsic::x86_fma_vfnmadd_pd_256:
10901       Opc = X86ISD::FNMADD;
10902       break;
10903     case Intrinsic::x86_fma_vfnmsub_ps:
10904     case Intrinsic::x86_fma_vfnmsub_pd:
10905     case Intrinsic::x86_fma_vfnmsub_ps_256:
10906     case Intrinsic::x86_fma_vfnmsub_pd_256:
10907       Opc = X86ISD::FNMSUB;
10908       break;
10909     case Intrinsic::x86_fma_vfmaddsub_ps:
10910     case Intrinsic::x86_fma_vfmaddsub_pd:
10911     case Intrinsic::x86_fma_vfmaddsub_ps_256:
10912     case Intrinsic::x86_fma_vfmaddsub_pd_256:
10913       Opc = X86ISD::FMADDSUB;
10914       break;
10915     case Intrinsic::x86_fma_vfmsubadd_ps:
10916     case Intrinsic::x86_fma_vfmsubadd_pd:
10917     case Intrinsic::x86_fma_vfmsubadd_ps_256:
10918     case Intrinsic::x86_fma_vfmsubadd_pd_256:
10919       Opc = X86ISD::FMSUBADD;
10920       break;
10921     }
10922
10923     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
10924                        Op.getOperand(2), Op.getOperand(3));
10925   }
10926   }
10927 }
10928
10929 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) {
10930   DebugLoc dl = Op.getDebugLoc();
10931   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10932   switch (IntNo) {
10933   default: return SDValue();    // Don't custom lower most intrinsics.
10934
10935   // RDRAND/RDSEED intrinsics.
10936   case Intrinsic::x86_rdrand_16:
10937   case Intrinsic::x86_rdrand_32:
10938   case Intrinsic::x86_rdrand_64:
10939   case Intrinsic::x86_rdseed_16:
10940   case Intrinsic::x86_rdseed_32:
10941   case Intrinsic::x86_rdseed_64: {
10942     unsigned Opcode = (IntNo == Intrinsic::x86_rdseed_16 ||
10943                        IntNo == Intrinsic::x86_rdseed_32 ||
10944                        IntNo == Intrinsic::x86_rdseed_64) ? X86ISD::RDSEED :
10945                                                             X86ISD::RDRAND;
10946     // Emit the node with the right value type.
10947     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
10948     SDValue Result = DAG.getNode(Opcode, dl, VTs, Op.getOperand(0));
10949
10950     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
10951     // Otherwise return the value from Rand, which is always 0, casted to i32.
10952     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
10953                       DAG.getConstant(1, Op->getValueType(1)),
10954                       DAG.getConstant(X86::COND_B, MVT::i32),
10955                       SDValue(Result.getNode(), 1) };
10956     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
10957                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
10958                                   Ops, 4);
10959
10960     // Return { result, isValid, chain }.
10961     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
10962                        SDValue(Result.getNode(), 2));
10963   }
10964
10965   // XTEST intrinsics.
10966   case Intrinsic::x86_xtest: {
10967     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
10968     SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
10969     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10970                                 DAG.getConstant(X86::COND_NE, MVT::i8),
10971                                 InTrans);
10972     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
10973     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
10974                        Ret, SDValue(InTrans.getNode(), 1));
10975   }
10976   }
10977 }
10978
10979 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
10980                                            SelectionDAG &DAG) const {
10981   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10982   MFI->setReturnAddressIsTaken(true);
10983
10984   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10985   DebugLoc dl = Op.getDebugLoc();
10986   EVT PtrVT = getPointerTy();
10987
10988   if (Depth > 0) {
10989     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
10990     SDValue Offset =
10991       DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
10992     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
10993                        DAG.getNode(ISD::ADD, dl, PtrVT,
10994                                    FrameAddr, Offset),
10995                        MachinePointerInfo(), false, false, false, 0);
10996   }
10997
10998   // Just load the return address.
10999   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
11000   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
11001                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
11002 }
11003
11004 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
11005   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11006   MFI->setFrameAddressIsTaken(true);
11007
11008   EVT VT = Op.getValueType();
11009   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
11010   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11011   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
11012   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
11013   while (Depth--)
11014     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
11015                             MachinePointerInfo(),
11016                             false, false, false, 0);
11017   return FrameAddr;
11018 }
11019
11020 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
11021                                                      SelectionDAG &DAG) const {
11022   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
11023 }
11024
11025 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
11026   SDValue Chain     = Op.getOperand(0);
11027   SDValue Offset    = Op.getOperand(1);
11028   SDValue Handler   = Op.getOperand(2);
11029   DebugLoc dl       = Op.getDebugLoc();
11030
11031   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
11032                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
11033                                      getPointerTy());
11034   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
11035
11036   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
11037                                   DAG.getIntPtrConstant(RegInfo->getSlotSize()));
11038   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
11039   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
11040                        false, false, 0);
11041   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
11042
11043   return DAG.getNode(X86ISD::EH_RETURN, dl,
11044                      MVT::Other,
11045                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
11046 }
11047
11048 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
11049                                                SelectionDAG &DAG) const {
11050   DebugLoc DL = Op.getDebugLoc();
11051   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
11052                      DAG.getVTList(MVT::i32, MVT::Other),
11053                      Op.getOperand(0), Op.getOperand(1));
11054 }
11055
11056 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
11057                                                 SelectionDAG &DAG) const {
11058   DebugLoc DL = Op.getDebugLoc();
11059   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
11060                      Op.getOperand(0), Op.getOperand(1));
11061 }
11062
11063 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
11064   return Op.getOperand(0);
11065 }
11066
11067 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
11068                                                 SelectionDAG &DAG) const {
11069   SDValue Root = Op.getOperand(0);
11070   SDValue Trmp = Op.getOperand(1); // trampoline
11071   SDValue FPtr = Op.getOperand(2); // nested function
11072   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
11073   DebugLoc dl  = Op.getDebugLoc();
11074
11075   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11076   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
11077
11078   if (Subtarget->is64Bit()) {
11079     SDValue OutChains[6];
11080
11081     // Large code-model.
11082     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
11083     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
11084
11085     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
11086     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
11087
11088     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
11089
11090     // Load the pointer to the nested function into R11.
11091     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
11092     SDValue Addr = Trmp;
11093     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11094                                 Addr, MachinePointerInfo(TrmpAddr),
11095                                 false, false, 0);
11096
11097     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11098                        DAG.getConstant(2, MVT::i64));
11099     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
11100                                 MachinePointerInfo(TrmpAddr, 2),
11101                                 false, false, 2);
11102
11103     // Load the 'nest' parameter value into R10.
11104     // R10 is specified in X86CallingConv.td
11105     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
11106     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11107                        DAG.getConstant(10, MVT::i64));
11108     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11109                                 Addr, MachinePointerInfo(TrmpAddr, 10),
11110                                 false, false, 0);
11111
11112     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11113                        DAG.getConstant(12, MVT::i64));
11114     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
11115                                 MachinePointerInfo(TrmpAddr, 12),
11116                                 false, false, 2);
11117
11118     // Jump to the nested function.
11119     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
11120     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11121                        DAG.getConstant(20, MVT::i64));
11122     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11123                                 Addr, MachinePointerInfo(TrmpAddr, 20),
11124                                 false, false, 0);
11125
11126     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
11127     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11128                        DAG.getConstant(22, MVT::i64));
11129     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
11130                                 MachinePointerInfo(TrmpAddr, 22),
11131                                 false, false, 0);
11132
11133     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
11134   } else {
11135     const Function *Func =
11136       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
11137     CallingConv::ID CC = Func->getCallingConv();
11138     unsigned NestReg;
11139
11140     switch (CC) {
11141     default:
11142       llvm_unreachable("Unsupported calling convention");
11143     case CallingConv::C:
11144     case CallingConv::X86_StdCall: {
11145       // Pass 'nest' parameter in ECX.
11146       // Must be kept in sync with X86CallingConv.td
11147       NestReg = X86::ECX;
11148
11149       // Check that ECX wasn't needed by an 'inreg' parameter.
11150       FunctionType *FTy = Func->getFunctionType();
11151       const AttributeSet &Attrs = Func->getAttributes();
11152
11153       if (!Attrs.isEmpty() && !Func->isVarArg()) {
11154         unsigned InRegCount = 0;
11155         unsigned Idx = 1;
11156
11157         for (FunctionType::param_iterator I = FTy->param_begin(),
11158              E = FTy->param_end(); I != E; ++I, ++Idx)
11159           if (Attrs.hasAttribute(Idx, Attribute::InReg))
11160             // FIXME: should only count parameters that are lowered to integers.
11161             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
11162
11163         if (InRegCount > 2) {
11164           report_fatal_error("Nest register in use - reduce number of inreg"
11165                              " parameters!");
11166         }
11167       }
11168       break;
11169     }
11170     case CallingConv::X86_FastCall:
11171     case CallingConv::X86_ThisCall:
11172     case CallingConv::Fast:
11173       // Pass 'nest' parameter in EAX.
11174       // Must be kept in sync with X86CallingConv.td
11175       NestReg = X86::EAX;
11176       break;
11177     }
11178
11179     SDValue OutChains[4];
11180     SDValue Addr, Disp;
11181
11182     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11183                        DAG.getConstant(10, MVT::i32));
11184     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
11185
11186     // This is storing the opcode for MOV32ri.
11187     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
11188     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
11189     OutChains[0] = DAG.getStore(Root, dl,
11190                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
11191                                 Trmp, MachinePointerInfo(TrmpAddr),
11192                                 false, false, 0);
11193
11194     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11195                        DAG.getConstant(1, MVT::i32));
11196     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
11197                                 MachinePointerInfo(TrmpAddr, 1),
11198                                 false, false, 1);
11199
11200     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
11201     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11202                        DAG.getConstant(5, MVT::i32));
11203     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
11204                                 MachinePointerInfo(TrmpAddr, 5),
11205                                 false, false, 1);
11206
11207     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11208                        DAG.getConstant(6, MVT::i32));
11209     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
11210                                 MachinePointerInfo(TrmpAddr, 6),
11211                                 false, false, 1);
11212
11213     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
11214   }
11215 }
11216
11217 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
11218                                             SelectionDAG &DAG) const {
11219   /*
11220    The rounding mode is in bits 11:10 of FPSR, and has the following
11221    settings:
11222      00 Round to nearest
11223      01 Round to -inf
11224      10 Round to +inf
11225      11 Round to 0
11226
11227   FLT_ROUNDS, on the other hand, expects the following:
11228     -1 Undefined
11229      0 Round to 0
11230      1 Round to nearest
11231      2 Round to +inf
11232      3 Round to -inf
11233
11234   To perform the conversion, we do:
11235     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
11236   */
11237
11238   MachineFunction &MF = DAG.getMachineFunction();
11239   const TargetMachine &TM = MF.getTarget();
11240   const TargetFrameLowering &TFI = *TM.getFrameLowering();
11241   unsigned StackAlignment = TFI.getStackAlignment();
11242   EVT VT = Op.getValueType();
11243   DebugLoc DL = Op.getDebugLoc();
11244
11245   // Save FP Control Word to stack slot
11246   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
11247   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11248
11249   MachineMemOperand *MMO =
11250    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11251                            MachineMemOperand::MOStore, 2, 2);
11252
11253   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
11254   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
11255                                           DAG.getVTList(MVT::Other),
11256                                           Ops, 2, MVT::i16, MMO);
11257
11258   // Load FP Control Word from stack slot
11259   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
11260                             MachinePointerInfo(), false, false, false, 0);
11261
11262   // Transform as necessary
11263   SDValue CWD1 =
11264     DAG.getNode(ISD::SRL, DL, MVT::i16,
11265                 DAG.getNode(ISD::AND, DL, MVT::i16,
11266                             CWD, DAG.getConstant(0x800, MVT::i16)),
11267                 DAG.getConstant(11, MVT::i8));
11268   SDValue CWD2 =
11269     DAG.getNode(ISD::SRL, DL, MVT::i16,
11270                 DAG.getNode(ISD::AND, DL, MVT::i16,
11271                             CWD, DAG.getConstant(0x400, MVT::i16)),
11272                 DAG.getConstant(9, MVT::i8));
11273
11274   SDValue RetVal =
11275     DAG.getNode(ISD::AND, DL, MVT::i16,
11276                 DAG.getNode(ISD::ADD, DL, MVT::i16,
11277                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
11278                             DAG.getConstant(1, MVT::i16)),
11279                 DAG.getConstant(3, MVT::i16));
11280
11281   return DAG.getNode((VT.getSizeInBits() < 16 ?
11282                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
11283 }
11284
11285 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
11286   EVT VT = Op.getValueType();
11287   EVT OpVT = VT;
11288   unsigned NumBits = VT.getSizeInBits();
11289   DebugLoc dl = Op.getDebugLoc();
11290
11291   Op = Op.getOperand(0);
11292   if (VT == MVT::i8) {
11293     // Zero extend to i32 since there is not an i8 bsr.
11294     OpVT = MVT::i32;
11295     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
11296   }
11297
11298   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
11299   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
11300   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
11301
11302   // If src is zero (i.e. bsr sets ZF), returns NumBits.
11303   SDValue Ops[] = {
11304     Op,
11305     DAG.getConstant(NumBits+NumBits-1, OpVT),
11306     DAG.getConstant(X86::COND_E, MVT::i8),
11307     Op.getValue(1)
11308   };
11309   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
11310
11311   // Finally xor with NumBits-1.
11312   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
11313
11314   if (VT == MVT::i8)
11315     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
11316   return Op;
11317 }
11318
11319 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
11320   EVT VT = Op.getValueType();
11321   EVT OpVT = VT;
11322   unsigned NumBits = VT.getSizeInBits();
11323   DebugLoc dl = Op.getDebugLoc();
11324
11325   Op = Op.getOperand(0);
11326   if (VT == MVT::i8) {
11327     // Zero extend to i32 since there is not an i8 bsr.
11328     OpVT = MVT::i32;
11329     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
11330   }
11331
11332   // Issue a bsr (scan bits in reverse).
11333   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
11334   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
11335
11336   // And xor with NumBits-1.
11337   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
11338
11339   if (VT == MVT::i8)
11340     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
11341   return Op;
11342 }
11343
11344 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
11345   EVT VT = Op.getValueType();
11346   unsigned NumBits = VT.getSizeInBits();
11347   DebugLoc dl = Op.getDebugLoc();
11348   Op = Op.getOperand(0);
11349
11350   // Issue a bsf (scan bits forward) which also sets EFLAGS.
11351   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11352   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
11353
11354   // If src is zero (i.e. bsf sets ZF), returns NumBits.
11355   SDValue Ops[] = {
11356     Op,
11357     DAG.getConstant(NumBits, VT),
11358     DAG.getConstant(X86::COND_E, MVT::i8),
11359     Op.getValue(1)
11360   };
11361   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
11362 }
11363
11364 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
11365 // ones, and then concatenate the result back.
11366 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
11367   EVT VT = Op.getValueType();
11368
11369   assert(VT.is256BitVector() && VT.isInteger() &&
11370          "Unsupported value type for operation");
11371
11372   unsigned NumElems = VT.getVectorNumElements();
11373   DebugLoc dl = Op.getDebugLoc();
11374
11375   // Extract the LHS vectors
11376   SDValue LHS = Op.getOperand(0);
11377   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11378   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11379
11380   // Extract the RHS vectors
11381   SDValue RHS = Op.getOperand(1);
11382   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
11383   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
11384
11385   MVT EltVT = VT.getVectorElementType().getSimpleVT();
11386   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11387
11388   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
11389                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
11390                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
11391 }
11392
11393 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
11394   assert(Op.getValueType().is256BitVector() &&
11395          Op.getValueType().isInteger() &&
11396          "Only handle AVX 256-bit vector integer operation");
11397   return Lower256IntArith(Op, DAG);
11398 }
11399
11400 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
11401   assert(Op.getValueType().is256BitVector() &&
11402          Op.getValueType().isInteger() &&
11403          "Only handle AVX 256-bit vector integer operation");
11404   return Lower256IntArith(Op, DAG);
11405 }
11406
11407 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
11408                         SelectionDAG &DAG) {
11409   DebugLoc dl = Op.getDebugLoc();
11410   EVT VT = Op.getValueType();
11411
11412   // Decompose 256-bit ops into smaller 128-bit ops.
11413   if (VT.is256BitVector() && !Subtarget->hasInt256())
11414     return Lower256IntArith(Op, DAG);
11415
11416   SDValue A = Op.getOperand(0);
11417   SDValue B = Op.getOperand(1);
11418
11419   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
11420   if (VT == MVT::v4i32) {
11421     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
11422            "Should not custom lower when pmuldq is available!");
11423
11424     // Extract the odd parts.
11425     const int UnpackMask[] = { 1, -1, 3, -1 };
11426     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
11427     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
11428
11429     // Multiply the even parts.
11430     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
11431     // Now multiply odd parts.
11432     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
11433
11434     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
11435     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
11436
11437     // Merge the two vectors back together with a shuffle. This expands into 2
11438     // shuffles.
11439     const int ShufMask[] = { 0, 4, 2, 6 };
11440     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
11441   }
11442
11443   assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
11444          "Only know how to lower V2I64/V4I64 multiply");
11445
11446   //  Ahi = psrlqi(a, 32);
11447   //  Bhi = psrlqi(b, 32);
11448   //
11449   //  AloBlo = pmuludq(a, b);
11450   //  AloBhi = pmuludq(a, Bhi);
11451   //  AhiBlo = pmuludq(Ahi, b);
11452
11453   //  AloBhi = psllqi(AloBhi, 32);
11454   //  AhiBlo = psllqi(AhiBlo, 32);
11455   //  return AloBlo + AloBhi + AhiBlo;
11456
11457   SDValue ShAmt = DAG.getConstant(32, MVT::i32);
11458
11459   SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
11460   SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
11461
11462   // Bit cast to 32-bit vectors for MULUDQ
11463   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
11464   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
11465   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
11466   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
11467   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
11468
11469   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
11470   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
11471   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
11472
11473   AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
11474   AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
11475
11476   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
11477   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
11478 }
11479
11480 SDValue X86TargetLowering::LowerSDIV(SDValue Op, SelectionDAG &DAG) const {
11481   EVT VT = Op.getValueType();
11482   EVT EltTy = VT.getVectorElementType();
11483   unsigned NumElts = VT.getVectorNumElements();
11484   SDValue N0 = Op.getOperand(0);
11485   DebugLoc dl = Op.getDebugLoc();
11486
11487   // Lower sdiv X, pow2-const.
11488   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(Op.getOperand(1));
11489   if (!C)
11490     return SDValue();
11491
11492   APInt SplatValue, SplatUndef;
11493   unsigned MinSplatBits;
11494   bool HasAnyUndefs;
11495   if (!C->isConstantSplat(SplatValue, SplatUndef, MinSplatBits, HasAnyUndefs))
11496     return SDValue();
11497
11498   if ((SplatValue != 0) &&
11499       (SplatValue.isPowerOf2() || (-SplatValue).isPowerOf2())) {
11500     unsigned lg2 = SplatValue.countTrailingZeros();
11501     // Splat the sign bit.
11502     SDValue Sz = DAG.getConstant(EltTy.getSizeInBits()-1, MVT::i32);
11503     SDValue SGN = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, N0, Sz, DAG);
11504     // Add (N0 < 0) ? abs2 - 1 : 0;
11505     SDValue Amt = DAG.getConstant(EltTy.getSizeInBits() - lg2, MVT::i32);
11506     SDValue SRL = getTargetVShiftNode(X86ISD::VSRLI, dl, VT, SGN, Amt, DAG);
11507     SDValue ADD = DAG.getNode(ISD::ADD, dl, VT, N0, SRL);
11508     SDValue Lg2Amt = DAG.getConstant(lg2, MVT::i32);
11509     SDValue SRA = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, ADD, Lg2Amt, DAG);
11510
11511     // If we're dividing by a positive value, we're done.  Otherwise, we must
11512     // negate the result.
11513     if (SplatValue.isNonNegative())
11514       return SRA;
11515
11516     SmallVector<SDValue, 16> V(NumElts, DAG.getConstant(0, EltTy));
11517     SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], NumElts);
11518     return DAG.getNode(ISD::SUB, dl, VT, Zero, SRA);
11519   }
11520   return SDValue();
11521 }
11522
11523 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
11524                                          const X86Subtarget *Subtarget) {
11525   EVT VT = Op.getValueType();
11526   DebugLoc dl = Op.getDebugLoc();
11527   SDValue R = Op.getOperand(0);
11528   SDValue Amt = Op.getOperand(1);
11529
11530   // Optimize shl/srl/sra with constant shift amount.
11531   if (isSplatVector(Amt.getNode())) {
11532     SDValue SclrAmt = Amt->getOperand(0);
11533     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
11534       uint64_t ShiftAmt = C->getZExtValue();
11535
11536       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
11537           (Subtarget->hasInt256() &&
11538            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
11539         if (Op.getOpcode() == ISD::SHL)
11540           return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
11541                              DAG.getConstant(ShiftAmt, MVT::i32));
11542         if (Op.getOpcode() == ISD::SRL)
11543           return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
11544                              DAG.getConstant(ShiftAmt, MVT::i32));
11545         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
11546           return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
11547                              DAG.getConstant(ShiftAmt, MVT::i32));
11548       }
11549
11550       if (VT == MVT::v16i8) {
11551         if (Op.getOpcode() == ISD::SHL) {
11552           // Make a large shift.
11553           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
11554                                     DAG.getConstant(ShiftAmt, MVT::i32));
11555           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11556           // Zero out the rightmost bits.
11557           SmallVector<SDValue, 16> V(16,
11558                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
11559                                                      MVT::i8));
11560           return DAG.getNode(ISD::AND, dl, VT, SHL,
11561                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11562         }
11563         if (Op.getOpcode() == ISD::SRL) {
11564           // Make a large shift.
11565           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
11566                                     DAG.getConstant(ShiftAmt, MVT::i32));
11567           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11568           // Zero out the leftmost bits.
11569           SmallVector<SDValue, 16> V(16,
11570                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11571                                                      MVT::i8));
11572           return DAG.getNode(ISD::AND, dl, VT, SRL,
11573                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11574         }
11575         if (Op.getOpcode() == ISD::SRA) {
11576           if (ShiftAmt == 7) {
11577             // R s>> 7  ===  R s< 0
11578             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11579             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11580           }
11581
11582           // R s>> a === ((R u>> a) ^ m) - m
11583           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11584           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
11585                                                          MVT::i8));
11586           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
11587           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11588           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11589           return Res;
11590         }
11591         llvm_unreachable("Unknown shift opcode.");
11592       }
11593
11594       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
11595         if (Op.getOpcode() == ISD::SHL) {
11596           // Make a large shift.
11597           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
11598                                     DAG.getConstant(ShiftAmt, MVT::i32));
11599           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11600           // Zero out the rightmost bits.
11601           SmallVector<SDValue, 32> V(32,
11602                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
11603                                                      MVT::i8));
11604           return DAG.getNode(ISD::AND, dl, VT, SHL,
11605                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11606         }
11607         if (Op.getOpcode() == ISD::SRL) {
11608           // Make a large shift.
11609           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
11610                                     DAG.getConstant(ShiftAmt, MVT::i32));
11611           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11612           // Zero out the leftmost bits.
11613           SmallVector<SDValue, 32> V(32,
11614                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11615                                                      MVT::i8));
11616           return DAG.getNode(ISD::AND, dl, VT, SRL,
11617                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11618         }
11619         if (Op.getOpcode() == ISD::SRA) {
11620           if (ShiftAmt == 7) {
11621             // R s>> 7  ===  R s< 0
11622             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11623             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11624           }
11625
11626           // R s>> a === ((R u>> a) ^ m) - m
11627           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11628           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
11629                                                          MVT::i8));
11630           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
11631           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11632           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11633           return Res;
11634         }
11635         llvm_unreachable("Unknown shift opcode.");
11636       }
11637     }
11638   }
11639
11640   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
11641   if (!Subtarget->is64Bit() &&
11642       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
11643       Amt.getOpcode() == ISD::BITCAST &&
11644       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
11645     Amt = Amt.getOperand(0);
11646     unsigned Ratio = Amt.getValueType().getVectorNumElements() /
11647                      VT.getVectorNumElements();
11648     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
11649     uint64_t ShiftAmt = 0;
11650     for (unsigned i = 0; i != Ratio; ++i) {
11651       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
11652       if (C == 0)
11653         return SDValue();
11654       // 6 == Log2(64)
11655       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
11656     }
11657     // Check remaining shift amounts.
11658     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
11659       uint64_t ShAmt = 0;
11660       for (unsigned j = 0; j != Ratio; ++j) {
11661         ConstantSDNode *C =
11662           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
11663         if (C == 0)
11664           return SDValue();
11665         // 6 == Log2(64)
11666         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
11667       }
11668       if (ShAmt != ShiftAmt)
11669         return SDValue();
11670     }
11671     switch (Op.getOpcode()) {
11672     default:
11673       llvm_unreachable("Unknown shift opcode!");
11674     case ISD::SHL:
11675       return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
11676                          DAG.getConstant(ShiftAmt, MVT::i32));
11677     case ISD::SRL:
11678       return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
11679                          DAG.getConstant(ShiftAmt, MVT::i32));
11680     case ISD::SRA:
11681       return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
11682                          DAG.getConstant(ShiftAmt, MVT::i32));
11683     }
11684   }
11685
11686   return SDValue();
11687 }
11688
11689 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
11690                                         const X86Subtarget* Subtarget) {
11691   EVT VT = Op.getValueType();
11692   DebugLoc dl = Op.getDebugLoc();
11693   SDValue R = Op.getOperand(0);
11694   SDValue Amt = Op.getOperand(1);
11695
11696   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
11697       VT == MVT::v4i32 || VT == MVT::v8i16 ||
11698       (Subtarget->hasInt256() &&
11699        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
11700         VT == MVT::v8i32 || VT == MVT::v16i16))) {
11701     SDValue BaseShAmt;
11702     EVT EltVT = VT.getVectorElementType();
11703
11704     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
11705       unsigned NumElts = VT.getVectorNumElements();
11706       unsigned i, j;
11707       for (i = 0; i != NumElts; ++i) {
11708         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
11709           continue;
11710         break;
11711       }
11712       for (j = i; j != NumElts; ++j) {
11713         SDValue Arg = Amt.getOperand(j);
11714         if (Arg.getOpcode() == ISD::UNDEF) continue;
11715         if (Arg != Amt.getOperand(i))
11716           break;
11717       }
11718       if (i != NumElts && j == NumElts)
11719         BaseShAmt = Amt.getOperand(i);
11720     } else {
11721       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
11722         Amt = Amt.getOperand(0);
11723       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
11724                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
11725         SDValue InVec = Amt.getOperand(0);
11726         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
11727           unsigned NumElts = InVec.getValueType().getVectorNumElements();
11728           unsigned i = 0;
11729           for (; i != NumElts; ++i) {
11730             SDValue Arg = InVec.getOperand(i);
11731             if (Arg.getOpcode() == ISD::UNDEF) continue;
11732             BaseShAmt = Arg;
11733             break;
11734           }
11735         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
11736            if (ConstantSDNode *C =
11737                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
11738              unsigned SplatIdx =
11739                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
11740              if (C->getZExtValue() == SplatIdx)
11741                BaseShAmt = InVec.getOperand(1);
11742            }
11743         }
11744         if (BaseShAmt.getNode() == 0)
11745           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
11746                                   DAG.getIntPtrConstant(0));
11747       }
11748     }
11749
11750     if (BaseShAmt.getNode()) {
11751       if (EltVT.bitsGT(MVT::i32))
11752         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
11753       else if (EltVT.bitsLT(MVT::i32))
11754         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
11755
11756       switch (Op.getOpcode()) {
11757       default:
11758         llvm_unreachable("Unknown shift opcode!");
11759       case ISD::SHL:
11760         switch (VT.getSimpleVT().SimpleTy) {
11761         default: return SDValue();
11762         case MVT::v2i64:
11763         case MVT::v4i32:
11764         case MVT::v8i16:
11765         case MVT::v4i64:
11766         case MVT::v8i32:
11767         case MVT::v16i16:
11768           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
11769         }
11770       case ISD::SRA:
11771         switch (VT.getSimpleVT().SimpleTy) {
11772         default: return SDValue();
11773         case MVT::v4i32:
11774         case MVT::v8i16:
11775         case MVT::v8i32:
11776         case MVT::v16i16:
11777           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
11778         }
11779       case ISD::SRL:
11780         switch (VT.getSimpleVT().SimpleTy) {
11781         default: return SDValue();
11782         case MVT::v2i64:
11783         case MVT::v4i32:
11784         case MVT::v8i16:
11785         case MVT::v4i64:
11786         case MVT::v8i32:
11787         case MVT::v16i16:
11788           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
11789         }
11790       }
11791     }
11792   }
11793
11794   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
11795   if (!Subtarget->is64Bit() &&
11796       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
11797       Amt.getOpcode() == ISD::BITCAST &&
11798       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
11799     Amt = Amt.getOperand(0);
11800     unsigned Ratio = Amt.getValueType().getVectorNumElements() /
11801                      VT.getVectorNumElements();
11802     std::vector<SDValue> Vals(Ratio);
11803     for (unsigned i = 0; i != Ratio; ++i)
11804       Vals[i] = Amt.getOperand(i);
11805     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
11806       for (unsigned j = 0; j != Ratio; ++j)
11807         if (Vals[j] != Amt.getOperand(i + j))
11808           return SDValue();
11809     }
11810     switch (Op.getOpcode()) {
11811     default:
11812       llvm_unreachable("Unknown shift opcode!");
11813     case ISD::SHL:
11814       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
11815     case ISD::SRL:
11816       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
11817     case ISD::SRA:
11818       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
11819     }
11820   }
11821
11822   return SDValue();
11823 }
11824
11825 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
11826
11827   EVT VT = Op.getValueType();
11828   DebugLoc dl = Op.getDebugLoc();
11829   SDValue R = Op.getOperand(0);
11830   SDValue Amt = Op.getOperand(1);
11831   SDValue V;
11832
11833   if (!Subtarget->hasSSE2())
11834     return SDValue();
11835
11836   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
11837   if (V.getNode())
11838     return V;
11839
11840   V = LowerScalarVariableShift(Op, DAG, Subtarget);
11841   if (V.getNode())
11842       return V;
11843
11844   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
11845   if (Subtarget->hasInt256()) {
11846     if (Op.getOpcode() == ISD::SRL &&
11847         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
11848          VT == MVT::v4i64 || VT == MVT::v8i32))
11849       return Op;
11850     if (Op.getOpcode() == ISD::SHL &&
11851         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
11852          VT == MVT::v4i64 || VT == MVT::v8i32))
11853       return Op;
11854     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
11855       return Op;
11856   }
11857
11858   // Lower SHL with variable shift amount.
11859   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
11860     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
11861
11862     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
11863     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
11864     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
11865     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
11866   }
11867   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
11868     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
11869
11870     // a = a << 5;
11871     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
11872     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
11873
11874     // Turn 'a' into a mask suitable for VSELECT
11875     SDValue VSelM = DAG.getConstant(0x80, VT);
11876     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11877     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11878
11879     SDValue CM1 = DAG.getConstant(0x0f, VT);
11880     SDValue CM2 = DAG.getConstant(0x3f, VT);
11881
11882     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
11883     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
11884     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11885                             DAG.getConstant(4, MVT::i32), DAG);
11886     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11887     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11888
11889     // a += a
11890     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11891     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11892     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11893
11894     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
11895     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
11896     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11897                             DAG.getConstant(2, MVT::i32), DAG);
11898     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11899     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11900
11901     // a += a
11902     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11903     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11904     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11905
11906     // return VSELECT(r, r+r, a);
11907     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
11908                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
11909     return R;
11910   }
11911
11912   // Decompose 256-bit shifts into smaller 128-bit shifts.
11913   if (VT.is256BitVector()) {
11914     unsigned NumElems = VT.getVectorNumElements();
11915     MVT EltVT = VT.getVectorElementType().getSimpleVT();
11916     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11917
11918     // Extract the two vectors
11919     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
11920     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
11921
11922     // Recreate the shift amount vectors
11923     SDValue Amt1, Amt2;
11924     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
11925       // Constant shift amount
11926       SmallVector<SDValue, 4> Amt1Csts;
11927       SmallVector<SDValue, 4> Amt2Csts;
11928       for (unsigned i = 0; i != NumElems/2; ++i)
11929         Amt1Csts.push_back(Amt->getOperand(i));
11930       for (unsigned i = NumElems/2; i != NumElems; ++i)
11931         Amt2Csts.push_back(Amt->getOperand(i));
11932
11933       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11934                                  &Amt1Csts[0], NumElems/2);
11935       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11936                                  &Amt2Csts[0], NumElems/2);
11937     } else {
11938       // Variable shift amount
11939       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
11940       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
11941     }
11942
11943     // Issue new vector shifts for the smaller types
11944     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
11945     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
11946
11947     // Concatenate the result back
11948     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
11949   }
11950
11951   return SDValue();
11952 }
11953
11954 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
11955   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
11956   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
11957   // looks for this combo and may remove the "setcc" instruction if the "setcc"
11958   // has only one use.
11959   SDNode *N = Op.getNode();
11960   SDValue LHS = N->getOperand(0);
11961   SDValue RHS = N->getOperand(1);
11962   unsigned BaseOp = 0;
11963   unsigned Cond = 0;
11964   DebugLoc DL = Op.getDebugLoc();
11965   switch (Op.getOpcode()) {
11966   default: llvm_unreachable("Unknown ovf instruction!");
11967   case ISD::SADDO:
11968     // A subtract of one will be selected as a INC. Note that INC doesn't
11969     // set CF, so we can't do this for UADDO.
11970     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11971       if (C->isOne()) {
11972         BaseOp = X86ISD::INC;
11973         Cond = X86::COND_O;
11974         break;
11975       }
11976     BaseOp = X86ISD::ADD;
11977     Cond = X86::COND_O;
11978     break;
11979   case ISD::UADDO:
11980     BaseOp = X86ISD::ADD;
11981     Cond = X86::COND_B;
11982     break;
11983   case ISD::SSUBO:
11984     // A subtract of one will be selected as a DEC. Note that DEC doesn't
11985     // set CF, so we can't do this for USUBO.
11986     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11987       if (C->isOne()) {
11988         BaseOp = X86ISD::DEC;
11989         Cond = X86::COND_O;
11990         break;
11991       }
11992     BaseOp = X86ISD::SUB;
11993     Cond = X86::COND_O;
11994     break;
11995   case ISD::USUBO:
11996     BaseOp = X86ISD::SUB;
11997     Cond = X86::COND_B;
11998     break;
11999   case ISD::SMULO:
12000     BaseOp = X86ISD::SMUL;
12001     Cond = X86::COND_O;
12002     break;
12003   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
12004     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
12005                                  MVT::i32);
12006     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
12007
12008     SDValue SetCC =
12009       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
12010                   DAG.getConstant(X86::COND_O, MVT::i32),
12011                   SDValue(Sum.getNode(), 2));
12012
12013     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
12014   }
12015   }
12016
12017   // Also sets EFLAGS.
12018   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
12019   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
12020
12021   SDValue SetCC =
12022     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
12023                 DAG.getConstant(Cond, MVT::i32),
12024                 SDValue(Sum.getNode(), 1));
12025
12026   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
12027 }
12028
12029 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
12030                                                   SelectionDAG &DAG) const {
12031   DebugLoc dl = Op.getDebugLoc();
12032   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
12033   EVT VT = Op.getValueType();
12034
12035   if (!Subtarget->hasSSE2() || !VT.isVector())
12036     return SDValue();
12037
12038   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
12039                       ExtraVT.getScalarType().getSizeInBits();
12040   SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
12041
12042   switch (VT.getSimpleVT().SimpleTy) {
12043     default: return SDValue();
12044     case MVT::v8i32:
12045     case MVT::v16i16:
12046       if (!Subtarget->hasFp256())
12047         return SDValue();
12048       if (!Subtarget->hasInt256()) {
12049         // needs to be split
12050         unsigned NumElems = VT.getVectorNumElements();
12051
12052         // Extract the LHS vectors
12053         SDValue LHS = Op.getOperand(0);
12054         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12055         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12056
12057         MVT EltVT = VT.getVectorElementType().getSimpleVT();
12058         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12059
12060         EVT ExtraEltVT = ExtraVT.getVectorElementType();
12061         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
12062         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
12063                                    ExtraNumElems/2);
12064         SDValue Extra = DAG.getValueType(ExtraVT);
12065
12066         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
12067         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
12068
12069         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
12070       }
12071       // fall through
12072     case MVT::v4i32:
12073     case MVT::v8i16: {
12074       // (sext (vzext x)) -> (vsext x)
12075       SDValue Op0 = Op.getOperand(0);
12076       SDValue Op00 = Op0.getOperand(0);
12077       SDValue Tmp1;
12078       // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
12079       if (Op0.getOpcode() == ISD::BITCAST &&
12080           Op00.getOpcode() == ISD::VECTOR_SHUFFLE)
12081         Tmp1 = LowerVectorIntExtend(Op00, DAG);
12082       if (Tmp1.getNode()) {
12083         SDValue Tmp1Op0 = Tmp1.getOperand(0);
12084         assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
12085                "This optimization is invalid without a VZEXT.");
12086         return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
12087       }
12088
12089       // If the above didn't work, then just use Shift-Left + Shift-Right.
12090       Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT, Op0, ShAmt, DAG);
12091       return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
12092     }
12093   }
12094 }
12095
12096 static SDValue LowerMEMBARRIER(SDValue Op, const X86Subtarget *Subtarget,
12097                               SelectionDAG &DAG) {
12098   DebugLoc dl = Op.getDebugLoc();
12099
12100   // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
12101   // There isn't any reason to disable it if the target processor supports it.
12102   if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
12103     SDValue Chain = Op.getOperand(0);
12104     SDValue Zero = DAG.getConstant(0, MVT::i32);
12105     SDValue Ops[] = {
12106       DAG.getRegister(X86::ESP, MVT::i32), // Base
12107       DAG.getTargetConstant(1, MVT::i8),   // Scale
12108       DAG.getRegister(0, MVT::i32),        // Index
12109       DAG.getTargetConstant(0, MVT::i32),  // Disp
12110       DAG.getRegister(0, MVT::i32),        // Segment.
12111       Zero,
12112       Chain
12113     };
12114     SDNode *Res =
12115       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
12116                           array_lengthof(Ops));
12117     return SDValue(Res, 0);
12118   }
12119
12120   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
12121   if (!isDev)
12122     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
12123
12124   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12125   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
12126   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
12127   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
12128
12129   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
12130   if (!Op1 && !Op2 && !Op3 && Op4)
12131     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
12132
12133   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
12134   if (Op1 && !Op2 && !Op3 && !Op4)
12135     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
12136
12137   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
12138   //           (MFENCE)>;
12139   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
12140 }
12141
12142 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
12143                                  SelectionDAG &DAG) {
12144   DebugLoc dl = Op.getDebugLoc();
12145   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
12146     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
12147   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
12148     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
12149
12150   // The only fence that needs an instruction is a sequentially-consistent
12151   // cross-thread fence.
12152   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
12153     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
12154     // no-sse2). There isn't any reason to disable it if the target processor
12155     // supports it.
12156     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
12157       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
12158
12159     SDValue Chain = Op.getOperand(0);
12160     SDValue Zero = DAG.getConstant(0, MVT::i32);
12161     SDValue Ops[] = {
12162       DAG.getRegister(X86::ESP, MVT::i32), // Base
12163       DAG.getTargetConstant(1, MVT::i8),   // Scale
12164       DAG.getRegister(0, MVT::i32),        // Index
12165       DAG.getTargetConstant(0, MVT::i32),  // Disp
12166       DAG.getRegister(0, MVT::i32),        // Segment.
12167       Zero,
12168       Chain
12169     };
12170     SDNode *Res =
12171       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
12172                          array_lengthof(Ops));
12173     return SDValue(Res, 0);
12174   }
12175
12176   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
12177   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
12178 }
12179
12180 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
12181                              SelectionDAG &DAG) {
12182   EVT T = Op.getValueType();
12183   DebugLoc DL = Op.getDebugLoc();
12184   unsigned Reg = 0;
12185   unsigned size = 0;
12186   switch(T.getSimpleVT().SimpleTy) {
12187   default: llvm_unreachable("Invalid value type!");
12188   case MVT::i8:  Reg = X86::AL;  size = 1; break;
12189   case MVT::i16: Reg = X86::AX;  size = 2; break;
12190   case MVT::i32: Reg = X86::EAX; size = 4; break;
12191   case MVT::i64:
12192     assert(Subtarget->is64Bit() && "Node not type legal!");
12193     Reg = X86::RAX; size = 8;
12194     break;
12195   }
12196   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
12197                                     Op.getOperand(2), SDValue());
12198   SDValue Ops[] = { cpIn.getValue(0),
12199                     Op.getOperand(1),
12200                     Op.getOperand(3),
12201                     DAG.getTargetConstant(size, MVT::i8),
12202                     cpIn.getValue(1) };
12203   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12204   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
12205   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
12206                                            Ops, 5, T, MMO);
12207   SDValue cpOut =
12208     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
12209   return cpOut;
12210 }
12211
12212 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
12213                                      SelectionDAG &DAG) {
12214   assert(Subtarget->is64Bit() && "Result not type legalized?");
12215   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12216   SDValue TheChain = Op.getOperand(0);
12217   DebugLoc dl = Op.getDebugLoc();
12218   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
12219   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
12220   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
12221                                    rax.getValue(2));
12222   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
12223                             DAG.getConstant(32, MVT::i8));
12224   SDValue Ops[] = {
12225     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
12226     rdx.getValue(1)
12227   };
12228   return DAG.getMergeValues(Ops, 2, dl);
12229 }
12230
12231 SDValue X86TargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
12232   EVT SrcVT = Op.getOperand(0).getValueType();
12233   EVT DstVT = Op.getValueType();
12234   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
12235          Subtarget->hasMMX() && "Unexpected custom BITCAST");
12236   assert((DstVT == MVT::i64 ||
12237           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
12238          "Unexpected custom BITCAST");
12239   // i64 <=> MMX conversions are Legal.
12240   if (SrcVT==MVT::i64 && DstVT.isVector())
12241     return Op;
12242   if (DstVT==MVT::i64 && SrcVT.isVector())
12243     return Op;
12244   // MMX <=> MMX conversions are Legal.
12245   if (SrcVT.isVector() && DstVT.isVector())
12246     return Op;
12247   // All other conversions need to be expanded.
12248   return SDValue();
12249 }
12250
12251 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
12252   SDNode *Node = Op.getNode();
12253   DebugLoc dl = Node->getDebugLoc();
12254   EVT T = Node->getValueType(0);
12255   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
12256                               DAG.getConstant(0, T), Node->getOperand(2));
12257   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
12258                        cast<AtomicSDNode>(Node)->getMemoryVT(),
12259                        Node->getOperand(0),
12260                        Node->getOperand(1), negOp,
12261                        cast<AtomicSDNode>(Node)->getSrcValue(),
12262                        cast<AtomicSDNode>(Node)->getAlignment(),
12263                        cast<AtomicSDNode>(Node)->getOrdering(),
12264                        cast<AtomicSDNode>(Node)->getSynchScope());
12265 }
12266
12267 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
12268   SDNode *Node = Op.getNode();
12269   DebugLoc dl = Node->getDebugLoc();
12270   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
12271
12272   // Convert seq_cst store -> xchg
12273   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
12274   // FIXME: On 32-bit, store -> fist or movq would be more efficient
12275   //        (The only way to get a 16-byte store is cmpxchg16b)
12276   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
12277   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
12278       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
12279     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
12280                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
12281                                  Node->getOperand(0),
12282                                  Node->getOperand(1), Node->getOperand(2),
12283                                  cast<AtomicSDNode>(Node)->getMemOperand(),
12284                                  cast<AtomicSDNode>(Node)->getOrdering(),
12285                                  cast<AtomicSDNode>(Node)->getSynchScope());
12286     return Swap.getValue(1);
12287   }
12288   // Other atomic stores have a simple pattern.
12289   return Op;
12290 }
12291
12292 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
12293   EVT VT = Op.getNode()->getValueType(0);
12294
12295   // Let legalize expand this if it isn't a legal type yet.
12296   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
12297     return SDValue();
12298
12299   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
12300
12301   unsigned Opc;
12302   bool ExtraOp = false;
12303   switch (Op.getOpcode()) {
12304   default: llvm_unreachable("Invalid code");
12305   case ISD::ADDC: Opc = X86ISD::ADD; break;
12306   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
12307   case ISD::SUBC: Opc = X86ISD::SUB; break;
12308   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
12309   }
12310
12311   if (!ExtraOp)
12312     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
12313                        Op.getOperand(1));
12314   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
12315                      Op.getOperand(1), Op.getOperand(2));
12316 }
12317
12318 SDValue X86TargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
12319   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
12320
12321   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
12322   // which returns the values as { float, float } (in XMM0) or
12323   // { double, double } (which is returned in XMM0, XMM1).
12324   DebugLoc dl = Op.getDebugLoc();
12325   SDValue Arg = Op.getOperand(0);
12326   EVT ArgVT = Arg.getValueType();
12327   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
12328
12329   ArgListTy Args;
12330   ArgListEntry Entry;
12331
12332   Entry.Node = Arg;
12333   Entry.Ty = ArgTy;
12334   Entry.isSExt = false;
12335   Entry.isZExt = false;
12336   Args.push_back(Entry);
12337
12338   bool isF64 = ArgVT == MVT::f64;
12339   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
12340   // the small struct {f32, f32} is returned in (eax, edx). For f64,
12341   // the results are returned via SRet in memory.
12342   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
12343   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
12344
12345   Type *RetTy = isF64
12346     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
12347     : (Type*)VectorType::get(ArgTy, 4);
12348   TargetLowering::
12349     CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
12350                          false, false, false, false, 0,
12351                          CallingConv::C, /*isTaillCall=*/false,
12352                          /*doesNotRet=*/false, /*isReturnValueUsed*/true,
12353                          Callee, Args, DAG, dl);
12354   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
12355
12356   if (isF64)
12357     // Returned in xmm0 and xmm1.
12358     return CallResult.first;
12359
12360   // Returned in bits 0:31 and 32:64 xmm0.
12361   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
12362                                CallResult.first, DAG.getIntPtrConstant(0));
12363   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
12364                                CallResult.first, DAG.getIntPtrConstant(1));
12365   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
12366   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
12367 }
12368
12369 /// LowerOperation - Provide custom lowering hooks for some operations.
12370 ///
12371 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
12372   switch (Op.getOpcode()) {
12373   default: llvm_unreachable("Should not custom lower this!");
12374   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
12375   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op, Subtarget, DAG);
12376   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
12377   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
12378   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
12379   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
12380   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
12381   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
12382   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
12383   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
12384   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
12385   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
12386   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
12387   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
12388   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
12389   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
12390   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
12391   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
12392   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
12393   case ISD::SHL_PARTS:
12394   case ISD::SRA_PARTS:
12395   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
12396   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
12397   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
12398   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
12399   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, DAG);
12400   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, DAG);
12401   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, DAG);
12402   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
12403   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
12404   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
12405   case ISD::FABS:               return LowerFABS(Op, DAG);
12406   case ISD::FNEG:               return LowerFNEG(Op, DAG);
12407   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
12408   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
12409   case ISD::SETCC:              return LowerSETCC(Op, DAG);
12410   case ISD::SELECT:             return LowerSELECT(Op, DAG);
12411   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
12412   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
12413   case ISD::VASTART:            return LowerVASTART(Op, DAG);
12414   case ISD::VAARG:              return LowerVAARG(Op, DAG);
12415   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
12416   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
12417   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, DAG);
12418   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
12419   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
12420   case ISD::FRAME_TO_ARGS_OFFSET:
12421                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
12422   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
12423   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
12424   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
12425   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
12426   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
12427   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
12428   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
12429   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
12430   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
12431   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
12432   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
12433   case ISD::SRA:
12434   case ISD::SRL:
12435   case ISD::SHL:                return LowerShift(Op, DAG);
12436   case ISD::SADDO:
12437   case ISD::UADDO:
12438   case ISD::SSUBO:
12439   case ISD::USUBO:
12440   case ISD::SMULO:
12441   case ISD::UMULO:              return LowerXALUO(Op, DAG);
12442   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
12443   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
12444   case ISD::ADDC:
12445   case ISD::ADDE:
12446   case ISD::SUBC:
12447   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
12448   case ISD::ADD:                return LowerADD(Op, DAG);
12449   case ISD::SUB:                return LowerSUB(Op, DAG);
12450   case ISD::SDIV:               return LowerSDIV(Op, DAG);
12451   case ISD::FSINCOS:            return LowerFSINCOS(Op, DAG);
12452   }
12453 }
12454
12455 static void ReplaceATOMIC_LOAD(SDNode *Node,
12456                                   SmallVectorImpl<SDValue> &Results,
12457                                   SelectionDAG &DAG) {
12458   DebugLoc dl = Node->getDebugLoc();
12459   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
12460
12461   // Convert wide load -> cmpxchg8b/cmpxchg16b
12462   // FIXME: On 32-bit, load -> fild or movq would be more efficient
12463   //        (The only way to get a 16-byte load is cmpxchg16b)
12464   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
12465   SDValue Zero = DAG.getConstant(0, VT);
12466   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
12467                                Node->getOperand(0),
12468                                Node->getOperand(1), Zero, Zero,
12469                                cast<AtomicSDNode>(Node)->getMemOperand(),
12470                                cast<AtomicSDNode>(Node)->getOrdering(),
12471                                cast<AtomicSDNode>(Node)->getSynchScope());
12472   Results.push_back(Swap.getValue(0));
12473   Results.push_back(Swap.getValue(1));
12474 }
12475
12476 static void
12477 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
12478                         SelectionDAG &DAG, unsigned NewOp) {
12479   DebugLoc dl = Node->getDebugLoc();
12480   assert (Node->getValueType(0) == MVT::i64 &&
12481           "Only know how to expand i64 atomics");
12482
12483   SDValue Chain = Node->getOperand(0);
12484   SDValue In1 = Node->getOperand(1);
12485   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
12486                              Node->getOperand(2), DAG.getIntPtrConstant(0));
12487   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
12488                              Node->getOperand(2), DAG.getIntPtrConstant(1));
12489   SDValue Ops[] = { Chain, In1, In2L, In2H };
12490   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
12491   SDValue Result =
12492     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
12493                             cast<MemSDNode>(Node)->getMemOperand());
12494   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
12495   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
12496   Results.push_back(Result.getValue(2));
12497 }
12498
12499 /// ReplaceNodeResults - Replace a node with an illegal result type
12500 /// with a new node built out of custom code.
12501 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
12502                                            SmallVectorImpl<SDValue>&Results,
12503                                            SelectionDAG &DAG) const {
12504   DebugLoc dl = N->getDebugLoc();
12505   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12506   switch (N->getOpcode()) {
12507   default:
12508     llvm_unreachable("Do not know how to custom type legalize this operation!");
12509   case ISD::SIGN_EXTEND_INREG:
12510   case ISD::ADDC:
12511   case ISD::ADDE:
12512   case ISD::SUBC:
12513   case ISD::SUBE:
12514     // We don't want to expand or promote these.
12515     return;
12516   case ISD::FP_TO_SINT:
12517   case ISD::FP_TO_UINT: {
12518     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
12519
12520     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
12521       return;
12522
12523     std::pair<SDValue,SDValue> Vals =
12524         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
12525     SDValue FIST = Vals.first, StackSlot = Vals.second;
12526     if (FIST.getNode() != 0) {
12527       EVT VT = N->getValueType(0);
12528       // Return a load from the stack slot.
12529       if (StackSlot.getNode() != 0)
12530         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
12531                                       MachinePointerInfo(),
12532                                       false, false, false, 0));
12533       else
12534         Results.push_back(FIST);
12535     }
12536     return;
12537   }
12538   case ISD::UINT_TO_FP: {
12539     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
12540     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
12541         N->getValueType(0) != MVT::v2f32)
12542       return;
12543     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
12544                                  N->getOperand(0));
12545     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
12546                                      MVT::f64);
12547     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
12548     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
12549                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
12550     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
12551     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
12552     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
12553     return;
12554   }
12555   case ISD::FP_ROUND: {
12556     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
12557         return;
12558     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
12559     Results.push_back(V);
12560     return;
12561   }
12562   case ISD::READCYCLECOUNTER: {
12563     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12564     SDValue TheChain = N->getOperand(0);
12565     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
12566     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
12567                                      rd.getValue(1));
12568     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
12569                                      eax.getValue(2));
12570     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
12571     SDValue Ops[] = { eax, edx };
12572     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
12573     Results.push_back(edx.getValue(1));
12574     return;
12575   }
12576   case ISD::ATOMIC_CMP_SWAP: {
12577     EVT T = N->getValueType(0);
12578     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
12579     bool Regs64bit = T == MVT::i128;
12580     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
12581     SDValue cpInL, cpInH;
12582     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
12583                         DAG.getConstant(0, HalfT));
12584     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
12585                         DAG.getConstant(1, HalfT));
12586     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
12587                              Regs64bit ? X86::RAX : X86::EAX,
12588                              cpInL, SDValue());
12589     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
12590                              Regs64bit ? X86::RDX : X86::EDX,
12591                              cpInH, cpInL.getValue(1));
12592     SDValue swapInL, swapInH;
12593     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
12594                           DAG.getConstant(0, HalfT));
12595     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
12596                           DAG.getConstant(1, HalfT));
12597     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
12598                                Regs64bit ? X86::RBX : X86::EBX,
12599                                swapInL, cpInH.getValue(1));
12600     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
12601                                Regs64bit ? X86::RCX : X86::ECX,
12602                                swapInH, swapInL.getValue(1));
12603     SDValue Ops[] = { swapInH.getValue(0),
12604                       N->getOperand(1),
12605                       swapInH.getValue(1) };
12606     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12607     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
12608     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
12609                                   X86ISD::LCMPXCHG8_DAG;
12610     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
12611                                              Ops, 3, T, MMO);
12612     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
12613                                         Regs64bit ? X86::RAX : X86::EAX,
12614                                         HalfT, Result.getValue(1));
12615     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
12616                                         Regs64bit ? X86::RDX : X86::EDX,
12617                                         HalfT, cpOutL.getValue(2));
12618     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
12619     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
12620     Results.push_back(cpOutH.getValue(1));
12621     return;
12622   }
12623   case ISD::ATOMIC_LOAD_ADD:
12624   case ISD::ATOMIC_LOAD_AND:
12625   case ISD::ATOMIC_LOAD_NAND:
12626   case ISD::ATOMIC_LOAD_OR:
12627   case ISD::ATOMIC_LOAD_SUB:
12628   case ISD::ATOMIC_LOAD_XOR:
12629   case ISD::ATOMIC_LOAD_MAX:
12630   case ISD::ATOMIC_LOAD_MIN:
12631   case ISD::ATOMIC_LOAD_UMAX:
12632   case ISD::ATOMIC_LOAD_UMIN:
12633   case ISD::ATOMIC_SWAP: {
12634     unsigned Opc;
12635     switch (N->getOpcode()) {
12636     default: llvm_unreachable("Unexpected opcode");
12637     case ISD::ATOMIC_LOAD_ADD:
12638       Opc = X86ISD::ATOMADD64_DAG;
12639       break;
12640     case ISD::ATOMIC_LOAD_AND:
12641       Opc = X86ISD::ATOMAND64_DAG;
12642       break;
12643     case ISD::ATOMIC_LOAD_NAND:
12644       Opc = X86ISD::ATOMNAND64_DAG;
12645       break;
12646     case ISD::ATOMIC_LOAD_OR:
12647       Opc = X86ISD::ATOMOR64_DAG;
12648       break;
12649     case ISD::ATOMIC_LOAD_SUB:
12650       Opc = X86ISD::ATOMSUB64_DAG;
12651       break;
12652     case ISD::ATOMIC_LOAD_XOR:
12653       Opc = X86ISD::ATOMXOR64_DAG;
12654       break;
12655     case ISD::ATOMIC_LOAD_MAX:
12656       Opc = X86ISD::ATOMMAX64_DAG;
12657       break;
12658     case ISD::ATOMIC_LOAD_MIN:
12659       Opc = X86ISD::ATOMMIN64_DAG;
12660       break;
12661     case ISD::ATOMIC_LOAD_UMAX:
12662       Opc = X86ISD::ATOMUMAX64_DAG;
12663       break;
12664     case ISD::ATOMIC_LOAD_UMIN:
12665       Opc = X86ISD::ATOMUMIN64_DAG;
12666       break;
12667     case ISD::ATOMIC_SWAP:
12668       Opc = X86ISD::ATOMSWAP64_DAG;
12669       break;
12670     }
12671     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
12672     return;
12673   }
12674   case ISD::ATOMIC_LOAD:
12675     ReplaceATOMIC_LOAD(N, Results, DAG);
12676   }
12677 }
12678
12679 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
12680   switch (Opcode) {
12681   default: return NULL;
12682   case X86ISD::BSF:                return "X86ISD::BSF";
12683   case X86ISD::BSR:                return "X86ISD::BSR";
12684   case X86ISD::SHLD:               return "X86ISD::SHLD";
12685   case X86ISD::SHRD:               return "X86ISD::SHRD";
12686   case X86ISD::FAND:               return "X86ISD::FAND";
12687   case X86ISD::FOR:                return "X86ISD::FOR";
12688   case X86ISD::FXOR:               return "X86ISD::FXOR";
12689   case X86ISD::FSRL:               return "X86ISD::FSRL";
12690   case X86ISD::FILD:               return "X86ISD::FILD";
12691   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
12692   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
12693   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
12694   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
12695   case X86ISD::FLD:                return "X86ISD::FLD";
12696   case X86ISD::FST:                return "X86ISD::FST";
12697   case X86ISD::CALL:               return "X86ISD::CALL";
12698   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
12699   case X86ISD::BT:                 return "X86ISD::BT";
12700   case X86ISD::CMP:                return "X86ISD::CMP";
12701   case X86ISD::COMI:               return "X86ISD::COMI";
12702   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
12703   case X86ISD::SETCC:              return "X86ISD::SETCC";
12704   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
12705   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
12706   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
12707   case X86ISD::CMOV:               return "X86ISD::CMOV";
12708   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
12709   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
12710   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
12711   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
12712   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
12713   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
12714   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
12715   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
12716   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
12717   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
12718   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
12719   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
12720   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
12721   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
12722   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
12723   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
12724   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
12725   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
12726   case X86ISD::HADD:               return "X86ISD::HADD";
12727   case X86ISD::HSUB:               return "X86ISD::HSUB";
12728   case X86ISD::FHADD:              return "X86ISD::FHADD";
12729   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
12730   case X86ISD::UMAX:               return "X86ISD::UMAX";
12731   case X86ISD::UMIN:               return "X86ISD::UMIN";
12732   case X86ISD::SMAX:               return "X86ISD::SMAX";
12733   case X86ISD::SMIN:               return "X86ISD::SMIN";
12734   case X86ISD::FMAX:               return "X86ISD::FMAX";
12735   case X86ISD::FMIN:               return "X86ISD::FMIN";
12736   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
12737   case X86ISD::FMINC:              return "X86ISD::FMINC";
12738   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
12739   case X86ISD::FRCP:               return "X86ISD::FRCP";
12740   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
12741   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
12742   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
12743   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
12744   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
12745   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
12746   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
12747   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
12748   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
12749   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
12750   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
12751   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
12752   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
12753   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
12754   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
12755   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
12756   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
12757   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
12758   case X86ISD::VSEXT_MOVL:         return "X86ISD::VSEXT_MOVL";
12759   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
12760   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
12761   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
12762   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
12763   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
12764   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
12765   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
12766   case X86ISD::VSHL:               return "X86ISD::VSHL";
12767   case X86ISD::VSRL:               return "X86ISD::VSRL";
12768   case X86ISD::VSRA:               return "X86ISD::VSRA";
12769   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
12770   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
12771   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
12772   case X86ISD::CMPP:               return "X86ISD::CMPP";
12773   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
12774   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
12775   case X86ISD::ADD:                return "X86ISD::ADD";
12776   case X86ISD::SUB:                return "X86ISD::SUB";
12777   case X86ISD::ADC:                return "X86ISD::ADC";
12778   case X86ISD::SBB:                return "X86ISD::SBB";
12779   case X86ISD::SMUL:               return "X86ISD::SMUL";
12780   case X86ISD::UMUL:               return "X86ISD::UMUL";
12781   case X86ISD::INC:                return "X86ISD::INC";
12782   case X86ISD::DEC:                return "X86ISD::DEC";
12783   case X86ISD::OR:                 return "X86ISD::OR";
12784   case X86ISD::XOR:                return "X86ISD::XOR";
12785   case X86ISD::AND:                return "X86ISD::AND";
12786   case X86ISD::BLSI:               return "X86ISD::BLSI";
12787   case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
12788   case X86ISD::BLSR:               return "X86ISD::BLSR";
12789   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
12790   case X86ISD::PTEST:              return "X86ISD::PTEST";
12791   case X86ISD::TESTP:              return "X86ISD::TESTP";
12792   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
12793   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
12794   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
12795   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
12796   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
12797   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
12798   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
12799   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
12800   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
12801   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
12802   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
12803   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
12804   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
12805   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
12806   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
12807   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
12808   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
12809   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
12810   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
12811   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
12812   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
12813   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
12814   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
12815   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
12816   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
12817   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
12818   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
12819   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
12820   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
12821   case X86ISD::SAHF:               return "X86ISD::SAHF";
12822   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
12823   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
12824   case X86ISD::FMADD:              return "X86ISD::FMADD";
12825   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
12826   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
12827   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
12828   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
12829   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
12830   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
12831   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
12832   case X86ISD::XTEST:              return "X86ISD::XTEST";
12833   }
12834 }
12835
12836 // isLegalAddressingMode - Return true if the addressing mode represented
12837 // by AM is legal for this target, for a load/store of the specified type.
12838 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
12839                                               Type *Ty) const {
12840   // X86 supports extremely general addressing modes.
12841   CodeModel::Model M = getTargetMachine().getCodeModel();
12842   Reloc::Model R = getTargetMachine().getRelocationModel();
12843
12844   // X86 allows a sign-extended 32-bit immediate field as a displacement.
12845   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
12846     return false;
12847
12848   if (AM.BaseGV) {
12849     unsigned GVFlags =
12850       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
12851
12852     // If a reference to this global requires an extra load, we can't fold it.
12853     if (isGlobalStubReference(GVFlags))
12854       return false;
12855
12856     // If BaseGV requires a register for the PIC base, we cannot also have a
12857     // BaseReg specified.
12858     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
12859       return false;
12860
12861     // If lower 4G is not available, then we must use rip-relative addressing.
12862     if ((M != CodeModel::Small || R != Reloc::Static) &&
12863         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
12864       return false;
12865   }
12866
12867   switch (AM.Scale) {
12868   case 0:
12869   case 1:
12870   case 2:
12871   case 4:
12872   case 8:
12873     // These scales always work.
12874     break;
12875   case 3:
12876   case 5:
12877   case 9:
12878     // These scales are formed with basereg+scalereg.  Only accept if there is
12879     // no basereg yet.
12880     if (AM.HasBaseReg)
12881       return false;
12882     break;
12883   default:  // Other stuff never works.
12884     return false;
12885   }
12886
12887   return true;
12888 }
12889
12890 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
12891   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
12892     return false;
12893   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
12894   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
12895   return NumBits1 > NumBits2;
12896 }
12897
12898 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
12899   return isInt<32>(Imm);
12900 }
12901
12902 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
12903   // Can also use sub to handle negated immediates.
12904   return isInt<32>(Imm);
12905 }
12906
12907 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
12908   if (!VT1.isInteger() || !VT2.isInteger())
12909     return false;
12910   unsigned NumBits1 = VT1.getSizeInBits();
12911   unsigned NumBits2 = VT2.getSizeInBits();
12912   return NumBits1 > NumBits2;
12913 }
12914
12915 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
12916   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12917   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
12918 }
12919
12920 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
12921   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12922   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
12923 }
12924
12925 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
12926   EVT VT1 = Val.getValueType();
12927   if (isZExtFree(VT1, VT2))
12928     return true;
12929
12930   if (Val.getOpcode() != ISD::LOAD)
12931     return false;
12932
12933   if (!VT1.isSimple() || !VT1.isInteger() ||
12934       !VT2.isSimple() || !VT2.isInteger())
12935     return false;
12936
12937   switch (VT1.getSimpleVT().SimpleTy) {
12938   default: break;
12939   case MVT::i8:
12940   case MVT::i16:
12941   case MVT::i32:
12942     // X86 has 8, 16, and 32-bit zero-extending loads.
12943     return true;
12944   }
12945
12946   return false;
12947 }
12948
12949 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
12950   // i16 instructions are longer (0x66 prefix) and potentially slower.
12951   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
12952 }
12953
12954 /// isShuffleMaskLegal - Targets can use this to indicate that they only
12955 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
12956 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
12957 /// are assumed to be legal.
12958 bool
12959 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
12960                                       EVT VT) const {
12961   // Very little shuffling can be done for 64-bit vectors right now.
12962   if (VT.getSizeInBits() == 64)
12963     return false;
12964
12965   // FIXME: pshufb, blends, shifts.
12966   return (VT.getVectorNumElements() == 2 ||
12967           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
12968           isMOVLMask(M, VT) ||
12969           isSHUFPMask(M, VT, Subtarget->hasFp256()) ||
12970           isPSHUFDMask(M, VT) ||
12971           isPSHUFHWMask(M, VT, Subtarget->hasInt256()) ||
12972           isPSHUFLWMask(M, VT, Subtarget->hasInt256()) ||
12973           isPALIGNRMask(M, VT, Subtarget) ||
12974           isUNPCKLMask(M, VT, Subtarget->hasInt256()) ||
12975           isUNPCKHMask(M, VT, Subtarget->hasInt256()) ||
12976           isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasInt256()) ||
12977           isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasInt256()));
12978 }
12979
12980 bool
12981 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
12982                                           EVT VT) const {
12983   unsigned NumElts = VT.getVectorNumElements();
12984   // FIXME: This collection of masks seems suspect.
12985   if (NumElts == 2)
12986     return true;
12987   if (NumElts == 4 && VT.is128BitVector()) {
12988     return (isMOVLMask(Mask, VT)  ||
12989             isCommutedMOVLMask(Mask, VT, true) ||
12990             isSHUFPMask(Mask, VT, Subtarget->hasFp256()) ||
12991             isSHUFPMask(Mask, VT, Subtarget->hasFp256(), /* Commuted */ true));
12992   }
12993   return false;
12994 }
12995
12996 //===----------------------------------------------------------------------===//
12997 //                           X86 Scheduler Hooks
12998 //===----------------------------------------------------------------------===//
12999
13000 /// Utility function to emit xbegin specifying the start of an RTM region.
13001 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
13002                                      const TargetInstrInfo *TII) {
13003   DebugLoc DL = MI->getDebugLoc();
13004
13005   const BasicBlock *BB = MBB->getBasicBlock();
13006   MachineFunction::iterator I = MBB;
13007   ++I;
13008
13009   // For the v = xbegin(), we generate
13010   //
13011   // thisMBB:
13012   //  xbegin sinkMBB
13013   //
13014   // mainMBB:
13015   //  eax = -1
13016   //
13017   // sinkMBB:
13018   //  v = eax
13019
13020   MachineBasicBlock *thisMBB = MBB;
13021   MachineFunction *MF = MBB->getParent();
13022   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13023   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13024   MF->insert(I, mainMBB);
13025   MF->insert(I, sinkMBB);
13026
13027   // Transfer the remainder of BB and its successor edges to sinkMBB.
13028   sinkMBB->splice(sinkMBB->begin(), MBB,
13029                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13030   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13031
13032   // thisMBB:
13033   //  xbegin sinkMBB
13034   //  # fallthrough to mainMBB
13035   //  # abortion to sinkMBB
13036   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
13037   thisMBB->addSuccessor(mainMBB);
13038   thisMBB->addSuccessor(sinkMBB);
13039
13040   // mainMBB:
13041   //  EAX = -1
13042   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
13043   mainMBB->addSuccessor(sinkMBB);
13044
13045   // sinkMBB:
13046   // EAX is live into the sinkMBB
13047   sinkMBB->addLiveIn(X86::EAX);
13048   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13049           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13050     .addReg(X86::EAX);
13051
13052   MI->eraseFromParent();
13053   return sinkMBB;
13054 }
13055
13056 // Get CMPXCHG opcode for the specified data type.
13057 static unsigned getCmpXChgOpcode(EVT VT) {
13058   switch (VT.getSimpleVT().SimpleTy) {
13059   case MVT::i8:  return X86::LCMPXCHG8;
13060   case MVT::i16: return X86::LCMPXCHG16;
13061   case MVT::i32: return X86::LCMPXCHG32;
13062   case MVT::i64: return X86::LCMPXCHG64;
13063   default:
13064     break;
13065   }
13066   llvm_unreachable("Invalid operand size!");
13067 }
13068
13069 // Get LOAD opcode for the specified data type.
13070 static unsigned getLoadOpcode(EVT VT) {
13071   switch (VT.getSimpleVT().SimpleTy) {
13072   case MVT::i8:  return X86::MOV8rm;
13073   case MVT::i16: return X86::MOV16rm;
13074   case MVT::i32: return X86::MOV32rm;
13075   case MVT::i64: return X86::MOV64rm;
13076   default:
13077     break;
13078   }
13079   llvm_unreachable("Invalid operand size!");
13080 }
13081
13082 // Get opcode of the non-atomic one from the specified atomic instruction.
13083 static unsigned getNonAtomicOpcode(unsigned Opc) {
13084   switch (Opc) {
13085   case X86::ATOMAND8:  return X86::AND8rr;
13086   case X86::ATOMAND16: return X86::AND16rr;
13087   case X86::ATOMAND32: return X86::AND32rr;
13088   case X86::ATOMAND64: return X86::AND64rr;
13089   case X86::ATOMOR8:   return X86::OR8rr;
13090   case X86::ATOMOR16:  return X86::OR16rr;
13091   case X86::ATOMOR32:  return X86::OR32rr;
13092   case X86::ATOMOR64:  return X86::OR64rr;
13093   case X86::ATOMXOR8:  return X86::XOR8rr;
13094   case X86::ATOMXOR16: return X86::XOR16rr;
13095   case X86::ATOMXOR32: return X86::XOR32rr;
13096   case X86::ATOMXOR64: return X86::XOR64rr;
13097   }
13098   llvm_unreachable("Unhandled atomic-load-op opcode!");
13099 }
13100
13101 // Get opcode of the non-atomic one from the specified atomic instruction with
13102 // extra opcode.
13103 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
13104                                                unsigned &ExtraOpc) {
13105   switch (Opc) {
13106   case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
13107   case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
13108   case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
13109   case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
13110   case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
13111   case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
13112   case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
13113   case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
13114   case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
13115   case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
13116   case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
13117   case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
13118   case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
13119   case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
13120   case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
13121   case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
13122   case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
13123   case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
13124   case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
13125   case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
13126   }
13127   llvm_unreachable("Unhandled atomic-load-op opcode!");
13128 }
13129
13130 // Get opcode of the non-atomic one from the specified atomic instruction for
13131 // 64-bit data type on 32-bit target.
13132 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
13133   switch (Opc) {
13134   case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
13135   case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
13136   case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
13137   case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
13138   case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
13139   case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
13140   case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
13141   case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
13142   case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
13143   case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
13144   }
13145   llvm_unreachable("Unhandled atomic-load-op opcode!");
13146 }
13147
13148 // Get opcode of the non-atomic one from the specified atomic instruction for
13149 // 64-bit data type on 32-bit target with extra opcode.
13150 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
13151                                                    unsigned &HiOpc,
13152                                                    unsigned &ExtraOpc) {
13153   switch (Opc) {
13154   case X86::ATOMNAND6432:
13155     ExtraOpc = X86::NOT32r;
13156     HiOpc = X86::AND32rr;
13157     return X86::AND32rr;
13158   }
13159   llvm_unreachable("Unhandled atomic-load-op opcode!");
13160 }
13161
13162 // Get pseudo CMOV opcode from the specified data type.
13163 static unsigned getPseudoCMOVOpc(EVT VT) {
13164   switch (VT.getSimpleVT().SimpleTy) {
13165   case MVT::i8:  return X86::CMOV_GR8;
13166   case MVT::i16: return X86::CMOV_GR16;
13167   case MVT::i32: return X86::CMOV_GR32;
13168   default:
13169     break;
13170   }
13171   llvm_unreachable("Unknown CMOV opcode!");
13172 }
13173
13174 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
13175 // They will be translated into a spin-loop or compare-exchange loop from
13176 //
13177 //    ...
13178 //    dst = atomic-fetch-op MI.addr, MI.val
13179 //    ...
13180 //
13181 // to
13182 //
13183 //    ...
13184 //    t1 = LOAD MI.addr
13185 // loop:
13186 //    t4 = phi(t1, t3 / loop)
13187 //    t2 = OP MI.val, t4
13188 //    EAX = t4
13189 //    LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
13190 //    t3 = EAX
13191 //    JNE loop
13192 // sink:
13193 //    dst = t3
13194 //    ...
13195 MachineBasicBlock *
13196 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
13197                                        MachineBasicBlock *MBB) const {
13198   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13199   DebugLoc DL = MI->getDebugLoc();
13200
13201   MachineFunction *MF = MBB->getParent();
13202   MachineRegisterInfo &MRI = MF->getRegInfo();
13203
13204   const BasicBlock *BB = MBB->getBasicBlock();
13205   MachineFunction::iterator I = MBB;
13206   ++I;
13207
13208   assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
13209          "Unexpected number of operands");
13210
13211   assert(MI->hasOneMemOperand() &&
13212          "Expected atomic-load-op to have one memoperand");
13213
13214   // Memory Reference
13215   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13216   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13217
13218   unsigned DstReg, SrcReg;
13219   unsigned MemOpndSlot;
13220
13221   unsigned CurOp = 0;
13222
13223   DstReg = MI->getOperand(CurOp++).getReg();
13224   MemOpndSlot = CurOp;
13225   CurOp += X86::AddrNumOperands;
13226   SrcReg = MI->getOperand(CurOp++).getReg();
13227
13228   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
13229   MVT::SimpleValueType VT = *RC->vt_begin();
13230   unsigned t1 = MRI.createVirtualRegister(RC);
13231   unsigned t2 = MRI.createVirtualRegister(RC);
13232   unsigned t3 = MRI.createVirtualRegister(RC);
13233   unsigned t4 = MRI.createVirtualRegister(RC);
13234   unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
13235
13236   unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
13237   unsigned LOADOpc = getLoadOpcode(VT);
13238
13239   // For the atomic load-arith operator, we generate
13240   //
13241   //  thisMBB:
13242   //    t1 = LOAD [MI.addr]
13243   //  mainMBB:
13244   //    t4 = phi(t1 / thisMBB, t3 / mainMBB)
13245   //    t1 = OP MI.val, EAX
13246   //    EAX = t4
13247   //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
13248   //    t3 = EAX
13249   //    JNE mainMBB
13250   //  sinkMBB:
13251   //    dst = t3
13252
13253   MachineBasicBlock *thisMBB = MBB;
13254   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13255   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13256   MF->insert(I, mainMBB);
13257   MF->insert(I, sinkMBB);
13258
13259   MachineInstrBuilder MIB;
13260
13261   // Transfer the remainder of BB and its successor edges to sinkMBB.
13262   sinkMBB->splice(sinkMBB->begin(), MBB,
13263                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13264   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13265
13266   // thisMBB:
13267   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
13268   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13269     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13270     if (NewMO.isReg())
13271       NewMO.setIsKill(false);
13272     MIB.addOperand(NewMO);
13273   }
13274   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
13275     unsigned flags = (*MMOI)->getFlags();
13276     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
13277     MachineMemOperand *MMO =
13278       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
13279                                (*MMOI)->getSize(),
13280                                (*MMOI)->getBaseAlignment(),
13281                                (*MMOI)->getTBAAInfo(),
13282                                (*MMOI)->getRanges());
13283     MIB.addMemOperand(MMO);
13284   }
13285
13286   thisMBB->addSuccessor(mainMBB);
13287
13288   // mainMBB:
13289   MachineBasicBlock *origMainMBB = mainMBB;
13290
13291   // Add a PHI.
13292   MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
13293                         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
13294
13295   unsigned Opc = MI->getOpcode();
13296   switch (Opc) {
13297   default:
13298     llvm_unreachable("Unhandled atomic-load-op opcode!");
13299   case X86::ATOMAND8:
13300   case X86::ATOMAND16:
13301   case X86::ATOMAND32:
13302   case X86::ATOMAND64:
13303   case X86::ATOMOR8:
13304   case X86::ATOMOR16:
13305   case X86::ATOMOR32:
13306   case X86::ATOMOR64:
13307   case X86::ATOMXOR8:
13308   case X86::ATOMXOR16:
13309   case X86::ATOMXOR32:
13310   case X86::ATOMXOR64: {
13311     unsigned ARITHOpc = getNonAtomicOpcode(Opc);
13312     BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
13313       .addReg(t4);
13314     break;
13315   }
13316   case X86::ATOMNAND8:
13317   case X86::ATOMNAND16:
13318   case X86::ATOMNAND32:
13319   case X86::ATOMNAND64: {
13320     unsigned Tmp = MRI.createVirtualRegister(RC);
13321     unsigned NOTOpc;
13322     unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
13323     BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
13324       .addReg(t4);
13325     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
13326     break;
13327   }
13328   case X86::ATOMMAX8:
13329   case X86::ATOMMAX16:
13330   case X86::ATOMMAX32:
13331   case X86::ATOMMAX64:
13332   case X86::ATOMMIN8:
13333   case X86::ATOMMIN16:
13334   case X86::ATOMMIN32:
13335   case X86::ATOMMIN64:
13336   case X86::ATOMUMAX8:
13337   case X86::ATOMUMAX16:
13338   case X86::ATOMUMAX32:
13339   case X86::ATOMUMAX64:
13340   case X86::ATOMUMIN8:
13341   case X86::ATOMUMIN16:
13342   case X86::ATOMUMIN32:
13343   case X86::ATOMUMIN64: {
13344     unsigned CMPOpc;
13345     unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
13346
13347     BuildMI(mainMBB, DL, TII->get(CMPOpc))
13348       .addReg(SrcReg)
13349       .addReg(t4);
13350
13351     if (Subtarget->hasCMov()) {
13352       if (VT != MVT::i8) {
13353         // Native support
13354         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
13355           .addReg(SrcReg)
13356           .addReg(t4);
13357       } else {
13358         // Promote i8 to i32 to use CMOV32
13359         const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
13360         const TargetRegisterClass *RC32 =
13361           TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
13362         unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
13363         unsigned AccReg32 = MRI.createVirtualRegister(RC32);
13364         unsigned Tmp = MRI.createVirtualRegister(RC32);
13365
13366         unsigned Undef = MRI.createVirtualRegister(RC32);
13367         BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
13368
13369         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
13370           .addReg(Undef)
13371           .addReg(SrcReg)
13372           .addImm(X86::sub_8bit);
13373         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
13374           .addReg(Undef)
13375           .addReg(t4)
13376           .addImm(X86::sub_8bit);
13377
13378         BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
13379           .addReg(SrcReg32)
13380           .addReg(AccReg32);
13381
13382         BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
13383           .addReg(Tmp, 0, X86::sub_8bit);
13384       }
13385     } else {
13386       // Use pseudo select and lower them.
13387       assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
13388              "Invalid atomic-load-op transformation!");
13389       unsigned SelOpc = getPseudoCMOVOpc(VT);
13390       X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
13391       assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
13392       MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
13393               .addReg(SrcReg).addReg(t4)
13394               .addImm(CC);
13395       mainMBB = EmitLoweredSelect(MIB, mainMBB);
13396       // Replace the original PHI node as mainMBB is changed after CMOV
13397       // lowering.
13398       BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
13399         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
13400       Phi->eraseFromParent();
13401     }
13402     break;
13403   }
13404   }
13405
13406   // Copy PhyReg back from virtual register.
13407   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
13408     .addReg(t4);
13409
13410   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
13411   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13412     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13413     if (NewMO.isReg())
13414       NewMO.setIsKill(false);
13415     MIB.addOperand(NewMO);
13416   }
13417   MIB.addReg(t2);
13418   MIB.setMemRefs(MMOBegin, MMOEnd);
13419
13420   // Copy PhyReg back to virtual register.
13421   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
13422     .addReg(PhyReg);
13423
13424   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
13425
13426   mainMBB->addSuccessor(origMainMBB);
13427   mainMBB->addSuccessor(sinkMBB);
13428
13429   // sinkMBB:
13430   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13431           TII->get(TargetOpcode::COPY), DstReg)
13432     .addReg(t3);
13433
13434   MI->eraseFromParent();
13435   return sinkMBB;
13436 }
13437
13438 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
13439 // instructions. They will be translated into a spin-loop or compare-exchange
13440 // loop from
13441 //
13442 //    ...
13443 //    dst = atomic-fetch-op MI.addr, MI.val
13444 //    ...
13445 //
13446 // to
13447 //
13448 //    ...
13449 //    t1L = LOAD [MI.addr + 0]
13450 //    t1H = LOAD [MI.addr + 4]
13451 // loop:
13452 //    t4L = phi(t1L, t3L / loop)
13453 //    t4H = phi(t1H, t3H / loop)
13454 //    t2L = OP MI.val.lo, t4L
13455 //    t2H = OP MI.val.hi, t4H
13456 //    EAX = t4L
13457 //    EDX = t4H
13458 //    EBX = t2L
13459 //    ECX = t2H
13460 //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
13461 //    t3L = EAX
13462 //    t3H = EDX
13463 //    JNE loop
13464 // sink:
13465 //    dstL = t3L
13466 //    dstH = t3H
13467 //    ...
13468 MachineBasicBlock *
13469 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
13470                                            MachineBasicBlock *MBB) const {
13471   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13472   DebugLoc DL = MI->getDebugLoc();
13473
13474   MachineFunction *MF = MBB->getParent();
13475   MachineRegisterInfo &MRI = MF->getRegInfo();
13476
13477   const BasicBlock *BB = MBB->getBasicBlock();
13478   MachineFunction::iterator I = MBB;
13479   ++I;
13480
13481   assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
13482          "Unexpected number of operands");
13483
13484   assert(MI->hasOneMemOperand() &&
13485          "Expected atomic-load-op32 to have one memoperand");
13486
13487   // Memory Reference
13488   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13489   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13490
13491   unsigned DstLoReg, DstHiReg;
13492   unsigned SrcLoReg, SrcHiReg;
13493   unsigned MemOpndSlot;
13494
13495   unsigned CurOp = 0;
13496
13497   DstLoReg = MI->getOperand(CurOp++).getReg();
13498   DstHiReg = MI->getOperand(CurOp++).getReg();
13499   MemOpndSlot = CurOp;
13500   CurOp += X86::AddrNumOperands;
13501   SrcLoReg = MI->getOperand(CurOp++).getReg();
13502   SrcHiReg = MI->getOperand(CurOp++).getReg();
13503
13504   const TargetRegisterClass *RC = &X86::GR32RegClass;
13505   const TargetRegisterClass *RC8 = &X86::GR8RegClass;
13506
13507   unsigned t1L = MRI.createVirtualRegister(RC);
13508   unsigned t1H = MRI.createVirtualRegister(RC);
13509   unsigned t2L = MRI.createVirtualRegister(RC);
13510   unsigned t2H = MRI.createVirtualRegister(RC);
13511   unsigned t3L = MRI.createVirtualRegister(RC);
13512   unsigned t3H = MRI.createVirtualRegister(RC);
13513   unsigned t4L = MRI.createVirtualRegister(RC);
13514   unsigned t4H = MRI.createVirtualRegister(RC);
13515
13516   unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
13517   unsigned LOADOpc = X86::MOV32rm;
13518
13519   // For the atomic load-arith operator, we generate
13520   //
13521   //  thisMBB:
13522   //    t1L = LOAD [MI.addr + 0]
13523   //    t1H = LOAD [MI.addr + 4]
13524   //  mainMBB:
13525   //    t4L = phi(t1L / thisMBB, t3L / mainMBB)
13526   //    t4H = phi(t1H / thisMBB, t3H / mainMBB)
13527   //    t2L = OP MI.val.lo, t4L
13528   //    t2H = OP MI.val.hi, t4H
13529   //    EBX = t2L
13530   //    ECX = t2H
13531   //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
13532   //    t3L = EAX
13533   //    t3H = EDX
13534   //    JNE loop
13535   //  sinkMBB:
13536   //    dstL = t3L
13537   //    dstH = t3H
13538
13539   MachineBasicBlock *thisMBB = MBB;
13540   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13541   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13542   MF->insert(I, mainMBB);
13543   MF->insert(I, sinkMBB);
13544
13545   MachineInstrBuilder MIB;
13546
13547   // Transfer the remainder of BB and its successor edges to sinkMBB.
13548   sinkMBB->splice(sinkMBB->begin(), MBB,
13549                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13550   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13551
13552   // thisMBB:
13553   // Lo
13554   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
13555   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13556     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13557     if (NewMO.isReg())
13558       NewMO.setIsKill(false);
13559     MIB.addOperand(NewMO);
13560   }
13561   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
13562     unsigned flags = (*MMOI)->getFlags();
13563     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
13564     MachineMemOperand *MMO =
13565       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
13566                                (*MMOI)->getSize(),
13567                                (*MMOI)->getBaseAlignment(),
13568                                (*MMOI)->getTBAAInfo(),
13569                                (*MMOI)->getRanges());
13570     MIB.addMemOperand(MMO);
13571   };
13572   MachineInstr *LowMI = MIB;
13573
13574   // Hi
13575   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
13576   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13577     if (i == X86::AddrDisp) {
13578       MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
13579     } else {
13580       MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13581       if (NewMO.isReg())
13582         NewMO.setIsKill(false);
13583       MIB.addOperand(NewMO);
13584     }
13585   }
13586   MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
13587
13588   thisMBB->addSuccessor(mainMBB);
13589
13590   // mainMBB:
13591   MachineBasicBlock *origMainMBB = mainMBB;
13592
13593   // Add PHIs.
13594   MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
13595                         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
13596   MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
13597                         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
13598
13599   unsigned Opc = MI->getOpcode();
13600   switch (Opc) {
13601   default:
13602     llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
13603   case X86::ATOMAND6432:
13604   case X86::ATOMOR6432:
13605   case X86::ATOMXOR6432:
13606   case X86::ATOMADD6432:
13607   case X86::ATOMSUB6432: {
13608     unsigned HiOpc;
13609     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13610     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
13611       .addReg(SrcLoReg);
13612     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
13613       .addReg(SrcHiReg);
13614     break;
13615   }
13616   case X86::ATOMNAND6432: {
13617     unsigned HiOpc, NOTOpc;
13618     unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
13619     unsigned TmpL = MRI.createVirtualRegister(RC);
13620     unsigned TmpH = MRI.createVirtualRegister(RC);
13621     BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
13622       .addReg(t4L);
13623     BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
13624       .addReg(t4H);
13625     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
13626     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
13627     break;
13628   }
13629   case X86::ATOMMAX6432:
13630   case X86::ATOMMIN6432:
13631   case X86::ATOMUMAX6432:
13632   case X86::ATOMUMIN6432: {
13633     unsigned HiOpc;
13634     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13635     unsigned cL = MRI.createVirtualRegister(RC8);
13636     unsigned cH = MRI.createVirtualRegister(RC8);
13637     unsigned cL32 = MRI.createVirtualRegister(RC);
13638     unsigned cH32 = MRI.createVirtualRegister(RC);
13639     unsigned cc = MRI.createVirtualRegister(RC);
13640     // cl := cmp src_lo, lo
13641     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
13642       .addReg(SrcLoReg).addReg(t4L);
13643     BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
13644     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
13645     // ch := cmp src_hi, hi
13646     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
13647       .addReg(SrcHiReg).addReg(t4H);
13648     BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
13649     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
13650     // cc := if (src_hi == hi) ? cl : ch;
13651     if (Subtarget->hasCMov()) {
13652       BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
13653         .addReg(cH32).addReg(cL32);
13654     } else {
13655       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
13656               .addReg(cH32).addReg(cL32)
13657               .addImm(X86::COND_E);
13658       mainMBB = EmitLoweredSelect(MIB, mainMBB);
13659     }
13660     BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
13661     if (Subtarget->hasCMov()) {
13662       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
13663         .addReg(SrcLoReg).addReg(t4L);
13664       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
13665         .addReg(SrcHiReg).addReg(t4H);
13666     } else {
13667       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
13668               .addReg(SrcLoReg).addReg(t4L)
13669               .addImm(X86::COND_NE);
13670       mainMBB = EmitLoweredSelect(MIB, mainMBB);
13671       // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
13672       // 2nd CMOV lowering.
13673       mainMBB->addLiveIn(X86::EFLAGS);
13674       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
13675               .addReg(SrcHiReg).addReg(t4H)
13676               .addImm(X86::COND_NE);
13677       mainMBB = EmitLoweredSelect(MIB, mainMBB);
13678       // Replace the original PHI node as mainMBB is changed after CMOV
13679       // lowering.
13680       BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
13681         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
13682       BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
13683         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
13684       PhiL->eraseFromParent();
13685       PhiH->eraseFromParent();
13686     }
13687     break;
13688   }
13689   case X86::ATOMSWAP6432: {
13690     unsigned HiOpc;
13691     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13692     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
13693     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
13694     break;
13695   }
13696   }
13697
13698   // Copy EDX:EAX back from HiReg:LoReg
13699   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
13700   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
13701   // Copy ECX:EBX from t1H:t1L
13702   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
13703   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
13704
13705   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
13706   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13707     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13708     if (NewMO.isReg())
13709       NewMO.setIsKill(false);
13710     MIB.addOperand(NewMO);
13711   }
13712   MIB.setMemRefs(MMOBegin, MMOEnd);
13713
13714   // Copy EDX:EAX back to t3H:t3L
13715   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
13716   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
13717
13718   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
13719
13720   mainMBB->addSuccessor(origMainMBB);
13721   mainMBB->addSuccessor(sinkMBB);
13722
13723   // sinkMBB:
13724   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13725           TII->get(TargetOpcode::COPY), DstLoReg)
13726     .addReg(t3L);
13727   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13728           TII->get(TargetOpcode::COPY), DstHiReg)
13729     .addReg(t3H);
13730
13731   MI->eraseFromParent();
13732   return sinkMBB;
13733 }
13734
13735 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
13736 // or XMM0_V32I8 in AVX all of this code can be replaced with that
13737 // in the .td file.
13738 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
13739                                        const TargetInstrInfo *TII) {
13740   unsigned Opc;
13741   switch (MI->getOpcode()) {
13742   default: llvm_unreachable("illegal opcode!");
13743   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
13744   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
13745   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
13746   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
13747   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
13748   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
13749   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
13750   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
13751   }
13752
13753   DebugLoc dl = MI->getDebugLoc();
13754   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
13755
13756   unsigned NumArgs = MI->getNumOperands();
13757   for (unsigned i = 1; i < NumArgs; ++i) {
13758     MachineOperand &Op = MI->getOperand(i);
13759     if (!(Op.isReg() && Op.isImplicit()))
13760       MIB.addOperand(Op);
13761   }
13762   if (MI->hasOneMemOperand())
13763     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
13764
13765   BuildMI(*BB, MI, dl,
13766     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13767     .addReg(X86::XMM0);
13768
13769   MI->eraseFromParent();
13770   return BB;
13771 }
13772
13773 // FIXME: Custom handling because TableGen doesn't support multiple implicit
13774 // defs in an instruction pattern
13775 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
13776                                        const TargetInstrInfo *TII) {
13777   unsigned Opc;
13778   switch (MI->getOpcode()) {
13779   default: llvm_unreachable("illegal opcode!");
13780   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
13781   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
13782   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
13783   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
13784   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
13785   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
13786   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
13787   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
13788   }
13789
13790   DebugLoc dl = MI->getDebugLoc();
13791   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
13792
13793   unsigned NumArgs = MI->getNumOperands(); // remove the results
13794   for (unsigned i = 1; i < NumArgs; ++i) {
13795     MachineOperand &Op = MI->getOperand(i);
13796     if (!(Op.isReg() && Op.isImplicit()))
13797       MIB.addOperand(Op);
13798   }
13799   if (MI->hasOneMemOperand())
13800     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
13801
13802   BuildMI(*BB, MI, dl,
13803     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13804     .addReg(X86::ECX);
13805
13806   MI->eraseFromParent();
13807   return BB;
13808 }
13809
13810 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
13811                                        const TargetInstrInfo *TII,
13812                                        const X86Subtarget* Subtarget) {
13813   DebugLoc dl = MI->getDebugLoc();
13814
13815   // Address into RAX/EAX, other two args into ECX, EDX.
13816   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
13817   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
13818   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
13819   for (int i = 0; i < X86::AddrNumOperands; ++i)
13820     MIB.addOperand(MI->getOperand(i));
13821
13822   unsigned ValOps = X86::AddrNumOperands;
13823   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
13824     .addReg(MI->getOperand(ValOps).getReg());
13825   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
13826     .addReg(MI->getOperand(ValOps+1).getReg());
13827
13828   // The instruction doesn't actually take any operands though.
13829   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
13830
13831   MI->eraseFromParent(); // The pseudo is gone now.
13832   return BB;
13833 }
13834
13835 MachineBasicBlock *
13836 X86TargetLowering::EmitVAARG64WithCustomInserter(
13837                    MachineInstr *MI,
13838                    MachineBasicBlock *MBB) const {
13839   // Emit va_arg instruction on X86-64.
13840
13841   // Operands to this pseudo-instruction:
13842   // 0  ) Output        : destination address (reg)
13843   // 1-5) Input         : va_list address (addr, i64mem)
13844   // 6  ) ArgSize       : Size (in bytes) of vararg type
13845   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
13846   // 8  ) Align         : Alignment of type
13847   // 9  ) EFLAGS (implicit-def)
13848
13849   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
13850   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
13851
13852   unsigned DestReg = MI->getOperand(0).getReg();
13853   MachineOperand &Base = MI->getOperand(1);
13854   MachineOperand &Scale = MI->getOperand(2);
13855   MachineOperand &Index = MI->getOperand(3);
13856   MachineOperand &Disp = MI->getOperand(4);
13857   MachineOperand &Segment = MI->getOperand(5);
13858   unsigned ArgSize = MI->getOperand(6).getImm();
13859   unsigned ArgMode = MI->getOperand(7).getImm();
13860   unsigned Align = MI->getOperand(8).getImm();
13861
13862   // Memory Reference
13863   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
13864   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13865   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13866
13867   // Machine Information
13868   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13869   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
13870   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
13871   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
13872   DebugLoc DL = MI->getDebugLoc();
13873
13874   // struct va_list {
13875   //   i32   gp_offset
13876   //   i32   fp_offset
13877   //   i64   overflow_area (address)
13878   //   i64   reg_save_area (address)
13879   // }
13880   // sizeof(va_list) = 24
13881   // alignment(va_list) = 8
13882
13883   unsigned TotalNumIntRegs = 6;
13884   unsigned TotalNumXMMRegs = 8;
13885   bool UseGPOffset = (ArgMode == 1);
13886   bool UseFPOffset = (ArgMode == 2);
13887   unsigned MaxOffset = TotalNumIntRegs * 8 +
13888                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
13889
13890   /* Align ArgSize to a multiple of 8 */
13891   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
13892   bool NeedsAlign = (Align > 8);
13893
13894   MachineBasicBlock *thisMBB = MBB;
13895   MachineBasicBlock *overflowMBB;
13896   MachineBasicBlock *offsetMBB;
13897   MachineBasicBlock *endMBB;
13898
13899   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
13900   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
13901   unsigned OffsetReg = 0;
13902
13903   if (!UseGPOffset && !UseFPOffset) {
13904     // If we only pull from the overflow region, we don't create a branch.
13905     // We don't need to alter control flow.
13906     OffsetDestReg = 0; // unused
13907     OverflowDestReg = DestReg;
13908
13909     offsetMBB = NULL;
13910     overflowMBB = thisMBB;
13911     endMBB = thisMBB;
13912   } else {
13913     // First emit code to check if gp_offset (or fp_offset) is below the bound.
13914     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
13915     // If not, pull from overflow_area. (branch to overflowMBB)
13916     //
13917     //       thisMBB
13918     //         |     .
13919     //         |        .
13920     //     offsetMBB   overflowMBB
13921     //         |        .
13922     //         |     .
13923     //        endMBB
13924
13925     // Registers for the PHI in endMBB
13926     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
13927     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
13928
13929     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
13930     MachineFunction *MF = MBB->getParent();
13931     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13932     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13933     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13934
13935     MachineFunction::iterator MBBIter = MBB;
13936     ++MBBIter;
13937
13938     // Insert the new basic blocks
13939     MF->insert(MBBIter, offsetMBB);
13940     MF->insert(MBBIter, overflowMBB);
13941     MF->insert(MBBIter, endMBB);
13942
13943     // Transfer the remainder of MBB and its successor edges to endMBB.
13944     endMBB->splice(endMBB->begin(), thisMBB,
13945                     llvm::next(MachineBasicBlock::iterator(MI)),
13946                     thisMBB->end());
13947     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
13948
13949     // Make offsetMBB and overflowMBB successors of thisMBB
13950     thisMBB->addSuccessor(offsetMBB);
13951     thisMBB->addSuccessor(overflowMBB);
13952
13953     // endMBB is a successor of both offsetMBB and overflowMBB
13954     offsetMBB->addSuccessor(endMBB);
13955     overflowMBB->addSuccessor(endMBB);
13956
13957     // Load the offset value into a register
13958     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
13959     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
13960       .addOperand(Base)
13961       .addOperand(Scale)
13962       .addOperand(Index)
13963       .addDisp(Disp, UseFPOffset ? 4 : 0)
13964       .addOperand(Segment)
13965       .setMemRefs(MMOBegin, MMOEnd);
13966
13967     // Check if there is enough room left to pull this argument.
13968     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
13969       .addReg(OffsetReg)
13970       .addImm(MaxOffset + 8 - ArgSizeA8);
13971
13972     // Branch to "overflowMBB" if offset >= max
13973     // Fall through to "offsetMBB" otherwise
13974     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
13975       .addMBB(overflowMBB);
13976   }
13977
13978   // In offsetMBB, emit code to use the reg_save_area.
13979   if (offsetMBB) {
13980     assert(OffsetReg != 0);
13981
13982     // Read the reg_save_area address.
13983     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
13984     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
13985       .addOperand(Base)
13986       .addOperand(Scale)
13987       .addOperand(Index)
13988       .addDisp(Disp, 16)
13989       .addOperand(Segment)
13990       .setMemRefs(MMOBegin, MMOEnd);
13991
13992     // Zero-extend the offset
13993     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
13994       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
13995         .addImm(0)
13996         .addReg(OffsetReg)
13997         .addImm(X86::sub_32bit);
13998
13999     // Add the offset to the reg_save_area to get the final address.
14000     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
14001       .addReg(OffsetReg64)
14002       .addReg(RegSaveReg);
14003
14004     // Compute the offset for the next argument
14005     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
14006     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
14007       .addReg(OffsetReg)
14008       .addImm(UseFPOffset ? 16 : 8);
14009
14010     // Store it back into the va_list.
14011     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
14012       .addOperand(Base)
14013       .addOperand(Scale)
14014       .addOperand(Index)
14015       .addDisp(Disp, UseFPOffset ? 4 : 0)
14016       .addOperand(Segment)
14017       .addReg(NextOffsetReg)
14018       .setMemRefs(MMOBegin, MMOEnd);
14019
14020     // Jump to endMBB
14021     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
14022       .addMBB(endMBB);
14023   }
14024
14025   //
14026   // Emit code to use overflow area
14027   //
14028
14029   // Load the overflow_area address into a register.
14030   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
14031   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
14032     .addOperand(Base)
14033     .addOperand(Scale)
14034     .addOperand(Index)
14035     .addDisp(Disp, 8)
14036     .addOperand(Segment)
14037     .setMemRefs(MMOBegin, MMOEnd);
14038
14039   // If we need to align it, do so. Otherwise, just copy the address
14040   // to OverflowDestReg.
14041   if (NeedsAlign) {
14042     // Align the overflow address
14043     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
14044     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
14045
14046     // aligned_addr = (addr + (align-1)) & ~(align-1)
14047     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
14048       .addReg(OverflowAddrReg)
14049       .addImm(Align-1);
14050
14051     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
14052       .addReg(TmpReg)
14053       .addImm(~(uint64_t)(Align-1));
14054   } else {
14055     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
14056       .addReg(OverflowAddrReg);
14057   }
14058
14059   // Compute the next overflow address after this argument.
14060   // (the overflow address should be kept 8-byte aligned)
14061   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
14062   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
14063     .addReg(OverflowDestReg)
14064     .addImm(ArgSizeA8);
14065
14066   // Store the new overflow address.
14067   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
14068     .addOperand(Base)
14069     .addOperand(Scale)
14070     .addOperand(Index)
14071     .addDisp(Disp, 8)
14072     .addOperand(Segment)
14073     .addReg(NextAddrReg)
14074     .setMemRefs(MMOBegin, MMOEnd);
14075
14076   // If we branched, emit the PHI to the front of endMBB.
14077   if (offsetMBB) {
14078     BuildMI(*endMBB, endMBB->begin(), DL,
14079             TII->get(X86::PHI), DestReg)
14080       .addReg(OffsetDestReg).addMBB(offsetMBB)
14081       .addReg(OverflowDestReg).addMBB(overflowMBB);
14082   }
14083
14084   // Erase the pseudo instruction
14085   MI->eraseFromParent();
14086
14087   return endMBB;
14088 }
14089
14090 MachineBasicBlock *
14091 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
14092                                                  MachineInstr *MI,
14093                                                  MachineBasicBlock *MBB) const {
14094   // Emit code to save XMM registers to the stack. The ABI says that the
14095   // number of registers to save is given in %al, so it's theoretically
14096   // possible to do an indirect jump trick to avoid saving all of them,
14097   // however this code takes a simpler approach and just executes all
14098   // of the stores if %al is non-zero. It's less code, and it's probably
14099   // easier on the hardware branch predictor, and stores aren't all that
14100   // expensive anyway.
14101
14102   // Create the new basic blocks. One block contains all the XMM stores,
14103   // and one block is the final destination regardless of whether any
14104   // stores were performed.
14105   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
14106   MachineFunction *F = MBB->getParent();
14107   MachineFunction::iterator MBBIter = MBB;
14108   ++MBBIter;
14109   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
14110   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
14111   F->insert(MBBIter, XMMSaveMBB);
14112   F->insert(MBBIter, EndMBB);
14113
14114   // Transfer the remainder of MBB and its successor edges to EndMBB.
14115   EndMBB->splice(EndMBB->begin(), MBB,
14116                  llvm::next(MachineBasicBlock::iterator(MI)),
14117                  MBB->end());
14118   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
14119
14120   // The original block will now fall through to the XMM save block.
14121   MBB->addSuccessor(XMMSaveMBB);
14122   // The XMMSaveMBB will fall through to the end block.
14123   XMMSaveMBB->addSuccessor(EndMBB);
14124
14125   // Now add the instructions.
14126   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14127   DebugLoc DL = MI->getDebugLoc();
14128
14129   unsigned CountReg = MI->getOperand(0).getReg();
14130   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
14131   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
14132
14133   if (!Subtarget->isTargetWin64()) {
14134     // If %al is 0, branch around the XMM save block.
14135     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
14136     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
14137     MBB->addSuccessor(EndMBB);
14138   }
14139
14140   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
14141   // In the XMM save block, save all the XMM argument registers.
14142   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
14143     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
14144     MachineMemOperand *MMO =
14145       F->getMachineMemOperand(
14146           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
14147         MachineMemOperand::MOStore,
14148         /*Size=*/16, /*Align=*/16);
14149     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
14150       .addFrameIndex(RegSaveFrameIndex)
14151       .addImm(/*Scale=*/1)
14152       .addReg(/*IndexReg=*/0)
14153       .addImm(/*Disp=*/Offset)
14154       .addReg(/*Segment=*/0)
14155       .addReg(MI->getOperand(i).getReg())
14156       .addMemOperand(MMO);
14157   }
14158
14159   MI->eraseFromParent();   // The pseudo instruction is gone now.
14160
14161   return EndMBB;
14162 }
14163
14164 // The EFLAGS operand of SelectItr might be missing a kill marker
14165 // because there were multiple uses of EFLAGS, and ISel didn't know
14166 // which to mark. Figure out whether SelectItr should have had a
14167 // kill marker, and set it if it should. Returns the correct kill
14168 // marker value.
14169 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
14170                                      MachineBasicBlock* BB,
14171                                      const TargetRegisterInfo* TRI) {
14172   // Scan forward through BB for a use/def of EFLAGS.
14173   MachineBasicBlock::iterator miI(llvm::next(SelectItr));
14174   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
14175     const MachineInstr& mi = *miI;
14176     if (mi.readsRegister(X86::EFLAGS))
14177       return false;
14178     if (mi.definesRegister(X86::EFLAGS))
14179       break; // Should have kill-flag - update below.
14180   }
14181
14182   // If we hit the end of the block, check whether EFLAGS is live into a
14183   // successor.
14184   if (miI == BB->end()) {
14185     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
14186                                           sEnd = BB->succ_end();
14187          sItr != sEnd; ++sItr) {
14188       MachineBasicBlock* succ = *sItr;
14189       if (succ->isLiveIn(X86::EFLAGS))
14190         return false;
14191     }
14192   }
14193
14194   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
14195   // out. SelectMI should have a kill flag on EFLAGS.
14196   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
14197   return true;
14198 }
14199
14200 MachineBasicBlock *
14201 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
14202                                      MachineBasicBlock *BB) const {
14203   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14204   DebugLoc DL = MI->getDebugLoc();
14205
14206   // To "insert" a SELECT_CC instruction, we actually have to insert the
14207   // diamond control-flow pattern.  The incoming instruction knows the
14208   // destination vreg to set, the condition code register to branch on, the
14209   // true/false values to select between, and a branch opcode to use.
14210   const BasicBlock *LLVM_BB = BB->getBasicBlock();
14211   MachineFunction::iterator It = BB;
14212   ++It;
14213
14214   //  thisMBB:
14215   //  ...
14216   //   TrueVal = ...
14217   //   cmpTY ccX, r1, r2
14218   //   bCC copy1MBB
14219   //   fallthrough --> copy0MBB
14220   MachineBasicBlock *thisMBB = BB;
14221   MachineFunction *F = BB->getParent();
14222   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
14223   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
14224   F->insert(It, copy0MBB);
14225   F->insert(It, sinkMBB);
14226
14227   // If the EFLAGS register isn't dead in the terminator, then claim that it's
14228   // live into the sink and copy blocks.
14229   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
14230   if (!MI->killsRegister(X86::EFLAGS) &&
14231       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
14232     copy0MBB->addLiveIn(X86::EFLAGS);
14233     sinkMBB->addLiveIn(X86::EFLAGS);
14234   }
14235
14236   // Transfer the remainder of BB and its successor edges to sinkMBB.
14237   sinkMBB->splice(sinkMBB->begin(), BB,
14238                   llvm::next(MachineBasicBlock::iterator(MI)),
14239                   BB->end());
14240   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
14241
14242   // Add the true and fallthrough blocks as its successors.
14243   BB->addSuccessor(copy0MBB);
14244   BB->addSuccessor(sinkMBB);
14245
14246   // Create the conditional branch instruction.
14247   unsigned Opc =
14248     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
14249   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
14250
14251   //  copy0MBB:
14252   //   %FalseValue = ...
14253   //   # fallthrough to sinkMBB
14254   copy0MBB->addSuccessor(sinkMBB);
14255
14256   //  sinkMBB:
14257   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
14258   //  ...
14259   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14260           TII->get(X86::PHI), MI->getOperand(0).getReg())
14261     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
14262     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
14263
14264   MI->eraseFromParent();   // The pseudo instruction is gone now.
14265   return sinkMBB;
14266 }
14267
14268 MachineBasicBlock *
14269 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
14270                                         bool Is64Bit) const {
14271   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14272   DebugLoc DL = MI->getDebugLoc();
14273   MachineFunction *MF = BB->getParent();
14274   const BasicBlock *LLVM_BB = BB->getBasicBlock();
14275
14276   assert(getTargetMachine().Options.EnableSegmentedStacks);
14277
14278   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
14279   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
14280
14281   // BB:
14282   //  ... [Till the alloca]
14283   // If stacklet is not large enough, jump to mallocMBB
14284   //
14285   // bumpMBB:
14286   //  Allocate by subtracting from RSP
14287   //  Jump to continueMBB
14288   //
14289   // mallocMBB:
14290   //  Allocate by call to runtime
14291   //
14292   // continueMBB:
14293   //  ...
14294   //  [rest of original BB]
14295   //
14296
14297   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14298   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14299   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14300
14301   MachineRegisterInfo &MRI = MF->getRegInfo();
14302   const TargetRegisterClass *AddrRegClass =
14303     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
14304
14305   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
14306     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
14307     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
14308     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
14309     sizeVReg = MI->getOperand(1).getReg(),
14310     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
14311
14312   MachineFunction::iterator MBBIter = BB;
14313   ++MBBIter;
14314
14315   MF->insert(MBBIter, bumpMBB);
14316   MF->insert(MBBIter, mallocMBB);
14317   MF->insert(MBBIter, continueMBB);
14318
14319   continueMBB->splice(continueMBB->begin(), BB, llvm::next
14320                       (MachineBasicBlock::iterator(MI)), BB->end());
14321   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
14322
14323   // Add code to the main basic block to check if the stack limit has been hit,
14324   // and if so, jump to mallocMBB otherwise to bumpMBB.
14325   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
14326   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
14327     .addReg(tmpSPVReg).addReg(sizeVReg);
14328   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
14329     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
14330     .addReg(SPLimitVReg);
14331   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
14332
14333   // bumpMBB simply decreases the stack pointer, since we know the current
14334   // stacklet has enough space.
14335   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
14336     .addReg(SPLimitVReg);
14337   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
14338     .addReg(SPLimitVReg);
14339   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
14340
14341   // Calls into a routine in libgcc to allocate more space from the heap.
14342   const uint32_t *RegMask =
14343     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
14344   if (Is64Bit) {
14345     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
14346       .addReg(sizeVReg);
14347     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
14348       .addExternalSymbol("__morestack_allocate_stack_space")
14349       .addRegMask(RegMask)
14350       .addReg(X86::RDI, RegState::Implicit)
14351       .addReg(X86::RAX, RegState::ImplicitDefine);
14352   } else {
14353     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
14354       .addImm(12);
14355     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
14356     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
14357       .addExternalSymbol("__morestack_allocate_stack_space")
14358       .addRegMask(RegMask)
14359       .addReg(X86::EAX, RegState::ImplicitDefine);
14360   }
14361
14362   if (!Is64Bit)
14363     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
14364       .addImm(16);
14365
14366   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
14367     .addReg(Is64Bit ? X86::RAX : X86::EAX);
14368   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
14369
14370   // Set up the CFG correctly.
14371   BB->addSuccessor(bumpMBB);
14372   BB->addSuccessor(mallocMBB);
14373   mallocMBB->addSuccessor(continueMBB);
14374   bumpMBB->addSuccessor(continueMBB);
14375
14376   // Take care of the PHI nodes.
14377   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
14378           MI->getOperand(0).getReg())
14379     .addReg(mallocPtrVReg).addMBB(mallocMBB)
14380     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
14381
14382   // Delete the original pseudo instruction.
14383   MI->eraseFromParent();
14384
14385   // And we're done.
14386   return continueMBB;
14387 }
14388
14389 MachineBasicBlock *
14390 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
14391                                           MachineBasicBlock *BB) const {
14392   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14393   DebugLoc DL = MI->getDebugLoc();
14394
14395   assert(!Subtarget->isTargetEnvMacho());
14396
14397   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
14398   // non-trivial part is impdef of ESP.
14399
14400   if (Subtarget->isTargetWin64()) {
14401     if (Subtarget->isTargetCygMing()) {
14402       // ___chkstk(Mingw64):
14403       // Clobbers R10, R11, RAX and EFLAGS.
14404       // Updates RSP.
14405       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
14406         .addExternalSymbol("___chkstk")
14407         .addReg(X86::RAX, RegState::Implicit)
14408         .addReg(X86::RSP, RegState::Implicit)
14409         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
14410         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
14411         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14412     } else {
14413       // __chkstk(MSVCRT): does not update stack pointer.
14414       // Clobbers R10, R11 and EFLAGS.
14415       // FIXME: RAX(allocated size) might be reused and not killed.
14416       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
14417         .addExternalSymbol("__chkstk")
14418         .addReg(X86::RAX, RegState::Implicit)
14419         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14420       // RAX has the offset to subtracted from RSP.
14421       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
14422         .addReg(X86::RSP)
14423         .addReg(X86::RAX);
14424     }
14425   } else {
14426     const char *StackProbeSymbol =
14427       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
14428
14429     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
14430       .addExternalSymbol(StackProbeSymbol)
14431       .addReg(X86::EAX, RegState::Implicit)
14432       .addReg(X86::ESP, RegState::Implicit)
14433       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
14434       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
14435       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14436   }
14437
14438   MI->eraseFromParent();   // The pseudo instruction is gone now.
14439   return BB;
14440 }
14441
14442 MachineBasicBlock *
14443 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
14444                                       MachineBasicBlock *BB) const {
14445   // This is pretty easy.  We're taking the value that we received from
14446   // our load from the relocation, sticking it in either RDI (x86-64)
14447   // or EAX and doing an indirect call.  The return value will then
14448   // be in the normal return register.
14449   const X86InstrInfo *TII
14450     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
14451   DebugLoc DL = MI->getDebugLoc();
14452   MachineFunction *F = BB->getParent();
14453
14454   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
14455   assert(MI->getOperand(3).isGlobal() && "This should be a global");
14456
14457   // Get a register mask for the lowered call.
14458   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
14459   // proper register mask.
14460   const uint32_t *RegMask =
14461     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
14462   if (Subtarget->is64Bit()) {
14463     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14464                                       TII->get(X86::MOV64rm), X86::RDI)
14465     .addReg(X86::RIP)
14466     .addImm(0).addReg(0)
14467     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14468                       MI->getOperand(3).getTargetFlags())
14469     .addReg(0);
14470     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
14471     addDirectMem(MIB, X86::RDI);
14472     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
14473   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
14474     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14475                                       TII->get(X86::MOV32rm), X86::EAX)
14476     .addReg(0)
14477     .addImm(0).addReg(0)
14478     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14479                       MI->getOperand(3).getTargetFlags())
14480     .addReg(0);
14481     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
14482     addDirectMem(MIB, X86::EAX);
14483     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
14484   } else {
14485     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14486                                       TII->get(X86::MOV32rm), X86::EAX)
14487     .addReg(TII->getGlobalBaseReg(F))
14488     .addImm(0).addReg(0)
14489     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14490                       MI->getOperand(3).getTargetFlags())
14491     .addReg(0);
14492     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
14493     addDirectMem(MIB, X86::EAX);
14494     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
14495   }
14496
14497   MI->eraseFromParent(); // The pseudo instruction is gone now.
14498   return BB;
14499 }
14500
14501 MachineBasicBlock *
14502 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
14503                                     MachineBasicBlock *MBB) const {
14504   DebugLoc DL = MI->getDebugLoc();
14505   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14506
14507   MachineFunction *MF = MBB->getParent();
14508   MachineRegisterInfo &MRI = MF->getRegInfo();
14509
14510   const BasicBlock *BB = MBB->getBasicBlock();
14511   MachineFunction::iterator I = MBB;
14512   ++I;
14513
14514   // Memory Reference
14515   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14516   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14517
14518   unsigned DstReg;
14519   unsigned MemOpndSlot = 0;
14520
14521   unsigned CurOp = 0;
14522
14523   DstReg = MI->getOperand(CurOp++).getReg();
14524   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
14525   assert(RC->hasType(MVT::i32) && "Invalid destination!");
14526   unsigned mainDstReg = MRI.createVirtualRegister(RC);
14527   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
14528
14529   MemOpndSlot = CurOp;
14530
14531   MVT PVT = getPointerTy();
14532   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
14533          "Invalid Pointer Size!");
14534
14535   // For v = setjmp(buf), we generate
14536   //
14537   // thisMBB:
14538   //  buf[LabelOffset] = restoreMBB
14539   //  SjLjSetup restoreMBB
14540   //
14541   // mainMBB:
14542   //  v_main = 0
14543   //
14544   // sinkMBB:
14545   //  v = phi(main, restore)
14546   //
14547   // restoreMBB:
14548   //  v_restore = 1
14549
14550   MachineBasicBlock *thisMBB = MBB;
14551   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14552   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14553   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
14554   MF->insert(I, mainMBB);
14555   MF->insert(I, sinkMBB);
14556   MF->push_back(restoreMBB);
14557
14558   MachineInstrBuilder MIB;
14559
14560   // Transfer the remainder of BB and its successor edges to sinkMBB.
14561   sinkMBB->splice(sinkMBB->begin(), MBB,
14562                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
14563   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14564
14565   // thisMBB:
14566   unsigned PtrStoreOpc = 0;
14567   unsigned LabelReg = 0;
14568   const int64_t LabelOffset = 1 * PVT.getStoreSize();
14569   Reloc::Model RM = getTargetMachine().getRelocationModel();
14570   bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
14571                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
14572
14573   // Prepare IP either in reg or imm.
14574   if (!UseImmLabel) {
14575     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
14576     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
14577     LabelReg = MRI.createVirtualRegister(PtrRC);
14578     if (Subtarget->is64Bit()) {
14579       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
14580               .addReg(X86::RIP)
14581               .addImm(0)
14582               .addReg(0)
14583               .addMBB(restoreMBB)
14584               .addReg(0);
14585     } else {
14586       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
14587       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
14588               .addReg(XII->getGlobalBaseReg(MF))
14589               .addImm(0)
14590               .addReg(0)
14591               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
14592               .addReg(0);
14593     }
14594   } else
14595     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
14596   // Store IP
14597   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
14598   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14599     if (i == X86::AddrDisp)
14600       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
14601     else
14602       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
14603   }
14604   if (!UseImmLabel)
14605     MIB.addReg(LabelReg);
14606   else
14607     MIB.addMBB(restoreMBB);
14608   MIB.setMemRefs(MMOBegin, MMOEnd);
14609   // Setup
14610   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
14611           .addMBB(restoreMBB);
14612   MIB.addRegMask(RegInfo->getNoPreservedMask());
14613   thisMBB->addSuccessor(mainMBB);
14614   thisMBB->addSuccessor(restoreMBB);
14615
14616   // mainMBB:
14617   //  EAX = 0
14618   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
14619   mainMBB->addSuccessor(sinkMBB);
14620
14621   // sinkMBB:
14622   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14623           TII->get(X86::PHI), DstReg)
14624     .addReg(mainDstReg).addMBB(mainMBB)
14625     .addReg(restoreDstReg).addMBB(restoreMBB);
14626
14627   // restoreMBB:
14628   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
14629   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
14630   restoreMBB->addSuccessor(sinkMBB);
14631
14632   MI->eraseFromParent();
14633   return sinkMBB;
14634 }
14635
14636 MachineBasicBlock *
14637 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
14638                                      MachineBasicBlock *MBB) const {
14639   DebugLoc DL = MI->getDebugLoc();
14640   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14641
14642   MachineFunction *MF = MBB->getParent();
14643   MachineRegisterInfo &MRI = MF->getRegInfo();
14644
14645   // Memory Reference
14646   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14647   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14648
14649   MVT PVT = getPointerTy();
14650   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
14651          "Invalid Pointer Size!");
14652
14653   const TargetRegisterClass *RC =
14654     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
14655   unsigned Tmp = MRI.createVirtualRegister(RC);
14656   // Since FP is only updated here but NOT referenced, it's treated as GPR.
14657   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
14658   unsigned SP = RegInfo->getStackRegister();
14659
14660   MachineInstrBuilder MIB;
14661
14662   const int64_t LabelOffset = 1 * PVT.getStoreSize();
14663   const int64_t SPOffset = 2 * PVT.getStoreSize();
14664
14665   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
14666   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
14667
14668   // Reload FP
14669   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
14670   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
14671     MIB.addOperand(MI->getOperand(i));
14672   MIB.setMemRefs(MMOBegin, MMOEnd);
14673   // Reload IP
14674   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
14675   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14676     if (i == X86::AddrDisp)
14677       MIB.addDisp(MI->getOperand(i), LabelOffset);
14678     else
14679       MIB.addOperand(MI->getOperand(i));
14680   }
14681   MIB.setMemRefs(MMOBegin, MMOEnd);
14682   // Reload SP
14683   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
14684   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14685     if (i == X86::AddrDisp)
14686       MIB.addDisp(MI->getOperand(i), SPOffset);
14687     else
14688       MIB.addOperand(MI->getOperand(i));
14689   }
14690   MIB.setMemRefs(MMOBegin, MMOEnd);
14691   // Jump
14692   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
14693
14694   MI->eraseFromParent();
14695   return MBB;
14696 }
14697
14698 MachineBasicBlock *
14699 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
14700                                                MachineBasicBlock *BB) const {
14701   switch (MI->getOpcode()) {
14702   default: llvm_unreachable("Unexpected instr type to insert");
14703   case X86::TAILJMPd64:
14704   case X86::TAILJMPr64:
14705   case X86::TAILJMPm64:
14706     llvm_unreachable("TAILJMP64 would not be touched here.");
14707   case X86::TCRETURNdi64:
14708   case X86::TCRETURNri64:
14709   case X86::TCRETURNmi64:
14710     return BB;
14711   case X86::WIN_ALLOCA:
14712     return EmitLoweredWinAlloca(MI, BB);
14713   case X86::SEG_ALLOCA_32:
14714     return EmitLoweredSegAlloca(MI, BB, false);
14715   case X86::SEG_ALLOCA_64:
14716     return EmitLoweredSegAlloca(MI, BB, true);
14717   case X86::TLSCall_32:
14718   case X86::TLSCall_64:
14719     return EmitLoweredTLSCall(MI, BB);
14720   case X86::CMOV_GR8:
14721   case X86::CMOV_FR32:
14722   case X86::CMOV_FR64:
14723   case X86::CMOV_V4F32:
14724   case X86::CMOV_V2F64:
14725   case X86::CMOV_V2I64:
14726   case X86::CMOV_V8F32:
14727   case X86::CMOV_V4F64:
14728   case X86::CMOV_V4I64:
14729   case X86::CMOV_GR16:
14730   case X86::CMOV_GR32:
14731   case X86::CMOV_RFP32:
14732   case X86::CMOV_RFP64:
14733   case X86::CMOV_RFP80:
14734     return EmitLoweredSelect(MI, BB);
14735
14736   case X86::FP32_TO_INT16_IN_MEM:
14737   case X86::FP32_TO_INT32_IN_MEM:
14738   case X86::FP32_TO_INT64_IN_MEM:
14739   case X86::FP64_TO_INT16_IN_MEM:
14740   case X86::FP64_TO_INT32_IN_MEM:
14741   case X86::FP64_TO_INT64_IN_MEM:
14742   case X86::FP80_TO_INT16_IN_MEM:
14743   case X86::FP80_TO_INT32_IN_MEM:
14744   case X86::FP80_TO_INT64_IN_MEM: {
14745     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14746     DebugLoc DL = MI->getDebugLoc();
14747
14748     // Change the floating point control register to use "round towards zero"
14749     // mode when truncating to an integer value.
14750     MachineFunction *F = BB->getParent();
14751     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
14752     addFrameReference(BuildMI(*BB, MI, DL,
14753                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
14754
14755     // Load the old value of the high byte of the control word...
14756     unsigned OldCW =
14757       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
14758     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
14759                       CWFrameIdx);
14760
14761     // Set the high part to be round to zero...
14762     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
14763       .addImm(0xC7F);
14764
14765     // Reload the modified control word now...
14766     addFrameReference(BuildMI(*BB, MI, DL,
14767                               TII->get(X86::FLDCW16m)), CWFrameIdx);
14768
14769     // Restore the memory image of control word to original value
14770     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
14771       .addReg(OldCW);
14772
14773     // Get the X86 opcode to use.
14774     unsigned Opc;
14775     switch (MI->getOpcode()) {
14776     default: llvm_unreachable("illegal opcode!");
14777     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
14778     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
14779     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
14780     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
14781     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
14782     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
14783     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
14784     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
14785     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
14786     }
14787
14788     X86AddressMode AM;
14789     MachineOperand &Op = MI->getOperand(0);
14790     if (Op.isReg()) {
14791       AM.BaseType = X86AddressMode::RegBase;
14792       AM.Base.Reg = Op.getReg();
14793     } else {
14794       AM.BaseType = X86AddressMode::FrameIndexBase;
14795       AM.Base.FrameIndex = Op.getIndex();
14796     }
14797     Op = MI->getOperand(1);
14798     if (Op.isImm())
14799       AM.Scale = Op.getImm();
14800     Op = MI->getOperand(2);
14801     if (Op.isImm())
14802       AM.IndexReg = Op.getImm();
14803     Op = MI->getOperand(3);
14804     if (Op.isGlobal()) {
14805       AM.GV = Op.getGlobal();
14806     } else {
14807       AM.Disp = Op.getImm();
14808     }
14809     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
14810                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
14811
14812     // Reload the original control word now.
14813     addFrameReference(BuildMI(*BB, MI, DL,
14814                               TII->get(X86::FLDCW16m)), CWFrameIdx);
14815
14816     MI->eraseFromParent();   // The pseudo instruction is gone now.
14817     return BB;
14818   }
14819     // String/text processing lowering.
14820   case X86::PCMPISTRM128REG:
14821   case X86::VPCMPISTRM128REG:
14822   case X86::PCMPISTRM128MEM:
14823   case X86::VPCMPISTRM128MEM:
14824   case X86::PCMPESTRM128REG:
14825   case X86::VPCMPESTRM128REG:
14826   case X86::PCMPESTRM128MEM:
14827   case X86::VPCMPESTRM128MEM:
14828     assert(Subtarget->hasSSE42() &&
14829            "Target must have SSE4.2 or AVX features enabled");
14830     return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
14831
14832   // String/text processing lowering.
14833   case X86::PCMPISTRIREG:
14834   case X86::VPCMPISTRIREG:
14835   case X86::PCMPISTRIMEM:
14836   case X86::VPCMPISTRIMEM:
14837   case X86::PCMPESTRIREG:
14838   case X86::VPCMPESTRIREG:
14839   case X86::PCMPESTRIMEM:
14840   case X86::VPCMPESTRIMEM:
14841     assert(Subtarget->hasSSE42() &&
14842            "Target must have SSE4.2 or AVX features enabled");
14843     return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
14844
14845   // Thread synchronization.
14846   case X86::MONITOR:
14847     return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
14848
14849   // xbegin
14850   case X86::XBEGIN:
14851     return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
14852
14853   // Atomic Lowering.
14854   case X86::ATOMAND8:
14855   case X86::ATOMAND16:
14856   case X86::ATOMAND32:
14857   case X86::ATOMAND64:
14858     // Fall through
14859   case X86::ATOMOR8:
14860   case X86::ATOMOR16:
14861   case X86::ATOMOR32:
14862   case X86::ATOMOR64:
14863     // Fall through
14864   case X86::ATOMXOR16:
14865   case X86::ATOMXOR8:
14866   case X86::ATOMXOR32:
14867   case X86::ATOMXOR64:
14868     // Fall through
14869   case X86::ATOMNAND8:
14870   case X86::ATOMNAND16:
14871   case X86::ATOMNAND32:
14872   case X86::ATOMNAND64:
14873     // Fall through
14874   case X86::ATOMMAX8:
14875   case X86::ATOMMAX16:
14876   case X86::ATOMMAX32:
14877   case X86::ATOMMAX64:
14878     // Fall through
14879   case X86::ATOMMIN8:
14880   case X86::ATOMMIN16:
14881   case X86::ATOMMIN32:
14882   case X86::ATOMMIN64:
14883     // Fall through
14884   case X86::ATOMUMAX8:
14885   case X86::ATOMUMAX16:
14886   case X86::ATOMUMAX32:
14887   case X86::ATOMUMAX64:
14888     // Fall through
14889   case X86::ATOMUMIN8:
14890   case X86::ATOMUMIN16:
14891   case X86::ATOMUMIN32:
14892   case X86::ATOMUMIN64:
14893     return EmitAtomicLoadArith(MI, BB);
14894
14895   // This group does 64-bit operations on a 32-bit host.
14896   case X86::ATOMAND6432:
14897   case X86::ATOMOR6432:
14898   case X86::ATOMXOR6432:
14899   case X86::ATOMNAND6432:
14900   case X86::ATOMADD6432:
14901   case X86::ATOMSUB6432:
14902   case X86::ATOMMAX6432:
14903   case X86::ATOMMIN6432:
14904   case X86::ATOMUMAX6432:
14905   case X86::ATOMUMIN6432:
14906   case X86::ATOMSWAP6432:
14907     return EmitAtomicLoadArith6432(MI, BB);
14908
14909   case X86::VASTART_SAVE_XMM_REGS:
14910     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
14911
14912   case X86::VAARG_64:
14913     return EmitVAARG64WithCustomInserter(MI, BB);
14914
14915   case X86::EH_SjLj_SetJmp32:
14916   case X86::EH_SjLj_SetJmp64:
14917     return emitEHSjLjSetJmp(MI, BB);
14918
14919   case X86::EH_SjLj_LongJmp32:
14920   case X86::EH_SjLj_LongJmp64:
14921     return emitEHSjLjLongJmp(MI, BB);
14922   }
14923 }
14924
14925 //===----------------------------------------------------------------------===//
14926 //                           X86 Optimization Hooks
14927 //===----------------------------------------------------------------------===//
14928
14929 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
14930                                                        APInt &KnownZero,
14931                                                        APInt &KnownOne,
14932                                                        const SelectionDAG &DAG,
14933                                                        unsigned Depth) const {
14934   unsigned BitWidth = KnownZero.getBitWidth();
14935   unsigned Opc = Op.getOpcode();
14936   assert((Opc >= ISD::BUILTIN_OP_END ||
14937           Opc == ISD::INTRINSIC_WO_CHAIN ||
14938           Opc == ISD::INTRINSIC_W_CHAIN ||
14939           Opc == ISD::INTRINSIC_VOID) &&
14940          "Should use MaskedValueIsZero if you don't know whether Op"
14941          " is a target node!");
14942
14943   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
14944   switch (Opc) {
14945   default: break;
14946   case X86ISD::ADD:
14947   case X86ISD::SUB:
14948   case X86ISD::ADC:
14949   case X86ISD::SBB:
14950   case X86ISD::SMUL:
14951   case X86ISD::UMUL:
14952   case X86ISD::INC:
14953   case X86ISD::DEC:
14954   case X86ISD::OR:
14955   case X86ISD::XOR:
14956   case X86ISD::AND:
14957     // These nodes' second result is a boolean.
14958     if (Op.getResNo() == 0)
14959       break;
14960     // Fallthrough
14961   case X86ISD::SETCC:
14962     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
14963     break;
14964   case ISD::INTRINSIC_WO_CHAIN: {
14965     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14966     unsigned NumLoBits = 0;
14967     switch (IntId) {
14968     default: break;
14969     case Intrinsic::x86_sse_movmsk_ps:
14970     case Intrinsic::x86_avx_movmsk_ps_256:
14971     case Intrinsic::x86_sse2_movmsk_pd:
14972     case Intrinsic::x86_avx_movmsk_pd_256:
14973     case Intrinsic::x86_mmx_pmovmskb:
14974     case Intrinsic::x86_sse2_pmovmskb_128:
14975     case Intrinsic::x86_avx2_pmovmskb: {
14976       // High bits of movmskp{s|d}, pmovmskb are known zero.
14977       switch (IntId) {
14978         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14979         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
14980         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
14981         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
14982         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
14983         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
14984         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
14985         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
14986       }
14987       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
14988       break;
14989     }
14990     }
14991     break;
14992   }
14993   }
14994 }
14995
14996 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
14997                                                          unsigned Depth) const {
14998   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
14999   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
15000     return Op.getValueType().getScalarType().getSizeInBits();
15001
15002   // Fallback case.
15003   return 1;
15004 }
15005
15006 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
15007 /// node is a GlobalAddress + offset.
15008 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
15009                                        const GlobalValue* &GA,
15010                                        int64_t &Offset) const {
15011   if (N->getOpcode() == X86ISD::Wrapper) {
15012     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
15013       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
15014       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
15015       return true;
15016     }
15017   }
15018   return TargetLowering::isGAPlusOffset(N, GA, Offset);
15019 }
15020
15021 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
15022 /// same as extracting the high 128-bit part of 256-bit vector and then
15023 /// inserting the result into the low part of a new 256-bit vector
15024 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
15025   EVT VT = SVOp->getValueType(0);
15026   unsigned NumElems = VT.getVectorNumElements();
15027
15028   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
15029   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
15030     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
15031         SVOp->getMaskElt(j) >= 0)
15032       return false;
15033
15034   return true;
15035 }
15036
15037 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
15038 /// same as extracting the low 128-bit part of 256-bit vector and then
15039 /// inserting the result into the high part of a new 256-bit vector
15040 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
15041   EVT VT = SVOp->getValueType(0);
15042   unsigned NumElems = VT.getVectorNumElements();
15043
15044   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
15045   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
15046     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
15047         SVOp->getMaskElt(j) >= 0)
15048       return false;
15049
15050   return true;
15051 }
15052
15053 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
15054 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
15055                                         TargetLowering::DAGCombinerInfo &DCI,
15056                                         const X86Subtarget* Subtarget) {
15057   DebugLoc dl = N->getDebugLoc();
15058   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
15059   SDValue V1 = SVOp->getOperand(0);
15060   SDValue V2 = SVOp->getOperand(1);
15061   EVT VT = SVOp->getValueType(0);
15062   unsigned NumElems = VT.getVectorNumElements();
15063
15064   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
15065       V2.getOpcode() == ISD::CONCAT_VECTORS) {
15066     //
15067     //                   0,0,0,...
15068     //                      |
15069     //    V      UNDEF    BUILD_VECTOR    UNDEF
15070     //     \      /           \           /
15071     //  CONCAT_VECTOR         CONCAT_VECTOR
15072     //         \                  /
15073     //          \                /
15074     //          RESULT: V + zero extended
15075     //
15076     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
15077         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
15078         V1.getOperand(1).getOpcode() != ISD::UNDEF)
15079       return SDValue();
15080
15081     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
15082       return SDValue();
15083
15084     // To match the shuffle mask, the first half of the mask should
15085     // be exactly the first vector, and all the rest a splat with the
15086     // first element of the second one.
15087     for (unsigned i = 0; i != NumElems/2; ++i)
15088       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
15089           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
15090         return SDValue();
15091
15092     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
15093     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
15094       if (Ld->hasNUsesOfValue(1, 0)) {
15095         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
15096         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
15097         SDValue ResNode =
15098           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2,
15099                                   Ld->getMemoryVT(),
15100                                   Ld->getPointerInfo(),
15101                                   Ld->getAlignment(),
15102                                   false/*isVolatile*/, true/*ReadMem*/,
15103                                   false/*WriteMem*/);
15104
15105         // Make sure the newly-created LOAD is in the same position as Ld in
15106         // terms of dependency. We create a TokenFactor for Ld and ResNode,
15107         // and update uses of Ld's output chain to use the TokenFactor.
15108         if (Ld->hasAnyUseOfValue(1)) {
15109           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
15110                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
15111           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
15112           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
15113                                  SDValue(ResNode.getNode(), 1));
15114         }
15115
15116         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
15117       }
15118     }
15119
15120     // Emit a zeroed vector and insert the desired subvector on its
15121     // first half.
15122     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15123     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
15124     return DCI.CombineTo(N, InsV);
15125   }
15126
15127   //===--------------------------------------------------------------------===//
15128   // Combine some shuffles into subvector extracts and inserts:
15129   //
15130
15131   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
15132   if (isShuffleHigh128VectorInsertLow(SVOp)) {
15133     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
15134     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
15135     return DCI.CombineTo(N, InsV);
15136   }
15137
15138   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
15139   if (isShuffleLow128VectorInsertHigh(SVOp)) {
15140     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
15141     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
15142     return DCI.CombineTo(N, InsV);
15143   }
15144
15145   return SDValue();
15146 }
15147
15148 /// PerformShuffleCombine - Performs several different shuffle combines.
15149 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
15150                                      TargetLowering::DAGCombinerInfo &DCI,
15151                                      const X86Subtarget *Subtarget) {
15152   DebugLoc dl = N->getDebugLoc();
15153   EVT VT = N->getValueType(0);
15154
15155   // Don't create instructions with illegal types after legalize types has run.
15156   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15157   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
15158     return SDValue();
15159
15160   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
15161   if (Subtarget->hasFp256() && VT.is256BitVector() &&
15162       N->getOpcode() == ISD::VECTOR_SHUFFLE)
15163     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
15164
15165   // Only handle 128 wide vector from here on.
15166   if (!VT.is128BitVector())
15167     return SDValue();
15168
15169   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
15170   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
15171   // consecutive, non-overlapping, and in the right order.
15172   SmallVector<SDValue, 16> Elts;
15173   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
15174     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
15175
15176   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
15177 }
15178
15179 /// PerformTruncateCombine - Converts truncate operation to
15180 /// a sequence of vector shuffle operations.
15181 /// It is possible when we truncate 256-bit vector to 128-bit vector
15182 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
15183                                       TargetLowering::DAGCombinerInfo &DCI,
15184                                       const X86Subtarget *Subtarget)  {
15185   return SDValue();
15186 }
15187
15188 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
15189 /// specific shuffle of a load can be folded into a single element load.
15190 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
15191 /// shuffles have been customed lowered so we need to handle those here.
15192 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
15193                                          TargetLowering::DAGCombinerInfo &DCI) {
15194   if (DCI.isBeforeLegalizeOps())
15195     return SDValue();
15196
15197   SDValue InVec = N->getOperand(0);
15198   SDValue EltNo = N->getOperand(1);
15199
15200   if (!isa<ConstantSDNode>(EltNo))
15201     return SDValue();
15202
15203   EVT VT = InVec.getValueType();
15204
15205   bool HasShuffleIntoBitcast = false;
15206   if (InVec.getOpcode() == ISD::BITCAST) {
15207     // Don't duplicate a load with other uses.
15208     if (!InVec.hasOneUse())
15209       return SDValue();
15210     EVT BCVT = InVec.getOperand(0).getValueType();
15211     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
15212       return SDValue();
15213     InVec = InVec.getOperand(0);
15214     HasShuffleIntoBitcast = true;
15215   }
15216
15217   if (!isTargetShuffle(InVec.getOpcode()))
15218     return SDValue();
15219
15220   // Don't duplicate a load with other uses.
15221   if (!InVec.hasOneUse())
15222     return SDValue();
15223
15224   SmallVector<int, 16> ShuffleMask;
15225   bool UnaryShuffle;
15226   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
15227                             UnaryShuffle))
15228     return SDValue();
15229
15230   // Select the input vector, guarding against out of range extract vector.
15231   unsigned NumElems = VT.getVectorNumElements();
15232   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
15233   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
15234   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
15235                                          : InVec.getOperand(1);
15236
15237   // If inputs to shuffle are the same for both ops, then allow 2 uses
15238   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
15239
15240   if (LdNode.getOpcode() == ISD::BITCAST) {
15241     // Don't duplicate a load with other uses.
15242     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
15243       return SDValue();
15244
15245     AllowedUses = 1; // only allow 1 load use if we have a bitcast
15246     LdNode = LdNode.getOperand(0);
15247   }
15248
15249   if (!ISD::isNormalLoad(LdNode.getNode()))
15250     return SDValue();
15251
15252   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
15253
15254   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
15255     return SDValue();
15256
15257   if (HasShuffleIntoBitcast) {
15258     // If there's a bitcast before the shuffle, check if the load type and
15259     // alignment is valid.
15260     unsigned Align = LN0->getAlignment();
15261     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15262     unsigned NewAlign = TLI.getDataLayout()->
15263       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
15264
15265     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
15266       return SDValue();
15267   }
15268
15269   // All checks match so transform back to vector_shuffle so that DAG combiner
15270   // can finish the job
15271   DebugLoc dl = N->getDebugLoc();
15272
15273   // Create shuffle node taking into account the case that its a unary shuffle
15274   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
15275   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
15276                                  InVec.getOperand(0), Shuffle,
15277                                  &ShuffleMask[0]);
15278   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
15279   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
15280                      EltNo);
15281 }
15282
15283 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
15284 /// generation and convert it from being a bunch of shuffles and extracts
15285 /// to a simple store and scalar loads to extract the elements.
15286 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
15287                                          TargetLowering::DAGCombinerInfo &DCI) {
15288   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
15289   if (NewOp.getNode())
15290     return NewOp;
15291
15292   SDValue InputVector = N->getOperand(0);
15293   // Detect whether we are trying to convert from mmx to i32 and the bitcast
15294   // from mmx to v2i32 has a single usage.
15295   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
15296       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
15297       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
15298     return DAG.getNode(X86ISD::MMX_MOVD2W, InputVector.getDebugLoc(),
15299                        N->getValueType(0),
15300                        InputVector.getNode()->getOperand(0));
15301
15302   // Only operate on vectors of 4 elements, where the alternative shuffling
15303   // gets to be more expensive.
15304   if (InputVector.getValueType() != MVT::v4i32)
15305     return SDValue();
15306
15307   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
15308   // single use which is a sign-extend or zero-extend, and all elements are
15309   // used.
15310   SmallVector<SDNode *, 4> Uses;
15311   unsigned ExtractedElements = 0;
15312   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
15313        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
15314     if (UI.getUse().getResNo() != InputVector.getResNo())
15315       return SDValue();
15316
15317     SDNode *Extract = *UI;
15318     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
15319       return SDValue();
15320
15321     if (Extract->getValueType(0) != MVT::i32)
15322       return SDValue();
15323     if (!Extract->hasOneUse())
15324       return SDValue();
15325     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
15326         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
15327       return SDValue();
15328     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
15329       return SDValue();
15330
15331     // Record which element was extracted.
15332     ExtractedElements |=
15333       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
15334
15335     Uses.push_back(Extract);
15336   }
15337
15338   // If not all the elements were used, this may not be worthwhile.
15339   if (ExtractedElements != 15)
15340     return SDValue();
15341
15342   // Ok, we've now decided to do the transformation.
15343   DebugLoc dl = InputVector.getDebugLoc();
15344
15345   // Store the value to a temporary stack slot.
15346   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
15347   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
15348                             MachinePointerInfo(), false, false, 0);
15349
15350   // Replace each use (extract) with a load of the appropriate element.
15351   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
15352        UE = Uses.end(); UI != UE; ++UI) {
15353     SDNode *Extract = *UI;
15354
15355     // cOMpute the element's address.
15356     SDValue Idx = Extract->getOperand(1);
15357     unsigned EltSize =
15358         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
15359     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
15360     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15361     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
15362
15363     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
15364                                      StackPtr, OffsetVal);
15365
15366     // Load the scalar.
15367     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
15368                                      ScalarAddr, MachinePointerInfo(),
15369                                      false, false, false, 0);
15370
15371     // Replace the exact with the load.
15372     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
15373   }
15374
15375   // The replacement was made in place; don't return anything.
15376   return SDValue();
15377 }
15378
15379 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
15380 static unsigned matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS,
15381                                    SDValue RHS, SelectionDAG &DAG,
15382                                    const X86Subtarget *Subtarget) {
15383   if (!VT.isVector())
15384     return 0;
15385
15386   switch (VT.getSimpleVT().SimpleTy) {
15387   default: return 0;
15388   case MVT::v32i8:
15389   case MVT::v16i16:
15390   case MVT::v8i32:
15391     if (!Subtarget->hasAVX2())
15392       return 0;
15393   case MVT::v16i8:
15394   case MVT::v8i16:
15395   case MVT::v4i32:
15396     if (!Subtarget->hasSSE2())
15397       return 0;
15398   }
15399
15400   // SSE2 has only a small subset of the operations.
15401   bool hasUnsigned = Subtarget->hasSSE41() ||
15402                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
15403   bool hasSigned = Subtarget->hasSSE41() ||
15404                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
15405
15406   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15407
15408   // Check for x CC y ? x : y.
15409   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15410       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15411     switch (CC) {
15412     default: break;
15413     case ISD::SETULT:
15414     case ISD::SETULE:
15415       return hasUnsigned ? X86ISD::UMIN : 0;
15416     case ISD::SETUGT:
15417     case ISD::SETUGE:
15418       return hasUnsigned ? X86ISD::UMAX : 0;
15419     case ISD::SETLT:
15420     case ISD::SETLE:
15421       return hasSigned ? X86ISD::SMIN : 0;
15422     case ISD::SETGT:
15423     case ISD::SETGE:
15424       return hasSigned ? X86ISD::SMAX : 0;
15425     }
15426   // Check for x CC y ? y : x -- a min/max with reversed arms.
15427   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
15428              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
15429     switch (CC) {
15430     default: break;
15431     case ISD::SETULT:
15432     case ISD::SETULE:
15433       return hasUnsigned ? X86ISD::UMAX : 0;
15434     case ISD::SETUGT:
15435     case ISD::SETUGE:
15436       return hasUnsigned ? X86ISD::UMIN : 0;
15437     case ISD::SETLT:
15438     case ISD::SETLE:
15439       return hasSigned ? X86ISD::SMAX : 0;
15440     case ISD::SETGT:
15441     case ISD::SETGE:
15442       return hasSigned ? X86ISD::SMIN : 0;
15443     }
15444   }
15445
15446   return 0;
15447 }
15448
15449 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
15450 /// nodes.
15451 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
15452                                     TargetLowering::DAGCombinerInfo &DCI,
15453                                     const X86Subtarget *Subtarget) {
15454   DebugLoc DL = N->getDebugLoc();
15455   SDValue Cond = N->getOperand(0);
15456   // Get the LHS/RHS of the select.
15457   SDValue LHS = N->getOperand(1);
15458   SDValue RHS = N->getOperand(2);
15459   EVT VT = LHS.getValueType();
15460
15461   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
15462   // instructions match the semantics of the common C idiom x<y?x:y but not
15463   // x<=y?x:y, because of how they handle negative zero (which can be
15464   // ignored in unsafe-math mode).
15465   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
15466       VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
15467       (Subtarget->hasSSE2() ||
15468        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
15469     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15470
15471     unsigned Opcode = 0;
15472     // Check for x CC y ? x : y.
15473     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15474         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15475       switch (CC) {
15476       default: break;
15477       case ISD::SETULT:
15478         // Converting this to a min would handle NaNs incorrectly, and swapping
15479         // the operands would cause it to handle comparisons between positive
15480         // and negative zero incorrectly.
15481         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
15482           if (!DAG.getTarget().Options.UnsafeFPMath &&
15483               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
15484             break;
15485           std::swap(LHS, RHS);
15486         }
15487         Opcode = X86ISD::FMIN;
15488         break;
15489       case ISD::SETOLE:
15490         // Converting this to a min would handle comparisons between positive
15491         // and negative zero incorrectly.
15492         if (!DAG.getTarget().Options.UnsafeFPMath &&
15493             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
15494           break;
15495         Opcode = X86ISD::FMIN;
15496         break;
15497       case ISD::SETULE:
15498         // Converting this to a min would handle both negative zeros and NaNs
15499         // incorrectly, but we can swap the operands to fix both.
15500         std::swap(LHS, RHS);
15501       case ISD::SETOLT:
15502       case ISD::SETLT:
15503       case ISD::SETLE:
15504         Opcode = X86ISD::FMIN;
15505         break;
15506
15507       case ISD::SETOGE:
15508         // Converting this to a max would handle comparisons between positive
15509         // and negative zero incorrectly.
15510         if (!DAG.getTarget().Options.UnsafeFPMath &&
15511             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
15512           break;
15513         Opcode = X86ISD::FMAX;
15514         break;
15515       case ISD::SETUGT:
15516         // Converting this to a max would handle NaNs incorrectly, and swapping
15517         // the operands would cause it to handle comparisons between positive
15518         // and negative zero incorrectly.
15519         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
15520           if (!DAG.getTarget().Options.UnsafeFPMath &&
15521               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
15522             break;
15523           std::swap(LHS, RHS);
15524         }
15525         Opcode = X86ISD::FMAX;
15526         break;
15527       case ISD::SETUGE:
15528         // Converting this to a max would handle both negative zeros and NaNs
15529         // incorrectly, but we can swap the operands to fix both.
15530         std::swap(LHS, RHS);
15531       case ISD::SETOGT:
15532       case ISD::SETGT:
15533       case ISD::SETGE:
15534         Opcode = X86ISD::FMAX;
15535         break;
15536       }
15537     // Check for x CC y ? y : x -- a min/max with reversed arms.
15538     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
15539                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
15540       switch (CC) {
15541       default: break;
15542       case ISD::SETOGE:
15543         // Converting this to a min would handle comparisons between positive
15544         // and negative zero incorrectly, and swapping the operands would
15545         // cause it to handle NaNs incorrectly.
15546         if (!DAG.getTarget().Options.UnsafeFPMath &&
15547             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
15548           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15549             break;
15550           std::swap(LHS, RHS);
15551         }
15552         Opcode = X86ISD::FMIN;
15553         break;
15554       case ISD::SETUGT:
15555         // Converting this to a min would handle NaNs incorrectly.
15556         if (!DAG.getTarget().Options.UnsafeFPMath &&
15557             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
15558           break;
15559         Opcode = X86ISD::FMIN;
15560         break;
15561       case ISD::SETUGE:
15562         // Converting this to a min would handle both negative zeros and NaNs
15563         // incorrectly, but we can swap the operands to fix both.
15564         std::swap(LHS, RHS);
15565       case ISD::SETOGT:
15566       case ISD::SETGT:
15567       case ISD::SETGE:
15568         Opcode = X86ISD::FMIN;
15569         break;
15570
15571       case ISD::SETULT:
15572         // Converting this to a max would handle NaNs incorrectly.
15573         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15574           break;
15575         Opcode = X86ISD::FMAX;
15576         break;
15577       case ISD::SETOLE:
15578         // Converting this to a max would handle comparisons between positive
15579         // and negative zero incorrectly, and swapping the operands would
15580         // cause it to handle NaNs incorrectly.
15581         if (!DAG.getTarget().Options.UnsafeFPMath &&
15582             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
15583           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15584             break;
15585           std::swap(LHS, RHS);
15586         }
15587         Opcode = X86ISD::FMAX;
15588         break;
15589       case ISD::SETULE:
15590         // Converting this to a max would handle both negative zeros and NaNs
15591         // incorrectly, but we can swap the operands to fix both.
15592         std::swap(LHS, RHS);
15593       case ISD::SETOLT:
15594       case ISD::SETLT:
15595       case ISD::SETLE:
15596         Opcode = X86ISD::FMAX;
15597         break;
15598       }
15599     }
15600
15601     if (Opcode)
15602       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
15603   }
15604
15605   // If this is a select between two integer constants, try to do some
15606   // optimizations.
15607   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
15608     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
15609       // Don't do this for crazy integer types.
15610       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
15611         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
15612         // so that TrueC (the true value) is larger than FalseC.
15613         bool NeedsCondInvert = false;
15614
15615         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
15616             // Efficiently invertible.
15617             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
15618              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
15619               isa<ConstantSDNode>(Cond.getOperand(1))))) {
15620           NeedsCondInvert = true;
15621           std::swap(TrueC, FalseC);
15622         }
15623
15624         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
15625         if (FalseC->getAPIntValue() == 0 &&
15626             TrueC->getAPIntValue().isPowerOf2()) {
15627           if (NeedsCondInvert) // Invert the condition if needed.
15628             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15629                                DAG.getConstant(1, Cond.getValueType()));
15630
15631           // Zero extend the condition if needed.
15632           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
15633
15634           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
15635           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
15636                              DAG.getConstant(ShAmt, MVT::i8));
15637         }
15638
15639         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
15640         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
15641           if (NeedsCondInvert) // Invert the condition if needed.
15642             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15643                                DAG.getConstant(1, Cond.getValueType()));
15644
15645           // Zero extend the condition if needed.
15646           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
15647                              FalseC->getValueType(0), Cond);
15648           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15649                              SDValue(FalseC, 0));
15650         }
15651
15652         // Optimize cases that will turn into an LEA instruction.  This requires
15653         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
15654         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
15655           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
15656           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
15657
15658           bool isFastMultiplier = false;
15659           if (Diff < 10) {
15660             switch ((unsigned char)Diff) {
15661               default: break;
15662               case 1:  // result = add base, cond
15663               case 2:  // result = lea base(    , cond*2)
15664               case 3:  // result = lea base(cond, cond*2)
15665               case 4:  // result = lea base(    , cond*4)
15666               case 5:  // result = lea base(cond, cond*4)
15667               case 8:  // result = lea base(    , cond*8)
15668               case 9:  // result = lea base(cond, cond*8)
15669                 isFastMultiplier = true;
15670                 break;
15671             }
15672           }
15673
15674           if (isFastMultiplier) {
15675             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
15676             if (NeedsCondInvert) // Invert the condition if needed.
15677               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15678                                  DAG.getConstant(1, Cond.getValueType()));
15679
15680             // Zero extend the condition if needed.
15681             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
15682                                Cond);
15683             // Scale the condition by the difference.
15684             if (Diff != 1)
15685               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
15686                                  DAG.getConstant(Diff, Cond.getValueType()));
15687
15688             // Add the base if non-zero.
15689             if (FalseC->getAPIntValue() != 0)
15690               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15691                                  SDValue(FalseC, 0));
15692             return Cond;
15693           }
15694         }
15695       }
15696   }
15697
15698   // Canonicalize max and min:
15699   // (x > y) ? x : y -> (x >= y) ? x : y
15700   // (x < y) ? x : y -> (x <= y) ? x : y
15701   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
15702   // the need for an extra compare
15703   // against zero. e.g.
15704   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
15705   // subl   %esi, %edi
15706   // testl  %edi, %edi
15707   // movl   $0, %eax
15708   // cmovgl %edi, %eax
15709   // =>
15710   // xorl   %eax, %eax
15711   // subl   %esi, $edi
15712   // cmovsl %eax, %edi
15713   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
15714       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15715       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15716     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15717     switch (CC) {
15718     default: break;
15719     case ISD::SETLT:
15720     case ISD::SETGT: {
15721       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
15722       Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
15723                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
15724       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
15725     }
15726     }
15727   }
15728
15729   // Match VSELECTs into subs with unsigned saturation.
15730   if (!DCI.isBeforeLegalize() &&
15731       N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
15732       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
15733       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
15734        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
15735     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15736
15737     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
15738     // left side invert the predicate to simplify logic below.
15739     SDValue Other;
15740     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
15741       Other = RHS;
15742       CC = ISD::getSetCCInverse(CC, true);
15743     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
15744       Other = LHS;
15745     }
15746
15747     if (Other.getNode() && Other->getNumOperands() == 2 &&
15748         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
15749       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
15750       SDValue CondRHS = Cond->getOperand(1);
15751
15752       // Look for a general sub with unsigned saturation first.
15753       // x >= y ? x-y : 0 --> subus x, y
15754       // x >  y ? x-y : 0 --> subus x, y
15755       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
15756           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
15757         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
15758
15759       // If the RHS is a constant we have to reverse the const canonicalization.
15760       // x > C-1 ? x+-C : 0 --> subus x, C
15761       if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
15762           isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
15763         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
15764         if (CondRHS.getConstantOperandVal(0) == -A-1)
15765           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
15766                              DAG.getConstant(-A, VT));
15767       }
15768
15769       // Another special case: If C was a sign bit, the sub has been
15770       // canonicalized into a xor.
15771       // FIXME: Would it be better to use ComputeMaskedBits to determine whether
15772       //        it's safe to decanonicalize the xor?
15773       // x s< 0 ? x^C : 0 --> subus x, C
15774       if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
15775           ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
15776           isSplatVector(OpRHS.getNode())) {
15777         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
15778         if (A.isSignBit())
15779           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
15780       }
15781     }
15782   }
15783
15784   // Try to match a min/max vector operation.
15785   if (!DCI.isBeforeLegalize() &&
15786       N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC)
15787     if (unsigned Op = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget))
15788       return DAG.getNode(Op, DL, N->getValueType(0), LHS, RHS);
15789
15790   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
15791   if (!DCI.isBeforeLegalize() && N->getOpcode() == ISD::VSELECT &&
15792       Cond.getOpcode() == ISD::SETCC) {
15793
15794     assert(Cond.getValueType().isVector() &&
15795            "vector select expects a vector selector!");
15796
15797     EVT IntVT = Cond.getValueType();
15798     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
15799     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
15800
15801     if (!TValIsAllOnes && !FValIsAllZeros) {
15802       // Try invert the condition if true value is not all 1s and false value
15803       // is not all 0s.
15804       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
15805       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
15806
15807       if (TValIsAllZeros || FValIsAllOnes) {
15808         SDValue CC = Cond.getOperand(2);
15809         ISD::CondCode NewCC =
15810           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
15811                                Cond.getOperand(0).getValueType().isInteger());
15812         Cond = DAG.getSetCC(DL, IntVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
15813         std::swap(LHS, RHS);
15814         TValIsAllOnes = FValIsAllOnes;
15815         FValIsAllZeros = TValIsAllZeros;
15816       }
15817     }
15818
15819     if (TValIsAllOnes || FValIsAllZeros) {
15820       SDValue Ret;
15821
15822       if (TValIsAllOnes && FValIsAllZeros)
15823         Ret = Cond;
15824       else if (TValIsAllOnes)
15825         Ret = DAG.getNode(ISD::OR, DL, IntVT, Cond,
15826                           DAG.getNode(ISD::BITCAST, DL, IntVT, RHS));
15827       else if (FValIsAllZeros)
15828         Ret = DAG.getNode(ISD::AND, DL, IntVT, Cond,
15829                           DAG.getNode(ISD::BITCAST, DL, IntVT, LHS));
15830
15831       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
15832     }
15833   }
15834
15835   // If we know that this node is legal then we know that it is going to be
15836   // matched by one of the SSE/AVX BLEND instructions. These instructions only
15837   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
15838   // to simplify previous instructions.
15839   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15840   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
15841       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
15842     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
15843
15844     // Don't optimize vector selects that map to mask-registers.
15845     if (BitWidth == 1)
15846       return SDValue();
15847
15848     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
15849     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
15850
15851     APInt KnownZero, KnownOne;
15852     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
15853                                           DCI.isBeforeLegalizeOps());
15854     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
15855         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
15856       DCI.CommitTargetLoweringOpt(TLO);
15857   }
15858
15859   return SDValue();
15860 }
15861
15862 // Check whether a boolean test is testing a boolean value generated by
15863 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
15864 // code.
15865 //
15866 // Simplify the following patterns:
15867 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
15868 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
15869 // to (Op EFLAGS Cond)
15870 //
15871 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
15872 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
15873 // to (Op EFLAGS !Cond)
15874 //
15875 // where Op could be BRCOND or CMOV.
15876 //
15877 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
15878   // Quit if not CMP and SUB with its value result used.
15879   if (Cmp.getOpcode() != X86ISD::CMP &&
15880       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
15881       return SDValue();
15882
15883   // Quit if not used as a boolean value.
15884   if (CC != X86::COND_E && CC != X86::COND_NE)
15885     return SDValue();
15886
15887   // Check CMP operands. One of them should be 0 or 1 and the other should be
15888   // an SetCC or extended from it.
15889   SDValue Op1 = Cmp.getOperand(0);
15890   SDValue Op2 = Cmp.getOperand(1);
15891
15892   SDValue SetCC;
15893   const ConstantSDNode* C = 0;
15894   bool needOppositeCond = (CC == X86::COND_E);
15895   bool checkAgainstTrue = false; // Is it a comparison against 1?
15896
15897   if ((C = dyn_cast<ConstantSDNode>(Op1)))
15898     SetCC = Op2;
15899   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
15900     SetCC = Op1;
15901   else // Quit if all operands are not constants.
15902     return SDValue();
15903
15904   if (C->getZExtValue() == 1) {
15905     needOppositeCond = !needOppositeCond;
15906     checkAgainstTrue = true;
15907   } else if (C->getZExtValue() != 0)
15908     // Quit if the constant is neither 0 or 1.
15909     return SDValue();
15910
15911   bool truncatedToBoolWithAnd = false;
15912   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
15913   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
15914          SetCC.getOpcode() == ISD::TRUNCATE ||
15915          SetCC.getOpcode() == ISD::AND) {
15916     if (SetCC.getOpcode() == ISD::AND) {
15917       int OpIdx = -1;
15918       ConstantSDNode *CS;
15919       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
15920           CS->getZExtValue() == 1)
15921         OpIdx = 1;
15922       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
15923           CS->getZExtValue() == 1)
15924         OpIdx = 0;
15925       if (OpIdx == -1)
15926         break;
15927       SetCC = SetCC.getOperand(OpIdx);
15928       truncatedToBoolWithAnd = true;
15929     } else
15930       SetCC = SetCC.getOperand(0);
15931   }
15932
15933   switch (SetCC.getOpcode()) {
15934   case X86ISD::SETCC_CARRY:
15935     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
15936     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
15937     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
15938     // truncated to i1 using 'and'.
15939     if (checkAgainstTrue && !truncatedToBoolWithAnd)
15940       break;
15941     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
15942            "Invalid use of SETCC_CARRY!");
15943     // FALL THROUGH
15944   case X86ISD::SETCC:
15945     // Set the condition code or opposite one if necessary.
15946     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
15947     if (needOppositeCond)
15948       CC = X86::GetOppositeBranchCondition(CC);
15949     return SetCC.getOperand(1);
15950   case X86ISD::CMOV: {
15951     // Check whether false/true value has canonical one, i.e. 0 or 1.
15952     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
15953     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
15954     // Quit if true value is not a constant.
15955     if (!TVal)
15956       return SDValue();
15957     // Quit if false value is not a constant.
15958     if (!FVal) {
15959       SDValue Op = SetCC.getOperand(0);
15960       // Skip 'zext' or 'trunc' node.
15961       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
15962           Op.getOpcode() == ISD::TRUNCATE)
15963         Op = Op.getOperand(0);
15964       // A special case for rdrand/rdseed, where 0 is set if false cond is
15965       // found.
15966       if ((Op.getOpcode() != X86ISD::RDRAND &&
15967            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
15968         return SDValue();
15969     }
15970     // Quit if false value is not the constant 0 or 1.
15971     bool FValIsFalse = true;
15972     if (FVal && FVal->getZExtValue() != 0) {
15973       if (FVal->getZExtValue() != 1)
15974         return SDValue();
15975       // If FVal is 1, opposite cond is needed.
15976       needOppositeCond = !needOppositeCond;
15977       FValIsFalse = false;
15978     }
15979     // Quit if TVal is not the constant opposite of FVal.
15980     if (FValIsFalse && TVal->getZExtValue() != 1)
15981       return SDValue();
15982     if (!FValIsFalse && TVal->getZExtValue() != 0)
15983       return SDValue();
15984     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
15985     if (needOppositeCond)
15986       CC = X86::GetOppositeBranchCondition(CC);
15987     return SetCC.getOperand(3);
15988   }
15989   }
15990
15991   return SDValue();
15992 }
15993
15994 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
15995 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
15996                                   TargetLowering::DAGCombinerInfo &DCI,
15997                                   const X86Subtarget *Subtarget) {
15998   DebugLoc DL = N->getDebugLoc();
15999
16000   // If the flag operand isn't dead, don't touch this CMOV.
16001   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
16002     return SDValue();
16003
16004   SDValue FalseOp = N->getOperand(0);
16005   SDValue TrueOp = N->getOperand(1);
16006   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
16007   SDValue Cond = N->getOperand(3);
16008
16009   if (CC == X86::COND_E || CC == X86::COND_NE) {
16010     switch (Cond.getOpcode()) {
16011     default: break;
16012     case X86ISD::BSR:
16013     case X86ISD::BSF:
16014       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
16015       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
16016         return (CC == X86::COND_E) ? FalseOp : TrueOp;
16017     }
16018   }
16019
16020   SDValue Flags;
16021
16022   Flags = checkBoolTestSetCCCombine(Cond, CC);
16023   if (Flags.getNode() &&
16024       // Extra check as FCMOV only supports a subset of X86 cond.
16025       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
16026     SDValue Ops[] = { FalseOp, TrueOp,
16027                       DAG.getConstant(CC, MVT::i8), Flags };
16028     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
16029                        Ops, array_lengthof(Ops));
16030   }
16031
16032   // If this is a select between two integer constants, try to do some
16033   // optimizations.  Note that the operands are ordered the opposite of SELECT
16034   // operands.
16035   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
16036     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
16037       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
16038       // larger than FalseC (the false value).
16039       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
16040         CC = X86::GetOppositeBranchCondition(CC);
16041         std::swap(TrueC, FalseC);
16042         std::swap(TrueOp, FalseOp);
16043       }
16044
16045       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
16046       // This is efficient for any integer data type (including i8/i16) and
16047       // shift amount.
16048       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
16049         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16050                            DAG.getConstant(CC, MVT::i8), Cond);
16051
16052         // Zero extend the condition if needed.
16053         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
16054
16055         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
16056         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
16057                            DAG.getConstant(ShAmt, MVT::i8));
16058         if (N->getNumValues() == 2)  // Dead flag value?
16059           return DCI.CombineTo(N, Cond, SDValue());
16060         return Cond;
16061       }
16062
16063       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
16064       // for any integer data type, including i8/i16.
16065       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
16066         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16067                            DAG.getConstant(CC, MVT::i8), Cond);
16068
16069         // Zero extend the condition if needed.
16070         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
16071                            FalseC->getValueType(0), Cond);
16072         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16073                            SDValue(FalseC, 0));
16074
16075         if (N->getNumValues() == 2)  // Dead flag value?
16076           return DCI.CombineTo(N, Cond, SDValue());
16077         return Cond;
16078       }
16079
16080       // Optimize cases that will turn into an LEA instruction.  This requires
16081       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
16082       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
16083         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
16084         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
16085
16086         bool isFastMultiplier = false;
16087         if (Diff < 10) {
16088           switch ((unsigned char)Diff) {
16089           default: break;
16090           case 1:  // result = add base, cond
16091           case 2:  // result = lea base(    , cond*2)
16092           case 3:  // result = lea base(cond, cond*2)
16093           case 4:  // result = lea base(    , cond*4)
16094           case 5:  // result = lea base(cond, cond*4)
16095           case 8:  // result = lea base(    , cond*8)
16096           case 9:  // result = lea base(cond, cond*8)
16097             isFastMultiplier = true;
16098             break;
16099           }
16100         }
16101
16102         if (isFastMultiplier) {
16103           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
16104           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16105                              DAG.getConstant(CC, MVT::i8), Cond);
16106           // Zero extend the condition if needed.
16107           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
16108                              Cond);
16109           // Scale the condition by the difference.
16110           if (Diff != 1)
16111             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
16112                                DAG.getConstant(Diff, Cond.getValueType()));
16113
16114           // Add the base if non-zero.
16115           if (FalseC->getAPIntValue() != 0)
16116             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16117                                SDValue(FalseC, 0));
16118           if (N->getNumValues() == 2)  // Dead flag value?
16119             return DCI.CombineTo(N, Cond, SDValue());
16120           return Cond;
16121         }
16122       }
16123     }
16124   }
16125
16126   // Handle these cases:
16127   //   (select (x != c), e, c) -> select (x != c), e, x),
16128   //   (select (x == c), c, e) -> select (x == c), x, e)
16129   // where the c is an integer constant, and the "select" is the combination
16130   // of CMOV and CMP.
16131   //
16132   // The rationale for this change is that the conditional-move from a constant
16133   // needs two instructions, however, conditional-move from a register needs
16134   // only one instruction.
16135   //
16136   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
16137   //  some instruction-combining opportunities. This opt needs to be
16138   //  postponed as late as possible.
16139   //
16140   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
16141     // the DCI.xxxx conditions are provided to postpone the optimization as
16142     // late as possible.
16143
16144     ConstantSDNode *CmpAgainst = 0;
16145     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
16146         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
16147         !isa<ConstantSDNode>(Cond.getOperand(0))) {
16148
16149       if (CC == X86::COND_NE &&
16150           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
16151         CC = X86::GetOppositeBranchCondition(CC);
16152         std::swap(TrueOp, FalseOp);
16153       }
16154
16155       if (CC == X86::COND_E &&
16156           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
16157         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
16158                           DAG.getConstant(CC, MVT::i8), Cond };
16159         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
16160                            array_lengthof(Ops));
16161       }
16162     }
16163   }
16164
16165   return SDValue();
16166 }
16167
16168 /// PerformMulCombine - Optimize a single multiply with constant into two
16169 /// in order to implement it with two cheaper instructions, e.g.
16170 /// LEA + SHL, LEA + LEA.
16171 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
16172                                  TargetLowering::DAGCombinerInfo &DCI) {
16173   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
16174     return SDValue();
16175
16176   EVT VT = N->getValueType(0);
16177   if (VT != MVT::i64)
16178     return SDValue();
16179
16180   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
16181   if (!C)
16182     return SDValue();
16183   uint64_t MulAmt = C->getZExtValue();
16184   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
16185     return SDValue();
16186
16187   uint64_t MulAmt1 = 0;
16188   uint64_t MulAmt2 = 0;
16189   if ((MulAmt % 9) == 0) {
16190     MulAmt1 = 9;
16191     MulAmt2 = MulAmt / 9;
16192   } else if ((MulAmt % 5) == 0) {
16193     MulAmt1 = 5;
16194     MulAmt2 = MulAmt / 5;
16195   } else if ((MulAmt % 3) == 0) {
16196     MulAmt1 = 3;
16197     MulAmt2 = MulAmt / 3;
16198   }
16199   if (MulAmt2 &&
16200       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
16201     DebugLoc DL = N->getDebugLoc();
16202
16203     if (isPowerOf2_64(MulAmt2) &&
16204         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
16205       // If second multiplifer is pow2, issue it first. We want the multiply by
16206       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
16207       // is an add.
16208       std::swap(MulAmt1, MulAmt2);
16209
16210     SDValue NewMul;
16211     if (isPowerOf2_64(MulAmt1))
16212       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
16213                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
16214     else
16215       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
16216                            DAG.getConstant(MulAmt1, VT));
16217
16218     if (isPowerOf2_64(MulAmt2))
16219       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
16220                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
16221     else
16222       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
16223                            DAG.getConstant(MulAmt2, VT));
16224
16225     // Do not add new nodes to DAG combiner worklist.
16226     DCI.CombineTo(N, NewMul, false);
16227   }
16228   return SDValue();
16229 }
16230
16231 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
16232   SDValue N0 = N->getOperand(0);
16233   SDValue N1 = N->getOperand(1);
16234   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
16235   EVT VT = N0.getValueType();
16236
16237   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
16238   // since the result of setcc_c is all zero's or all ones.
16239   if (VT.isInteger() && !VT.isVector() &&
16240       N1C && N0.getOpcode() == ISD::AND &&
16241       N0.getOperand(1).getOpcode() == ISD::Constant) {
16242     SDValue N00 = N0.getOperand(0);
16243     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
16244         ((N00.getOpcode() == ISD::ANY_EXTEND ||
16245           N00.getOpcode() == ISD::ZERO_EXTEND) &&
16246          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
16247       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
16248       APInt ShAmt = N1C->getAPIntValue();
16249       Mask = Mask.shl(ShAmt);
16250       if (Mask != 0)
16251         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
16252                            N00, DAG.getConstant(Mask, VT));
16253     }
16254   }
16255
16256   // Hardware support for vector shifts is sparse which makes us scalarize the
16257   // vector operations in many cases. Also, on sandybridge ADD is faster than
16258   // shl.
16259   // (shl V, 1) -> add V,V
16260   if (isSplatVector(N1.getNode())) {
16261     assert(N0.getValueType().isVector() && "Invalid vector shift type");
16262     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
16263     // We shift all of the values by one. In many cases we do not have
16264     // hardware support for this operation. This is better expressed as an ADD
16265     // of two values.
16266     if (N1C && (1 == N1C->getZExtValue())) {
16267       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
16268     }
16269   }
16270
16271   return SDValue();
16272 }
16273
16274 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
16275 ///                       when possible.
16276 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
16277                                    TargetLowering::DAGCombinerInfo &DCI,
16278                                    const X86Subtarget *Subtarget) {
16279   if (N->getOpcode() == ISD::SHL) {
16280     SDValue V = PerformSHLCombine(N, DAG);
16281     if (V.getNode()) return V;
16282   }
16283
16284   return SDValue();
16285 }
16286
16287 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
16288 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
16289 // and friends.  Likewise for OR -> CMPNEQSS.
16290 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
16291                             TargetLowering::DAGCombinerInfo &DCI,
16292                             const X86Subtarget *Subtarget) {
16293   unsigned opcode;
16294
16295   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
16296   // we're requiring SSE2 for both.
16297   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
16298     SDValue N0 = N->getOperand(0);
16299     SDValue N1 = N->getOperand(1);
16300     SDValue CMP0 = N0->getOperand(1);
16301     SDValue CMP1 = N1->getOperand(1);
16302     DebugLoc DL = N->getDebugLoc();
16303
16304     // The SETCCs should both refer to the same CMP.
16305     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
16306       return SDValue();
16307
16308     SDValue CMP00 = CMP0->getOperand(0);
16309     SDValue CMP01 = CMP0->getOperand(1);
16310     EVT     VT    = CMP00.getValueType();
16311
16312     if (VT == MVT::f32 || VT == MVT::f64) {
16313       bool ExpectingFlags = false;
16314       // Check for any users that want flags:
16315       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
16316            !ExpectingFlags && UI != UE; ++UI)
16317         switch (UI->getOpcode()) {
16318         default:
16319         case ISD::BR_CC:
16320         case ISD::BRCOND:
16321         case ISD::SELECT:
16322           ExpectingFlags = true;
16323           break;
16324         case ISD::CopyToReg:
16325         case ISD::SIGN_EXTEND:
16326         case ISD::ZERO_EXTEND:
16327         case ISD::ANY_EXTEND:
16328           break;
16329         }
16330
16331       if (!ExpectingFlags) {
16332         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
16333         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
16334
16335         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
16336           X86::CondCode tmp = cc0;
16337           cc0 = cc1;
16338           cc1 = tmp;
16339         }
16340
16341         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
16342             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
16343           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
16344           X86ISD::NodeType NTOperator = is64BitFP ?
16345             X86ISD::FSETCCsd : X86ISD::FSETCCss;
16346           // FIXME: need symbolic constants for these magic numbers.
16347           // See X86ATTInstPrinter.cpp:printSSECC().
16348           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
16349           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
16350                                               DAG.getConstant(x86cc, MVT::i8));
16351           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
16352                                               OnesOrZeroesF);
16353           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
16354                                       DAG.getConstant(1, MVT::i32));
16355           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
16356           return OneBitOfTruth;
16357         }
16358       }
16359     }
16360   }
16361   return SDValue();
16362 }
16363
16364 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
16365 /// so it can be folded inside ANDNP.
16366 static bool CanFoldXORWithAllOnes(const SDNode *N) {
16367   EVT VT = N->getValueType(0);
16368
16369   // Match direct AllOnes for 128 and 256-bit vectors
16370   if (ISD::isBuildVectorAllOnes(N))
16371     return true;
16372
16373   // Look through a bit convert.
16374   if (N->getOpcode() == ISD::BITCAST)
16375     N = N->getOperand(0).getNode();
16376
16377   // Sometimes the operand may come from a insert_subvector building a 256-bit
16378   // allones vector
16379   if (VT.is256BitVector() &&
16380       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
16381     SDValue V1 = N->getOperand(0);
16382     SDValue V2 = N->getOperand(1);
16383
16384     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
16385         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
16386         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
16387         ISD::isBuildVectorAllOnes(V2.getNode()))
16388       return true;
16389   }
16390
16391   return false;
16392 }
16393
16394 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
16395 // register. In most cases we actually compare or select YMM-sized registers
16396 // and mixing the two types creates horrible code. This method optimizes
16397 // some of the transition sequences.
16398 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
16399                                  TargetLowering::DAGCombinerInfo &DCI,
16400                                  const X86Subtarget *Subtarget) {
16401   EVT VT = N->getValueType(0);
16402   if (!VT.is256BitVector())
16403     return SDValue();
16404
16405   assert((N->getOpcode() == ISD::ANY_EXTEND ||
16406           N->getOpcode() == ISD::ZERO_EXTEND ||
16407           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
16408
16409   SDValue Narrow = N->getOperand(0);
16410   EVT NarrowVT = Narrow->getValueType(0);
16411   if (!NarrowVT.is128BitVector())
16412     return SDValue();
16413
16414   if (Narrow->getOpcode() != ISD::XOR &&
16415       Narrow->getOpcode() != ISD::AND &&
16416       Narrow->getOpcode() != ISD::OR)
16417     return SDValue();
16418
16419   SDValue N0  = Narrow->getOperand(0);
16420   SDValue N1  = Narrow->getOperand(1);
16421   DebugLoc DL = Narrow->getDebugLoc();
16422
16423   // The Left side has to be a trunc.
16424   if (N0.getOpcode() != ISD::TRUNCATE)
16425     return SDValue();
16426
16427   // The type of the truncated inputs.
16428   EVT WideVT = N0->getOperand(0)->getValueType(0);
16429   if (WideVT != VT)
16430     return SDValue();
16431
16432   // The right side has to be a 'trunc' or a constant vector.
16433   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
16434   bool RHSConst = (isSplatVector(N1.getNode()) &&
16435                    isa<ConstantSDNode>(N1->getOperand(0)));
16436   if (!RHSTrunc && !RHSConst)
16437     return SDValue();
16438
16439   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16440
16441   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
16442     return SDValue();
16443
16444   // Set N0 and N1 to hold the inputs to the new wide operation.
16445   N0 = N0->getOperand(0);
16446   if (RHSConst) {
16447     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
16448                      N1->getOperand(0));
16449     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
16450     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, &C[0], C.size());
16451   } else if (RHSTrunc) {
16452     N1 = N1->getOperand(0);
16453   }
16454
16455   // Generate the wide operation.
16456   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
16457   unsigned Opcode = N->getOpcode();
16458   switch (Opcode) {
16459   case ISD::ANY_EXTEND:
16460     return Op;
16461   case ISD::ZERO_EXTEND: {
16462     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
16463     APInt Mask = APInt::getAllOnesValue(InBits);
16464     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
16465     return DAG.getNode(ISD::AND, DL, VT,
16466                        Op, DAG.getConstant(Mask, VT));
16467   }
16468   case ISD::SIGN_EXTEND:
16469     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
16470                        Op, DAG.getValueType(NarrowVT));
16471   default:
16472     llvm_unreachable("Unexpected opcode");
16473   }
16474 }
16475
16476 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
16477                                  TargetLowering::DAGCombinerInfo &DCI,
16478                                  const X86Subtarget *Subtarget) {
16479   EVT VT = N->getValueType(0);
16480   if (DCI.isBeforeLegalizeOps())
16481     return SDValue();
16482
16483   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
16484   if (R.getNode())
16485     return R;
16486
16487   // Create BLSI, and BLSR instructions
16488   // BLSI is X & (-X)
16489   // BLSR is X & (X-1)
16490   if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
16491     SDValue N0 = N->getOperand(0);
16492     SDValue N1 = N->getOperand(1);
16493     DebugLoc DL = N->getDebugLoc();
16494
16495     // Check LHS for neg
16496     if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
16497         isZero(N0.getOperand(0)))
16498       return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
16499
16500     // Check RHS for neg
16501     if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
16502         isZero(N1.getOperand(0)))
16503       return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
16504
16505     // Check LHS for X-1
16506     if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
16507         isAllOnes(N0.getOperand(1)))
16508       return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
16509
16510     // Check RHS for X-1
16511     if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
16512         isAllOnes(N1.getOperand(1)))
16513       return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
16514
16515     return SDValue();
16516   }
16517
16518   // Want to form ANDNP nodes:
16519   // 1) In the hopes of then easily combining them with OR and AND nodes
16520   //    to form PBLEND/PSIGN.
16521   // 2) To match ANDN packed intrinsics
16522   if (VT != MVT::v2i64 && VT != MVT::v4i64)
16523     return SDValue();
16524
16525   SDValue N0 = N->getOperand(0);
16526   SDValue N1 = N->getOperand(1);
16527   DebugLoc DL = N->getDebugLoc();
16528
16529   // Check LHS for vnot
16530   if (N0.getOpcode() == ISD::XOR &&
16531       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
16532       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
16533     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
16534
16535   // Check RHS for vnot
16536   if (N1.getOpcode() == ISD::XOR &&
16537       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
16538       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
16539     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
16540
16541   return SDValue();
16542 }
16543
16544 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
16545                                 TargetLowering::DAGCombinerInfo &DCI,
16546                                 const X86Subtarget *Subtarget) {
16547   EVT VT = N->getValueType(0);
16548   if (DCI.isBeforeLegalizeOps())
16549     return SDValue();
16550
16551   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
16552   if (R.getNode())
16553     return R;
16554
16555   SDValue N0 = N->getOperand(0);
16556   SDValue N1 = N->getOperand(1);
16557
16558   // look for psign/blend
16559   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
16560     if (!Subtarget->hasSSSE3() ||
16561         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
16562       return SDValue();
16563
16564     // Canonicalize pandn to RHS
16565     if (N0.getOpcode() == X86ISD::ANDNP)
16566       std::swap(N0, N1);
16567     // or (and (m, y), (pandn m, x))
16568     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
16569       SDValue Mask = N1.getOperand(0);
16570       SDValue X    = N1.getOperand(1);
16571       SDValue Y;
16572       if (N0.getOperand(0) == Mask)
16573         Y = N0.getOperand(1);
16574       if (N0.getOperand(1) == Mask)
16575         Y = N0.getOperand(0);
16576
16577       // Check to see if the mask appeared in both the AND and ANDNP and
16578       if (!Y.getNode())
16579         return SDValue();
16580
16581       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
16582       // Look through mask bitcast.
16583       if (Mask.getOpcode() == ISD::BITCAST)
16584         Mask = Mask.getOperand(0);
16585       if (X.getOpcode() == ISD::BITCAST)
16586         X = X.getOperand(0);
16587       if (Y.getOpcode() == ISD::BITCAST)
16588         Y = Y.getOperand(0);
16589
16590       EVT MaskVT = Mask.getValueType();
16591
16592       // Validate that the Mask operand is a vector sra node.
16593       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
16594       // there is no psrai.b
16595       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
16596       unsigned SraAmt = ~0;
16597       if (Mask.getOpcode() == ISD::SRA) {
16598         SDValue Amt = Mask.getOperand(1);
16599         if (isSplatVector(Amt.getNode())) {
16600           SDValue SclrAmt = Amt->getOperand(0);
16601           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
16602             SraAmt = C->getZExtValue();
16603         }
16604       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
16605         SDValue SraC = Mask.getOperand(1);
16606         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
16607       }
16608       if ((SraAmt + 1) != EltBits)
16609         return SDValue();
16610
16611       DebugLoc DL = N->getDebugLoc();
16612
16613       // Now we know we at least have a plendvb with the mask val.  See if
16614       // we can form a psignb/w/d.
16615       // psign = x.type == y.type == mask.type && y = sub(0, x);
16616       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
16617           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
16618           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
16619         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
16620                "Unsupported VT for PSIGN");
16621         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
16622         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
16623       }
16624       // PBLENDVB only available on SSE 4.1
16625       if (!Subtarget->hasSSE41())
16626         return SDValue();
16627
16628       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
16629
16630       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
16631       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
16632       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
16633       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
16634       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
16635     }
16636   }
16637
16638   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
16639     return SDValue();
16640
16641   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
16642   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
16643     std::swap(N0, N1);
16644   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
16645     return SDValue();
16646   if (!N0.hasOneUse() || !N1.hasOneUse())
16647     return SDValue();
16648
16649   SDValue ShAmt0 = N0.getOperand(1);
16650   if (ShAmt0.getValueType() != MVT::i8)
16651     return SDValue();
16652   SDValue ShAmt1 = N1.getOperand(1);
16653   if (ShAmt1.getValueType() != MVT::i8)
16654     return SDValue();
16655   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
16656     ShAmt0 = ShAmt0.getOperand(0);
16657   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
16658     ShAmt1 = ShAmt1.getOperand(0);
16659
16660   DebugLoc DL = N->getDebugLoc();
16661   unsigned Opc = X86ISD::SHLD;
16662   SDValue Op0 = N0.getOperand(0);
16663   SDValue Op1 = N1.getOperand(0);
16664   if (ShAmt0.getOpcode() == ISD::SUB) {
16665     Opc = X86ISD::SHRD;
16666     std::swap(Op0, Op1);
16667     std::swap(ShAmt0, ShAmt1);
16668   }
16669
16670   unsigned Bits = VT.getSizeInBits();
16671   if (ShAmt1.getOpcode() == ISD::SUB) {
16672     SDValue Sum = ShAmt1.getOperand(0);
16673     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
16674       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
16675       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
16676         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
16677       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
16678         return DAG.getNode(Opc, DL, VT,
16679                            Op0, Op1,
16680                            DAG.getNode(ISD::TRUNCATE, DL,
16681                                        MVT::i8, ShAmt0));
16682     }
16683   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
16684     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
16685     if (ShAmt0C &&
16686         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
16687       return DAG.getNode(Opc, DL, VT,
16688                          N0.getOperand(0), N1.getOperand(0),
16689                          DAG.getNode(ISD::TRUNCATE, DL,
16690                                        MVT::i8, ShAmt0));
16691   }
16692
16693   return SDValue();
16694 }
16695
16696 // Generate NEG and CMOV for integer abs.
16697 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
16698   EVT VT = N->getValueType(0);
16699
16700   // Since X86 does not have CMOV for 8-bit integer, we don't convert
16701   // 8-bit integer abs to NEG and CMOV.
16702   if (VT.isInteger() && VT.getSizeInBits() == 8)
16703     return SDValue();
16704
16705   SDValue N0 = N->getOperand(0);
16706   SDValue N1 = N->getOperand(1);
16707   DebugLoc DL = N->getDebugLoc();
16708
16709   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
16710   // and change it to SUB and CMOV.
16711   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
16712       N0.getOpcode() == ISD::ADD &&
16713       N0.getOperand(1) == N1 &&
16714       N1.getOpcode() == ISD::SRA &&
16715       N1.getOperand(0) == N0.getOperand(0))
16716     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
16717       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
16718         // Generate SUB & CMOV.
16719         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
16720                                   DAG.getConstant(0, VT), N0.getOperand(0));
16721
16722         SDValue Ops[] = { N0.getOperand(0), Neg,
16723                           DAG.getConstant(X86::COND_GE, MVT::i8),
16724                           SDValue(Neg.getNode(), 1) };
16725         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
16726                            Ops, array_lengthof(Ops));
16727       }
16728   return SDValue();
16729 }
16730
16731 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
16732 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
16733                                  TargetLowering::DAGCombinerInfo &DCI,
16734                                  const X86Subtarget *Subtarget) {
16735   EVT VT = N->getValueType(0);
16736   if (DCI.isBeforeLegalizeOps())
16737     return SDValue();
16738
16739   if (Subtarget->hasCMov()) {
16740     SDValue RV = performIntegerAbsCombine(N, DAG);
16741     if (RV.getNode())
16742       return RV;
16743   }
16744
16745   // Try forming BMI if it is available.
16746   if (!Subtarget->hasBMI())
16747     return SDValue();
16748
16749   if (VT != MVT::i32 && VT != MVT::i64)
16750     return SDValue();
16751
16752   assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
16753
16754   // Create BLSMSK instructions by finding X ^ (X-1)
16755   SDValue N0 = N->getOperand(0);
16756   SDValue N1 = N->getOperand(1);
16757   DebugLoc DL = N->getDebugLoc();
16758
16759   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
16760       isAllOnes(N0.getOperand(1)))
16761     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
16762
16763   if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
16764       isAllOnes(N1.getOperand(1)))
16765     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
16766
16767   return SDValue();
16768 }
16769
16770 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
16771 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
16772                                   TargetLowering::DAGCombinerInfo &DCI,
16773                                   const X86Subtarget *Subtarget) {
16774   LoadSDNode *Ld = cast<LoadSDNode>(N);
16775   EVT RegVT = Ld->getValueType(0);
16776   EVT MemVT = Ld->getMemoryVT();
16777   DebugLoc dl = Ld->getDebugLoc();
16778   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16779   unsigned RegSz = RegVT.getSizeInBits();
16780
16781   // On Sandybridge unaligned 256bit loads are inefficient.
16782   ISD::LoadExtType Ext = Ld->getExtensionType();
16783   unsigned Alignment = Ld->getAlignment();
16784   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
16785   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
16786       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
16787     unsigned NumElems = RegVT.getVectorNumElements();
16788     if (NumElems < 2)
16789       return SDValue();
16790
16791     SDValue Ptr = Ld->getBasePtr();
16792     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
16793
16794     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
16795                                   NumElems/2);
16796     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
16797                                 Ld->getPointerInfo(), Ld->isVolatile(),
16798                                 Ld->isNonTemporal(), Ld->isInvariant(),
16799                                 Alignment);
16800     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16801     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
16802                                 Ld->getPointerInfo(), Ld->isVolatile(),
16803                                 Ld->isNonTemporal(), Ld->isInvariant(),
16804                                 std::min(16U, Alignment));
16805     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
16806                              Load1.getValue(1),
16807                              Load2.getValue(1));
16808
16809     SDValue NewVec = DAG.getUNDEF(RegVT);
16810     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
16811     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
16812     return DCI.CombineTo(N, NewVec, TF, true);
16813   }
16814
16815   // If this is a vector EXT Load then attempt to optimize it using a
16816   // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
16817   // expansion is still better than scalar code.
16818   // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
16819   // emit a shuffle and a arithmetic shift.
16820   // TODO: It is possible to support ZExt by zeroing the undef values
16821   // during the shuffle phase or after the shuffle.
16822   if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
16823       (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
16824     assert(MemVT != RegVT && "Cannot extend to the same type");
16825     assert(MemVT.isVector() && "Must load a vector from memory");
16826
16827     unsigned NumElems = RegVT.getVectorNumElements();
16828     unsigned MemSz = MemVT.getSizeInBits();
16829     assert(RegSz > MemSz && "Register size must be greater than the mem size");
16830
16831     if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
16832       return SDValue();
16833
16834     // All sizes must be a power of two.
16835     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
16836       return SDValue();
16837
16838     // Attempt to load the original value using scalar loads.
16839     // Find the largest scalar type that divides the total loaded size.
16840     MVT SclrLoadTy = MVT::i8;
16841     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
16842          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
16843       MVT Tp = (MVT::SimpleValueType)tp;
16844       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
16845         SclrLoadTy = Tp;
16846       }
16847     }
16848
16849     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
16850     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
16851         (64 <= MemSz))
16852       SclrLoadTy = MVT::f64;
16853
16854     // Calculate the number of scalar loads that we need to perform
16855     // in order to load our vector from memory.
16856     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
16857     if (Ext == ISD::SEXTLOAD && NumLoads > 1)
16858       return SDValue();
16859
16860     unsigned loadRegZize = RegSz;
16861     if (Ext == ISD::SEXTLOAD && RegSz == 256)
16862       loadRegZize /= 2;
16863
16864     // Represent our vector as a sequence of elements which are the
16865     // largest scalar that we can load.
16866     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
16867       loadRegZize/SclrLoadTy.getSizeInBits());
16868
16869     // Represent the data using the same element type that is stored in
16870     // memory. In practice, we ''widen'' MemVT.
16871     EVT WideVecVT =
16872           EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
16873                        loadRegZize/MemVT.getScalarType().getSizeInBits());
16874
16875     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
16876       "Invalid vector type");
16877
16878     // We can't shuffle using an illegal type.
16879     if (!TLI.isTypeLegal(WideVecVT))
16880       return SDValue();
16881
16882     SmallVector<SDValue, 8> Chains;
16883     SDValue Ptr = Ld->getBasePtr();
16884     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
16885                                         TLI.getPointerTy());
16886     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
16887
16888     for (unsigned i = 0; i < NumLoads; ++i) {
16889       // Perform a single load.
16890       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
16891                                        Ptr, Ld->getPointerInfo(),
16892                                        Ld->isVolatile(), Ld->isNonTemporal(),
16893                                        Ld->isInvariant(), Ld->getAlignment());
16894       Chains.push_back(ScalarLoad.getValue(1));
16895       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
16896       // another round of DAGCombining.
16897       if (i == 0)
16898         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
16899       else
16900         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
16901                           ScalarLoad, DAG.getIntPtrConstant(i));
16902
16903       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16904     }
16905
16906     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
16907                                Chains.size());
16908
16909     // Bitcast the loaded value to a vector of the original element type, in
16910     // the size of the target vector type.
16911     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
16912     unsigned SizeRatio = RegSz/MemSz;
16913
16914     if (Ext == ISD::SEXTLOAD) {
16915       // If we have SSE4.1 we can directly emit a VSEXT node.
16916       if (Subtarget->hasSSE41()) {
16917         SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
16918         return DCI.CombineTo(N, Sext, TF, true);
16919       }
16920
16921       // Otherwise we'll shuffle the small elements in the high bits of the
16922       // larger type and perform an arithmetic shift. If the shift is not legal
16923       // it's better to scalarize.
16924       if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
16925         return SDValue();
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 + SizeRatio-1] = i;
16931
16932       SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
16933                                            DAG.getUNDEF(WideVecVT),
16934                                            &ShuffleVec[0]);
16935
16936       Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
16937
16938       // Build the arithmetic shift.
16939       unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
16940                      MemVT.getVectorElementType().getSizeInBits();
16941       Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
16942                           DAG.getConstant(Amt, RegVT));
16943
16944       return DCI.CombineTo(N, Shuff, TF, true);
16945     }
16946
16947     // Redistribute the loaded elements into the different locations.
16948     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16949     for (unsigned i = 0; i != NumElems; ++i)
16950       ShuffleVec[i*SizeRatio] = i;
16951
16952     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
16953                                          DAG.getUNDEF(WideVecVT),
16954                                          &ShuffleVec[0]);
16955
16956     // Bitcast to the requested type.
16957     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
16958     // Replace the original load with the new sequence
16959     // and return the new chain.
16960     return DCI.CombineTo(N, Shuff, TF, true);
16961   }
16962
16963   return SDValue();
16964 }
16965
16966 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
16967 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
16968                                    const X86Subtarget *Subtarget) {
16969   StoreSDNode *St = cast<StoreSDNode>(N);
16970   EVT VT = St->getValue().getValueType();
16971   EVT StVT = St->getMemoryVT();
16972   DebugLoc dl = St->getDebugLoc();
16973   SDValue StoredVal = St->getOperand(1);
16974   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16975
16976   // If we are saving a concatenation of two XMM registers, perform two stores.
16977   // On Sandy Bridge, 256-bit memory operations are executed by two
16978   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
16979   // memory  operation.
16980   unsigned Alignment = St->getAlignment();
16981   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
16982   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
16983       StVT == VT && !IsAligned) {
16984     unsigned NumElems = VT.getVectorNumElements();
16985     if (NumElems < 2)
16986       return SDValue();
16987
16988     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
16989     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
16990
16991     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
16992     SDValue Ptr0 = St->getBasePtr();
16993     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
16994
16995     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
16996                                 St->getPointerInfo(), St->isVolatile(),
16997                                 St->isNonTemporal(), Alignment);
16998     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
16999                                 St->getPointerInfo(), St->isVolatile(),
17000                                 St->isNonTemporal(),
17001                                 std::min(16U, Alignment));
17002     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
17003   }
17004
17005   // Optimize trunc store (of multiple scalars) to shuffle and store.
17006   // First, pack all of the elements in one place. Next, store to memory
17007   // in fewer chunks.
17008   if (St->isTruncatingStore() && VT.isVector()) {
17009     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17010     unsigned NumElems = VT.getVectorNumElements();
17011     assert(StVT != VT && "Cannot truncate to the same type");
17012     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
17013     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
17014
17015     // From, To sizes and ElemCount must be pow of two
17016     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
17017     // We are going to use the original vector elt for storing.
17018     // Accumulated smaller vector elements must be a multiple of the store size.
17019     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
17020
17021     unsigned SizeRatio  = FromSz / ToSz;
17022
17023     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
17024
17025     // Create a type on which we perform the shuffle
17026     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
17027             StVT.getScalarType(), NumElems*SizeRatio);
17028
17029     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
17030
17031     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
17032     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
17033     for (unsigned i = 0; i != NumElems; ++i)
17034       ShuffleVec[i] = i * SizeRatio;
17035
17036     // Can't shuffle using an illegal type.
17037     if (!TLI.isTypeLegal(WideVecVT))
17038       return SDValue();
17039
17040     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
17041                                          DAG.getUNDEF(WideVecVT),
17042                                          &ShuffleVec[0]);
17043     // At this point all of the data is stored at the bottom of the
17044     // register. We now need to save it to mem.
17045
17046     // Find the largest store unit
17047     MVT StoreType = MVT::i8;
17048     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
17049          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
17050       MVT Tp = (MVT::SimpleValueType)tp;
17051       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
17052         StoreType = Tp;
17053     }
17054
17055     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
17056     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
17057         (64 <= NumElems * ToSz))
17058       StoreType = MVT::f64;
17059
17060     // Bitcast the original vector into a vector of store-size units
17061     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
17062             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
17063     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
17064     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
17065     SmallVector<SDValue, 8> Chains;
17066     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
17067                                         TLI.getPointerTy());
17068     SDValue Ptr = St->getBasePtr();
17069
17070     // Perform one or more big stores into memory.
17071     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
17072       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
17073                                    StoreType, ShuffWide,
17074                                    DAG.getIntPtrConstant(i));
17075       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
17076                                 St->getPointerInfo(), St->isVolatile(),
17077                                 St->isNonTemporal(), St->getAlignment());
17078       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
17079       Chains.push_back(Ch);
17080     }
17081
17082     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
17083                                Chains.size());
17084   }
17085
17086   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
17087   // the FP state in cases where an emms may be missing.
17088   // A preferable solution to the general problem is to figure out the right
17089   // places to insert EMMS.  This qualifies as a quick hack.
17090
17091   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
17092   if (VT.getSizeInBits() != 64)
17093     return SDValue();
17094
17095   const Function *F = DAG.getMachineFunction().getFunction();
17096   bool NoImplicitFloatOps = F->getAttributes().
17097     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
17098   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
17099                      && Subtarget->hasSSE2();
17100   if ((VT.isVector() ||
17101        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
17102       isa<LoadSDNode>(St->getValue()) &&
17103       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
17104       St->getChain().hasOneUse() && !St->isVolatile()) {
17105     SDNode* LdVal = St->getValue().getNode();
17106     LoadSDNode *Ld = 0;
17107     int TokenFactorIndex = -1;
17108     SmallVector<SDValue, 8> Ops;
17109     SDNode* ChainVal = St->getChain().getNode();
17110     // Must be a store of a load.  We currently handle two cases:  the load
17111     // is a direct child, and it's under an intervening TokenFactor.  It is
17112     // possible to dig deeper under nested TokenFactors.
17113     if (ChainVal == LdVal)
17114       Ld = cast<LoadSDNode>(St->getChain());
17115     else if (St->getValue().hasOneUse() &&
17116              ChainVal->getOpcode() == ISD::TokenFactor) {
17117       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
17118         if (ChainVal->getOperand(i).getNode() == LdVal) {
17119           TokenFactorIndex = i;
17120           Ld = cast<LoadSDNode>(St->getValue());
17121         } else
17122           Ops.push_back(ChainVal->getOperand(i));
17123       }
17124     }
17125
17126     if (!Ld || !ISD::isNormalLoad(Ld))
17127       return SDValue();
17128
17129     // If this is not the MMX case, i.e. we are just turning i64 load/store
17130     // into f64 load/store, avoid the transformation if there are multiple
17131     // uses of the loaded value.
17132     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
17133       return SDValue();
17134
17135     DebugLoc LdDL = Ld->getDebugLoc();
17136     DebugLoc StDL = N->getDebugLoc();
17137     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
17138     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
17139     // pair instead.
17140     if (Subtarget->is64Bit() || F64IsLegal) {
17141       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
17142       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
17143                                   Ld->getPointerInfo(), Ld->isVolatile(),
17144                                   Ld->isNonTemporal(), Ld->isInvariant(),
17145                                   Ld->getAlignment());
17146       SDValue NewChain = NewLd.getValue(1);
17147       if (TokenFactorIndex != -1) {
17148         Ops.push_back(NewChain);
17149         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
17150                                Ops.size());
17151       }
17152       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
17153                           St->getPointerInfo(),
17154                           St->isVolatile(), St->isNonTemporal(),
17155                           St->getAlignment());
17156     }
17157
17158     // Otherwise, lower to two pairs of 32-bit loads / stores.
17159     SDValue LoAddr = Ld->getBasePtr();
17160     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
17161                                  DAG.getConstant(4, MVT::i32));
17162
17163     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
17164                                Ld->getPointerInfo(),
17165                                Ld->isVolatile(), Ld->isNonTemporal(),
17166                                Ld->isInvariant(), Ld->getAlignment());
17167     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
17168                                Ld->getPointerInfo().getWithOffset(4),
17169                                Ld->isVolatile(), Ld->isNonTemporal(),
17170                                Ld->isInvariant(),
17171                                MinAlign(Ld->getAlignment(), 4));
17172
17173     SDValue NewChain = LoLd.getValue(1);
17174     if (TokenFactorIndex != -1) {
17175       Ops.push_back(LoLd);
17176       Ops.push_back(HiLd);
17177       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
17178                              Ops.size());
17179     }
17180
17181     LoAddr = St->getBasePtr();
17182     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
17183                          DAG.getConstant(4, MVT::i32));
17184
17185     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
17186                                 St->getPointerInfo(),
17187                                 St->isVolatile(), St->isNonTemporal(),
17188                                 St->getAlignment());
17189     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
17190                                 St->getPointerInfo().getWithOffset(4),
17191                                 St->isVolatile(),
17192                                 St->isNonTemporal(),
17193                                 MinAlign(St->getAlignment(), 4));
17194     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
17195   }
17196   return SDValue();
17197 }
17198
17199 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
17200 /// and return the operands for the horizontal operation in LHS and RHS.  A
17201 /// horizontal operation performs the binary operation on successive elements
17202 /// of its first operand, then on successive elements of its second operand,
17203 /// returning the resulting values in a vector.  For example, if
17204 ///   A = < float a0, float a1, float a2, float a3 >
17205 /// and
17206 ///   B = < float b0, float b1, float b2, float b3 >
17207 /// then the result of doing a horizontal operation on A and B is
17208 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
17209 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
17210 /// A horizontal-op B, for some already available A and B, and if so then LHS is
17211 /// set to A, RHS to B, and the routine returns 'true'.
17212 /// Note that the binary operation should have the property that if one of the
17213 /// operands is UNDEF then the result is UNDEF.
17214 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
17215   // Look for the following pattern: if
17216   //   A = < float a0, float a1, float a2, float a3 >
17217   //   B = < float b0, float b1, float b2, float b3 >
17218   // and
17219   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
17220   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
17221   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
17222   // which is A horizontal-op B.
17223
17224   // At least one of the operands should be a vector shuffle.
17225   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
17226       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
17227     return false;
17228
17229   EVT VT = LHS.getValueType();
17230
17231   assert((VT.is128BitVector() || VT.is256BitVector()) &&
17232          "Unsupported vector type for horizontal add/sub");
17233
17234   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
17235   // operate independently on 128-bit lanes.
17236   unsigned NumElts = VT.getVectorNumElements();
17237   unsigned NumLanes = VT.getSizeInBits()/128;
17238   unsigned NumLaneElts = NumElts / NumLanes;
17239   assert((NumLaneElts % 2 == 0) &&
17240          "Vector type should have an even number of elements in each lane");
17241   unsigned HalfLaneElts = NumLaneElts/2;
17242
17243   // View LHS in the form
17244   //   LHS = VECTOR_SHUFFLE A, B, LMask
17245   // If LHS is not a shuffle then pretend it is the shuffle
17246   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
17247   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
17248   // type VT.
17249   SDValue A, B;
17250   SmallVector<int, 16> LMask(NumElts);
17251   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
17252     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
17253       A = LHS.getOperand(0);
17254     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
17255       B = LHS.getOperand(1);
17256     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
17257     std::copy(Mask.begin(), Mask.end(), LMask.begin());
17258   } else {
17259     if (LHS.getOpcode() != ISD::UNDEF)
17260       A = LHS;
17261     for (unsigned i = 0; i != NumElts; ++i)
17262       LMask[i] = i;
17263   }
17264
17265   // Likewise, view RHS in the form
17266   //   RHS = VECTOR_SHUFFLE C, D, RMask
17267   SDValue C, D;
17268   SmallVector<int, 16> RMask(NumElts);
17269   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
17270     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
17271       C = RHS.getOperand(0);
17272     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
17273       D = RHS.getOperand(1);
17274     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
17275     std::copy(Mask.begin(), Mask.end(), RMask.begin());
17276   } else {
17277     if (RHS.getOpcode() != ISD::UNDEF)
17278       C = RHS;
17279     for (unsigned i = 0; i != NumElts; ++i)
17280       RMask[i] = i;
17281   }
17282
17283   // Check that the shuffles are both shuffling the same vectors.
17284   if (!(A == C && B == D) && !(A == D && B == C))
17285     return false;
17286
17287   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
17288   if (!A.getNode() && !B.getNode())
17289     return false;
17290
17291   // If A and B occur in reverse order in RHS, then "swap" them (which means
17292   // rewriting the mask).
17293   if (A != C)
17294     CommuteVectorShuffleMask(RMask, NumElts);
17295
17296   // At this point LHS and RHS are equivalent to
17297   //   LHS = VECTOR_SHUFFLE A, B, LMask
17298   //   RHS = VECTOR_SHUFFLE A, B, RMask
17299   // Check that the masks correspond to performing a horizontal operation.
17300   for (unsigned i = 0; i != NumElts; ++i) {
17301     int LIdx = LMask[i], RIdx = RMask[i];
17302
17303     // Ignore any UNDEF components.
17304     if (LIdx < 0 || RIdx < 0 ||
17305         (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
17306         (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
17307       continue;
17308
17309     // Check that successive elements are being operated on.  If not, this is
17310     // not a horizontal operation.
17311     unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
17312     unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
17313     int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
17314     if (!(LIdx == Index && RIdx == Index + 1) &&
17315         !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
17316       return false;
17317   }
17318
17319   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
17320   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
17321   return true;
17322 }
17323
17324 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
17325 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
17326                                   const X86Subtarget *Subtarget) {
17327   EVT VT = N->getValueType(0);
17328   SDValue LHS = N->getOperand(0);
17329   SDValue RHS = N->getOperand(1);
17330
17331   // Try to synthesize horizontal adds from adds of shuffles.
17332   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
17333        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
17334       isHorizontalBinOp(LHS, RHS, true))
17335     return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
17336   return SDValue();
17337 }
17338
17339 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
17340 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
17341                                   const X86Subtarget *Subtarget) {
17342   EVT VT = N->getValueType(0);
17343   SDValue LHS = N->getOperand(0);
17344   SDValue RHS = N->getOperand(1);
17345
17346   // Try to synthesize horizontal subs from subs of shuffles.
17347   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
17348        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
17349       isHorizontalBinOp(LHS, RHS, false))
17350     return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
17351   return SDValue();
17352 }
17353
17354 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
17355 /// X86ISD::FXOR nodes.
17356 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
17357   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
17358   // F[X]OR(0.0, x) -> x
17359   // F[X]OR(x, 0.0) -> x
17360   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
17361     if (C->getValueAPF().isPosZero())
17362       return N->getOperand(1);
17363   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
17364     if (C->getValueAPF().isPosZero())
17365       return N->getOperand(0);
17366   return SDValue();
17367 }
17368
17369 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
17370 /// X86ISD::FMAX nodes.
17371 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
17372   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
17373
17374   // Only perform optimizations if UnsafeMath is used.
17375   if (!DAG.getTarget().Options.UnsafeFPMath)
17376     return SDValue();
17377
17378   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
17379   // into FMINC and FMAXC, which are Commutative operations.
17380   unsigned NewOp = 0;
17381   switch (N->getOpcode()) {
17382     default: llvm_unreachable("unknown opcode");
17383     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
17384     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
17385   }
17386
17387   return DAG.getNode(NewOp, N->getDebugLoc(), N->getValueType(0),
17388                      N->getOperand(0), N->getOperand(1));
17389 }
17390
17391 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
17392 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
17393   // FAND(0.0, x) -> 0.0
17394   // FAND(x, 0.0) -> 0.0
17395   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
17396     if (C->getValueAPF().isPosZero())
17397       return N->getOperand(0);
17398   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
17399     if (C->getValueAPF().isPosZero())
17400       return N->getOperand(1);
17401   return SDValue();
17402 }
17403
17404 static SDValue PerformBTCombine(SDNode *N,
17405                                 SelectionDAG &DAG,
17406                                 TargetLowering::DAGCombinerInfo &DCI) {
17407   // BT ignores high bits in the bit index operand.
17408   SDValue Op1 = N->getOperand(1);
17409   if (Op1.hasOneUse()) {
17410     unsigned BitWidth = Op1.getValueSizeInBits();
17411     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
17412     APInt KnownZero, KnownOne;
17413     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
17414                                           !DCI.isBeforeLegalizeOps());
17415     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17416     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
17417         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
17418       DCI.CommitTargetLoweringOpt(TLO);
17419   }
17420   return SDValue();
17421 }
17422
17423 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
17424   SDValue Op = N->getOperand(0);
17425   if (Op.getOpcode() == ISD::BITCAST)
17426     Op = Op.getOperand(0);
17427   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
17428   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
17429       VT.getVectorElementType().getSizeInBits() ==
17430       OpVT.getVectorElementType().getSizeInBits()) {
17431     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
17432   }
17433   return SDValue();
17434 }
17435
17436 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG, 
17437                                                const X86Subtarget *Subtarget) {
17438   EVT VT = N->getValueType(0);
17439   if (!VT.isVector())
17440     return SDValue();
17441
17442   SDValue N0 = N->getOperand(0);
17443   SDValue N1 = N->getOperand(1);
17444   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
17445   DebugLoc dl = N->getDebugLoc();
17446
17447   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
17448   // both SSE and AVX2 since there is no sign-extended shift right
17449   // operation on a vector with 64-bit elements.
17450   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
17451   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
17452   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
17453       N0.getOpcode() == ISD::SIGN_EXTEND)) {
17454     SDValue N00 = N0.getOperand(0);
17455
17456     // EXTLOAD has a better solution on AVX2, 
17457     // it may be replaced with X86ISD::VSEXT node.
17458     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
17459       if (!ISD::isNormalLoad(N00.getNode()))
17460         return SDValue();
17461
17462     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
17463         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, 
17464                                   N00, N1);
17465       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
17466     }
17467   }
17468   return SDValue();
17469 }
17470
17471 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
17472                                   TargetLowering::DAGCombinerInfo &DCI,
17473                                   const X86Subtarget *Subtarget) {
17474   if (!DCI.isBeforeLegalizeOps())
17475     return SDValue();
17476
17477   if (!Subtarget->hasFp256())
17478     return SDValue();
17479
17480   EVT VT = N->getValueType(0);
17481   if (VT.isVector() && VT.getSizeInBits() == 256) {
17482     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
17483     if (R.getNode())
17484       return R;
17485   }
17486
17487   return SDValue();
17488 }
17489
17490 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
17491                                  const X86Subtarget* Subtarget) {
17492   DebugLoc dl = N->getDebugLoc();
17493   EVT VT = N->getValueType(0);
17494
17495   // Let legalize expand this if it isn't a legal type yet.
17496   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
17497     return SDValue();
17498
17499   EVT ScalarVT = VT.getScalarType();
17500   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
17501       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
17502     return SDValue();
17503
17504   SDValue A = N->getOperand(0);
17505   SDValue B = N->getOperand(1);
17506   SDValue C = N->getOperand(2);
17507
17508   bool NegA = (A.getOpcode() == ISD::FNEG);
17509   bool NegB = (B.getOpcode() == ISD::FNEG);
17510   bool NegC = (C.getOpcode() == ISD::FNEG);
17511
17512   // Negative multiplication when NegA xor NegB
17513   bool NegMul = (NegA != NegB);
17514   if (NegA)
17515     A = A.getOperand(0);
17516   if (NegB)
17517     B = B.getOperand(0);
17518   if (NegC)
17519     C = C.getOperand(0);
17520
17521   unsigned Opcode;
17522   if (!NegMul)
17523     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
17524   else
17525     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
17526
17527   return DAG.getNode(Opcode, dl, VT, A, B, C);
17528 }
17529
17530 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
17531                                   TargetLowering::DAGCombinerInfo &DCI,
17532                                   const X86Subtarget *Subtarget) {
17533   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
17534   //           (and (i32 x86isd::setcc_carry), 1)
17535   // This eliminates the zext. This transformation is necessary because
17536   // ISD::SETCC is always legalized to i8.
17537   DebugLoc dl = N->getDebugLoc();
17538   SDValue N0 = N->getOperand(0);
17539   EVT VT = N->getValueType(0);
17540
17541   if (N0.getOpcode() == ISD::AND &&
17542       N0.hasOneUse() &&
17543       N0.getOperand(0).hasOneUse()) {
17544     SDValue N00 = N0.getOperand(0);
17545     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
17546       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
17547       if (!C || C->getZExtValue() != 1)
17548         return SDValue();
17549       return DAG.getNode(ISD::AND, dl, VT,
17550                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
17551                                      N00.getOperand(0), N00.getOperand(1)),
17552                          DAG.getConstant(1, VT));
17553     }
17554   }
17555
17556   if (VT.is256BitVector()) {
17557     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
17558     if (R.getNode())
17559       return R;
17560   }
17561
17562   return SDValue();
17563 }
17564
17565 // Optimize x == -y --> x+y == 0
17566 //          x != -y --> x+y != 0
17567 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
17568   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
17569   SDValue LHS = N->getOperand(0);
17570   SDValue RHS = N->getOperand(1);
17571
17572   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
17573     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
17574       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
17575         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
17576                                    LHS.getValueType(), RHS, LHS.getOperand(1));
17577         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
17578                             addV, DAG.getConstant(0, addV.getValueType()), CC);
17579       }
17580   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
17581     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
17582       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
17583         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
17584                                    RHS.getValueType(), LHS, RHS.getOperand(1));
17585         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
17586                             addV, DAG.getConstant(0, addV.getValueType()), CC);
17587       }
17588   return SDValue();
17589 }
17590
17591 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
17592 // as "sbb reg,reg", since it can be extended without zext and produces
17593 // an all-ones bit which is more useful than 0/1 in some cases.
17594 static SDValue MaterializeSETB(DebugLoc DL, SDValue EFLAGS, SelectionDAG &DAG) {
17595   return DAG.getNode(ISD::AND, DL, MVT::i8,
17596                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
17597                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
17598                      DAG.getConstant(1, MVT::i8));
17599 }
17600
17601 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
17602 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
17603                                    TargetLowering::DAGCombinerInfo &DCI,
17604                                    const X86Subtarget *Subtarget) {
17605   DebugLoc DL = N->getDebugLoc();
17606   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
17607   SDValue EFLAGS = N->getOperand(1);
17608
17609   if (CC == X86::COND_A) {
17610     // Try to convert COND_A into COND_B in an attempt to facilitate
17611     // materializing "setb reg".
17612     //
17613     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
17614     // cannot take an immediate as its first operand.
17615     //
17616     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
17617         EFLAGS.getValueType().isInteger() &&
17618         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
17619       SDValue NewSub = DAG.getNode(X86ISD::SUB, EFLAGS.getDebugLoc(),
17620                                    EFLAGS.getNode()->getVTList(),
17621                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
17622       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
17623       return MaterializeSETB(DL, NewEFLAGS, DAG);
17624     }
17625   }
17626
17627   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
17628   // a zext and produces an all-ones bit which is more useful than 0/1 in some
17629   // cases.
17630   if (CC == X86::COND_B)
17631     return MaterializeSETB(DL, EFLAGS, DAG);
17632
17633   SDValue Flags;
17634
17635   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
17636   if (Flags.getNode()) {
17637     SDValue Cond = DAG.getConstant(CC, MVT::i8);
17638     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
17639   }
17640
17641   return SDValue();
17642 }
17643
17644 // Optimize branch condition evaluation.
17645 //
17646 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
17647                                     TargetLowering::DAGCombinerInfo &DCI,
17648                                     const X86Subtarget *Subtarget) {
17649   DebugLoc DL = N->getDebugLoc();
17650   SDValue Chain = N->getOperand(0);
17651   SDValue Dest = N->getOperand(1);
17652   SDValue EFLAGS = N->getOperand(3);
17653   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
17654
17655   SDValue Flags;
17656
17657   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
17658   if (Flags.getNode()) {
17659     SDValue Cond = DAG.getConstant(CC, MVT::i8);
17660     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
17661                        Flags);
17662   }
17663
17664   return SDValue();
17665 }
17666
17667 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
17668                                         const X86TargetLowering *XTLI) {
17669   SDValue Op0 = N->getOperand(0);
17670   EVT InVT = Op0->getValueType(0);
17671
17672   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
17673   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
17674     DebugLoc dl = N->getDebugLoc();
17675     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
17676     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
17677     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
17678   }
17679
17680   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
17681   // a 32-bit target where SSE doesn't support i64->FP operations.
17682   if (Op0.getOpcode() == ISD::LOAD) {
17683     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
17684     EVT VT = Ld->getValueType(0);
17685     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
17686         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
17687         !XTLI->getSubtarget()->is64Bit() &&
17688         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
17689       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
17690                                           Ld->getChain(), Op0, DAG);
17691       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
17692       return FILDChain;
17693     }
17694   }
17695   return SDValue();
17696 }
17697
17698 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
17699 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
17700                                  X86TargetLowering::DAGCombinerInfo &DCI) {
17701   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
17702   // the result is either zero or one (depending on the input carry bit).
17703   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
17704   if (X86::isZeroNode(N->getOperand(0)) &&
17705       X86::isZeroNode(N->getOperand(1)) &&
17706       // We don't have a good way to replace an EFLAGS use, so only do this when
17707       // dead right now.
17708       SDValue(N, 1).use_empty()) {
17709     DebugLoc DL = N->getDebugLoc();
17710     EVT VT = N->getValueType(0);
17711     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
17712     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
17713                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
17714                                            DAG.getConstant(X86::COND_B,MVT::i8),
17715                                            N->getOperand(2)),
17716                                DAG.getConstant(1, VT));
17717     return DCI.CombineTo(N, Res1, CarryOut);
17718   }
17719
17720   return SDValue();
17721 }
17722
17723 // fold (add Y, (sete  X, 0)) -> adc  0, Y
17724 //      (add Y, (setne X, 0)) -> sbb -1, Y
17725 //      (sub (sete  X, 0), Y) -> sbb  0, Y
17726 //      (sub (setne X, 0), Y) -> adc -1, Y
17727 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
17728   DebugLoc DL = N->getDebugLoc();
17729
17730   // Look through ZExts.
17731   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
17732   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
17733     return SDValue();
17734
17735   SDValue SetCC = Ext.getOperand(0);
17736   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
17737     return SDValue();
17738
17739   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
17740   if (CC != X86::COND_E && CC != X86::COND_NE)
17741     return SDValue();
17742
17743   SDValue Cmp = SetCC.getOperand(1);
17744   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
17745       !X86::isZeroNode(Cmp.getOperand(1)) ||
17746       !Cmp.getOperand(0).getValueType().isInteger())
17747     return SDValue();
17748
17749   SDValue CmpOp0 = Cmp.getOperand(0);
17750   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
17751                                DAG.getConstant(1, CmpOp0.getValueType()));
17752
17753   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
17754   if (CC == X86::COND_NE)
17755     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
17756                        DL, OtherVal.getValueType(), OtherVal,
17757                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
17758   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
17759                      DL, OtherVal.getValueType(), OtherVal,
17760                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
17761 }
17762
17763 /// PerformADDCombine - Do target-specific dag combines on integer adds.
17764 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
17765                                  const X86Subtarget *Subtarget) {
17766   EVT VT = N->getValueType(0);
17767   SDValue Op0 = N->getOperand(0);
17768   SDValue Op1 = N->getOperand(1);
17769
17770   // Try to synthesize horizontal adds from adds of shuffles.
17771   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
17772        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
17773       isHorizontalBinOp(Op0, Op1, true))
17774     return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
17775
17776   return OptimizeConditionalInDecrement(N, DAG);
17777 }
17778
17779 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
17780                                  const X86Subtarget *Subtarget) {
17781   SDValue Op0 = N->getOperand(0);
17782   SDValue Op1 = N->getOperand(1);
17783
17784   // X86 can't encode an immediate LHS of a sub. See if we can push the
17785   // negation into a preceding instruction.
17786   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
17787     // If the RHS of the sub is a XOR with one use and a constant, invert the
17788     // immediate. Then add one to the LHS of the sub so we can turn
17789     // X-Y -> X+~Y+1, saving one register.
17790     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
17791         isa<ConstantSDNode>(Op1.getOperand(1))) {
17792       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
17793       EVT VT = Op0.getValueType();
17794       SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
17795                                    Op1.getOperand(0),
17796                                    DAG.getConstant(~XorC, VT));
17797       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
17798                          DAG.getConstant(C->getAPIntValue()+1, VT));
17799     }
17800   }
17801
17802   // Try to synthesize horizontal adds from adds of shuffles.
17803   EVT VT = N->getValueType(0);
17804   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
17805        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
17806       isHorizontalBinOp(Op0, Op1, true))
17807     return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
17808
17809   return OptimizeConditionalInDecrement(N, DAG);
17810 }
17811
17812 /// performVZEXTCombine - Performs build vector combines
17813 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
17814                                         TargetLowering::DAGCombinerInfo &DCI,
17815                                         const X86Subtarget *Subtarget) {
17816   // (vzext (bitcast (vzext (x)) -> (vzext x)
17817   SDValue In = N->getOperand(0);
17818   while (In.getOpcode() == ISD::BITCAST)
17819     In = In.getOperand(0);
17820
17821   if (In.getOpcode() != X86ISD::VZEXT)
17822     return SDValue();
17823
17824   return DAG.getNode(X86ISD::VZEXT, N->getDebugLoc(), N->getValueType(0),
17825                      In.getOperand(0));
17826 }
17827
17828 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
17829                                              DAGCombinerInfo &DCI) const {
17830   SelectionDAG &DAG = DCI.DAG;
17831   switch (N->getOpcode()) {
17832   default: break;
17833   case ISD::EXTRACT_VECTOR_ELT:
17834     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
17835   case ISD::VSELECT:
17836   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
17837   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
17838   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
17839   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
17840   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
17841   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
17842   case ISD::SHL:
17843   case ISD::SRA:
17844   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
17845   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
17846   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
17847   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
17848   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
17849   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
17850   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
17851   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
17852   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
17853   case X86ISD::FXOR:
17854   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
17855   case X86ISD::FMIN:
17856   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
17857   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
17858   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
17859   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
17860   case ISD::ANY_EXTEND:
17861   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
17862   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
17863   case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
17864   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
17865   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG);
17866   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
17867   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
17868   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
17869   case X86ISD::SHUFP:       // Handle all target specific shuffles
17870   case X86ISD::PALIGNR:
17871   case X86ISD::UNPCKH:
17872   case X86ISD::UNPCKL:
17873   case X86ISD::MOVHLPS:
17874   case X86ISD::MOVLHPS:
17875   case X86ISD::PSHUFD:
17876   case X86ISD::PSHUFHW:
17877   case X86ISD::PSHUFLW:
17878   case X86ISD::MOVSS:
17879   case X86ISD::MOVSD:
17880   case X86ISD::VPERMILP:
17881   case X86ISD::VPERM2X128:
17882   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
17883   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
17884   }
17885
17886   return SDValue();
17887 }
17888
17889 /// isTypeDesirableForOp - Return true if the target has native support for
17890 /// the specified value type and it is 'desirable' to use the type for the
17891 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
17892 /// instruction encodings are longer and some i16 instructions are slow.
17893 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
17894   if (!isTypeLegal(VT))
17895     return false;
17896   if (VT != MVT::i16)
17897     return true;
17898
17899   switch (Opc) {
17900   default:
17901     return true;
17902   case ISD::LOAD:
17903   case ISD::SIGN_EXTEND:
17904   case ISD::ZERO_EXTEND:
17905   case ISD::ANY_EXTEND:
17906   case ISD::SHL:
17907   case ISD::SRL:
17908   case ISD::SUB:
17909   case ISD::ADD:
17910   case ISD::MUL:
17911   case ISD::AND:
17912   case ISD::OR:
17913   case ISD::XOR:
17914     return false;
17915   }
17916 }
17917
17918 /// IsDesirableToPromoteOp - This method query the target whether it is
17919 /// beneficial for dag combiner to promote the specified node. If true, it
17920 /// should return the desired promotion type by reference.
17921 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
17922   EVT VT = Op.getValueType();
17923   if (VT != MVT::i16)
17924     return false;
17925
17926   bool Promote = false;
17927   bool Commute = false;
17928   switch (Op.getOpcode()) {
17929   default: break;
17930   case ISD::LOAD: {
17931     LoadSDNode *LD = cast<LoadSDNode>(Op);
17932     // If the non-extending load has a single use and it's not live out, then it
17933     // might be folded.
17934     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
17935                                                      Op.hasOneUse()*/) {
17936       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
17937              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
17938         // The only case where we'd want to promote LOAD (rather then it being
17939         // promoted as an operand is when it's only use is liveout.
17940         if (UI->getOpcode() != ISD::CopyToReg)
17941           return false;
17942       }
17943     }
17944     Promote = true;
17945     break;
17946   }
17947   case ISD::SIGN_EXTEND:
17948   case ISD::ZERO_EXTEND:
17949   case ISD::ANY_EXTEND:
17950     Promote = true;
17951     break;
17952   case ISD::SHL:
17953   case ISD::SRL: {
17954     SDValue N0 = Op.getOperand(0);
17955     // Look out for (store (shl (load), x)).
17956     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
17957       return false;
17958     Promote = true;
17959     break;
17960   }
17961   case ISD::ADD:
17962   case ISD::MUL:
17963   case ISD::AND:
17964   case ISD::OR:
17965   case ISD::XOR:
17966     Commute = true;
17967     // fallthrough
17968   case ISD::SUB: {
17969     SDValue N0 = Op.getOperand(0);
17970     SDValue N1 = Op.getOperand(1);
17971     if (!Commute && MayFoldLoad(N1))
17972       return false;
17973     // Avoid disabling potential load folding opportunities.
17974     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
17975       return false;
17976     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
17977       return false;
17978     Promote = true;
17979   }
17980   }
17981
17982   PVT = MVT::i32;
17983   return Promote;
17984 }
17985
17986 //===----------------------------------------------------------------------===//
17987 //                           X86 Inline Assembly Support
17988 //===----------------------------------------------------------------------===//
17989
17990 namespace {
17991   // Helper to match a string separated by whitespace.
17992   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
17993     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
17994
17995     for (unsigned i = 0, e = args.size(); i != e; ++i) {
17996       StringRef piece(*args[i]);
17997       if (!s.startswith(piece)) // Check if the piece matches.
17998         return false;
17999
18000       s = s.substr(piece.size());
18001       StringRef::size_type pos = s.find_first_not_of(" \t");
18002       if (pos == 0) // We matched a prefix.
18003         return false;
18004
18005       s = s.substr(pos);
18006     }
18007
18008     return s.empty();
18009   }
18010   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
18011 }
18012
18013 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
18014   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
18015
18016   std::string AsmStr = IA->getAsmString();
18017
18018   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
18019   if (!Ty || Ty->getBitWidth() % 16 != 0)
18020     return false;
18021
18022   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
18023   SmallVector<StringRef, 4> AsmPieces;
18024   SplitString(AsmStr, AsmPieces, ";\n");
18025
18026   switch (AsmPieces.size()) {
18027   default: return false;
18028   case 1:
18029     // FIXME: this should verify that we are targeting a 486 or better.  If not,
18030     // we will turn this bswap into something that will be lowered to logical
18031     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
18032     // lower so don't worry about this.
18033     // bswap $0
18034     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
18035         matchAsm(AsmPieces[0], "bswapl", "$0") ||
18036         matchAsm(AsmPieces[0], "bswapq", "$0") ||
18037         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
18038         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
18039         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
18040       // No need to check constraints, nothing other than the equivalent of
18041       // "=r,0" would be valid here.
18042       return IntrinsicLowering::LowerToByteSwap(CI);
18043     }
18044
18045     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
18046     if (CI->getType()->isIntegerTy(16) &&
18047         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
18048         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
18049          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
18050       AsmPieces.clear();
18051       const std::string &ConstraintsStr = IA->getConstraintString();
18052       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
18053       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
18054       if (AsmPieces.size() == 4 &&
18055           AsmPieces[0] == "~{cc}" &&
18056           AsmPieces[1] == "~{dirflag}" &&
18057           AsmPieces[2] == "~{flags}" &&
18058           AsmPieces[3] == "~{fpsr}")
18059       return IntrinsicLowering::LowerToByteSwap(CI);
18060     }
18061     break;
18062   case 3:
18063     if (CI->getType()->isIntegerTy(32) &&
18064         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
18065         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
18066         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
18067         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
18068       AsmPieces.clear();
18069       const std::string &ConstraintsStr = IA->getConstraintString();
18070       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
18071       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
18072       if (AsmPieces.size() == 4 &&
18073           AsmPieces[0] == "~{cc}" &&
18074           AsmPieces[1] == "~{dirflag}" &&
18075           AsmPieces[2] == "~{flags}" &&
18076           AsmPieces[3] == "~{fpsr}")
18077         return IntrinsicLowering::LowerToByteSwap(CI);
18078     }
18079
18080     if (CI->getType()->isIntegerTy(64)) {
18081       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
18082       if (Constraints.size() >= 2 &&
18083           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
18084           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
18085         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
18086         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
18087             matchAsm(AsmPieces[1], "bswap", "%edx") &&
18088             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
18089           return IntrinsicLowering::LowerToByteSwap(CI);
18090       }
18091     }
18092     break;
18093   }
18094   return false;
18095 }
18096
18097 /// getConstraintType - Given a constraint letter, return the type of
18098 /// constraint it is for this target.
18099 X86TargetLowering::ConstraintType
18100 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
18101   if (Constraint.size() == 1) {
18102     switch (Constraint[0]) {
18103     case 'R':
18104     case 'q':
18105     case 'Q':
18106     case 'f':
18107     case 't':
18108     case 'u':
18109     case 'y':
18110     case 'x':
18111     case 'Y':
18112     case 'l':
18113       return C_RegisterClass;
18114     case 'a':
18115     case 'b':
18116     case 'c':
18117     case 'd':
18118     case 'S':
18119     case 'D':
18120     case 'A':
18121       return C_Register;
18122     case 'I':
18123     case 'J':
18124     case 'K':
18125     case 'L':
18126     case 'M':
18127     case 'N':
18128     case 'G':
18129     case 'C':
18130     case 'e':
18131     case 'Z':
18132       return C_Other;
18133     default:
18134       break;
18135     }
18136   }
18137   return TargetLowering::getConstraintType(Constraint);
18138 }
18139
18140 /// Examine constraint type and operand type and determine a weight value.
18141 /// This object must already have been set up with the operand type
18142 /// and the current alternative constraint selected.
18143 TargetLowering::ConstraintWeight
18144   X86TargetLowering::getSingleConstraintMatchWeight(
18145     AsmOperandInfo &info, const char *constraint) const {
18146   ConstraintWeight weight = CW_Invalid;
18147   Value *CallOperandVal = info.CallOperandVal;
18148     // If we don't have a value, we can't do a match,
18149     // but allow it at the lowest weight.
18150   if (CallOperandVal == NULL)
18151     return CW_Default;
18152   Type *type = CallOperandVal->getType();
18153   // Look at the constraint type.
18154   switch (*constraint) {
18155   default:
18156     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
18157   case 'R':
18158   case 'q':
18159   case 'Q':
18160   case 'a':
18161   case 'b':
18162   case 'c':
18163   case 'd':
18164   case 'S':
18165   case 'D':
18166   case 'A':
18167     if (CallOperandVal->getType()->isIntegerTy())
18168       weight = CW_SpecificReg;
18169     break;
18170   case 'f':
18171   case 't':
18172   case 'u':
18173     if (type->isFloatingPointTy())
18174       weight = CW_SpecificReg;
18175     break;
18176   case 'y':
18177     if (type->isX86_MMXTy() && Subtarget->hasMMX())
18178       weight = CW_SpecificReg;
18179     break;
18180   case 'x':
18181   case 'Y':
18182     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
18183         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
18184       weight = CW_Register;
18185     break;
18186   case 'I':
18187     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
18188       if (C->getZExtValue() <= 31)
18189         weight = CW_Constant;
18190     }
18191     break;
18192   case 'J':
18193     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18194       if (C->getZExtValue() <= 63)
18195         weight = CW_Constant;
18196     }
18197     break;
18198   case 'K':
18199     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18200       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
18201         weight = CW_Constant;
18202     }
18203     break;
18204   case 'L':
18205     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18206       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
18207         weight = CW_Constant;
18208     }
18209     break;
18210   case 'M':
18211     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18212       if (C->getZExtValue() <= 3)
18213         weight = CW_Constant;
18214     }
18215     break;
18216   case 'N':
18217     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18218       if (C->getZExtValue() <= 0xff)
18219         weight = CW_Constant;
18220     }
18221     break;
18222   case 'G':
18223   case 'C':
18224     if (dyn_cast<ConstantFP>(CallOperandVal)) {
18225       weight = CW_Constant;
18226     }
18227     break;
18228   case 'e':
18229     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18230       if ((C->getSExtValue() >= -0x80000000LL) &&
18231           (C->getSExtValue() <= 0x7fffffffLL))
18232         weight = CW_Constant;
18233     }
18234     break;
18235   case 'Z':
18236     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18237       if (C->getZExtValue() <= 0xffffffff)
18238         weight = CW_Constant;
18239     }
18240     break;
18241   }
18242   return weight;
18243 }
18244
18245 /// LowerXConstraint - try to replace an X constraint, which matches anything,
18246 /// with another that has more specific requirements based on the type of the
18247 /// corresponding operand.
18248 const char *X86TargetLowering::
18249 LowerXConstraint(EVT ConstraintVT) const {
18250   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
18251   // 'f' like normal targets.
18252   if (ConstraintVT.isFloatingPoint()) {
18253     if (Subtarget->hasSSE2())
18254       return "Y";
18255     if (Subtarget->hasSSE1())
18256       return "x";
18257   }
18258
18259   return TargetLowering::LowerXConstraint(ConstraintVT);
18260 }
18261
18262 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
18263 /// vector.  If it is invalid, don't add anything to Ops.
18264 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
18265                                                      std::string &Constraint,
18266                                                      std::vector<SDValue>&Ops,
18267                                                      SelectionDAG &DAG) const {
18268   SDValue Result(0, 0);
18269
18270   // Only support length 1 constraints for now.
18271   if (Constraint.length() > 1) return;
18272
18273   char ConstraintLetter = Constraint[0];
18274   switch (ConstraintLetter) {
18275   default: break;
18276   case 'I':
18277     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18278       if (C->getZExtValue() <= 31) {
18279         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18280         break;
18281       }
18282     }
18283     return;
18284   case 'J':
18285     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18286       if (C->getZExtValue() <= 63) {
18287         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18288         break;
18289       }
18290     }
18291     return;
18292   case 'K':
18293     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18294       if (isInt<8>(C->getSExtValue())) {
18295         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18296         break;
18297       }
18298     }
18299     return;
18300   case 'N':
18301     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18302       if (C->getZExtValue() <= 255) {
18303         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18304         break;
18305       }
18306     }
18307     return;
18308   case 'e': {
18309     // 32-bit signed value
18310     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18311       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
18312                                            C->getSExtValue())) {
18313         // Widen to 64 bits here to get it sign extended.
18314         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
18315         break;
18316       }
18317     // FIXME gcc accepts some relocatable values here too, but only in certain
18318     // memory models; it's complicated.
18319     }
18320     return;
18321   }
18322   case 'Z': {
18323     // 32-bit unsigned value
18324     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18325       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
18326                                            C->getZExtValue())) {
18327         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18328         break;
18329       }
18330     }
18331     // FIXME gcc accepts some relocatable values here too, but only in certain
18332     // memory models; it's complicated.
18333     return;
18334   }
18335   case 'i': {
18336     // Literal immediates are always ok.
18337     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
18338       // Widen to 64 bits here to get it sign extended.
18339       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
18340       break;
18341     }
18342
18343     // In any sort of PIC mode addresses need to be computed at runtime by
18344     // adding in a register or some sort of table lookup.  These can't
18345     // be used as immediates.
18346     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
18347       return;
18348
18349     // If we are in non-pic codegen mode, we allow the address of a global (with
18350     // an optional displacement) to be used with 'i'.
18351     GlobalAddressSDNode *GA = 0;
18352     int64_t Offset = 0;
18353
18354     // Match either (GA), (GA+C), (GA+C1+C2), etc.
18355     while (1) {
18356       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
18357         Offset += GA->getOffset();
18358         break;
18359       } else if (Op.getOpcode() == ISD::ADD) {
18360         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
18361           Offset += C->getZExtValue();
18362           Op = Op.getOperand(0);
18363           continue;
18364         }
18365       } else if (Op.getOpcode() == ISD::SUB) {
18366         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
18367           Offset += -C->getZExtValue();
18368           Op = Op.getOperand(0);
18369           continue;
18370         }
18371       }
18372
18373       // Otherwise, this isn't something we can handle, reject it.
18374       return;
18375     }
18376
18377     const GlobalValue *GV = GA->getGlobal();
18378     // If we require an extra load to get this address, as in PIC mode, we
18379     // can't accept it.
18380     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
18381                                                         getTargetMachine())))
18382       return;
18383
18384     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
18385                                         GA->getValueType(0), Offset);
18386     break;
18387   }
18388   }
18389
18390   if (Result.getNode()) {
18391     Ops.push_back(Result);
18392     return;
18393   }
18394   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
18395 }
18396
18397 std::pair<unsigned, const TargetRegisterClass*>
18398 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
18399                                                 EVT VT) const {
18400   // First, see if this is a constraint that directly corresponds to an LLVM
18401   // register class.
18402   if (Constraint.size() == 1) {
18403     // GCC Constraint Letters
18404     switch (Constraint[0]) {
18405     default: break;
18406       // TODO: Slight differences here in allocation order and leaving
18407       // RIP in the class. Do they matter any more here than they do
18408       // in the normal allocation?
18409     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
18410       if (Subtarget->is64Bit()) {
18411         if (VT == MVT::i32 || VT == MVT::f32)
18412           return std::make_pair(0U, &X86::GR32RegClass);
18413         if (VT == MVT::i16)
18414           return std::make_pair(0U, &X86::GR16RegClass);
18415         if (VT == MVT::i8 || VT == MVT::i1)
18416           return std::make_pair(0U, &X86::GR8RegClass);
18417         if (VT == MVT::i64 || VT == MVT::f64)
18418           return std::make_pair(0U, &X86::GR64RegClass);
18419         break;
18420       }
18421       // 32-bit fallthrough
18422     case 'Q':   // Q_REGS
18423       if (VT == MVT::i32 || VT == MVT::f32)
18424         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
18425       if (VT == MVT::i16)
18426         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
18427       if (VT == MVT::i8 || VT == MVT::i1)
18428         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
18429       if (VT == MVT::i64)
18430         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
18431       break;
18432     case 'r':   // GENERAL_REGS
18433     case 'l':   // INDEX_REGS
18434       if (VT == MVT::i8 || VT == MVT::i1)
18435         return std::make_pair(0U, &X86::GR8RegClass);
18436       if (VT == MVT::i16)
18437         return std::make_pair(0U, &X86::GR16RegClass);
18438       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
18439         return std::make_pair(0U, &X86::GR32RegClass);
18440       return std::make_pair(0U, &X86::GR64RegClass);
18441     case 'R':   // LEGACY_REGS
18442       if (VT == MVT::i8 || VT == MVT::i1)
18443         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
18444       if (VT == MVT::i16)
18445         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
18446       if (VT == MVT::i32 || !Subtarget->is64Bit())
18447         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
18448       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
18449     case 'f':  // FP Stack registers.
18450       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
18451       // value to the correct fpstack register class.
18452       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
18453         return std::make_pair(0U, &X86::RFP32RegClass);
18454       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
18455         return std::make_pair(0U, &X86::RFP64RegClass);
18456       return std::make_pair(0U, &X86::RFP80RegClass);
18457     case 'y':   // MMX_REGS if MMX allowed.
18458       if (!Subtarget->hasMMX()) break;
18459       return std::make_pair(0U, &X86::VR64RegClass);
18460     case 'Y':   // SSE_REGS if SSE2 allowed
18461       if (!Subtarget->hasSSE2()) break;
18462       // FALL THROUGH.
18463     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
18464       if (!Subtarget->hasSSE1()) break;
18465
18466       switch (VT.getSimpleVT().SimpleTy) {
18467       default: break;
18468       // Scalar SSE types.
18469       case MVT::f32:
18470       case MVT::i32:
18471         return std::make_pair(0U, &X86::FR32RegClass);
18472       case MVT::f64:
18473       case MVT::i64:
18474         return std::make_pair(0U, &X86::FR64RegClass);
18475       // Vector types.
18476       case MVT::v16i8:
18477       case MVT::v8i16:
18478       case MVT::v4i32:
18479       case MVT::v2i64:
18480       case MVT::v4f32:
18481       case MVT::v2f64:
18482         return std::make_pair(0U, &X86::VR128RegClass);
18483       // AVX types.
18484       case MVT::v32i8:
18485       case MVT::v16i16:
18486       case MVT::v8i32:
18487       case MVT::v4i64:
18488       case MVT::v8f32:
18489       case MVT::v4f64:
18490         return std::make_pair(0U, &X86::VR256RegClass);
18491       }
18492       break;
18493     }
18494   }
18495
18496   // Use the default implementation in TargetLowering to convert the register
18497   // constraint into a member of a register class.
18498   std::pair<unsigned, const TargetRegisterClass*> Res;
18499   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
18500
18501   // Not found as a standard register?
18502   if (Res.second == 0) {
18503     // Map st(0) -> st(7) -> ST0
18504     if (Constraint.size() == 7 && Constraint[0] == '{' &&
18505         tolower(Constraint[1]) == 's' &&
18506         tolower(Constraint[2]) == 't' &&
18507         Constraint[3] == '(' &&
18508         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
18509         Constraint[5] == ')' &&
18510         Constraint[6] == '}') {
18511
18512       Res.first = X86::ST0+Constraint[4]-'0';
18513       Res.second = &X86::RFP80RegClass;
18514       return Res;
18515     }
18516
18517     // GCC allows "st(0)" to be called just plain "st".
18518     if (StringRef("{st}").equals_lower(Constraint)) {
18519       Res.first = X86::ST0;
18520       Res.second = &X86::RFP80RegClass;
18521       return Res;
18522     }
18523
18524     // flags -> EFLAGS
18525     if (StringRef("{flags}").equals_lower(Constraint)) {
18526       Res.first = X86::EFLAGS;
18527       Res.second = &X86::CCRRegClass;
18528       return Res;
18529     }
18530
18531     // 'A' means EAX + EDX.
18532     if (Constraint == "A") {
18533       Res.first = X86::EAX;
18534       Res.second = &X86::GR32_ADRegClass;
18535       return Res;
18536     }
18537     return Res;
18538   }
18539
18540   // Otherwise, check to see if this is a register class of the wrong value
18541   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
18542   // turn into {ax},{dx}.
18543   if (Res.second->hasType(VT))
18544     return Res;   // Correct type already, nothing to do.
18545
18546   // All of the single-register GCC register classes map their values onto
18547   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
18548   // really want an 8-bit or 32-bit register, map to the appropriate register
18549   // class and return the appropriate register.
18550   if (Res.second == &X86::GR16RegClass) {
18551     if (VT == MVT::i8 || VT == MVT::i1) {
18552       unsigned DestReg = 0;
18553       switch (Res.first) {
18554       default: break;
18555       case X86::AX: DestReg = X86::AL; break;
18556       case X86::DX: DestReg = X86::DL; break;
18557       case X86::CX: DestReg = X86::CL; break;
18558       case X86::BX: DestReg = X86::BL; break;
18559       }
18560       if (DestReg) {
18561         Res.first = DestReg;
18562         Res.second = &X86::GR8RegClass;
18563       }
18564     } else if (VT == MVT::i32 || VT == MVT::f32) {
18565       unsigned DestReg = 0;
18566       switch (Res.first) {
18567       default: break;
18568       case X86::AX: DestReg = X86::EAX; break;
18569       case X86::DX: DestReg = X86::EDX; break;
18570       case X86::CX: DestReg = X86::ECX; break;
18571       case X86::BX: DestReg = X86::EBX; break;
18572       case X86::SI: DestReg = X86::ESI; break;
18573       case X86::DI: DestReg = X86::EDI; break;
18574       case X86::BP: DestReg = X86::EBP; break;
18575       case X86::SP: DestReg = X86::ESP; break;
18576       }
18577       if (DestReg) {
18578         Res.first = DestReg;
18579         Res.second = &X86::GR32RegClass;
18580       }
18581     } else if (VT == MVT::i64 || VT == MVT::f64) {
18582       unsigned DestReg = 0;
18583       switch (Res.first) {
18584       default: break;
18585       case X86::AX: DestReg = X86::RAX; break;
18586       case X86::DX: DestReg = X86::RDX; break;
18587       case X86::CX: DestReg = X86::RCX; break;
18588       case X86::BX: DestReg = X86::RBX; break;
18589       case X86::SI: DestReg = X86::RSI; break;
18590       case X86::DI: DestReg = X86::RDI; break;
18591       case X86::BP: DestReg = X86::RBP; break;
18592       case X86::SP: DestReg = X86::RSP; break;
18593       }
18594       if (DestReg) {
18595         Res.first = DestReg;
18596         Res.second = &X86::GR64RegClass;
18597       }
18598     }
18599   } else if (Res.second == &X86::FR32RegClass ||
18600              Res.second == &X86::FR64RegClass ||
18601              Res.second == &X86::VR128RegClass) {
18602     // Handle references to XMM physical registers that got mapped into the
18603     // wrong class.  This can happen with constraints like {xmm0} where the
18604     // target independent register mapper will just pick the first match it can
18605     // find, ignoring the required type.
18606
18607     if (VT == MVT::f32 || VT == MVT::i32)
18608       Res.second = &X86::FR32RegClass;
18609     else if (VT == MVT::f64 || VT == MVT::i64)
18610       Res.second = &X86::FR64RegClass;
18611     else if (X86::VR128RegClass.hasType(VT))
18612       Res.second = &X86::VR128RegClass;
18613     else if (X86::VR256RegClass.hasType(VT))
18614       Res.second = &X86::VR256RegClass;
18615   }
18616
18617   return Res;
18618 }