Use the target options specified on a function to reset the back-end.
[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 in two XMM registers.
12323   DebugLoc dl = Op.getDebugLoc();
12324   SDValue Arg = Op.getOperand(0);
12325   EVT ArgVT = Arg.getValueType();
12326   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
12327
12328   ArgListTy Args;
12329   ArgListEntry Entry;
12330
12331   Entry.Node = Arg;
12332   Entry.Ty = ArgTy;
12333   Entry.isSExt = false;
12334   Entry.isZExt = false;
12335   Args.push_back(Entry);
12336
12337   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
12338   // the small struct {f32, f32} is returned in (eax, edx). For f64,
12339   // the results are returned via SRet in memory.
12340   const char *LibcallName = (ArgVT == MVT::f64)
12341     ? "__sincos_stret" : "__sincosf_stret";
12342   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
12343
12344   StructType *RetTy = StructType::get(ArgTy, ArgTy, NULL);
12345   TargetLowering::
12346     CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
12347                          false, false, false, false, 0,
12348                          CallingConv::C, /*isTaillCall=*/false,
12349                          /*doesNotRet=*/false, /*isReturnValueUsed*/true,
12350                          Callee, Args, DAG, dl);
12351   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
12352   return CallResult.first;
12353 }
12354
12355 /// LowerOperation - Provide custom lowering hooks for some operations.
12356 ///
12357 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
12358   switch (Op.getOpcode()) {
12359   default: llvm_unreachable("Should not custom lower this!");
12360   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
12361   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op, Subtarget, DAG);
12362   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
12363   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
12364   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
12365   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
12366   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
12367   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
12368   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
12369   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
12370   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
12371   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
12372   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
12373   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
12374   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
12375   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
12376   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
12377   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
12378   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
12379   case ISD::SHL_PARTS:
12380   case ISD::SRA_PARTS:
12381   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
12382   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
12383   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
12384   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
12385   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, DAG);
12386   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, DAG);
12387   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, DAG);
12388   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
12389   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
12390   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
12391   case ISD::FABS:               return LowerFABS(Op, DAG);
12392   case ISD::FNEG:               return LowerFNEG(Op, DAG);
12393   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
12394   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
12395   case ISD::SETCC:              return LowerSETCC(Op, DAG);
12396   case ISD::SELECT:             return LowerSELECT(Op, DAG);
12397   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
12398   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
12399   case ISD::VASTART:            return LowerVASTART(Op, DAG);
12400   case ISD::VAARG:              return LowerVAARG(Op, DAG);
12401   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
12402   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
12403   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, DAG);
12404   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
12405   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
12406   case ISD::FRAME_TO_ARGS_OFFSET:
12407                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
12408   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
12409   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
12410   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
12411   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
12412   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
12413   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
12414   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
12415   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
12416   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
12417   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
12418   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
12419   case ISD::SRA:
12420   case ISD::SRL:
12421   case ISD::SHL:                return LowerShift(Op, DAG);
12422   case ISD::SADDO:
12423   case ISD::UADDO:
12424   case ISD::SSUBO:
12425   case ISD::USUBO:
12426   case ISD::SMULO:
12427   case ISD::UMULO:              return LowerXALUO(Op, DAG);
12428   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
12429   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
12430   case ISD::ADDC:
12431   case ISD::ADDE:
12432   case ISD::SUBC:
12433   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
12434   case ISD::ADD:                return LowerADD(Op, DAG);
12435   case ISD::SUB:                return LowerSUB(Op, DAG);
12436   case ISD::SDIV:               return LowerSDIV(Op, DAG);
12437   case ISD::FSINCOS:            return LowerFSINCOS(Op, DAG);
12438   }
12439 }
12440
12441 static void ReplaceATOMIC_LOAD(SDNode *Node,
12442                                   SmallVectorImpl<SDValue> &Results,
12443                                   SelectionDAG &DAG) {
12444   DebugLoc dl = Node->getDebugLoc();
12445   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
12446
12447   // Convert wide load -> cmpxchg8b/cmpxchg16b
12448   // FIXME: On 32-bit, load -> fild or movq would be more efficient
12449   //        (The only way to get a 16-byte load is cmpxchg16b)
12450   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
12451   SDValue Zero = DAG.getConstant(0, VT);
12452   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
12453                                Node->getOperand(0),
12454                                Node->getOperand(1), Zero, Zero,
12455                                cast<AtomicSDNode>(Node)->getMemOperand(),
12456                                cast<AtomicSDNode>(Node)->getOrdering(),
12457                                cast<AtomicSDNode>(Node)->getSynchScope());
12458   Results.push_back(Swap.getValue(0));
12459   Results.push_back(Swap.getValue(1));
12460 }
12461
12462 static void
12463 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
12464                         SelectionDAG &DAG, unsigned NewOp) {
12465   DebugLoc dl = Node->getDebugLoc();
12466   assert (Node->getValueType(0) == MVT::i64 &&
12467           "Only know how to expand i64 atomics");
12468
12469   SDValue Chain = Node->getOperand(0);
12470   SDValue In1 = Node->getOperand(1);
12471   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
12472                              Node->getOperand(2), DAG.getIntPtrConstant(0));
12473   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
12474                              Node->getOperand(2), DAG.getIntPtrConstant(1));
12475   SDValue Ops[] = { Chain, In1, In2L, In2H };
12476   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
12477   SDValue Result =
12478     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
12479                             cast<MemSDNode>(Node)->getMemOperand());
12480   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
12481   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
12482   Results.push_back(Result.getValue(2));
12483 }
12484
12485 /// ReplaceNodeResults - Replace a node with an illegal result type
12486 /// with a new node built out of custom code.
12487 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
12488                                            SmallVectorImpl<SDValue>&Results,
12489                                            SelectionDAG &DAG) const {
12490   DebugLoc dl = N->getDebugLoc();
12491   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12492   switch (N->getOpcode()) {
12493   default:
12494     llvm_unreachable("Do not know how to custom type legalize this operation!");
12495   case ISD::SIGN_EXTEND_INREG:
12496   case ISD::ADDC:
12497   case ISD::ADDE:
12498   case ISD::SUBC:
12499   case ISD::SUBE:
12500     // We don't want to expand or promote these.
12501     return;
12502   case ISD::FP_TO_SINT:
12503   case ISD::FP_TO_UINT: {
12504     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
12505
12506     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
12507       return;
12508
12509     std::pair<SDValue,SDValue> Vals =
12510         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
12511     SDValue FIST = Vals.first, StackSlot = Vals.second;
12512     if (FIST.getNode() != 0) {
12513       EVT VT = N->getValueType(0);
12514       // Return a load from the stack slot.
12515       if (StackSlot.getNode() != 0)
12516         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
12517                                       MachinePointerInfo(),
12518                                       false, false, false, 0));
12519       else
12520         Results.push_back(FIST);
12521     }
12522     return;
12523   }
12524   case ISD::UINT_TO_FP: {
12525     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
12526     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
12527         N->getValueType(0) != MVT::v2f32)
12528       return;
12529     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
12530                                  N->getOperand(0));
12531     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
12532                                      MVT::f64);
12533     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
12534     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
12535                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
12536     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
12537     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
12538     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
12539     return;
12540   }
12541   case ISD::FP_ROUND: {
12542     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
12543         return;
12544     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
12545     Results.push_back(V);
12546     return;
12547   }
12548   case ISD::READCYCLECOUNTER: {
12549     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12550     SDValue TheChain = N->getOperand(0);
12551     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
12552     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
12553                                      rd.getValue(1));
12554     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
12555                                      eax.getValue(2));
12556     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
12557     SDValue Ops[] = { eax, edx };
12558     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
12559     Results.push_back(edx.getValue(1));
12560     return;
12561   }
12562   case ISD::ATOMIC_CMP_SWAP: {
12563     EVT T = N->getValueType(0);
12564     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
12565     bool Regs64bit = T == MVT::i128;
12566     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
12567     SDValue cpInL, cpInH;
12568     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
12569                         DAG.getConstant(0, HalfT));
12570     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
12571                         DAG.getConstant(1, HalfT));
12572     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
12573                              Regs64bit ? X86::RAX : X86::EAX,
12574                              cpInL, SDValue());
12575     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
12576                              Regs64bit ? X86::RDX : X86::EDX,
12577                              cpInH, cpInL.getValue(1));
12578     SDValue swapInL, swapInH;
12579     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
12580                           DAG.getConstant(0, HalfT));
12581     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
12582                           DAG.getConstant(1, HalfT));
12583     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
12584                                Regs64bit ? X86::RBX : X86::EBX,
12585                                swapInL, cpInH.getValue(1));
12586     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
12587                                Regs64bit ? X86::RCX : X86::ECX,
12588                                swapInH, swapInL.getValue(1));
12589     SDValue Ops[] = { swapInH.getValue(0),
12590                       N->getOperand(1),
12591                       swapInH.getValue(1) };
12592     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12593     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
12594     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
12595                                   X86ISD::LCMPXCHG8_DAG;
12596     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
12597                                              Ops, 3, T, MMO);
12598     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
12599                                         Regs64bit ? X86::RAX : X86::EAX,
12600                                         HalfT, Result.getValue(1));
12601     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
12602                                         Regs64bit ? X86::RDX : X86::EDX,
12603                                         HalfT, cpOutL.getValue(2));
12604     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
12605     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
12606     Results.push_back(cpOutH.getValue(1));
12607     return;
12608   }
12609   case ISD::ATOMIC_LOAD_ADD:
12610   case ISD::ATOMIC_LOAD_AND:
12611   case ISD::ATOMIC_LOAD_NAND:
12612   case ISD::ATOMIC_LOAD_OR:
12613   case ISD::ATOMIC_LOAD_SUB:
12614   case ISD::ATOMIC_LOAD_XOR:
12615   case ISD::ATOMIC_LOAD_MAX:
12616   case ISD::ATOMIC_LOAD_MIN:
12617   case ISD::ATOMIC_LOAD_UMAX:
12618   case ISD::ATOMIC_LOAD_UMIN:
12619   case ISD::ATOMIC_SWAP: {
12620     unsigned Opc;
12621     switch (N->getOpcode()) {
12622     default: llvm_unreachable("Unexpected opcode");
12623     case ISD::ATOMIC_LOAD_ADD:
12624       Opc = X86ISD::ATOMADD64_DAG;
12625       break;
12626     case ISD::ATOMIC_LOAD_AND:
12627       Opc = X86ISD::ATOMAND64_DAG;
12628       break;
12629     case ISD::ATOMIC_LOAD_NAND:
12630       Opc = X86ISD::ATOMNAND64_DAG;
12631       break;
12632     case ISD::ATOMIC_LOAD_OR:
12633       Opc = X86ISD::ATOMOR64_DAG;
12634       break;
12635     case ISD::ATOMIC_LOAD_SUB:
12636       Opc = X86ISD::ATOMSUB64_DAG;
12637       break;
12638     case ISD::ATOMIC_LOAD_XOR:
12639       Opc = X86ISD::ATOMXOR64_DAG;
12640       break;
12641     case ISD::ATOMIC_LOAD_MAX:
12642       Opc = X86ISD::ATOMMAX64_DAG;
12643       break;
12644     case ISD::ATOMIC_LOAD_MIN:
12645       Opc = X86ISD::ATOMMIN64_DAG;
12646       break;
12647     case ISD::ATOMIC_LOAD_UMAX:
12648       Opc = X86ISD::ATOMUMAX64_DAG;
12649       break;
12650     case ISD::ATOMIC_LOAD_UMIN:
12651       Opc = X86ISD::ATOMUMIN64_DAG;
12652       break;
12653     case ISD::ATOMIC_SWAP:
12654       Opc = X86ISD::ATOMSWAP64_DAG;
12655       break;
12656     }
12657     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
12658     return;
12659   }
12660   case ISD::ATOMIC_LOAD:
12661     ReplaceATOMIC_LOAD(N, Results, DAG);
12662   }
12663 }
12664
12665 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
12666   switch (Opcode) {
12667   default: return NULL;
12668   case X86ISD::BSF:                return "X86ISD::BSF";
12669   case X86ISD::BSR:                return "X86ISD::BSR";
12670   case X86ISD::SHLD:               return "X86ISD::SHLD";
12671   case X86ISD::SHRD:               return "X86ISD::SHRD";
12672   case X86ISD::FAND:               return "X86ISD::FAND";
12673   case X86ISD::FOR:                return "X86ISD::FOR";
12674   case X86ISD::FXOR:               return "X86ISD::FXOR";
12675   case X86ISD::FSRL:               return "X86ISD::FSRL";
12676   case X86ISD::FILD:               return "X86ISD::FILD";
12677   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
12678   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
12679   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
12680   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
12681   case X86ISD::FLD:                return "X86ISD::FLD";
12682   case X86ISD::FST:                return "X86ISD::FST";
12683   case X86ISD::CALL:               return "X86ISD::CALL";
12684   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
12685   case X86ISD::BT:                 return "X86ISD::BT";
12686   case X86ISD::CMP:                return "X86ISD::CMP";
12687   case X86ISD::COMI:               return "X86ISD::COMI";
12688   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
12689   case X86ISD::SETCC:              return "X86ISD::SETCC";
12690   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
12691   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
12692   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
12693   case X86ISD::CMOV:               return "X86ISD::CMOV";
12694   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
12695   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
12696   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
12697   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
12698   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
12699   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
12700   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
12701   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
12702   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
12703   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
12704   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
12705   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
12706   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
12707   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
12708   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
12709   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
12710   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
12711   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
12712   case X86ISD::HADD:               return "X86ISD::HADD";
12713   case X86ISD::HSUB:               return "X86ISD::HSUB";
12714   case X86ISD::FHADD:              return "X86ISD::FHADD";
12715   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
12716   case X86ISD::UMAX:               return "X86ISD::UMAX";
12717   case X86ISD::UMIN:               return "X86ISD::UMIN";
12718   case X86ISD::SMAX:               return "X86ISD::SMAX";
12719   case X86ISD::SMIN:               return "X86ISD::SMIN";
12720   case X86ISD::FMAX:               return "X86ISD::FMAX";
12721   case X86ISD::FMIN:               return "X86ISD::FMIN";
12722   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
12723   case X86ISD::FMINC:              return "X86ISD::FMINC";
12724   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
12725   case X86ISD::FRCP:               return "X86ISD::FRCP";
12726   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
12727   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
12728   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
12729   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
12730   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
12731   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
12732   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
12733   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
12734   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
12735   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
12736   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
12737   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
12738   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
12739   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
12740   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
12741   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
12742   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
12743   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
12744   case X86ISD::VSEXT_MOVL:         return "X86ISD::VSEXT_MOVL";
12745   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
12746   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
12747   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
12748   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
12749   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
12750   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
12751   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
12752   case X86ISD::VSHL:               return "X86ISD::VSHL";
12753   case X86ISD::VSRL:               return "X86ISD::VSRL";
12754   case X86ISD::VSRA:               return "X86ISD::VSRA";
12755   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
12756   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
12757   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
12758   case X86ISD::CMPP:               return "X86ISD::CMPP";
12759   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
12760   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
12761   case X86ISD::ADD:                return "X86ISD::ADD";
12762   case X86ISD::SUB:                return "X86ISD::SUB";
12763   case X86ISD::ADC:                return "X86ISD::ADC";
12764   case X86ISD::SBB:                return "X86ISD::SBB";
12765   case X86ISD::SMUL:               return "X86ISD::SMUL";
12766   case X86ISD::UMUL:               return "X86ISD::UMUL";
12767   case X86ISD::INC:                return "X86ISD::INC";
12768   case X86ISD::DEC:                return "X86ISD::DEC";
12769   case X86ISD::OR:                 return "X86ISD::OR";
12770   case X86ISD::XOR:                return "X86ISD::XOR";
12771   case X86ISD::AND:                return "X86ISD::AND";
12772   case X86ISD::BLSI:               return "X86ISD::BLSI";
12773   case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
12774   case X86ISD::BLSR:               return "X86ISD::BLSR";
12775   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
12776   case X86ISD::PTEST:              return "X86ISD::PTEST";
12777   case X86ISD::TESTP:              return "X86ISD::TESTP";
12778   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
12779   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
12780   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
12781   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
12782   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
12783   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
12784   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
12785   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
12786   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
12787   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
12788   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
12789   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
12790   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
12791   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
12792   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
12793   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
12794   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
12795   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
12796   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
12797   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
12798   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
12799   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
12800   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
12801   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
12802   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
12803   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
12804   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
12805   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
12806   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
12807   case X86ISD::SAHF:               return "X86ISD::SAHF";
12808   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
12809   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
12810   case X86ISD::FMADD:              return "X86ISD::FMADD";
12811   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
12812   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
12813   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
12814   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
12815   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
12816   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
12817   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
12818   case X86ISD::XTEST:              return "X86ISD::XTEST";
12819   }
12820 }
12821
12822 // isLegalAddressingMode - Return true if the addressing mode represented
12823 // by AM is legal for this target, for a load/store of the specified type.
12824 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
12825                                               Type *Ty) const {
12826   // X86 supports extremely general addressing modes.
12827   CodeModel::Model M = getTargetMachine().getCodeModel();
12828   Reloc::Model R = getTargetMachine().getRelocationModel();
12829
12830   // X86 allows a sign-extended 32-bit immediate field as a displacement.
12831   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
12832     return false;
12833
12834   if (AM.BaseGV) {
12835     unsigned GVFlags =
12836       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
12837
12838     // If a reference to this global requires an extra load, we can't fold it.
12839     if (isGlobalStubReference(GVFlags))
12840       return false;
12841
12842     // If BaseGV requires a register for the PIC base, we cannot also have a
12843     // BaseReg specified.
12844     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
12845       return false;
12846
12847     // If lower 4G is not available, then we must use rip-relative addressing.
12848     if ((M != CodeModel::Small || R != Reloc::Static) &&
12849         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
12850       return false;
12851   }
12852
12853   switch (AM.Scale) {
12854   case 0:
12855   case 1:
12856   case 2:
12857   case 4:
12858   case 8:
12859     // These scales always work.
12860     break;
12861   case 3:
12862   case 5:
12863   case 9:
12864     // These scales are formed with basereg+scalereg.  Only accept if there is
12865     // no basereg yet.
12866     if (AM.HasBaseReg)
12867       return false;
12868     break;
12869   default:  // Other stuff never works.
12870     return false;
12871   }
12872
12873   return true;
12874 }
12875
12876 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
12877   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
12878     return false;
12879   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
12880   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
12881   return NumBits1 > NumBits2;
12882 }
12883
12884 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
12885   return isInt<32>(Imm);
12886 }
12887
12888 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
12889   // Can also use sub to handle negated immediates.
12890   return isInt<32>(Imm);
12891 }
12892
12893 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
12894   if (!VT1.isInteger() || !VT2.isInteger())
12895     return false;
12896   unsigned NumBits1 = VT1.getSizeInBits();
12897   unsigned NumBits2 = VT2.getSizeInBits();
12898   return NumBits1 > NumBits2;
12899 }
12900
12901 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
12902   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12903   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
12904 }
12905
12906 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
12907   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12908   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
12909 }
12910
12911 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
12912   EVT VT1 = Val.getValueType();
12913   if (isZExtFree(VT1, VT2))
12914     return true;
12915
12916   if (Val.getOpcode() != ISD::LOAD)
12917     return false;
12918
12919   if (!VT1.isSimple() || !VT1.isInteger() ||
12920       !VT2.isSimple() || !VT2.isInteger())
12921     return false;
12922
12923   switch (VT1.getSimpleVT().SimpleTy) {
12924   default: break;
12925   case MVT::i8:
12926   case MVT::i16:
12927   case MVT::i32:
12928     // X86 has 8, 16, and 32-bit zero-extending loads.
12929     return true;
12930   }
12931
12932   return false;
12933 }
12934
12935 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
12936   // i16 instructions are longer (0x66 prefix) and potentially slower.
12937   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
12938 }
12939
12940 /// isShuffleMaskLegal - Targets can use this to indicate that they only
12941 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
12942 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
12943 /// are assumed to be legal.
12944 bool
12945 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
12946                                       EVT VT) const {
12947   // Very little shuffling can be done for 64-bit vectors right now.
12948   if (VT.getSizeInBits() == 64)
12949     return false;
12950
12951   // FIXME: pshufb, blends, shifts.
12952   return (VT.getVectorNumElements() == 2 ||
12953           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
12954           isMOVLMask(M, VT) ||
12955           isSHUFPMask(M, VT, Subtarget->hasFp256()) ||
12956           isPSHUFDMask(M, VT) ||
12957           isPSHUFHWMask(M, VT, Subtarget->hasInt256()) ||
12958           isPSHUFLWMask(M, VT, Subtarget->hasInt256()) ||
12959           isPALIGNRMask(M, VT, Subtarget) ||
12960           isUNPCKLMask(M, VT, Subtarget->hasInt256()) ||
12961           isUNPCKHMask(M, VT, Subtarget->hasInt256()) ||
12962           isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasInt256()) ||
12963           isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasInt256()));
12964 }
12965
12966 bool
12967 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
12968                                           EVT VT) const {
12969   unsigned NumElts = VT.getVectorNumElements();
12970   // FIXME: This collection of masks seems suspect.
12971   if (NumElts == 2)
12972     return true;
12973   if (NumElts == 4 && VT.is128BitVector()) {
12974     return (isMOVLMask(Mask, VT)  ||
12975             isCommutedMOVLMask(Mask, VT, true) ||
12976             isSHUFPMask(Mask, VT, Subtarget->hasFp256()) ||
12977             isSHUFPMask(Mask, VT, Subtarget->hasFp256(), /* Commuted */ true));
12978   }
12979   return false;
12980 }
12981
12982 //===----------------------------------------------------------------------===//
12983 //                           X86 Scheduler Hooks
12984 //===----------------------------------------------------------------------===//
12985
12986 /// Utility function to emit xbegin specifying the start of an RTM region.
12987 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
12988                                      const TargetInstrInfo *TII) {
12989   DebugLoc DL = MI->getDebugLoc();
12990
12991   const BasicBlock *BB = MBB->getBasicBlock();
12992   MachineFunction::iterator I = MBB;
12993   ++I;
12994
12995   // For the v = xbegin(), we generate
12996   //
12997   // thisMBB:
12998   //  xbegin sinkMBB
12999   //
13000   // mainMBB:
13001   //  eax = -1
13002   //
13003   // sinkMBB:
13004   //  v = eax
13005
13006   MachineBasicBlock *thisMBB = MBB;
13007   MachineFunction *MF = MBB->getParent();
13008   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13009   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13010   MF->insert(I, mainMBB);
13011   MF->insert(I, sinkMBB);
13012
13013   // Transfer the remainder of BB and its successor edges to sinkMBB.
13014   sinkMBB->splice(sinkMBB->begin(), MBB,
13015                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13016   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13017
13018   // thisMBB:
13019   //  xbegin sinkMBB
13020   //  # fallthrough to mainMBB
13021   //  # abortion to sinkMBB
13022   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
13023   thisMBB->addSuccessor(mainMBB);
13024   thisMBB->addSuccessor(sinkMBB);
13025
13026   // mainMBB:
13027   //  EAX = -1
13028   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
13029   mainMBB->addSuccessor(sinkMBB);
13030
13031   // sinkMBB:
13032   // EAX is live into the sinkMBB
13033   sinkMBB->addLiveIn(X86::EAX);
13034   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13035           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13036     .addReg(X86::EAX);
13037
13038   MI->eraseFromParent();
13039   return sinkMBB;
13040 }
13041
13042 // Get CMPXCHG opcode for the specified data type.
13043 static unsigned getCmpXChgOpcode(EVT VT) {
13044   switch (VT.getSimpleVT().SimpleTy) {
13045   case MVT::i8:  return X86::LCMPXCHG8;
13046   case MVT::i16: return X86::LCMPXCHG16;
13047   case MVT::i32: return X86::LCMPXCHG32;
13048   case MVT::i64: return X86::LCMPXCHG64;
13049   default:
13050     break;
13051   }
13052   llvm_unreachable("Invalid operand size!");
13053 }
13054
13055 // Get LOAD opcode for the specified data type.
13056 static unsigned getLoadOpcode(EVT VT) {
13057   switch (VT.getSimpleVT().SimpleTy) {
13058   case MVT::i8:  return X86::MOV8rm;
13059   case MVT::i16: return X86::MOV16rm;
13060   case MVT::i32: return X86::MOV32rm;
13061   case MVT::i64: return X86::MOV64rm;
13062   default:
13063     break;
13064   }
13065   llvm_unreachable("Invalid operand size!");
13066 }
13067
13068 // Get opcode of the non-atomic one from the specified atomic instruction.
13069 static unsigned getNonAtomicOpcode(unsigned Opc) {
13070   switch (Opc) {
13071   case X86::ATOMAND8:  return X86::AND8rr;
13072   case X86::ATOMAND16: return X86::AND16rr;
13073   case X86::ATOMAND32: return X86::AND32rr;
13074   case X86::ATOMAND64: return X86::AND64rr;
13075   case X86::ATOMOR8:   return X86::OR8rr;
13076   case X86::ATOMOR16:  return X86::OR16rr;
13077   case X86::ATOMOR32:  return X86::OR32rr;
13078   case X86::ATOMOR64:  return X86::OR64rr;
13079   case X86::ATOMXOR8:  return X86::XOR8rr;
13080   case X86::ATOMXOR16: return X86::XOR16rr;
13081   case X86::ATOMXOR32: return X86::XOR32rr;
13082   case X86::ATOMXOR64: return X86::XOR64rr;
13083   }
13084   llvm_unreachable("Unhandled atomic-load-op opcode!");
13085 }
13086
13087 // Get opcode of the non-atomic one from the specified atomic instruction with
13088 // extra opcode.
13089 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
13090                                                unsigned &ExtraOpc) {
13091   switch (Opc) {
13092   case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
13093   case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
13094   case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
13095   case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
13096   case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
13097   case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
13098   case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
13099   case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
13100   case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
13101   case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
13102   case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
13103   case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
13104   case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
13105   case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
13106   case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
13107   case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
13108   case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
13109   case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
13110   case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
13111   case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
13112   }
13113   llvm_unreachable("Unhandled atomic-load-op opcode!");
13114 }
13115
13116 // Get opcode of the non-atomic one from the specified atomic instruction for
13117 // 64-bit data type on 32-bit target.
13118 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
13119   switch (Opc) {
13120   case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
13121   case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
13122   case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
13123   case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
13124   case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
13125   case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
13126   case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
13127   case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
13128   case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
13129   case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
13130   }
13131   llvm_unreachable("Unhandled atomic-load-op opcode!");
13132 }
13133
13134 // Get opcode of the non-atomic one from the specified atomic instruction for
13135 // 64-bit data type on 32-bit target with extra opcode.
13136 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
13137                                                    unsigned &HiOpc,
13138                                                    unsigned &ExtraOpc) {
13139   switch (Opc) {
13140   case X86::ATOMNAND6432:
13141     ExtraOpc = X86::NOT32r;
13142     HiOpc = X86::AND32rr;
13143     return X86::AND32rr;
13144   }
13145   llvm_unreachable("Unhandled atomic-load-op opcode!");
13146 }
13147
13148 // Get pseudo CMOV opcode from the specified data type.
13149 static unsigned getPseudoCMOVOpc(EVT VT) {
13150   switch (VT.getSimpleVT().SimpleTy) {
13151   case MVT::i8:  return X86::CMOV_GR8;
13152   case MVT::i16: return X86::CMOV_GR16;
13153   case MVT::i32: return X86::CMOV_GR32;
13154   default:
13155     break;
13156   }
13157   llvm_unreachable("Unknown CMOV opcode!");
13158 }
13159
13160 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
13161 // They will be translated into a spin-loop or compare-exchange loop from
13162 //
13163 //    ...
13164 //    dst = atomic-fetch-op MI.addr, MI.val
13165 //    ...
13166 //
13167 // to
13168 //
13169 //    ...
13170 //    t1 = LOAD MI.addr
13171 // loop:
13172 //    t4 = phi(t1, t3 / loop)
13173 //    t2 = OP MI.val, t4
13174 //    EAX = t4
13175 //    LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
13176 //    t3 = EAX
13177 //    JNE loop
13178 // sink:
13179 //    dst = t3
13180 //    ...
13181 MachineBasicBlock *
13182 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
13183                                        MachineBasicBlock *MBB) const {
13184   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13185   DebugLoc DL = MI->getDebugLoc();
13186
13187   MachineFunction *MF = MBB->getParent();
13188   MachineRegisterInfo &MRI = MF->getRegInfo();
13189
13190   const BasicBlock *BB = MBB->getBasicBlock();
13191   MachineFunction::iterator I = MBB;
13192   ++I;
13193
13194   assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
13195          "Unexpected number of operands");
13196
13197   assert(MI->hasOneMemOperand() &&
13198          "Expected atomic-load-op to have one memoperand");
13199
13200   // Memory Reference
13201   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13202   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13203
13204   unsigned DstReg, SrcReg;
13205   unsigned MemOpndSlot;
13206
13207   unsigned CurOp = 0;
13208
13209   DstReg = MI->getOperand(CurOp++).getReg();
13210   MemOpndSlot = CurOp;
13211   CurOp += X86::AddrNumOperands;
13212   SrcReg = MI->getOperand(CurOp++).getReg();
13213
13214   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
13215   MVT::SimpleValueType VT = *RC->vt_begin();
13216   unsigned t1 = MRI.createVirtualRegister(RC);
13217   unsigned t2 = MRI.createVirtualRegister(RC);
13218   unsigned t3 = MRI.createVirtualRegister(RC);
13219   unsigned t4 = MRI.createVirtualRegister(RC);
13220   unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
13221
13222   unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
13223   unsigned LOADOpc = getLoadOpcode(VT);
13224
13225   // For the atomic load-arith operator, we generate
13226   //
13227   //  thisMBB:
13228   //    t1 = LOAD [MI.addr]
13229   //  mainMBB:
13230   //    t4 = phi(t1 / thisMBB, t3 / mainMBB)
13231   //    t1 = OP MI.val, EAX
13232   //    EAX = t4
13233   //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
13234   //    t3 = EAX
13235   //    JNE mainMBB
13236   //  sinkMBB:
13237   //    dst = t3
13238
13239   MachineBasicBlock *thisMBB = MBB;
13240   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13241   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13242   MF->insert(I, mainMBB);
13243   MF->insert(I, sinkMBB);
13244
13245   MachineInstrBuilder MIB;
13246
13247   // Transfer the remainder of BB and its successor edges to sinkMBB.
13248   sinkMBB->splice(sinkMBB->begin(), MBB,
13249                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13250   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13251
13252   // thisMBB:
13253   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
13254   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13255     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13256     if (NewMO.isReg())
13257       NewMO.setIsKill(false);
13258     MIB.addOperand(NewMO);
13259   }
13260   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
13261     unsigned flags = (*MMOI)->getFlags();
13262     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
13263     MachineMemOperand *MMO =
13264       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
13265                                (*MMOI)->getSize(),
13266                                (*MMOI)->getBaseAlignment(),
13267                                (*MMOI)->getTBAAInfo(),
13268                                (*MMOI)->getRanges());
13269     MIB.addMemOperand(MMO);
13270   }
13271
13272   thisMBB->addSuccessor(mainMBB);
13273
13274   // mainMBB:
13275   MachineBasicBlock *origMainMBB = mainMBB;
13276
13277   // Add a PHI.
13278   MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
13279                         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
13280
13281   unsigned Opc = MI->getOpcode();
13282   switch (Opc) {
13283   default:
13284     llvm_unreachable("Unhandled atomic-load-op opcode!");
13285   case X86::ATOMAND8:
13286   case X86::ATOMAND16:
13287   case X86::ATOMAND32:
13288   case X86::ATOMAND64:
13289   case X86::ATOMOR8:
13290   case X86::ATOMOR16:
13291   case X86::ATOMOR32:
13292   case X86::ATOMOR64:
13293   case X86::ATOMXOR8:
13294   case X86::ATOMXOR16:
13295   case X86::ATOMXOR32:
13296   case X86::ATOMXOR64: {
13297     unsigned ARITHOpc = getNonAtomicOpcode(Opc);
13298     BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
13299       .addReg(t4);
13300     break;
13301   }
13302   case X86::ATOMNAND8:
13303   case X86::ATOMNAND16:
13304   case X86::ATOMNAND32:
13305   case X86::ATOMNAND64: {
13306     unsigned Tmp = MRI.createVirtualRegister(RC);
13307     unsigned NOTOpc;
13308     unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
13309     BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
13310       .addReg(t4);
13311     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
13312     break;
13313   }
13314   case X86::ATOMMAX8:
13315   case X86::ATOMMAX16:
13316   case X86::ATOMMAX32:
13317   case X86::ATOMMAX64:
13318   case X86::ATOMMIN8:
13319   case X86::ATOMMIN16:
13320   case X86::ATOMMIN32:
13321   case X86::ATOMMIN64:
13322   case X86::ATOMUMAX8:
13323   case X86::ATOMUMAX16:
13324   case X86::ATOMUMAX32:
13325   case X86::ATOMUMAX64:
13326   case X86::ATOMUMIN8:
13327   case X86::ATOMUMIN16:
13328   case X86::ATOMUMIN32:
13329   case X86::ATOMUMIN64: {
13330     unsigned CMPOpc;
13331     unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
13332
13333     BuildMI(mainMBB, DL, TII->get(CMPOpc))
13334       .addReg(SrcReg)
13335       .addReg(t4);
13336
13337     if (Subtarget->hasCMov()) {
13338       if (VT != MVT::i8) {
13339         // Native support
13340         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
13341           .addReg(SrcReg)
13342           .addReg(t4);
13343       } else {
13344         // Promote i8 to i32 to use CMOV32
13345         const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
13346         const TargetRegisterClass *RC32 =
13347           TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
13348         unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
13349         unsigned AccReg32 = MRI.createVirtualRegister(RC32);
13350         unsigned Tmp = MRI.createVirtualRegister(RC32);
13351
13352         unsigned Undef = MRI.createVirtualRegister(RC32);
13353         BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
13354
13355         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
13356           .addReg(Undef)
13357           .addReg(SrcReg)
13358           .addImm(X86::sub_8bit);
13359         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
13360           .addReg(Undef)
13361           .addReg(t4)
13362           .addImm(X86::sub_8bit);
13363
13364         BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
13365           .addReg(SrcReg32)
13366           .addReg(AccReg32);
13367
13368         BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
13369           .addReg(Tmp, 0, X86::sub_8bit);
13370       }
13371     } else {
13372       // Use pseudo select and lower them.
13373       assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
13374              "Invalid atomic-load-op transformation!");
13375       unsigned SelOpc = getPseudoCMOVOpc(VT);
13376       X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
13377       assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
13378       MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
13379               .addReg(SrcReg).addReg(t4)
13380               .addImm(CC);
13381       mainMBB = EmitLoweredSelect(MIB, mainMBB);
13382       // Replace the original PHI node as mainMBB is changed after CMOV
13383       // lowering.
13384       BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
13385         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
13386       Phi->eraseFromParent();
13387     }
13388     break;
13389   }
13390   }
13391
13392   // Copy PhyReg back from virtual register.
13393   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
13394     .addReg(t4);
13395
13396   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
13397   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13398     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13399     if (NewMO.isReg())
13400       NewMO.setIsKill(false);
13401     MIB.addOperand(NewMO);
13402   }
13403   MIB.addReg(t2);
13404   MIB.setMemRefs(MMOBegin, MMOEnd);
13405
13406   // Copy PhyReg back to virtual register.
13407   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
13408     .addReg(PhyReg);
13409
13410   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
13411
13412   mainMBB->addSuccessor(origMainMBB);
13413   mainMBB->addSuccessor(sinkMBB);
13414
13415   // sinkMBB:
13416   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13417           TII->get(TargetOpcode::COPY), DstReg)
13418     .addReg(t3);
13419
13420   MI->eraseFromParent();
13421   return sinkMBB;
13422 }
13423
13424 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
13425 // instructions. They will be translated into a spin-loop or compare-exchange
13426 // loop from
13427 //
13428 //    ...
13429 //    dst = atomic-fetch-op MI.addr, MI.val
13430 //    ...
13431 //
13432 // to
13433 //
13434 //    ...
13435 //    t1L = LOAD [MI.addr + 0]
13436 //    t1H = LOAD [MI.addr + 4]
13437 // loop:
13438 //    t4L = phi(t1L, t3L / loop)
13439 //    t4H = phi(t1H, t3H / loop)
13440 //    t2L = OP MI.val.lo, t4L
13441 //    t2H = OP MI.val.hi, t4H
13442 //    EAX = t4L
13443 //    EDX = t4H
13444 //    EBX = t2L
13445 //    ECX = t2H
13446 //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
13447 //    t3L = EAX
13448 //    t3H = EDX
13449 //    JNE loop
13450 // sink:
13451 //    dstL = t3L
13452 //    dstH = t3H
13453 //    ...
13454 MachineBasicBlock *
13455 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
13456                                            MachineBasicBlock *MBB) const {
13457   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13458   DebugLoc DL = MI->getDebugLoc();
13459
13460   MachineFunction *MF = MBB->getParent();
13461   MachineRegisterInfo &MRI = MF->getRegInfo();
13462
13463   const BasicBlock *BB = MBB->getBasicBlock();
13464   MachineFunction::iterator I = MBB;
13465   ++I;
13466
13467   assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
13468          "Unexpected number of operands");
13469
13470   assert(MI->hasOneMemOperand() &&
13471          "Expected atomic-load-op32 to have one memoperand");
13472
13473   // Memory Reference
13474   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13475   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13476
13477   unsigned DstLoReg, DstHiReg;
13478   unsigned SrcLoReg, SrcHiReg;
13479   unsigned MemOpndSlot;
13480
13481   unsigned CurOp = 0;
13482
13483   DstLoReg = MI->getOperand(CurOp++).getReg();
13484   DstHiReg = MI->getOperand(CurOp++).getReg();
13485   MemOpndSlot = CurOp;
13486   CurOp += X86::AddrNumOperands;
13487   SrcLoReg = MI->getOperand(CurOp++).getReg();
13488   SrcHiReg = MI->getOperand(CurOp++).getReg();
13489
13490   const TargetRegisterClass *RC = &X86::GR32RegClass;
13491   const TargetRegisterClass *RC8 = &X86::GR8RegClass;
13492
13493   unsigned t1L = MRI.createVirtualRegister(RC);
13494   unsigned t1H = MRI.createVirtualRegister(RC);
13495   unsigned t2L = MRI.createVirtualRegister(RC);
13496   unsigned t2H = MRI.createVirtualRegister(RC);
13497   unsigned t3L = MRI.createVirtualRegister(RC);
13498   unsigned t3H = MRI.createVirtualRegister(RC);
13499   unsigned t4L = MRI.createVirtualRegister(RC);
13500   unsigned t4H = MRI.createVirtualRegister(RC);
13501
13502   unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
13503   unsigned LOADOpc = X86::MOV32rm;
13504
13505   // For the atomic load-arith operator, we generate
13506   //
13507   //  thisMBB:
13508   //    t1L = LOAD [MI.addr + 0]
13509   //    t1H = LOAD [MI.addr + 4]
13510   //  mainMBB:
13511   //    t4L = phi(t1L / thisMBB, t3L / mainMBB)
13512   //    t4H = phi(t1H / thisMBB, t3H / mainMBB)
13513   //    t2L = OP MI.val.lo, t4L
13514   //    t2H = OP MI.val.hi, t4H
13515   //    EBX = t2L
13516   //    ECX = t2H
13517   //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
13518   //    t3L = EAX
13519   //    t3H = EDX
13520   //    JNE loop
13521   //  sinkMBB:
13522   //    dstL = t3L
13523   //    dstH = t3H
13524
13525   MachineBasicBlock *thisMBB = MBB;
13526   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13527   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13528   MF->insert(I, mainMBB);
13529   MF->insert(I, sinkMBB);
13530
13531   MachineInstrBuilder MIB;
13532
13533   // Transfer the remainder of BB and its successor edges to sinkMBB.
13534   sinkMBB->splice(sinkMBB->begin(), MBB,
13535                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13536   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13537
13538   // thisMBB:
13539   // Lo
13540   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
13541   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13542     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13543     if (NewMO.isReg())
13544       NewMO.setIsKill(false);
13545     MIB.addOperand(NewMO);
13546   }
13547   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
13548     unsigned flags = (*MMOI)->getFlags();
13549     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
13550     MachineMemOperand *MMO =
13551       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
13552                                (*MMOI)->getSize(),
13553                                (*MMOI)->getBaseAlignment(),
13554                                (*MMOI)->getTBAAInfo(),
13555                                (*MMOI)->getRanges());
13556     MIB.addMemOperand(MMO);
13557   };
13558   MachineInstr *LowMI = MIB;
13559
13560   // Hi
13561   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
13562   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13563     if (i == X86::AddrDisp) {
13564       MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
13565     } else {
13566       MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13567       if (NewMO.isReg())
13568         NewMO.setIsKill(false);
13569       MIB.addOperand(NewMO);
13570     }
13571   }
13572   MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
13573
13574   thisMBB->addSuccessor(mainMBB);
13575
13576   // mainMBB:
13577   MachineBasicBlock *origMainMBB = mainMBB;
13578
13579   // Add PHIs.
13580   MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
13581                         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
13582   MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
13583                         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
13584
13585   unsigned Opc = MI->getOpcode();
13586   switch (Opc) {
13587   default:
13588     llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
13589   case X86::ATOMAND6432:
13590   case X86::ATOMOR6432:
13591   case X86::ATOMXOR6432:
13592   case X86::ATOMADD6432:
13593   case X86::ATOMSUB6432: {
13594     unsigned HiOpc;
13595     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13596     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
13597       .addReg(SrcLoReg);
13598     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
13599       .addReg(SrcHiReg);
13600     break;
13601   }
13602   case X86::ATOMNAND6432: {
13603     unsigned HiOpc, NOTOpc;
13604     unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
13605     unsigned TmpL = MRI.createVirtualRegister(RC);
13606     unsigned TmpH = MRI.createVirtualRegister(RC);
13607     BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
13608       .addReg(t4L);
13609     BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
13610       .addReg(t4H);
13611     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
13612     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
13613     break;
13614   }
13615   case X86::ATOMMAX6432:
13616   case X86::ATOMMIN6432:
13617   case X86::ATOMUMAX6432:
13618   case X86::ATOMUMIN6432: {
13619     unsigned HiOpc;
13620     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13621     unsigned cL = MRI.createVirtualRegister(RC8);
13622     unsigned cH = MRI.createVirtualRegister(RC8);
13623     unsigned cL32 = MRI.createVirtualRegister(RC);
13624     unsigned cH32 = MRI.createVirtualRegister(RC);
13625     unsigned cc = MRI.createVirtualRegister(RC);
13626     // cl := cmp src_lo, lo
13627     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
13628       .addReg(SrcLoReg).addReg(t4L);
13629     BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
13630     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
13631     // ch := cmp src_hi, hi
13632     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
13633       .addReg(SrcHiReg).addReg(t4H);
13634     BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
13635     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
13636     // cc := if (src_hi == hi) ? cl : ch;
13637     if (Subtarget->hasCMov()) {
13638       BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
13639         .addReg(cH32).addReg(cL32);
13640     } else {
13641       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
13642               .addReg(cH32).addReg(cL32)
13643               .addImm(X86::COND_E);
13644       mainMBB = EmitLoweredSelect(MIB, mainMBB);
13645     }
13646     BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
13647     if (Subtarget->hasCMov()) {
13648       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
13649         .addReg(SrcLoReg).addReg(t4L);
13650       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
13651         .addReg(SrcHiReg).addReg(t4H);
13652     } else {
13653       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
13654               .addReg(SrcLoReg).addReg(t4L)
13655               .addImm(X86::COND_NE);
13656       mainMBB = EmitLoweredSelect(MIB, mainMBB);
13657       // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
13658       // 2nd CMOV lowering.
13659       mainMBB->addLiveIn(X86::EFLAGS);
13660       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
13661               .addReg(SrcHiReg).addReg(t4H)
13662               .addImm(X86::COND_NE);
13663       mainMBB = EmitLoweredSelect(MIB, mainMBB);
13664       // Replace the original PHI node as mainMBB is changed after CMOV
13665       // lowering.
13666       BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
13667         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
13668       BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
13669         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
13670       PhiL->eraseFromParent();
13671       PhiH->eraseFromParent();
13672     }
13673     break;
13674   }
13675   case X86::ATOMSWAP6432: {
13676     unsigned HiOpc;
13677     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13678     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
13679     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
13680     break;
13681   }
13682   }
13683
13684   // Copy EDX:EAX back from HiReg:LoReg
13685   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
13686   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
13687   // Copy ECX:EBX from t1H:t1L
13688   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
13689   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
13690
13691   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
13692   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13693     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13694     if (NewMO.isReg())
13695       NewMO.setIsKill(false);
13696     MIB.addOperand(NewMO);
13697   }
13698   MIB.setMemRefs(MMOBegin, MMOEnd);
13699
13700   // Copy EDX:EAX back to t3H:t3L
13701   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
13702   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
13703
13704   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
13705
13706   mainMBB->addSuccessor(origMainMBB);
13707   mainMBB->addSuccessor(sinkMBB);
13708
13709   // sinkMBB:
13710   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13711           TII->get(TargetOpcode::COPY), DstLoReg)
13712     .addReg(t3L);
13713   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13714           TII->get(TargetOpcode::COPY), DstHiReg)
13715     .addReg(t3H);
13716
13717   MI->eraseFromParent();
13718   return sinkMBB;
13719 }
13720
13721 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
13722 // or XMM0_V32I8 in AVX all of this code can be replaced with that
13723 // in the .td file.
13724 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
13725                                        const TargetInstrInfo *TII) {
13726   unsigned Opc;
13727   switch (MI->getOpcode()) {
13728   default: llvm_unreachable("illegal opcode!");
13729   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
13730   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
13731   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
13732   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
13733   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
13734   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
13735   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
13736   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
13737   }
13738
13739   DebugLoc dl = MI->getDebugLoc();
13740   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
13741
13742   unsigned NumArgs = MI->getNumOperands();
13743   for (unsigned i = 1; i < NumArgs; ++i) {
13744     MachineOperand &Op = MI->getOperand(i);
13745     if (!(Op.isReg() && Op.isImplicit()))
13746       MIB.addOperand(Op);
13747   }
13748   if (MI->hasOneMemOperand())
13749     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
13750
13751   BuildMI(*BB, MI, dl,
13752     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13753     .addReg(X86::XMM0);
13754
13755   MI->eraseFromParent();
13756   return BB;
13757 }
13758
13759 // FIXME: Custom handling because TableGen doesn't support multiple implicit
13760 // defs in an instruction pattern
13761 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
13762                                        const TargetInstrInfo *TII) {
13763   unsigned Opc;
13764   switch (MI->getOpcode()) {
13765   default: llvm_unreachable("illegal opcode!");
13766   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
13767   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
13768   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
13769   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
13770   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
13771   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
13772   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
13773   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
13774   }
13775
13776   DebugLoc dl = MI->getDebugLoc();
13777   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
13778
13779   unsigned NumArgs = MI->getNumOperands(); // remove the results
13780   for (unsigned i = 1; i < NumArgs; ++i) {
13781     MachineOperand &Op = MI->getOperand(i);
13782     if (!(Op.isReg() && Op.isImplicit()))
13783       MIB.addOperand(Op);
13784   }
13785   if (MI->hasOneMemOperand())
13786     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
13787
13788   BuildMI(*BB, MI, dl,
13789     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13790     .addReg(X86::ECX);
13791
13792   MI->eraseFromParent();
13793   return BB;
13794 }
13795
13796 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
13797                                        const TargetInstrInfo *TII,
13798                                        const X86Subtarget* Subtarget) {
13799   DebugLoc dl = MI->getDebugLoc();
13800
13801   // Address into RAX/EAX, other two args into ECX, EDX.
13802   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
13803   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
13804   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
13805   for (int i = 0; i < X86::AddrNumOperands; ++i)
13806     MIB.addOperand(MI->getOperand(i));
13807
13808   unsigned ValOps = X86::AddrNumOperands;
13809   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
13810     .addReg(MI->getOperand(ValOps).getReg());
13811   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
13812     .addReg(MI->getOperand(ValOps+1).getReg());
13813
13814   // The instruction doesn't actually take any operands though.
13815   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
13816
13817   MI->eraseFromParent(); // The pseudo is gone now.
13818   return BB;
13819 }
13820
13821 MachineBasicBlock *
13822 X86TargetLowering::EmitVAARG64WithCustomInserter(
13823                    MachineInstr *MI,
13824                    MachineBasicBlock *MBB) const {
13825   // Emit va_arg instruction on X86-64.
13826
13827   // Operands to this pseudo-instruction:
13828   // 0  ) Output        : destination address (reg)
13829   // 1-5) Input         : va_list address (addr, i64mem)
13830   // 6  ) ArgSize       : Size (in bytes) of vararg type
13831   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
13832   // 8  ) Align         : Alignment of type
13833   // 9  ) EFLAGS (implicit-def)
13834
13835   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
13836   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
13837
13838   unsigned DestReg = MI->getOperand(0).getReg();
13839   MachineOperand &Base = MI->getOperand(1);
13840   MachineOperand &Scale = MI->getOperand(2);
13841   MachineOperand &Index = MI->getOperand(3);
13842   MachineOperand &Disp = MI->getOperand(4);
13843   MachineOperand &Segment = MI->getOperand(5);
13844   unsigned ArgSize = MI->getOperand(6).getImm();
13845   unsigned ArgMode = MI->getOperand(7).getImm();
13846   unsigned Align = MI->getOperand(8).getImm();
13847
13848   // Memory Reference
13849   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
13850   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13851   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13852
13853   // Machine Information
13854   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13855   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
13856   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
13857   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
13858   DebugLoc DL = MI->getDebugLoc();
13859
13860   // struct va_list {
13861   //   i32   gp_offset
13862   //   i32   fp_offset
13863   //   i64   overflow_area (address)
13864   //   i64   reg_save_area (address)
13865   // }
13866   // sizeof(va_list) = 24
13867   // alignment(va_list) = 8
13868
13869   unsigned TotalNumIntRegs = 6;
13870   unsigned TotalNumXMMRegs = 8;
13871   bool UseGPOffset = (ArgMode == 1);
13872   bool UseFPOffset = (ArgMode == 2);
13873   unsigned MaxOffset = TotalNumIntRegs * 8 +
13874                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
13875
13876   /* Align ArgSize to a multiple of 8 */
13877   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
13878   bool NeedsAlign = (Align > 8);
13879
13880   MachineBasicBlock *thisMBB = MBB;
13881   MachineBasicBlock *overflowMBB;
13882   MachineBasicBlock *offsetMBB;
13883   MachineBasicBlock *endMBB;
13884
13885   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
13886   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
13887   unsigned OffsetReg = 0;
13888
13889   if (!UseGPOffset && !UseFPOffset) {
13890     // If we only pull from the overflow region, we don't create a branch.
13891     // We don't need to alter control flow.
13892     OffsetDestReg = 0; // unused
13893     OverflowDestReg = DestReg;
13894
13895     offsetMBB = NULL;
13896     overflowMBB = thisMBB;
13897     endMBB = thisMBB;
13898   } else {
13899     // First emit code to check if gp_offset (or fp_offset) is below the bound.
13900     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
13901     // If not, pull from overflow_area. (branch to overflowMBB)
13902     //
13903     //       thisMBB
13904     //         |     .
13905     //         |        .
13906     //     offsetMBB   overflowMBB
13907     //         |        .
13908     //         |     .
13909     //        endMBB
13910
13911     // Registers for the PHI in endMBB
13912     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
13913     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
13914
13915     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
13916     MachineFunction *MF = MBB->getParent();
13917     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13918     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13919     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13920
13921     MachineFunction::iterator MBBIter = MBB;
13922     ++MBBIter;
13923
13924     // Insert the new basic blocks
13925     MF->insert(MBBIter, offsetMBB);
13926     MF->insert(MBBIter, overflowMBB);
13927     MF->insert(MBBIter, endMBB);
13928
13929     // Transfer the remainder of MBB and its successor edges to endMBB.
13930     endMBB->splice(endMBB->begin(), thisMBB,
13931                     llvm::next(MachineBasicBlock::iterator(MI)),
13932                     thisMBB->end());
13933     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
13934
13935     // Make offsetMBB and overflowMBB successors of thisMBB
13936     thisMBB->addSuccessor(offsetMBB);
13937     thisMBB->addSuccessor(overflowMBB);
13938
13939     // endMBB is a successor of both offsetMBB and overflowMBB
13940     offsetMBB->addSuccessor(endMBB);
13941     overflowMBB->addSuccessor(endMBB);
13942
13943     // Load the offset value into a register
13944     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
13945     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
13946       .addOperand(Base)
13947       .addOperand(Scale)
13948       .addOperand(Index)
13949       .addDisp(Disp, UseFPOffset ? 4 : 0)
13950       .addOperand(Segment)
13951       .setMemRefs(MMOBegin, MMOEnd);
13952
13953     // Check if there is enough room left to pull this argument.
13954     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
13955       .addReg(OffsetReg)
13956       .addImm(MaxOffset + 8 - ArgSizeA8);
13957
13958     // Branch to "overflowMBB" if offset >= max
13959     // Fall through to "offsetMBB" otherwise
13960     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
13961       .addMBB(overflowMBB);
13962   }
13963
13964   // In offsetMBB, emit code to use the reg_save_area.
13965   if (offsetMBB) {
13966     assert(OffsetReg != 0);
13967
13968     // Read the reg_save_area address.
13969     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
13970     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
13971       .addOperand(Base)
13972       .addOperand(Scale)
13973       .addOperand(Index)
13974       .addDisp(Disp, 16)
13975       .addOperand(Segment)
13976       .setMemRefs(MMOBegin, MMOEnd);
13977
13978     // Zero-extend the offset
13979     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
13980       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
13981         .addImm(0)
13982         .addReg(OffsetReg)
13983         .addImm(X86::sub_32bit);
13984
13985     // Add the offset to the reg_save_area to get the final address.
13986     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
13987       .addReg(OffsetReg64)
13988       .addReg(RegSaveReg);
13989
13990     // Compute the offset for the next argument
13991     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
13992     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
13993       .addReg(OffsetReg)
13994       .addImm(UseFPOffset ? 16 : 8);
13995
13996     // Store it back into the va_list.
13997     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
13998       .addOperand(Base)
13999       .addOperand(Scale)
14000       .addOperand(Index)
14001       .addDisp(Disp, UseFPOffset ? 4 : 0)
14002       .addOperand(Segment)
14003       .addReg(NextOffsetReg)
14004       .setMemRefs(MMOBegin, MMOEnd);
14005
14006     // Jump to endMBB
14007     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
14008       .addMBB(endMBB);
14009   }
14010
14011   //
14012   // Emit code to use overflow area
14013   //
14014
14015   // Load the overflow_area address into a register.
14016   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
14017   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
14018     .addOperand(Base)
14019     .addOperand(Scale)
14020     .addOperand(Index)
14021     .addDisp(Disp, 8)
14022     .addOperand(Segment)
14023     .setMemRefs(MMOBegin, MMOEnd);
14024
14025   // If we need to align it, do so. Otherwise, just copy the address
14026   // to OverflowDestReg.
14027   if (NeedsAlign) {
14028     // Align the overflow address
14029     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
14030     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
14031
14032     // aligned_addr = (addr + (align-1)) & ~(align-1)
14033     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
14034       .addReg(OverflowAddrReg)
14035       .addImm(Align-1);
14036
14037     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
14038       .addReg(TmpReg)
14039       .addImm(~(uint64_t)(Align-1));
14040   } else {
14041     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
14042       .addReg(OverflowAddrReg);
14043   }
14044
14045   // Compute the next overflow address after this argument.
14046   // (the overflow address should be kept 8-byte aligned)
14047   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
14048   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
14049     .addReg(OverflowDestReg)
14050     .addImm(ArgSizeA8);
14051
14052   // Store the new overflow address.
14053   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
14054     .addOperand(Base)
14055     .addOperand(Scale)
14056     .addOperand(Index)
14057     .addDisp(Disp, 8)
14058     .addOperand(Segment)
14059     .addReg(NextAddrReg)
14060     .setMemRefs(MMOBegin, MMOEnd);
14061
14062   // If we branched, emit the PHI to the front of endMBB.
14063   if (offsetMBB) {
14064     BuildMI(*endMBB, endMBB->begin(), DL,
14065             TII->get(X86::PHI), DestReg)
14066       .addReg(OffsetDestReg).addMBB(offsetMBB)
14067       .addReg(OverflowDestReg).addMBB(overflowMBB);
14068   }
14069
14070   // Erase the pseudo instruction
14071   MI->eraseFromParent();
14072
14073   return endMBB;
14074 }
14075
14076 MachineBasicBlock *
14077 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
14078                                                  MachineInstr *MI,
14079                                                  MachineBasicBlock *MBB) const {
14080   // Emit code to save XMM registers to the stack. The ABI says that the
14081   // number of registers to save is given in %al, so it's theoretically
14082   // possible to do an indirect jump trick to avoid saving all of them,
14083   // however this code takes a simpler approach and just executes all
14084   // of the stores if %al is non-zero. It's less code, and it's probably
14085   // easier on the hardware branch predictor, and stores aren't all that
14086   // expensive anyway.
14087
14088   // Create the new basic blocks. One block contains all the XMM stores,
14089   // and one block is the final destination regardless of whether any
14090   // stores were performed.
14091   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
14092   MachineFunction *F = MBB->getParent();
14093   MachineFunction::iterator MBBIter = MBB;
14094   ++MBBIter;
14095   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
14096   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
14097   F->insert(MBBIter, XMMSaveMBB);
14098   F->insert(MBBIter, EndMBB);
14099
14100   // Transfer the remainder of MBB and its successor edges to EndMBB.
14101   EndMBB->splice(EndMBB->begin(), MBB,
14102                  llvm::next(MachineBasicBlock::iterator(MI)),
14103                  MBB->end());
14104   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
14105
14106   // The original block will now fall through to the XMM save block.
14107   MBB->addSuccessor(XMMSaveMBB);
14108   // The XMMSaveMBB will fall through to the end block.
14109   XMMSaveMBB->addSuccessor(EndMBB);
14110
14111   // Now add the instructions.
14112   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14113   DebugLoc DL = MI->getDebugLoc();
14114
14115   unsigned CountReg = MI->getOperand(0).getReg();
14116   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
14117   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
14118
14119   if (!Subtarget->isTargetWin64()) {
14120     // If %al is 0, branch around the XMM save block.
14121     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
14122     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
14123     MBB->addSuccessor(EndMBB);
14124   }
14125
14126   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
14127   // In the XMM save block, save all the XMM argument registers.
14128   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
14129     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
14130     MachineMemOperand *MMO =
14131       F->getMachineMemOperand(
14132           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
14133         MachineMemOperand::MOStore,
14134         /*Size=*/16, /*Align=*/16);
14135     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
14136       .addFrameIndex(RegSaveFrameIndex)
14137       .addImm(/*Scale=*/1)
14138       .addReg(/*IndexReg=*/0)
14139       .addImm(/*Disp=*/Offset)
14140       .addReg(/*Segment=*/0)
14141       .addReg(MI->getOperand(i).getReg())
14142       .addMemOperand(MMO);
14143   }
14144
14145   MI->eraseFromParent();   // The pseudo instruction is gone now.
14146
14147   return EndMBB;
14148 }
14149
14150 // The EFLAGS operand of SelectItr might be missing a kill marker
14151 // because there were multiple uses of EFLAGS, and ISel didn't know
14152 // which to mark. Figure out whether SelectItr should have had a
14153 // kill marker, and set it if it should. Returns the correct kill
14154 // marker value.
14155 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
14156                                      MachineBasicBlock* BB,
14157                                      const TargetRegisterInfo* TRI) {
14158   // Scan forward through BB for a use/def of EFLAGS.
14159   MachineBasicBlock::iterator miI(llvm::next(SelectItr));
14160   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
14161     const MachineInstr& mi = *miI;
14162     if (mi.readsRegister(X86::EFLAGS))
14163       return false;
14164     if (mi.definesRegister(X86::EFLAGS))
14165       break; // Should have kill-flag - update below.
14166   }
14167
14168   // If we hit the end of the block, check whether EFLAGS is live into a
14169   // successor.
14170   if (miI == BB->end()) {
14171     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
14172                                           sEnd = BB->succ_end();
14173          sItr != sEnd; ++sItr) {
14174       MachineBasicBlock* succ = *sItr;
14175       if (succ->isLiveIn(X86::EFLAGS))
14176         return false;
14177     }
14178   }
14179
14180   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
14181   // out. SelectMI should have a kill flag on EFLAGS.
14182   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
14183   return true;
14184 }
14185
14186 MachineBasicBlock *
14187 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
14188                                      MachineBasicBlock *BB) const {
14189   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14190   DebugLoc DL = MI->getDebugLoc();
14191
14192   // To "insert" a SELECT_CC instruction, we actually have to insert the
14193   // diamond control-flow pattern.  The incoming instruction knows the
14194   // destination vreg to set, the condition code register to branch on, the
14195   // true/false values to select between, and a branch opcode to use.
14196   const BasicBlock *LLVM_BB = BB->getBasicBlock();
14197   MachineFunction::iterator It = BB;
14198   ++It;
14199
14200   //  thisMBB:
14201   //  ...
14202   //   TrueVal = ...
14203   //   cmpTY ccX, r1, r2
14204   //   bCC copy1MBB
14205   //   fallthrough --> copy0MBB
14206   MachineBasicBlock *thisMBB = BB;
14207   MachineFunction *F = BB->getParent();
14208   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
14209   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
14210   F->insert(It, copy0MBB);
14211   F->insert(It, sinkMBB);
14212
14213   // If the EFLAGS register isn't dead in the terminator, then claim that it's
14214   // live into the sink and copy blocks.
14215   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
14216   if (!MI->killsRegister(X86::EFLAGS) &&
14217       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
14218     copy0MBB->addLiveIn(X86::EFLAGS);
14219     sinkMBB->addLiveIn(X86::EFLAGS);
14220   }
14221
14222   // Transfer the remainder of BB and its successor edges to sinkMBB.
14223   sinkMBB->splice(sinkMBB->begin(), BB,
14224                   llvm::next(MachineBasicBlock::iterator(MI)),
14225                   BB->end());
14226   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
14227
14228   // Add the true and fallthrough blocks as its successors.
14229   BB->addSuccessor(copy0MBB);
14230   BB->addSuccessor(sinkMBB);
14231
14232   // Create the conditional branch instruction.
14233   unsigned Opc =
14234     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
14235   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
14236
14237   //  copy0MBB:
14238   //   %FalseValue = ...
14239   //   # fallthrough to sinkMBB
14240   copy0MBB->addSuccessor(sinkMBB);
14241
14242   //  sinkMBB:
14243   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
14244   //  ...
14245   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14246           TII->get(X86::PHI), MI->getOperand(0).getReg())
14247     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
14248     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
14249
14250   MI->eraseFromParent();   // The pseudo instruction is gone now.
14251   return sinkMBB;
14252 }
14253
14254 MachineBasicBlock *
14255 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
14256                                         bool Is64Bit) const {
14257   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14258   DebugLoc DL = MI->getDebugLoc();
14259   MachineFunction *MF = BB->getParent();
14260   const BasicBlock *LLVM_BB = BB->getBasicBlock();
14261
14262   assert(getTargetMachine().Options.EnableSegmentedStacks);
14263
14264   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
14265   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
14266
14267   // BB:
14268   //  ... [Till the alloca]
14269   // If stacklet is not large enough, jump to mallocMBB
14270   //
14271   // bumpMBB:
14272   //  Allocate by subtracting from RSP
14273   //  Jump to continueMBB
14274   //
14275   // mallocMBB:
14276   //  Allocate by call to runtime
14277   //
14278   // continueMBB:
14279   //  ...
14280   //  [rest of original BB]
14281   //
14282
14283   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14284   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14285   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14286
14287   MachineRegisterInfo &MRI = MF->getRegInfo();
14288   const TargetRegisterClass *AddrRegClass =
14289     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
14290
14291   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
14292     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
14293     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
14294     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
14295     sizeVReg = MI->getOperand(1).getReg(),
14296     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
14297
14298   MachineFunction::iterator MBBIter = BB;
14299   ++MBBIter;
14300
14301   MF->insert(MBBIter, bumpMBB);
14302   MF->insert(MBBIter, mallocMBB);
14303   MF->insert(MBBIter, continueMBB);
14304
14305   continueMBB->splice(continueMBB->begin(), BB, llvm::next
14306                       (MachineBasicBlock::iterator(MI)), BB->end());
14307   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
14308
14309   // Add code to the main basic block to check if the stack limit has been hit,
14310   // and if so, jump to mallocMBB otherwise to bumpMBB.
14311   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
14312   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
14313     .addReg(tmpSPVReg).addReg(sizeVReg);
14314   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
14315     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
14316     .addReg(SPLimitVReg);
14317   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
14318
14319   // bumpMBB simply decreases the stack pointer, since we know the current
14320   // stacklet has enough space.
14321   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
14322     .addReg(SPLimitVReg);
14323   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
14324     .addReg(SPLimitVReg);
14325   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
14326
14327   // Calls into a routine in libgcc to allocate more space from the heap.
14328   const uint32_t *RegMask =
14329     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
14330   if (Is64Bit) {
14331     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
14332       .addReg(sizeVReg);
14333     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
14334       .addExternalSymbol("__morestack_allocate_stack_space")
14335       .addRegMask(RegMask)
14336       .addReg(X86::RDI, RegState::Implicit)
14337       .addReg(X86::RAX, RegState::ImplicitDefine);
14338   } else {
14339     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
14340       .addImm(12);
14341     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
14342     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
14343       .addExternalSymbol("__morestack_allocate_stack_space")
14344       .addRegMask(RegMask)
14345       .addReg(X86::EAX, RegState::ImplicitDefine);
14346   }
14347
14348   if (!Is64Bit)
14349     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
14350       .addImm(16);
14351
14352   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
14353     .addReg(Is64Bit ? X86::RAX : X86::EAX);
14354   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
14355
14356   // Set up the CFG correctly.
14357   BB->addSuccessor(bumpMBB);
14358   BB->addSuccessor(mallocMBB);
14359   mallocMBB->addSuccessor(continueMBB);
14360   bumpMBB->addSuccessor(continueMBB);
14361
14362   // Take care of the PHI nodes.
14363   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
14364           MI->getOperand(0).getReg())
14365     .addReg(mallocPtrVReg).addMBB(mallocMBB)
14366     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
14367
14368   // Delete the original pseudo instruction.
14369   MI->eraseFromParent();
14370
14371   // And we're done.
14372   return continueMBB;
14373 }
14374
14375 MachineBasicBlock *
14376 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
14377                                           MachineBasicBlock *BB) const {
14378   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14379   DebugLoc DL = MI->getDebugLoc();
14380
14381   assert(!Subtarget->isTargetEnvMacho());
14382
14383   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
14384   // non-trivial part is impdef of ESP.
14385
14386   if (Subtarget->isTargetWin64()) {
14387     if (Subtarget->isTargetCygMing()) {
14388       // ___chkstk(Mingw64):
14389       // Clobbers R10, R11, RAX and EFLAGS.
14390       // Updates RSP.
14391       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
14392         .addExternalSymbol("___chkstk")
14393         .addReg(X86::RAX, RegState::Implicit)
14394         .addReg(X86::RSP, RegState::Implicit)
14395         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
14396         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
14397         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14398     } else {
14399       // __chkstk(MSVCRT): does not update stack pointer.
14400       // Clobbers R10, R11 and EFLAGS.
14401       // FIXME: RAX(allocated size) might be reused and not killed.
14402       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
14403         .addExternalSymbol("__chkstk")
14404         .addReg(X86::RAX, RegState::Implicit)
14405         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14406       // RAX has the offset to subtracted from RSP.
14407       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
14408         .addReg(X86::RSP)
14409         .addReg(X86::RAX);
14410     }
14411   } else {
14412     const char *StackProbeSymbol =
14413       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
14414
14415     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
14416       .addExternalSymbol(StackProbeSymbol)
14417       .addReg(X86::EAX, RegState::Implicit)
14418       .addReg(X86::ESP, RegState::Implicit)
14419       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
14420       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
14421       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14422   }
14423
14424   MI->eraseFromParent();   // The pseudo instruction is gone now.
14425   return BB;
14426 }
14427
14428 MachineBasicBlock *
14429 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
14430                                       MachineBasicBlock *BB) const {
14431   // This is pretty easy.  We're taking the value that we received from
14432   // our load from the relocation, sticking it in either RDI (x86-64)
14433   // or EAX and doing an indirect call.  The return value will then
14434   // be in the normal return register.
14435   const X86InstrInfo *TII
14436     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
14437   DebugLoc DL = MI->getDebugLoc();
14438   MachineFunction *F = BB->getParent();
14439
14440   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
14441   assert(MI->getOperand(3).isGlobal() && "This should be a global");
14442
14443   // Get a register mask for the lowered call.
14444   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
14445   // proper register mask.
14446   const uint32_t *RegMask =
14447     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
14448   if (Subtarget->is64Bit()) {
14449     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14450                                       TII->get(X86::MOV64rm), X86::RDI)
14451     .addReg(X86::RIP)
14452     .addImm(0).addReg(0)
14453     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14454                       MI->getOperand(3).getTargetFlags())
14455     .addReg(0);
14456     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
14457     addDirectMem(MIB, X86::RDI);
14458     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
14459   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
14460     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14461                                       TII->get(X86::MOV32rm), X86::EAX)
14462     .addReg(0)
14463     .addImm(0).addReg(0)
14464     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14465                       MI->getOperand(3).getTargetFlags())
14466     .addReg(0);
14467     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
14468     addDirectMem(MIB, X86::EAX);
14469     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
14470   } else {
14471     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14472                                       TII->get(X86::MOV32rm), X86::EAX)
14473     .addReg(TII->getGlobalBaseReg(F))
14474     .addImm(0).addReg(0)
14475     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14476                       MI->getOperand(3).getTargetFlags())
14477     .addReg(0);
14478     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
14479     addDirectMem(MIB, X86::EAX);
14480     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
14481   }
14482
14483   MI->eraseFromParent(); // The pseudo instruction is gone now.
14484   return BB;
14485 }
14486
14487 MachineBasicBlock *
14488 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
14489                                     MachineBasicBlock *MBB) const {
14490   DebugLoc DL = MI->getDebugLoc();
14491   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14492
14493   MachineFunction *MF = MBB->getParent();
14494   MachineRegisterInfo &MRI = MF->getRegInfo();
14495
14496   const BasicBlock *BB = MBB->getBasicBlock();
14497   MachineFunction::iterator I = MBB;
14498   ++I;
14499
14500   // Memory Reference
14501   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14502   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14503
14504   unsigned DstReg;
14505   unsigned MemOpndSlot = 0;
14506
14507   unsigned CurOp = 0;
14508
14509   DstReg = MI->getOperand(CurOp++).getReg();
14510   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
14511   assert(RC->hasType(MVT::i32) && "Invalid destination!");
14512   unsigned mainDstReg = MRI.createVirtualRegister(RC);
14513   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
14514
14515   MemOpndSlot = CurOp;
14516
14517   MVT PVT = getPointerTy();
14518   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
14519          "Invalid Pointer Size!");
14520
14521   // For v = setjmp(buf), we generate
14522   //
14523   // thisMBB:
14524   //  buf[LabelOffset] = restoreMBB
14525   //  SjLjSetup restoreMBB
14526   //
14527   // mainMBB:
14528   //  v_main = 0
14529   //
14530   // sinkMBB:
14531   //  v = phi(main, restore)
14532   //
14533   // restoreMBB:
14534   //  v_restore = 1
14535
14536   MachineBasicBlock *thisMBB = MBB;
14537   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14538   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14539   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
14540   MF->insert(I, mainMBB);
14541   MF->insert(I, sinkMBB);
14542   MF->push_back(restoreMBB);
14543
14544   MachineInstrBuilder MIB;
14545
14546   // Transfer the remainder of BB and its successor edges to sinkMBB.
14547   sinkMBB->splice(sinkMBB->begin(), MBB,
14548                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
14549   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14550
14551   // thisMBB:
14552   unsigned PtrStoreOpc = 0;
14553   unsigned LabelReg = 0;
14554   const int64_t LabelOffset = 1 * PVT.getStoreSize();
14555   Reloc::Model RM = getTargetMachine().getRelocationModel();
14556   bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
14557                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
14558
14559   // Prepare IP either in reg or imm.
14560   if (!UseImmLabel) {
14561     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
14562     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
14563     LabelReg = MRI.createVirtualRegister(PtrRC);
14564     if (Subtarget->is64Bit()) {
14565       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
14566               .addReg(X86::RIP)
14567               .addImm(0)
14568               .addReg(0)
14569               .addMBB(restoreMBB)
14570               .addReg(0);
14571     } else {
14572       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
14573       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
14574               .addReg(XII->getGlobalBaseReg(MF))
14575               .addImm(0)
14576               .addReg(0)
14577               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
14578               .addReg(0);
14579     }
14580   } else
14581     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
14582   // Store IP
14583   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
14584   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14585     if (i == X86::AddrDisp)
14586       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
14587     else
14588       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
14589   }
14590   if (!UseImmLabel)
14591     MIB.addReg(LabelReg);
14592   else
14593     MIB.addMBB(restoreMBB);
14594   MIB.setMemRefs(MMOBegin, MMOEnd);
14595   // Setup
14596   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
14597           .addMBB(restoreMBB);
14598   MIB.addRegMask(RegInfo->getNoPreservedMask());
14599   thisMBB->addSuccessor(mainMBB);
14600   thisMBB->addSuccessor(restoreMBB);
14601
14602   // mainMBB:
14603   //  EAX = 0
14604   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
14605   mainMBB->addSuccessor(sinkMBB);
14606
14607   // sinkMBB:
14608   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14609           TII->get(X86::PHI), DstReg)
14610     .addReg(mainDstReg).addMBB(mainMBB)
14611     .addReg(restoreDstReg).addMBB(restoreMBB);
14612
14613   // restoreMBB:
14614   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
14615   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
14616   restoreMBB->addSuccessor(sinkMBB);
14617
14618   MI->eraseFromParent();
14619   return sinkMBB;
14620 }
14621
14622 MachineBasicBlock *
14623 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
14624                                      MachineBasicBlock *MBB) const {
14625   DebugLoc DL = MI->getDebugLoc();
14626   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14627
14628   MachineFunction *MF = MBB->getParent();
14629   MachineRegisterInfo &MRI = MF->getRegInfo();
14630
14631   // Memory Reference
14632   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14633   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14634
14635   MVT PVT = getPointerTy();
14636   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
14637          "Invalid Pointer Size!");
14638
14639   const TargetRegisterClass *RC =
14640     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
14641   unsigned Tmp = MRI.createVirtualRegister(RC);
14642   // Since FP is only updated here but NOT referenced, it's treated as GPR.
14643   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
14644   unsigned SP = RegInfo->getStackRegister();
14645
14646   MachineInstrBuilder MIB;
14647
14648   const int64_t LabelOffset = 1 * PVT.getStoreSize();
14649   const int64_t SPOffset = 2 * PVT.getStoreSize();
14650
14651   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
14652   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
14653
14654   // Reload FP
14655   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
14656   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
14657     MIB.addOperand(MI->getOperand(i));
14658   MIB.setMemRefs(MMOBegin, MMOEnd);
14659   // Reload IP
14660   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
14661   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14662     if (i == X86::AddrDisp)
14663       MIB.addDisp(MI->getOperand(i), LabelOffset);
14664     else
14665       MIB.addOperand(MI->getOperand(i));
14666   }
14667   MIB.setMemRefs(MMOBegin, MMOEnd);
14668   // Reload SP
14669   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
14670   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14671     if (i == X86::AddrDisp)
14672       MIB.addDisp(MI->getOperand(i), SPOffset);
14673     else
14674       MIB.addOperand(MI->getOperand(i));
14675   }
14676   MIB.setMemRefs(MMOBegin, MMOEnd);
14677   // Jump
14678   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
14679
14680   MI->eraseFromParent();
14681   return MBB;
14682 }
14683
14684 MachineBasicBlock *
14685 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
14686                                                MachineBasicBlock *BB) const {
14687   switch (MI->getOpcode()) {
14688   default: llvm_unreachable("Unexpected instr type to insert");
14689   case X86::TAILJMPd64:
14690   case X86::TAILJMPr64:
14691   case X86::TAILJMPm64:
14692     llvm_unreachable("TAILJMP64 would not be touched here.");
14693   case X86::TCRETURNdi64:
14694   case X86::TCRETURNri64:
14695   case X86::TCRETURNmi64:
14696     return BB;
14697   case X86::WIN_ALLOCA:
14698     return EmitLoweredWinAlloca(MI, BB);
14699   case X86::SEG_ALLOCA_32:
14700     return EmitLoweredSegAlloca(MI, BB, false);
14701   case X86::SEG_ALLOCA_64:
14702     return EmitLoweredSegAlloca(MI, BB, true);
14703   case X86::TLSCall_32:
14704   case X86::TLSCall_64:
14705     return EmitLoweredTLSCall(MI, BB);
14706   case X86::CMOV_GR8:
14707   case X86::CMOV_FR32:
14708   case X86::CMOV_FR64:
14709   case X86::CMOV_V4F32:
14710   case X86::CMOV_V2F64:
14711   case X86::CMOV_V2I64:
14712   case X86::CMOV_V8F32:
14713   case X86::CMOV_V4F64:
14714   case X86::CMOV_V4I64:
14715   case X86::CMOV_GR16:
14716   case X86::CMOV_GR32:
14717   case X86::CMOV_RFP32:
14718   case X86::CMOV_RFP64:
14719   case X86::CMOV_RFP80:
14720     return EmitLoweredSelect(MI, BB);
14721
14722   case X86::FP32_TO_INT16_IN_MEM:
14723   case X86::FP32_TO_INT32_IN_MEM:
14724   case X86::FP32_TO_INT64_IN_MEM:
14725   case X86::FP64_TO_INT16_IN_MEM:
14726   case X86::FP64_TO_INT32_IN_MEM:
14727   case X86::FP64_TO_INT64_IN_MEM:
14728   case X86::FP80_TO_INT16_IN_MEM:
14729   case X86::FP80_TO_INT32_IN_MEM:
14730   case X86::FP80_TO_INT64_IN_MEM: {
14731     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14732     DebugLoc DL = MI->getDebugLoc();
14733
14734     // Change the floating point control register to use "round towards zero"
14735     // mode when truncating to an integer value.
14736     MachineFunction *F = BB->getParent();
14737     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
14738     addFrameReference(BuildMI(*BB, MI, DL,
14739                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
14740
14741     // Load the old value of the high byte of the control word...
14742     unsigned OldCW =
14743       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
14744     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
14745                       CWFrameIdx);
14746
14747     // Set the high part to be round to zero...
14748     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
14749       .addImm(0xC7F);
14750
14751     // Reload the modified control word now...
14752     addFrameReference(BuildMI(*BB, MI, DL,
14753                               TII->get(X86::FLDCW16m)), CWFrameIdx);
14754
14755     // Restore the memory image of control word to original value
14756     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
14757       .addReg(OldCW);
14758
14759     // Get the X86 opcode to use.
14760     unsigned Opc;
14761     switch (MI->getOpcode()) {
14762     default: llvm_unreachable("illegal opcode!");
14763     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
14764     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
14765     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
14766     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
14767     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
14768     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
14769     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
14770     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
14771     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
14772     }
14773
14774     X86AddressMode AM;
14775     MachineOperand &Op = MI->getOperand(0);
14776     if (Op.isReg()) {
14777       AM.BaseType = X86AddressMode::RegBase;
14778       AM.Base.Reg = Op.getReg();
14779     } else {
14780       AM.BaseType = X86AddressMode::FrameIndexBase;
14781       AM.Base.FrameIndex = Op.getIndex();
14782     }
14783     Op = MI->getOperand(1);
14784     if (Op.isImm())
14785       AM.Scale = Op.getImm();
14786     Op = MI->getOperand(2);
14787     if (Op.isImm())
14788       AM.IndexReg = Op.getImm();
14789     Op = MI->getOperand(3);
14790     if (Op.isGlobal()) {
14791       AM.GV = Op.getGlobal();
14792     } else {
14793       AM.Disp = Op.getImm();
14794     }
14795     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
14796                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
14797
14798     // Reload the original control word now.
14799     addFrameReference(BuildMI(*BB, MI, DL,
14800                               TII->get(X86::FLDCW16m)), CWFrameIdx);
14801
14802     MI->eraseFromParent();   // The pseudo instruction is gone now.
14803     return BB;
14804   }
14805     // String/text processing lowering.
14806   case X86::PCMPISTRM128REG:
14807   case X86::VPCMPISTRM128REG:
14808   case X86::PCMPISTRM128MEM:
14809   case X86::VPCMPISTRM128MEM:
14810   case X86::PCMPESTRM128REG:
14811   case X86::VPCMPESTRM128REG:
14812   case X86::PCMPESTRM128MEM:
14813   case X86::VPCMPESTRM128MEM:
14814     assert(Subtarget->hasSSE42() &&
14815            "Target must have SSE4.2 or AVX features enabled");
14816     return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
14817
14818   // String/text processing lowering.
14819   case X86::PCMPISTRIREG:
14820   case X86::VPCMPISTRIREG:
14821   case X86::PCMPISTRIMEM:
14822   case X86::VPCMPISTRIMEM:
14823   case X86::PCMPESTRIREG:
14824   case X86::VPCMPESTRIREG:
14825   case X86::PCMPESTRIMEM:
14826   case X86::VPCMPESTRIMEM:
14827     assert(Subtarget->hasSSE42() &&
14828            "Target must have SSE4.2 or AVX features enabled");
14829     return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
14830
14831   // Thread synchronization.
14832   case X86::MONITOR:
14833     return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
14834
14835   // xbegin
14836   case X86::XBEGIN:
14837     return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
14838
14839   // Atomic Lowering.
14840   case X86::ATOMAND8:
14841   case X86::ATOMAND16:
14842   case X86::ATOMAND32:
14843   case X86::ATOMAND64:
14844     // Fall through
14845   case X86::ATOMOR8:
14846   case X86::ATOMOR16:
14847   case X86::ATOMOR32:
14848   case X86::ATOMOR64:
14849     // Fall through
14850   case X86::ATOMXOR16:
14851   case X86::ATOMXOR8:
14852   case X86::ATOMXOR32:
14853   case X86::ATOMXOR64:
14854     // Fall through
14855   case X86::ATOMNAND8:
14856   case X86::ATOMNAND16:
14857   case X86::ATOMNAND32:
14858   case X86::ATOMNAND64:
14859     // Fall through
14860   case X86::ATOMMAX8:
14861   case X86::ATOMMAX16:
14862   case X86::ATOMMAX32:
14863   case X86::ATOMMAX64:
14864     // Fall through
14865   case X86::ATOMMIN8:
14866   case X86::ATOMMIN16:
14867   case X86::ATOMMIN32:
14868   case X86::ATOMMIN64:
14869     // Fall through
14870   case X86::ATOMUMAX8:
14871   case X86::ATOMUMAX16:
14872   case X86::ATOMUMAX32:
14873   case X86::ATOMUMAX64:
14874     // Fall through
14875   case X86::ATOMUMIN8:
14876   case X86::ATOMUMIN16:
14877   case X86::ATOMUMIN32:
14878   case X86::ATOMUMIN64:
14879     return EmitAtomicLoadArith(MI, BB);
14880
14881   // This group does 64-bit operations on a 32-bit host.
14882   case X86::ATOMAND6432:
14883   case X86::ATOMOR6432:
14884   case X86::ATOMXOR6432:
14885   case X86::ATOMNAND6432:
14886   case X86::ATOMADD6432:
14887   case X86::ATOMSUB6432:
14888   case X86::ATOMMAX6432:
14889   case X86::ATOMMIN6432:
14890   case X86::ATOMUMAX6432:
14891   case X86::ATOMUMIN6432:
14892   case X86::ATOMSWAP6432:
14893     return EmitAtomicLoadArith6432(MI, BB);
14894
14895   case X86::VASTART_SAVE_XMM_REGS:
14896     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
14897
14898   case X86::VAARG_64:
14899     return EmitVAARG64WithCustomInserter(MI, BB);
14900
14901   case X86::EH_SjLj_SetJmp32:
14902   case X86::EH_SjLj_SetJmp64:
14903     return emitEHSjLjSetJmp(MI, BB);
14904
14905   case X86::EH_SjLj_LongJmp32:
14906   case X86::EH_SjLj_LongJmp64:
14907     return emitEHSjLjLongJmp(MI, BB);
14908   }
14909 }
14910
14911 //===----------------------------------------------------------------------===//
14912 //                           X86 Optimization Hooks
14913 //===----------------------------------------------------------------------===//
14914
14915 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
14916                                                        APInt &KnownZero,
14917                                                        APInt &KnownOne,
14918                                                        const SelectionDAG &DAG,
14919                                                        unsigned Depth) const {
14920   unsigned BitWidth = KnownZero.getBitWidth();
14921   unsigned Opc = Op.getOpcode();
14922   assert((Opc >= ISD::BUILTIN_OP_END ||
14923           Opc == ISD::INTRINSIC_WO_CHAIN ||
14924           Opc == ISD::INTRINSIC_W_CHAIN ||
14925           Opc == ISD::INTRINSIC_VOID) &&
14926          "Should use MaskedValueIsZero if you don't know whether Op"
14927          " is a target node!");
14928
14929   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
14930   switch (Opc) {
14931   default: break;
14932   case X86ISD::ADD:
14933   case X86ISD::SUB:
14934   case X86ISD::ADC:
14935   case X86ISD::SBB:
14936   case X86ISD::SMUL:
14937   case X86ISD::UMUL:
14938   case X86ISD::INC:
14939   case X86ISD::DEC:
14940   case X86ISD::OR:
14941   case X86ISD::XOR:
14942   case X86ISD::AND:
14943     // These nodes' second result is a boolean.
14944     if (Op.getResNo() == 0)
14945       break;
14946     // Fallthrough
14947   case X86ISD::SETCC:
14948     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
14949     break;
14950   case ISD::INTRINSIC_WO_CHAIN: {
14951     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14952     unsigned NumLoBits = 0;
14953     switch (IntId) {
14954     default: break;
14955     case Intrinsic::x86_sse_movmsk_ps:
14956     case Intrinsic::x86_avx_movmsk_ps_256:
14957     case Intrinsic::x86_sse2_movmsk_pd:
14958     case Intrinsic::x86_avx_movmsk_pd_256:
14959     case Intrinsic::x86_mmx_pmovmskb:
14960     case Intrinsic::x86_sse2_pmovmskb_128:
14961     case Intrinsic::x86_avx2_pmovmskb: {
14962       // High bits of movmskp{s|d}, pmovmskb are known zero.
14963       switch (IntId) {
14964         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14965         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
14966         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
14967         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
14968         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
14969         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
14970         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
14971         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
14972       }
14973       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
14974       break;
14975     }
14976     }
14977     break;
14978   }
14979   }
14980 }
14981
14982 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
14983                                                          unsigned Depth) const {
14984   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
14985   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
14986     return Op.getValueType().getScalarType().getSizeInBits();
14987
14988   // Fallback case.
14989   return 1;
14990 }
14991
14992 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
14993 /// node is a GlobalAddress + offset.
14994 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
14995                                        const GlobalValue* &GA,
14996                                        int64_t &Offset) const {
14997   if (N->getOpcode() == X86ISD::Wrapper) {
14998     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
14999       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
15000       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
15001       return true;
15002     }
15003   }
15004   return TargetLowering::isGAPlusOffset(N, GA, Offset);
15005 }
15006
15007 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
15008 /// same as extracting the high 128-bit part of 256-bit vector and then
15009 /// inserting the result into the low part of a new 256-bit vector
15010 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
15011   EVT VT = SVOp->getValueType(0);
15012   unsigned NumElems = VT.getVectorNumElements();
15013
15014   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
15015   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
15016     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
15017         SVOp->getMaskElt(j) >= 0)
15018       return false;
15019
15020   return true;
15021 }
15022
15023 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
15024 /// same as extracting the low 128-bit part of 256-bit vector and then
15025 /// inserting the result into the high part of a new 256-bit vector
15026 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
15027   EVT VT = SVOp->getValueType(0);
15028   unsigned NumElems = VT.getVectorNumElements();
15029
15030   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
15031   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
15032     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
15033         SVOp->getMaskElt(j) >= 0)
15034       return false;
15035
15036   return true;
15037 }
15038
15039 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
15040 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
15041                                         TargetLowering::DAGCombinerInfo &DCI,
15042                                         const X86Subtarget* Subtarget) {
15043   DebugLoc dl = N->getDebugLoc();
15044   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
15045   SDValue V1 = SVOp->getOperand(0);
15046   SDValue V2 = SVOp->getOperand(1);
15047   EVT VT = SVOp->getValueType(0);
15048   unsigned NumElems = VT.getVectorNumElements();
15049
15050   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
15051       V2.getOpcode() == ISD::CONCAT_VECTORS) {
15052     //
15053     //                   0,0,0,...
15054     //                      |
15055     //    V      UNDEF    BUILD_VECTOR    UNDEF
15056     //     \      /           \           /
15057     //  CONCAT_VECTOR         CONCAT_VECTOR
15058     //         \                  /
15059     //          \                /
15060     //          RESULT: V + zero extended
15061     //
15062     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
15063         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
15064         V1.getOperand(1).getOpcode() != ISD::UNDEF)
15065       return SDValue();
15066
15067     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
15068       return SDValue();
15069
15070     // To match the shuffle mask, the first half of the mask should
15071     // be exactly the first vector, and all the rest a splat with the
15072     // first element of the second one.
15073     for (unsigned i = 0; i != NumElems/2; ++i)
15074       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
15075           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
15076         return SDValue();
15077
15078     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
15079     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
15080       if (Ld->hasNUsesOfValue(1, 0)) {
15081         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
15082         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
15083         SDValue ResNode =
15084           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2,
15085                                   Ld->getMemoryVT(),
15086                                   Ld->getPointerInfo(),
15087                                   Ld->getAlignment(),
15088                                   false/*isVolatile*/, true/*ReadMem*/,
15089                                   false/*WriteMem*/);
15090
15091         // Make sure the newly-created LOAD is in the same position as Ld in
15092         // terms of dependency. We create a TokenFactor for Ld and ResNode,
15093         // and update uses of Ld's output chain to use the TokenFactor.
15094         if (Ld->hasAnyUseOfValue(1)) {
15095           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
15096                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
15097           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
15098           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
15099                                  SDValue(ResNode.getNode(), 1));
15100         }
15101
15102         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
15103       }
15104     }
15105
15106     // Emit a zeroed vector and insert the desired subvector on its
15107     // first half.
15108     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15109     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
15110     return DCI.CombineTo(N, InsV);
15111   }
15112
15113   //===--------------------------------------------------------------------===//
15114   // Combine some shuffles into subvector extracts and inserts:
15115   //
15116
15117   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
15118   if (isShuffleHigh128VectorInsertLow(SVOp)) {
15119     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
15120     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
15121     return DCI.CombineTo(N, InsV);
15122   }
15123
15124   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
15125   if (isShuffleLow128VectorInsertHigh(SVOp)) {
15126     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
15127     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
15128     return DCI.CombineTo(N, InsV);
15129   }
15130
15131   return SDValue();
15132 }
15133
15134 /// PerformShuffleCombine - Performs several different shuffle combines.
15135 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
15136                                      TargetLowering::DAGCombinerInfo &DCI,
15137                                      const X86Subtarget *Subtarget) {
15138   DebugLoc dl = N->getDebugLoc();
15139   EVT VT = N->getValueType(0);
15140
15141   // Don't create instructions with illegal types after legalize types has run.
15142   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15143   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
15144     return SDValue();
15145
15146   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
15147   if (Subtarget->hasFp256() && VT.is256BitVector() &&
15148       N->getOpcode() == ISD::VECTOR_SHUFFLE)
15149     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
15150
15151   // Only handle 128 wide vector from here on.
15152   if (!VT.is128BitVector())
15153     return SDValue();
15154
15155   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
15156   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
15157   // consecutive, non-overlapping, and in the right order.
15158   SmallVector<SDValue, 16> Elts;
15159   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
15160     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
15161
15162   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
15163 }
15164
15165 /// PerformTruncateCombine - Converts truncate operation to
15166 /// a sequence of vector shuffle operations.
15167 /// It is possible when we truncate 256-bit vector to 128-bit vector
15168 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
15169                                       TargetLowering::DAGCombinerInfo &DCI,
15170                                       const X86Subtarget *Subtarget)  {
15171   return SDValue();
15172 }
15173
15174 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
15175 /// specific shuffle of a load can be folded into a single element load.
15176 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
15177 /// shuffles have been customed lowered so we need to handle those here.
15178 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
15179                                          TargetLowering::DAGCombinerInfo &DCI) {
15180   if (DCI.isBeforeLegalizeOps())
15181     return SDValue();
15182
15183   SDValue InVec = N->getOperand(0);
15184   SDValue EltNo = N->getOperand(1);
15185
15186   if (!isa<ConstantSDNode>(EltNo))
15187     return SDValue();
15188
15189   EVT VT = InVec.getValueType();
15190
15191   bool HasShuffleIntoBitcast = false;
15192   if (InVec.getOpcode() == ISD::BITCAST) {
15193     // Don't duplicate a load with other uses.
15194     if (!InVec.hasOneUse())
15195       return SDValue();
15196     EVT BCVT = InVec.getOperand(0).getValueType();
15197     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
15198       return SDValue();
15199     InVec = InVec.getOperand(0);
15200     HasShuffleIntoBitcast = true;
15201   }
15202
15203   if (!isTargetShuffle(InVec.getOpcode()))
15204     return SDValue();
15205
15206   // Don't duplicate a load with other uses.
15207   if (!InVec.hasOneUse())
15208     return SDValue();
15209
15210   SmallVector<int, 16> ShuffleMask;
15211   bool UnaryShuffle;
15212   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
15213                             UnaryShuffle))
15214     return SDValue();
15215
15216   // Select the input vector, guarding against out of range extract vector.
15217   unsigned NumElems = VT.getVectorNumElements();
15218   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
15219   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
15220   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
15221                                          : InVec.getOperand(1);
15222
15223   // If inputs to shuffle are the same for both ops, then allow 2 uses
15224   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
15225
15226   if (LdNode.getOpcode() == ISD::BITCAST) {
15227     // Don't duplicate a load with other uses.
15228     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
15229       return SDValue();
15230
15231     AllowedUses = 1; // only allow 1 load use if we have a bitcast
15232     LdNode = LdNode.getOperand(0);
15233   }
15234
15235   if (!ISD::isNormalLoad(LdNode.getNode()))
15236     return SDValue();
15237
15238   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
15239
15240   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
15241     return SDValue();
15242
15243   if (HasShuffleIntoBitcast) {
15244     // If there's a bitcast before the shuffle, check if the load type and
15245     // alignment is valid.
15246     unsigned Align = LN0->getAlignment();
15247     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15248     unsigned NewAlign = TLI.getDataLayout()->
15249       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
15250
15251     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
15252       return SDValue();
15253   }
15254
15255   // All checks match so transform back to vector_shuffle so that DAG combiner
15256   // can finish the job
15257   DebugLoc dl = N->getDebugLoc();
15258
15259   // Create shuffle node taking into account the case that its a unary shuffle
15260   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
15261   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
15262                                  InVec.getOperand(0), Shuffle,
15263                                  &ShuffleMask[0]);
15264   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
15265   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
15266                      EltNo);
15267 }
15268
15269 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
15270 /// generation and convert it from being a bunch of shuffles and extracts
15271 /// to a simple store and scalar loads to extract the elements.
15272 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
15273                                          TargetLowering::DAGCombinerInfo &DCI) {
15274   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
15275   if (NewOp.getNode())
15276     return NewOp;
15277
15278   SDValue InputVector = N->getOperand(0);
15279   // Detect whether we are trying to convert from mmx to i32 and the bitcast
15280   // from mmx to v2i32 has a single usage.
15281   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
15282       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
15283       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
15284     return DAG.getNode(X86ISD::MMX_MOVD2W, InputVector.getDebugLoc(),
15285                        N->getValueType(0),
15286                        InputVector.getNode()->getOperand(0));
15287
15288   // Only operate on vectors of 4 elements, where the alternative shuffling
15289   // gets to be more expensive.
15290   if (InputVector.getValueType() != MVT::v4i32)
15291     return SDValue();
15292
15293   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
15294   // single use which is a sign-extend or zero-extend, and all elements are
15295   // used.
15296   SmallVector<SDNode *, 4> Uses;
15297   unsigned ExtractedElements = 0;
15298   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
15299        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
15300     if (UI.getUse().getResNo() != InputVector.getResNo())
15301       return SDValue();
15302
15303     SDNode *Extract = *UI;
15304     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
15305       return SDValue();
15306
15307     if (Extract->getValueType(0) != MVT::i32)
15308       return SDValue();
15309     if (!Extract->hasOneUse())
15310       return SDValue();
15311     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
15312         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
15313       return SDValue();
15314     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
15315       return SDValue();
15316
15317     // Record which element was extracted.
15318     ExtractedElements |=
15319       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
15320
15321     Uses.push_back(Extract);
15322   }
15323
15324   // If not all the elements were used, this may not be worthwhile.
15325   if (ExtractedElements != 15)
15326     return SDValue();
15327
15328   // Ok, we've now decided to do the transformation.
15329   DebugLoc dl = InputVector.getDebugLoc();
15330
15331   // Store the value to a temporary stack slot.
15332   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
15333   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
15334                             MachinePointerInfo(), false, false, 0);
15335
15336   // Replace each use (extract) with a load of the appropriate element.
15337   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
15338        UE = Uses.end(); UI != UE; ++UI) {
15339     SDNode *Extract = *UI;
15340
15341     // cOMpute the element's address.
15342     SDValue Idx = Extract->getOperand(1);
15343     unsigned EltSize =
15344         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
15345     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
15346     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15347     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
15348
15349     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
15350                                      StackPtr, OffsetVal);
15351
15352     // Load the scalar.
15353     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
15354                                      ScalarAddr, MachinePointerInfo(),
15355                                      false, false, false, 0);
15356
15357     // Replace the exact with the load.
15358     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
15359   }
15360
15361   // The replacement was made in place; don't return anything.
15362   return SDValue();
15363 }
15364
15365 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
15366 static unsigned matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS,
15367                                    SDValue RHS, SelectionDAG &DAG,
15368                                    const X86Subtarget *Subtarget) {
15369   if (!VT.isVector())
15370     return 0;
15371
15372   switch (VT.getSimpleVT().SimpleTy) {
15373   default: return 0;
15374   case MVT::v32i8:
15375   case MVT::v16i16:
15376   case MVT::v8i32:
15377     if (!Subtarget->hasAVX2())
15378       return 0;
15379   case MVT::v16i8:
15380   case MVT::v8i16:
15381   case MVT::v4i32:
15382     if (!Subtarget->hasSSE2())
15383       return 0;
15384   }
15385
15386   // SSE2 has only a small subset of the operations.
15387   bool hasUnsigned = Subtarget->hasSSE41() ||
15388                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
15389   bool hasSigned = Subtarget->hasSSE41() ||
15390                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
15391
15392   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15393
15394   // Check for x CC y ? x : y.
15395   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15396       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15397     switch (CC) {
15398     default: break;
15399     case ISD::SETULT:
15400     case ISD::SETULE:
15401       return hasUnsigned ? X86ISD::UMIN : 0;
15402     case ISD::SETUGT:
15403     case ISD::SETUGE:
15404       return hasUnsigned ? X86ISD::UMAX : 0;
15405     case ISD::SETLT:
15406     case ISD::SETLE:
15407       return hasSigned ? X86ISD::SMIN : 0;
15408     case ISD::SETGT:
15409     case ISD::SETGE:
15410       return hasSigned ? X86ISD::SMAX : 0;
15411     }
15412   // Check for x CC y ? y : x -- a min/max with reversed arms.
15413   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
15414              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
15415     switch (CC) {
15416     default: break;
15417     case ISD::SETULT:
15418     case ISD::SETULE:
15419       return hasUnsigned ? X86ISD::UMAX : 0;
15420     case ISD::SETUGT:
15421     case ISD::SETUGE:
15422       return hasUnsigned ? X86ISD::UMIN : 0;
15423     case ISD::SETLT:
15424     case ISD::SETLE:
15425       return hasSigned ? X86ISD::SMAX : 0;
15426     case ISD::SETGT:
15427     case ISD::SETGE:
15428       return hasSigned ? X86ISD::SMIN : 0;
15429     }
15430   }
15431
15432   return 0;
15433 }
15434
15435 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
15436 /// nodes.
15437 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
15438                                     TargetLowering::DAGCombinerInfo &DCI,
15439                                     const X86Subtarget *Subtarget) {
15440   DebugLoc DL = N->getDebugLoc();
15441   SDValue Cond = N->getOperand(0);
15442   // Get the LHS/RHS of the select.
15443   SDValue LHS = N->getOperand(1);
15444   SDValue RHS = N->getOperand(2);
15445   EVT VT = LHS.getValueType();
15446
15447   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
15448   // instructions match the semantics of the common C idiom x<y?x:y but not
15449   // x<=y?x:y, because of how they handle negative zero (which can be
15450   // ignored in unsafe-math mode).
15451   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
15452       VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
15453       (Subtarget->hasSSE2() ||
15454        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
15455     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15456
15457     unsigned Opcode = 0;
15458     // Check for x CC y ? x : y.
15459     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15460         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15461       switch (CC) {
15462       default: break;
15463       case ISD::SETULT:
15464         // Converting this to a min would handle NaNs incorrectly, and swapping
15465         // the operands would cause it to handle comparisons between positive
15466         // and negative zero incorrectly.
15467         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
15468           if (!DAG.getTarget().Options.UnsafeFPMath &&
15469               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
15470             break;
15471           std::swap(LHS, RHS);
15472         }
15473         Opcode = X86ISD::FMIN;
15474         break;
15475       case ISD::SETOLE:
15476         // Converting this to a min would handle comparisons between positive
15477         // and negative zero incorrectly.
15478         if (!DAG.getTarget().Options.UnsafeFPMath &&
15479             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
15480           break;
15481         Opcode = X86ISD::FMIN;
15482         break;
15483       case ISD::SETULE:
15484         // Converting this to a min would handle both negative zeros and NaNs
15485         // incorrectly, but we can swap the operands to fix both.
15486         std::swap(LHS, RHS);
15487       case ISD::SETOLT:
15488       case ISD::SETLT:
15489       case ISD::SETLE:
15490         Opcode = X86ISD::FMIN;
15491         break;
15492
15493       case ISD::SETOGE:
15494         // Converting this to a max would handle comparisons between positive
15495         // and negative zero incorrectly.
15496         if (!DAG.getTarget().Options.UnsafeFPMath &&
15497             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
15498           break;
15499         Opcode = X86ISD::FMAX;
15500         break;
15501       case ISD::SETUGT:
15502         // Converting this to a max would handle NaNs incorrectly, and swapping
15503         // the operands would cause it to handle comparisons between positive
15504         // and negative zero incorrectly.
15505         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
15506           if (!DAG.getTarget().Options.UnsafeFPMath &&
15507               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
15508             break;
15509           std::swap(LHS, RHS);
15510         }
15511         Opcode = X86ISD::FMAX;
15512         break;
15513       case ISD::SETUGE:
15514         // Converting this to a max would handle both negative zeros and NaNs
15515         // incorrectly, but we can swap the operands to fix both.
15516         std::swap(LHS, RHS);
15517       case ISD::SETOGT:
15518       case ISD::SETGT:
15519       case ISD::SETGE:
15520         Opcode = X86ISD::FMAX;
15521         break;
15522       }
15523     // Check for x CC y ? y : x -- a min/max with reversed arms.
15524     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
15525                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
15526       switch (CC) {
15527       default: break;
15528       case ISD::SETOGE:
15529         // Converting this to a min would handle comparisons between positive
15530         // and negative zero incorrectly, and swapping the operands would
15531         // cause it to handle NaNs incorrectly.
15532         if (!DAG.getTarget().Options.UnsafeFPMath &&
15533             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
15534           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15535             break;
15536           std::swap(LHS, RHS);
15537         }
15538         Opcode = X86ISD::FMIN;
15539         break;
15540       case ISD::SETUGT:
15541         // Converting this to a min would handle NaNs incorrectly.
15542         if (!DAG.getTarget().Options.UnsafeFPMath &&
15543             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
15544           break;
15545         Opcode = X86ISD::FMIN;
15546         break;
15547       case ISD::SETUGE:
15548         // Converting this to a min would handle both negative zeros and NaNs
15549         // incorrectly, but we can swap the operands to fix both.
15550         std::swap(LHS, RHS);
15551       case ISD::SETOGT:
15552       case ISD::SETGT:
15553       case ISD::SETGE:
15554         Opcode = X86ISD::FMIN;
15555         break;
15556
15557       case ISD::SETULT:
15558         // Converting this to a max would handle NaNs incorrectly.
15559         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15560           break;
15561         Opcode = X86ISD::FMAX;
15562         break;
15563       case ISD::SETOLE:
15564         // Converting this to a max would handle comparisons between positive
15565         // and negative zero incorrectly, and swapping the operands would
15566         // cause it to handle NaNs incorrectly.
15567         if (!DAG.getTarget().Options.UnsafeFPMath &&
15568             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
15569           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15570             break;
15571           std::swap(LHS, RHS);
15572         }
15573         Opcode = X86ISD::FMAX;
15574         break;
15575       case ISD::SETULE:
15576         // Converting this to a max would handle both negative zeros and NaNs
15577         // incorrectly, but we can swap the operands to fix both.
15578         std::swap(LHS, RHS);
15579       case ISD::SETOLT:
15580       case ISD::SETLT:
15581       case ISD::SETLE:
15582         Opcode = X86ISD::FMAX;
15583         break;
15584       }
15585     }
15586
15587     if (Opcode)
15588       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
15589   }
15590
15591   // If this is a select between two integer constants, try to do some
15592   // optimizations.
15593   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
15594     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
15595       // Don't do this for crazy integer types.
15596       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
15597         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
15598         // so that TrueC (the true value) is larger than FalseC.
15599         bool NeedsCondInvert = false;
15600
15601         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
15602             // Efficiently invertible.
15603             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
15604              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
15605               isa<ConstantSDNode>(Cond.getOperand(1))))) {
15606           NeedsCondInvert = true;
15607           std::swap(TrueC, FalseC);
15608         }
15609
15610         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
15611         if (FalseC->getAPIntValue() == 0 &&
15612             TrueC->getAPIntValue().isPowerOf2()) {
15613           if (NeedsCondInvert) // Invert the condition if needed.
15614             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15615                                DAG.getConstant(1, Cond.getValueType()));
15616
15617           // Zero extend the condition if needed.
15618           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
15619
15620           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
15621           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
15622                              DAG.getConstant(ShAmt, MVT::i8));
15623         }
15624
15625         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
15626         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
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,
15633                              FalseC->getValueType(0), Cond);
15634           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15635                              SDValue(FalseC, 0));
15636         }
15637
15638         // Optimize cases that will turn into an LEA instruction.  This requires
15639         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
15640         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
15641           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
15642           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
15643
15644           bool isFastMultiplier = false;
15645           if (Diff < 10) {
15646             switch ((unsigned char)Diff) {
15647               default: break;
15648               case 1:  // result = add base, cond
15649               case 2:  // result = lea base(    , cond*2)
15650               case 3:  // result = lea base(cond, cond*2)
15651               case 4:  // result = lea base(    , cond*4)
15652               case 5:  // result = lea base(cond, cond*4)
15653               case 8:  // result = lea base(    , cond*8)
15654               case 9:  // result = lea base(cond, cond*8)
15655                 isFastMultiplier = true;
15656                 break;
15657             }
15658           }
15659
15660           if (isFastMultiplier) {
15661             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
15662             if (NeedsCondInvert) // Invert the condition if needed.
15663               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15664                                  DAG.getConstant(1, Cond.getValueType()));
15665
15666             // Zero extend the condition if needed.
15667             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
15668                                Cond);
15669             // Scale the condition by the difference.
15670             if (Diff != 1)
15671               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
15672                                  DAG.getConstant(Diff, Cond.getValueType()));
15673
15674             // Add the base if non-zero.
15675             if (FalseC->getAPIntValue() != 0)
15676               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15677                                  SDValue(FalseC, 0));
15678             return Cond;
15679           }
15680         }
15681       }
15682   }
15683
15684   // Canonicalize max and min:
15685   // (x > y) ? x : y -> (x >= y) ? x : y
15686   // (x < y) ? x : y -> (x <= y) ? x : y
15687   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
15688   // the need for an extra compare
15689   // against zero. e.g.
15690   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
15691   // subl   %esi, %edi
15692   // testl  %edi, %edi
15693   // movl   $0, %eax
15694   // cmovgl %edi, %eax
15695   // =>
15696   // xorl   %eax, %eax
15697   // subl   %esi, $edi
15698   // cmovsl %eax, %edi
15699   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
15700       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15701       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15702     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15703     switch (CC) {
15704     default: break;
15705     case ISD::SETLT:
15706     case ISD::SETGT: {
15707       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
15708       Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
15709                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
15710       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
15711     }
15712     }
15713   }
15714
15715   // Match VSELECTs into subs with unsigned saturation.
15716   if (!DCI.isBeforeLegalize() &&
15717       N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
15718       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
15719       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
15720        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
15721     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15722
15723     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
15724     // left side invert the predicate to simplify logic below.
15725     SDValue Other;
15726     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
15727       Other = RHS;
15728       CC = ISD::getSetCCInverse(CC, true);
15729     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
15730       Other = LHS;
15731     }
15732
15733     if (Other.getNode() && Other->getNumOperands() == 2 &&
15734         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
15735       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
15736       SDValue CondRHS = Cond->getOperand(1);
15737
15738       // Look for a general sub with unsigned saturation first.
15739       // x >= y ? x-y : 0 --> subus x, y
15740       // x >  y ? x-y : 0 --> subus x, y
15741       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
15742           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
15743         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
15744
15745       // If the RHS is a constant we have to reverse the const canonicalization.
15746       // x > C-1 ? x+-C : 0 --> subus x, C
15747       if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
15748           isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
15749         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
15750         if (CondRHS.getConstantOperandVal(0) == -A-1)
15751           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
15752                              DAG.getConstant(-A, VT));
15753       }
15754
15755       // Another special case: If C was a sign bit, the sub has been
15756       // canonicalized into a xor.
15757       // FIXME: Would it be better to use ComputeMaskedBits to determine whether
15758       //        it's safe to decanonicalize the xor?
15759       // x s< 0 ? x^C : 0 --> subus x, C
15760       if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
15761           ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
15762           isSplatVector(OpRHS.getNode())) {
15763         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
15764         if (A.isSignBit())
15765           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
15766       }
15767     }
15768   }
15769
15770   // Try to match a min/max vector operation.
15771   if (!DCI.isBeforeLegalize() &&
15772       N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC)
15773     if (unsigned Op = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget))
15774       return DAG.getNode(Op, DL, N->getValueType(0), LHS, RHS);
15775
15776   // If we know that this node is legal then we know that it is going to be
15777   // matched by one of the SSE/AVX BLEND instructions. These instructions only
15778   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
15779   // to simplify previous instructions.
15780   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15781   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
15782       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
15783     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
15784
15785     // Don't optimize vector selects that map to mask-registers.
15786     if (BitWidth == 1)
15787       return SDValue();
15788
15789     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
15790     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
15791
15792     APInt KnownZero, KnownOne;
15793     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
15794                                           DCI.isBeforeLegalizeOps());
15795     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
15796         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
15797       DCI.CommitTargetLoweringOpt(TLO);
15798   }
15799
15800   return SDValue();
15801 }
15802
15803 // Check whether a boolean test is testing a boolean value generated by
15804 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
15805 // code.
15806 //
15807 // Simplify the following patterns:
15808 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
15809 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
15810 // to (Op EFLAGS Cond)
15811 //
15812 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
15813 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
15814 // to (Op EFLAGS !Cond)
15815 //
15816 // where Op could be BRCOND or CMOV.
15817 //
15818 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
15819   // Quit if not CMP and SUB with its value result used.
15820   if (Cmp.getOpcode() != X86ISD::CMP &&
15821       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
15822       return SDValue();
15823
15824   // Quit if not used as a boolean value.
15825   if (CC != X86::COND_E && CC != X86::COND_NE)
15826     return SDValue();
15827
15828   // Check CMP operands. One of them should be 0 or 1 and the other should be
15829   // an SetCC or extended from it.
15830   SDValue Op1 = Cmp.getOperand(0);
15831   SDValue Op2 = Cmp.getOperand(1);
15832
15833   SDValue SetCC;
15834   const ConstantSDNode* C = 0;
15835   bool needOppositeCond = (CC == X86::COND_E);
15836
15837   if ((C = dyn_cast<ConstantSDNode>(Op1)))
15838     SetCC = Op2;
15839   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
15840     SetCC = Op1;
15841   else // Quit if all operands are not constants.
15842     return SDValue();
15843
15844   if (C->getZExtValue() == 1)
15845     needOppositeCond = !needOppositeCond;
15846   else if (C->getZExtValue() != 0)
15847     // Quit if the constant is neither 0 or 1.
15848     return SDValue();
15849
15850   // Skip 'zext' or 'trunc' node.
15851   if (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
15852       SetCC.getOpcode() == ISD::TRUNCATE)
15853     SetCC = SetCC.getOperand(0);
15854
15855   switch (SetCC.getOpcode()) {
15856   case X86ISD::SETCC:
15857     // Set the condition code or opposite one if necessary.
15858     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
15859     if (needOppositeCond)
15860       CC = X86::GetOppositeBranchCondition(CC);
15861     return SetCC.getOperand(1);
15862   case X86ISD::CMOV: {
15863     // Check whether false/true value has canonical one, i.e. 0 or 1.
15864     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
15865     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
15866     // Quit if true value is not a constant.
15867     if (!TVal)
15868       return SDValue();
15869     // Quit if false value is not a constant.
15870     if (!FVal) {
15871       SDValue Op = SetCC.getOperand(0);
15872       // Skip 'zext' or 'trunc' node.
15873       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
15874           Op.getOpcode() == ISD::TRUNCATE)
15875         Op = Op.getOperand(0);
15876       // A special case for rdrand/rdseed, where 0 is set if false cond is
15877       // found.
15878       if ((Op.getOpcode() != X86ISD::RDRAND &&
15879            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
15880         return SDValue();
15881     }
15882     // Quit if false value is not the constant 0 or 1.
15883     bool FValIsFalse = true;
15884     if (FVal && FVal->getZExtValue() != 0) {
15885       if (FVal->getZExtValue() != 1)
15886         return SDValue();
15887       // If FVal is 1, opposite cond is needed.
15888       needOppositeCond = !needOppositeCond;
15889       FValIsFalse = false;
15890     }
15891     // Quit if TVal is not the constant opposite of FVal.
15892     if (FValIsFalse && TVal->getZExtValue() != 1)
15893       return SDValue();
15894     if (!FValIsFalse && TVal->getZExtValue() != 0)
15895       return SDValue();
15896     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
15897     if (needOppositeCond)
15898       CC = X86::GetOppositeBranchCondition(CC);
15899     return SetCC.getOperand(3);
15900   }
15901   }
15902
15903   return SDValue();
15904 }
15905
15906 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
15907 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
15908                                   TargetLowering::DAGCombinerInfo &DCI,
15909                                   const X86Subtarget *Subtarget) {
15910   DebugLoc DL = N->getDebugLoc();
15911
15912   // If the flag operand isn't dead, don't touch this CMOV.
15913   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
15914     return SDValue();
15915
15916   SDValue FalseOp = N->getOperand(0);
15917   SDValue TrueOp = N->getOperand(1);
15918   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
15919   SDValue Cond = N->getOperand(3);
15920
15921   if (CC == X86::COND_E || CC == X86::COND_NE) {
15922     switch (Cond.getOpcode()) {
15923     default: break;
15924     case X86ISD::BSR:
15925     case X86ISD::BSF:
15926       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
15927       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
15928         return (CC == X86::COND_E) ? FalseOp : TrueOp;
15929     }
15930   }
15931
15932   SDValue Flags;
15933
15934   Flags = checkBoolTestSetCCCombine(Cond, CC);
15935   if (Flags.getNode() &&
15936       // Extra check as FCMOV only supports a subset of X86 cond.
15937       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
15938     SDValue Ops[] = { FalseOp, TrueOp,
15939                       DAG.getConstant(CC, MVT::i8), Flags };
15940     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
15941                        Ops, array_lengthof(Ops));
15942   }
15943
15944   // If this is a select between two integer constants, try to do some
15945   // optimizations.  Note that the operands are ordered the opposite of SELECT
15946   // operands.
15947   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
15948     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
15949       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
15950       // larger than FalseC (the false value).
15951       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
15952         CC = X86::GetOppositeBranchCondition(CC);
15953         std::swap(TrueC, FalseC);
15954         std::swap(TrueOp, FalseOp);
15955       }
15956
15957       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
15958       // This is efficient for any integer data type (including i8/i16) and
15959       // shift amount.
15960       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
15961         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15962                            DAG.getConstant(CC, MVT::i8), Cond);
15963
15964         // Zero extend the condition if needed.
15965         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
15966
15967         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
15968         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
15969                            DAG.getConstant(ShAmt, MVT::i8));
15970         if (N->getNumValues() == 2)  // Dead flag value?
15971           return DCI.CombineTo(N, Cond, SDValue());
15972         return Cond;
15973       }
15974
15975       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
15976       // for any integer data type, including i8/i16.
15977       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
15978         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15979                            DAG.getConstant(CC, MVT::i8), Cond);
15980
15981         // Zero extend the condition if needed.
15982         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
15983                            FalseC->getValueType(0), Cond);
15984         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15985                            SDValue(FalseC, 0));
15986
15987         if (N->getNumValues() == 2)  // Dead flag value?
15988           return DCI.CombineTo(N, Cond, SDValue());
15989         return Cond;
15990       }
15991
15992       // Optimize cases that will turn into an LEA instruction.  This requires
15993       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
15994       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
15995         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
15996         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
15997
15998         bool isFastMultiplier = false;
15999         if (Diff < 10) {
16000           switch ((unsigned char)Diff) {
16001           default: break;
16002           case 1:  // result = add base, cond
16003           case 2:  // result = lea base(    , cond*2)
16004           case 3:  // result = lea base(cond, cond*2)
16005           case 4:  // result = lea base(    , cond*4)
16006           case 5:  // result = lea base(cond, cond*4)
16007           case 8:  // result = lea base(    , cond*8)
16008           case 9:  // result = lea base(cond, cond*8)
16009             isFastMultiplier = true;
16010             break;
16011           }
16012         }
16013
16014         if (isFastMultiplier) {
16015           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
16016           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16017                              DAG.getConstant(CC, MVT::i8), Cond);
16018           // Zero extend the condition if needed.
16019           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
16020                              Cond);
16021           // Scale the condition by the difference.
16022           if (Diff != 1)
16023             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
16024                                DAG.getConstant(Diff, Cond.getValueType()));
16025
16026           // Add the base if non-zero.
16027           if (FalseC->getAPIntValue() != 0)
16028             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16029                                SDValue(FalseC, 0));
16030           if (N->getNumValues() == 2)  // Dead flag value?
16031             return DCI.CombineTo(N, Cond, SDValue());
16032           return Cond;
16033         }
16034       }
16035     }
16036   }
16037
16038   // Handle these cases:
16039   //   (select (x != c), e, c) -> select (x != c), e, x),
16040   //   (select (x == c), c, e) -> select (x == c), x, e)
16041   // where the c is an integer constant, and the "select" is the combination
16042   // of CMOV and CMP.
16043   //
16044   // The rationale for this change is that the conditional-move from a constant
16045   // needs two instructions, however, conditional-move from a register needs
16046   // only one instruction.
16047   //
16048   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
16049   //  some instruction-combining opportunities. This opt needs to be
16050   //  postponed as late as possible.
16051   //
16052   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
16053     // the DCI.xxxx conditions are provided to postpone the optimization as
16054     // late as possible.
16055
16056     ConstantSDNode *CmpAgainst = 0;
16057     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
16058         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
16059         !isa<ConstantSDNode>(Cond.getOperand(0))) {
16060
16061       if (CC == X86::COND_NE &&
16062           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
16063         CC = X86::GetOppositeBranchCondition(CC);
16064         std::swap(TrueOp, FalseOp);
16065       }
16066
16067       if (CC == X86::COND_E &&
16068           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
16069         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
16070                           DAG.getConstant(CC, MVT::i8), Cond };
16071         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
16072                            array_lengthof(Ops));
16073       }
16074     }
16075   }
16076
16077   return SDValue();
16078 }
16079
16080 /// PerformMulCombine - Optimize a single multiply with constant into two
16081 /// in order to implement it with two cheaper instructions, e.g.
16082 /// LEA + SHL, LEA + LEA.
16083 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
16084                                  TargetLowering::DAGCombinerInfo &DCI) {
16085   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
16086     return SDValue();
16087
16088   EVT VT = N->getValueType(0);
16089   if (VT != MVT::i64)
16090     return SDValue();
16091
16092   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
16093   if (!C)
16094     return SDValue();
16095   uint64_t MulAmt = C->getZExtValue();
16096   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
16097     return SDValue();
16098
16099   uint64_t MulAmt1 = 0;
16100   uint64_t MulAmt2 = 0;
16101   if ((MulAmt % 9) == 0) {
16102     MulAmt1 = 9;
16103     MulAmt2 = MulAmt / 9;
16104   } else if ((MulAmt % 5) == 0) {
16105     MulAmt1 = 5;
16106     MulAmt2 = MulAmt / 5;
16107   } else if ((MulAmt % 3) == 0) {
16108     MulAmt1 = 3;
16109     MulAmt2 = MulAmt / 3;
16110   }
16111   if (MulAmt2 &&
16112       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
16113     DebugLoc DL = N->getDebugLoc();
16114
16115     if (isPowerOf2_64(MulAmt2) &&
16116         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
16117       // If second multiplifer is pow2, issue it first. We want the multiply by
16118       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
16119       // is an add.
16120       std::swap(MulAmt1, MulAmt2);
16121
16122     SDValue NewMul;
16123     if (isPowerOf2_64(MulAmt1))
16124       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
16125                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
16126     else
16127       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
16128                            DAG.getConstant(MulAmt1, VT));
16129
16130     if (isPowerOf2_64(MulAmt2))
16131       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
16132                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
16133     else
16134       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
16135                            DAG.getConstant(MulAmt2, VT));
16136
16137     // Do not add new nodes to DAG combiner worklist.
16138     DCI.CombineTo(N, NewMul, false);
16139   }
16140   return SDValue();
16141 }
16142
16143 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
16144   SDValue N0 = N->getOperand(0);
16145   SDValue N1 = N->getOperand(1);
16146   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
16147   EVT VT = N0.getValueType();
16148
16149   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
16150   // since the result of setcc_c is all zero's or all ones.
16151   if (VT.isInteger() && !VT.isVector() &&
16152       N1C && N0.getOpcode() == ISD::AND &&
16153       N0.getOperand(1).getOpcode() == ISD::Constant) {
16154     SDValue N00 = N0.getOperand(0);
16155     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
16156         ((N00.getOpcode() == ISD::ANY_EXTEND ||
16157           N00.getOpcode() == ISD::ZERO_EXTEND) &&
16158          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
16159       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
16160       APInt ShAmt = N1C->getAPIntValue();
16161       Mask = Mask.shl(ShAmt);
16162       if (Mask != 0)
16163         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
16164                            N00, DAG.getConstant(Mask, VT));
16165     }
16166   }
16167
16168   // Hardware support for vector shifts is sparse which makes us scalarize the
16169   // vector operations in many cases. Also, on sandybridge ADD is faster than
16170   // shl.
16171   // (shl V, 1) -> add V,V
16172   if (isSplatVector(N1.getNode())) {
16173     assert(N0.getValueType().isVector() && "Invalid vector shift type");
16174     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
16175     // We shift all of the values by one. In many cases we do not have
16176     // hardware support for this operation. This is better expressed as an ADD
16177     // of two values.
16178     if (N1C && (1 == N1C->getZExtValue())) {
16179       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
16180     }
16181   }
16182
16183   return SDValue();
16184 }
16185
16186 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
16187 ///                       when possible.
16188 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
16189                                    TargetLowering::DAGCombinerInfo &DCI,
16190                                    const X86Subtarget *Subtarget) {
16191   if (N->getOpcode() == ISD::SHL) {
16192     SDValue V = PerformSHLCombine(N, DAG);
16193     if (V.getNode()) return V;
16194   }
16195
16196   return SDValue();
16197 }
16198
16199 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
16200 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
16201 // and friends.  Likewise for OR -> CMPNEQSS.
16202 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
16203                             TargetLowering::DAGCombinerInfo &DCI,
16204                             const X86Subtarget *Subtarget) {
16205   unsigned opcode;
16206
16207   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
16208   // we're requiring SSE2 for both.
16209   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
16210     SDValue N0 = N->getOperand(0);
16211     SDValue N1 = N->getOperand(1);
16212     SDValue CMP0 = N0->getOperand(1);
16213     SDValue CMP1 = N1->getOperand(1);
16214     DebugLoc DL = N->getDebugLoc();
16215
16216     // The SETCCs should both refer to the same CMP.
16217     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
16218       return SDValue();
16219
16220     SDValue CMP00 = CMP0->getOperand(0);
16221     SDValue CMP01 = CMP0->getOperand(1);
16222     EVT     VT    = CMP00.getValueType();
16223
16224     if (VT == MVT::f32 || VT == MVT::f64) {
16225       bool ExpectingFlags = false;
16226       // Check for any users that want flags:
16227       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
16228            !ExpectingFlags && UI != UE; ++UI)
16229         switch (UI->getOpcode()) {
16230         default:
16231         case ISD::BR_CC:
16232         case ISD::BRCOND:
16233         case ISD::SELECT:
16234           ExpectingFlags = true;
16235           break;
16236         case ISD::CopyToReg:
16237         case ISD::SIGN_EXTEND:
16238         case ISD::ZERO_EXTEND:
16239         case ISD::ANY_EXTEND:
16240           break;
16241         }
16242
16243       if (!ExpectingFlags) {
16244         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
16245         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
16246
16247         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
16248           X86::CondCode tmp = cc0;
16249           cc0 = cc1;
16250           cc1 = tmp;
16251         }
16252
16253         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
16254             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
16255           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
16256           X86ISD::NodeType NTOperator = is64BitFP ?
16257             X86ISD::FSETCCsd : X86ISD::FSETCCss;
16258           // FIXME: need symbolic constants for these magic numbers.
16259           // See X86ATTInstPrinter.cpp:printSSECC().
16260           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
16261           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
16262                                               DAG.getConstant(x86cc, MVT::i8));
16263           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
16264                                               OnesOrZeroesF);
16265           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
16266                                       DAG.getConstant(1, MVT::i32));
16267           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
16268           return OneBitOfTruth;
16269         }
16270       }
16271     }
16272   }
16273   return SDValue();
16274 }
16275
16276 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
16277 /// so it can be folded inside ANDNP.
16278 static bool CanFoldXORWithAllOnes(const SDNode *N) {
16279   EVT VT = N->getValueType(0);
16280
16281   // Match direct AllOnes for 128 and 256-bit vectors
16282   if (ISD::isBuildVectorAllOnes(N))
16283     return true;
16284
16285   // Look through a bit convert.
16286   if (N->getOpcode() == ISD::BITCAST)
16287     N = N->getOperand(0).getNode();
16288
16289   // Sometimes the operand may come from a insert_subvector building a 256-bit
16290   // allones vector
16291   if (VT.is256BitVector() &&
16292       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
16293     SDValue V1 = N->getOperand(0);
16294     SDValue V2 = N->getOperand(1);
16295
16296     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
16297         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
16298         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
16299         ISD::isBuildVectorAllOnes(V2.getNode()))
16300       return true;
16301   }
16302
16303   return false;
16304 }
16305
16306 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
16307 // register. In most cases we actually compare or select YMM-sized registers
16308 // and mixing the two types creates horrible code. This method optimizes
16309 // some of the transition sequences.
16310 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
16311                                  TargetLowering::DAGCombinerInfo &DCI,
16312                                  const X86Subtarget *Subtarget) {
16313   EVT VT = N->getValueType(0);
16314   if (!VT.is256BitVector())
16315     return SDValue();
16316
16317   assert((N->getOpcode() == ISD::ANY_EXTEND ||
16318           N->getOpcode() == ISD::ZERO_EXTEND ||
16319           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
16320
16321   SDValue Narrow = N->getOperand(0);
16322   EVT NarrowVT = Narrow->getValueType(0);
16323   if (!NarrowVT.is128BitVector())
16324     return SDValue();
16325
16326   if (Narrow->getOpcode() != ISD::XOR &&
16327       Narrow->getOpcode() != ISD::AND &&
16328       Narrow->getOpcode() != ISD::OR)
16329     return SDValue();
16330
16331   SDValue N0  = Narrow->getOperand(0);
16332   SDValue N1  = Narrow->getOperand(1);
16333   DebugLoc DL = Narrow->getDebugLoc();
16334
16335   // The Left side has to be a trunc.
16336   if (N0.getOpcode() != ISD::TRUNCATE)
16337     return SDValue();
16338
16339   // The type of the truncated inputs.
16340   EVT WideVT = N0->getOperand(0)->getValueType(0);
16341   if (WideVT != VT)
16342     return SDValue();
16343
16344   // The right side has to be a 'trunc' or a constant vector.
16345   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
16346   bool RHSConst = (isSplatVector(N1.getNode()) &&
16347                    isa<ConstantSDNode>(N1->getOperand(0)));
16348   if (!RHSTrunc && !RHSConst)
16349     return SDValue();
16350
16351   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16352
16353   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
16354     return SDValue();
16355
16356   // Set N0 and N1 to hold the inputs to the new wide operation.
16357   N0 = N0->getOperand(0);
16358   if (RHSConst) {
16359     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
16360                      N1->getOperand(0));
16361     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
16362     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, &C[0], C.size());
16363   } else if (RHSTrunc) {
16364     N1 = N1->getOperand(0);
16365   }
16366
16367   // Generate the wide operation.
16368   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
16369   unsigned Opcode = N->getOpcode();
16370   switch (Opcode) {
16371   case ISD::ANY_EXTEND:
16372     return Op;
16373   case ISD::ZERO_EXTEND: {
16374     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
16375     APInt Mask = APInt::getAllOnesValue(InBits);
16376     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
16377     return DAG.getNode(ISD::AND, DL, VT,
16378                        Op, DAG.getConstant(Mask, VT));
16379   }
16380   case ISD::SIGN_EXTEND:
16381     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
16382                        Op, DAG.getValueType(NarrowVT));
16383   default:
16384     llvm_unreachable("Unexpected opcode");
16385   }
16386 }
16387
16388 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
16389                                  TargetLowering::DAGCombinerInfo &DCI,
16390                                  const X86Subtarget *Subtarget) {
16391   EVT VT = N->getValueType(0);
16392   if (DCI.isBeforeLegalizeOps())
16393     return SDValue();
16394
16395   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
16396   if (R.getNode())
16397     return R;
16398
16399   // Create BLSI, and BLSR instructions
16400   // BLSI is X & (-X)
16401   // BLSR is X & (X-1)
16402   if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
16403     SDValue N0 = N->getOperand(0);
16404     SDValue N1 = N->getOperand(1);
16405     DebugLoc DL = N->getDebugLoc();
16406
16407     // Check LHS for neg
16408     if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
16409         isZero(N0.getOperand(0)))
16410       return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
16411
16412     // Check RHS for neg
16413     if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
16414         isZero(N1.getOperand(0)))
16415       return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
16416
16417     // Check LHS for X-1
16418     if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
16419         isAllOnes(N0.getOperand(1)))
16420       return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
16421
16422     // Check RHS for X-1
16423     if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
16424         isAllOnes(N1.getOperand(1)))
16425       return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
16426
16427     return SDValue();
16428   }
16429
16430   // Want to form ANDNP nodes:
16431   // 1) In the hopes of then easily combining them with OR and AND nodes
16432   //    to form PBLEND/PSIGN.
16433   // 2) To match ANDN packed intrinsics
16434   if (VT != MVT::v2i64 && VT != MVT::v4i64)
16435     return SDValue();
16436
16437   SDValue N0 = N->getOperand(0);
16438   SDValue N1 = N->getOperand(1);
16439   DebugLoc DL = N->getDebugLoc();
16440
16441   // Check LHS for vnot
16442   if (N0.getOpcode() == ISD::XOR &&
16443       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
16444       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
16445     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
16446
16447   // Check RHS for vnot
16448   if (N1.getOpcode() == ISD::XOR &&
16449       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
16450       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
16451     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
16452
16453   return SDValue();
16454 }
16455
16456 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
16457                                 TargetLowering::DAGCombinerInfo &DCI,
16458                                 const X86Subtarget *Subtarget) {
16459   EVT VT = N->getValueType(0);
16460   if (DCI.isBeforeLegalizeOps())
16461     return SDValue();
16462
16463   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
16464   if (R.getNode())
16465     return R;
16466
16467   SDValue N0 = N->getOperand(0);
16468   SDValue N1 = N->getOperand(1);
16469
16470   // look for psign/blend
16471   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
16472     if (!Subtarget->hasSSSE3() ||
16473         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
16474       return SDValue();
16475
16476     // Canonicalize pandn to RHS
16477     if (N0.getOpcode() == X86ISD::ANDNP)
16478       std::swap(N0, N1);
16479     // or (and (m, y), (pandn m, x))
16480     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
16481       SDValue Mask = N1.getOperand(0);
16482       SDValue X    = N1.getOperand(1);
16483       SDValue Y;
16484       if (N0.getOperand(0) == Mask)
16485         Y = N0.getOperand(1);
16486       if (N0.getOperand(1) == Mask)
16487         Y = N0.getOperand(0);
16488
16489       // Check to see if the mask appeared in both the AND and ANDNP and
16490       if (!Y.getNode())
16491         return SDValue();
16492
16493       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
16494       // Look through mask bitcast.
16495       if (Mask.getOpcode() == ISD::BITCAST)
16496         Mask = Mask.getOperand(0);
16497       if (X.getOpcode() == ISD::BITCAST)
16498         X = X.getOperand(0);
16499       if (Y.getOpcode() == ISD::BITCAST)
16500         Y = Y.getOperand(0);
16501
16502       EVT MaskVT = Mask.getValueType();
16503
16504       // Validate that the Mask operand is a vector sra node.
16505       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
16506       // there is no psrai.b
16507       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
16508       unsigned SraAmt = ~0;
16509       if (Mask.getOpcode() == ISD::SRA) {
16510         SDValue Amt = Mask.getOperand(1);
16511         if (isSplatVector(Amt.getNode())) {
16512           SDValue SclrAmt = Amt->getOperand(0);
16513           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
16514             SraAmt = C->getZExtValue();
16515         }
16516       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
16517         SDValue SraC = Mask.getOperand(1);
16518         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
16519       }
16520       if ((SraAmt + 1) != EltBits)
16521         return SDValue();
16522
16523       DebugLoc DL = N->getDebugLoc();
16524
16525       // Now we know we at least have a plendvb with the mask val.  See if
16526       // we can form a psignb/w/d.
16527       // psign = x.type == y.type == mask.type && y = sub(0, x);
16528       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
16529           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
16530           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
16531         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
16532                "Unsupported VT for PSIGN");
16533         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
16534         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
16535       }
16536       // PBLENDVB only available on SSE 4.1
16537       if (!Subtarget->hasSSE41())
16538         return SDValue();
16539
16540       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
16541
16542       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
16543       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
16544       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
16545       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
16546       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
16547     }
16548   }
16549
16550   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
16551     return SDValue();
16552
16553   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
16554   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
16555     std::swap(N0, N1);
16556   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
16557     return SDValue();
16558   if (!N0.hasOneUse() || !N1.hasOneUse())
16559     return SDValue();
16560
16561   SDValue ShAmt0 = N0.getOperand(1);
16562   if (ShAmt0.getValueType() != MVT::i8)
16563     return SDValue();
16564   SDValue ShAmt1 = N1.getOperand(1);
16565   if (ShAmt1.getValueType() != MVT::i8)
16566     return SDValue();
16567   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
16568     ShAmt0 = ShAmt0.getOperand(0);
16569   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
16570     ShAmt1 = ShAmt1.getOperand(0);
16571
16572   DebugLoc DL = N->getDebugLoc();
16573   unsigned Opc = X86ISD::SHLD;
16574   SDValue Op0 = N0.getOperand(0);
16575   SDValue Op1 = N1.getOperand(0);
16576   if (ShAmt0.getOpcode() == ISD::SUB) {
16577     Opc = X86ISD::SHRD;
16578     std::swap(Op0, Op1);
16579     std::swap(ShAmt0, ShAmt1);
16580   }
16581
16582   unsigned Bits = VT.getSizeInBits();
16583   if (ShAmt1.getOpcode() == ISD::SUB) {
16584     SDValue Sum = ShAmt1.getOperand(0);
16585     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
16586       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
16587       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
16588         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
16589       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
16590         return DAG.getNode(Opc, DL, VT,
16591                            Op0, Op1,
16592                            DAG.getNode(ISD::TRUNCATE, DL,
16593                                        MVT::i8, ShAmt0));
16594     }
16595   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
16596     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
16597     if (ShAmt0C &&
16598         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
16599       return DAG.getNode(Opc, DL, VT,
16600                          N0.getOperand(0), N1.getOperand(0),
16601                          DAG.getNode(ISD::TRUNCATE, DL,
16602                                        MVT::i8, ShAmt0));
16603   }
16604
16605   return SDValue();
16606 }
16607
16608 // Generate NEG and CMOV for integer abs.
16609 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
16610   EVT VT = N->getValueType(0);
16611
16612   // Since X86 does not have CMOV for 8-bit integer, we don't convert
16613   // 8-bit integer abs to NEG and CMOV.
16614   if (VT.isInteger() && VT.getSizeInBits() == 8)
16615     return SDValue();
16616
16617   SDValue N0 = N->getOperand(0);
16618   SDValue N1 = N->getOperand(1);
16619   DebugLoc DL = N->getDebugLoc();
16620
16621   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
16622   // and change it to SUB and CMOV.
16623   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
16624       N0.getOpcode() == ISD::ADD &&
16625       N0.getOperand(1) == N1 &&
16626       N1.getOpcode() == ISD::SRA &&
16627       N1.getOperand(0) == N0.getOperand(0))
16628     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
16629       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
16630         // Generate SUB & CMOV.
16631         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
16632                                   DAG.getConstant(0, VT), N0.getOperand(0));
16633
16634         SDValue Ops[] = { N0.getOperand(0), Neg,
16635                           DAG.getConstant(X86::COND_GE, MVT::i8),
16636                           SDValue(Neg.getNode(), 1) };
16637         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
16638                            Ops, array_lengthof(Ops));
16639       }
16640   return SDValue();
16641 }
16642
16643 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
16644 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
16645                                  TargetLowering::DAGCombinerInfo &DCI,
16646                                  const X86Subtarget *Subtarget) {
16647   EVT VT = N->getValueType(0);
16648   if (DCI.isBeforeLegalizeOps())
16649     return SDValue();
16650
16651   if (Subtarget->hasCMov()) {
16652     SDValue RV = performIntegerAbsCombine(N, DAG);
16653     if (RV.getNode())
16654       return RV;
16655   }
16656
16657   // Try forming BMI if it is available.
16658   if (!Subtarget->hasBMI())
16659     return SDValue();
16660
16661   if (VT != MVT::i32 && VT != MVT::i64)
16662     return SDValue();
16663
16664   assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
16665
16666   // Create BLSMSK instructions by finding X ^ (X-1)
16667   SDValue N0 = N->getOperand(0);
16668   SDValue N1 = N->getOperand(1);
16669   DebugLoc DL = N->getDebugLoc();
16670
16671   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
16672       isAllOnes(N0.getOperand(1)))
16673     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
16674
16675   if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
16676       isAllOnes(N1.getOperand(1)))
16677     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
16678
16679   return SDValue();
16680 }
16681
16682 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
16683 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
16684                                   TargetLowering::DAGCombinerInfo &DCI,
16685                                   const X86Subtarget *Subtarget) {
16686   LoadSDNode *Ld = cast<LoadSDNode>(N);
16687   EVT RegVT = Ld->getValueType(0);
16688   EVT MemVT = Ld->getMemoryVT();
16689   DebugLoc dl = Ld->getDebugLoc();
16690   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16691   unsigned RegSz = RegVT.getSizeInBits();
16692
16693   // On Sandybridge unaligned 256bit loads are inefficient.
16694   ISD::LoadExtType Ext = Ld->getExtensionType();
16695   unsigned Alignment = Ld->getAlignment();
16696   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
16697   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
16698       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
16699     unsigned NumElems = RegVT.getVectorNumElements();
16700     if (NumElems < 2)
16701       return SDValue();
16702
16703     SDValue Ptr = Ld->getBasePtr();
16704     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
16705
16706     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
16707                                   NumElems/2);
16708     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
16709                                 Ld->getPointerInfo(), Ld->isVolatile(),
16710                                 Ld->isNonTemporal(), Ld->isInvariant(),
16711                                 Alignment);
16712     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16713     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
16714                                 Ld->getPointerInfo(), Ld->isVolatile(),
16715                                 Ld->isNonTemporal(), Ld->isInvariant(),
16716                                 std::min(16U, Alignment));
16717     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
16718                              Load1.getValue(1),
16719                              Load2.getValue(1));
16720
16721     SDValue NewVec = DAG.getUNDEF(RegVT);
16722     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
16723     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
16724     return DCI.CombineTo(N, NewVec, TF, true);
16725   }
16726
16727   // If this is a vector EXT Load then attempt to optimize it using a
16728   // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
16729   // expansion is still better than scalar code.
16730   // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
16731   // emit a shuffle and a arithmetic shift.
16732   // TODO: It is possible to support ZExt by zeroing the undef values
16733   // during the shuffle phase or after the shuffle.
16734   if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
16735       (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
16736     assert(MemVT != RegVT && "Cannot extend to the same type");
16737     assert(MemVT.isVector() && "Must load a vector from memory");
16738
16739     unsigned NumElems = RegVT.getVectorNumElements();
16740     unsigned MemSz = MemVT.getSizeInBits();
16741     assert(RegSz > MemSz && "Register size must be greater than the mem size");
16742
16743     if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
16744       return SDValue();
16745
16746     // All sizes must be a power of two.
16747     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
16748       return SDValue();
16749
16750     // Attempt to load the original value using scalar loads.
16751     // Find the largest scalar type that divides the total loaded size.
16752     MVT SclrLoadTy = MVT::i8;
16753     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
16754          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
16755       MVT Tp = (MVT::SimpleValueType)tp;
16756       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
16757         SclrLoadTy = Tp;
16758       }
16759     }
16760
16761     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
16762     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
16763         (64 <= MemSz))
16764       SclrLoadTy = MVT::f64;
16765
16766     // Calculate the number of scalar loads that we need to perform
16767     // in order to load our vector from memory.
16768     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
16769     if (Ext == ISD::SEXTLOAD && NumLoads > 1)
16770       return SDValue();
16771
16772     unsigned loadRegZize = RegSz;
16773     if (Ext == ISD::SEXTLOAD && RegSz == 256)
16774       loadRegZize /= 2;
16775
16776     // Represent our vector as a sequence of elements which are the
16777     // largest scalar that we can load.
16778     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
16779       loadRegZize/SclrLoadTy.getSizeInBits());
16780
16781     // Represent the data using the same element type that is stored in
16782     // memory. In practice, we ''widen'' MemVT.
16783     EVT WideVecVT =
16784           EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
16785                        loadRegZize/MemVT.getScalarType().getSizeInBits());
16786
16787     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
16788       "Invalid vector type");
16789
16790     // We can't shuffle using an illegal type.
16791     if (!TLI.isTypeLegal(WideVecVT))
16792       return SDValue();
16793
16794     SmallVector<SDValue, 8> Chains;
16795     SDValue Ptr = Ld->getBasePtr();
16796     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
16797                                         TLI.getPointerTy());
16798     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
16799
16800     for (unsigned i = 0; i < NumLoads; ++i) {
16801       // Perform a single load.
16802       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
16803                                        Ptr, Ld->getPointerInfo(),
16804                                        Ld->isVolatile(), Ld->isNonTemporal(),
16805                                        Ld->isInvariant(), Ld->getAlignment());
16806       Chains.push_back(ScalarLoad.getValue(1));
16807       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
16808       // another round of DAGCombining.
16809       if (i == 0)
16810         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
16811       else
16812         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
16813                           ScalarLoad, DAG.getIntPtrConstant(i));
16814
16815       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16816     }
16817
16818     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
16819                                Chains.size());
16820
16821     // Bitcast the loaded value to a vector of the original element type, in
16822     // the size of the target vector type.
16823     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
16824     unsigned SizeRatio = RegSz/MemSz;
16825
16826     if (Ext == ISD::SEXTLOAD) {
16827       // If we have SSE4.1 we can directly emit a VSEXT node.
16828       if (Subtarget->hasSSE41()) {
16829         SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
16830         return DCI.CombineTo(N, Sext, TF, true);
16831       }
16832
16833       // Otherwise we'll shuffle the small elements in the high bits of the
16834       // larger type and perform an arithmetic shift. If the shift is not legal
16835       // it's better to scalarize.
16836       if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
16837         return SDValue();
16838
16839       // Redistribute the loaded elements into the different locations.
16840       SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16841       for (unsigned i = 0; i != NumElems; ++i)
16842         ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
16843
16844       SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
16845                                            DAG.getUNDEF(WideVecVT),
16846                                            &ShuffleVec[0]);
16847
16848       Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
16849
16850       // Build the arithmetic shift.
16851       unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
16852                      MemVT.getVectorElementType().getSizeInBits();
16853       Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
16854                           DAG.getConstant(Amt, RegVT));
16855
16856       return DCI.CombineTo(N, Shuff, TF, true);
16857     }
16858
16859     // Redistribute the loaded elements into the different locations.
16860     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16861     for (unsigned i = 0; i != NumElems; ++i)
16862       ShuffleVec[i*SizeRatio] = i;
16863
16864     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
16865                                          DAG.getUNDEF(WideVecVT),
16866                                          &ShuffleVec[0]);
16867
16868     // Bitcast to the requested type.
16869     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
16870     // Replace the original load with the new sequence
16871     // and return the new chain.
16872     return DCI.CombineTo(N, Shuff, TF, true);
16873   }
16874
16875   return SDValue();
16876 }
16877
16878 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
16879 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
16880                                    const X86Subtarget *Subtarget) {
16881   StoreSDNode *St = cast<StoreSDNode>(N);
16882   EVT VT = St->getValue().getValueType();
16883   EVT StVT = St->getMemoryVT();
16884   DebugLoc dl = St->getDebugLoc();
16885   SDValue StoredVal = St->getOperand(1);
16886   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16887
16888   // If we are saving a concatenation of two XMM registers, perform two stores.
16889   // On Sandy Bridge, 256-bit memory operations are executed by two
16890   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
16891   // memory  operation.
16892   unsigned Alignment = St->getAlignment();
16893   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
16894   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
16895       StVT == VT && !IsAligned) {
16896     unsigned NumElems = VT.getVectorNumElements();
16897     if (NumElems < 2)
16898       return SDValue();
16899
16900     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
16901     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
16902
16903     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
16904     SDValue Ptr0 = St->getBasePtr();
16905     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
16906
16907     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
16908                                 St->getPointerInfo(), St->isVolatile(),
16909                                 St->isNonTemporal(), Alignment);
16910     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
16911                                 St->getPointerInfo(), St->isVolatile(),
16912                                 St->isNonTemporal(),
16913                                 std::min(16U, Alignment));
16914     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
16915   }
16916
16917   // Optimize trunc store (of multiple scalars) to shuffle and store.
16918   // First, pack all of the elements in one place. Next, store to memory
16919   // in fewer chunks.
16920   if (St->isTruncatingStore() && VT.isVector()) {
16921     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16922     unsigned NumElems = VT.getVectorNumElements();
16923     assert(StVT != VT && "Cannot truncate to the same type");
16924     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
16925     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
16926
16927     // From, To sizes and ElemCount must be pow of two
16928     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
16929     // We are going to use the original vector elt for storing.
16930     // Accumulated smaller vector elements must be a multiple of the store size.
16931     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
16932
16933     unsigned SizeRatio  = FromSz / ToSz;
16934
16935     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
16936
16937     // Create a type on which we perform the shuffle
16938     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
16939             StVT.getScalarType(), NumElems*SizeRatio);
16940
16941     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
16942
16943     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
16944     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16945     for (unsigned i = 0; i != NumElems; ++i)
16946       ShuffleVec[i] = i * SizeRatio;
16947
16948     // Can't shuffle using an illegal type.
16949     if (!TLI.isTypeLegal(WideVecVT))
16950       return SDValue();
16951
16952     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
16953                                          DAG.getUNDEF(WideVecVT),
16954                                          &ShuffleVec[0]);
16955     // At this point all of the data is stored at the bottom of the
16956     // register. We now need to save it to mem.
16957
16958     // Find the largest store unit
16959     MVT StoreType = MVT::i8;
16960     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
16961          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
16962       MVT Tp = (MVT::SimpleValueType)tp;
16963       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
16964         StoreType = Tp;
16965     }
16966
16967     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
16968     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
16969         (64 <= NumElems * ToSz))
16970       StoreType = MVT::f64;
16971
16972     // Bitcast the original vector into a vector of store-size units
16973     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
16974             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
16975     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
16976     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
16977     SmallVector<SDValue, 8> Chains;
16978     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
16979                                         TLI.getPointerTy());
16980     SDValue Ptr = St->getBasePtr();
16981
16982     // Perform one or more big stores into memory.
16983     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
16984       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
16985                                    StoreType, ShuffWide,
16986                                    DAG.getIntPtrConstant(i));
16987       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
16988                                 St->getPointerInfo(), St->isVolatile(),
16989                                 St->isNonTemporal(), St->getAlignment());
16990       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16991       Chains.push_back(Ch);
16992     }
16993
16994     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
16995                                Chains.size());
16996   }
16997
16998   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
16999   // the FP state in cases where an emms may be missing.
17000   // A preferable solution to the general problem is to figure out the right
17001   // places to insert EMMS.  This qualifies as a quick hack.
17002
17003   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
17004   if (VT.getSizeInBits() != 64)
17005     return SDValue();
17006
17007   const Function *F = DAG.getMachineFunction().getFunction();
17008   bool NoImplicitFloatOps = F->getAttributes().
17009     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
17010   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
17011                      && Subtarget->hasSSE2();
17012   if ((VT.isVector() ||
17013        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
17014       isa<LoadSDNode>(St->getValue()) &&
17015       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
17016       St->getChain().hasOneUse() && !St->isVolatile()) {
17017     SDNode* LdVal = St->getValue().getNode();
17018     LoadSDNode *Ld = 0;
17019     int TokenFactorIndex = -1;
17020     SmallVector<SDValue, 8> Ops;
17021     SDNode* ChainVal = St->getChain().getNode();
17022     // Must be a store of a load.  We currently handle two cases:  the load
17023     // is a direct child, and it's under an intervening TokenFactor.  It is
17024     // possible to dig deeper under nested TokenFactors.
17025     if (ChainVal == LdVal)
17026       Ld = cast<LoadSDNode>(St->getChain());
17027     else if (St->getValue().hasOneUse() &&
17028              ChainVal->getOpcode() == ISD::TokenFactor) {
17029       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
17030         if (ChainVal->getOperand(i).getNode() == LdVal) {
17031           TokenFactorIndex = i;
17032           Ld = cast<LoadSDNode>(St->getValue());
17033         } else
17034           Ops.push_back(ChainVal->getOperand(i));
17035       }
17036     }
17037
17038     if (!Ld || !ISD::isNormalLoad(Ld))
17039       return SDValue();
17040
17041     // If this is not the MMX case, i.e. we are just turning i64 load/store
17042     // into f64 load/store, avoid the transformation if there are multiple
17043     // uses of the loaded value.
17044     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
17045       return SDValue();
17046
17047     DebugLoc LdDL = Ld->getDebugLoc();
17048     DebugLoc StDL = N->getDebugLoc();
17049     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
17050     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
17051     // pair instead.
17052     if (Subtarget->is64Bit() || F64IsLegal) {
17053       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
17054       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
17055                                   Ld->getPointerInfo(), Ld->isVolatile(),
17056                                   Ld->isNonTemporal(), Ld->isInvariant(),
17057                                   Ld->getAlignment());
17058       SDValue NewChain = NewLd.getValue(1);
17059       if (TokenFactorIndex != -1) {
17060         Ops.push_back(NewChain);
17061         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
17062                                Ops.size());
17063       }
17064       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
17065                           St->getPointerInfo(),
17066                           St->isVolatile(), St->isNonTemporal(),
17067                           St->getAlignment());
17068     }
17069
17070     // Otherwise, lower to two pairs of 32-bit loads / stores.
17071     SDValue LoAddr = Ld->getBasePtr();
17072     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
17073                                  DAG.getConstant(4, MVT::i32));
17074
17075     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
17076                                Ld->getPointerInfo(),
17077                                Ld->isVolatile(), Ld->isNonTemporal(),
17078                                Ld->isInvariant(), Ld->getAlignment());
17079     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
17080                                Ld->getPointerInfo().getWithOffset(4),
17081                                Ld->isVolatile(), Ld->isNonTemporal(),
17082                                Ld->isInvariant(),
17083                                MinAlign(Ld->getAlignment(), 4));
17084
17085     SDValue NewChain = LoLd.getValue(1);
17086     if (TokenFactorIndex != -1) {
17087       Ops.push_back(LoLd);
17088       Ops.push_back(HiLd);
17089       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
17090                              Ops.size());
17091     }
17092
17093     LoAddr = St->getBasePtr();
17094     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
17095                          DAG.getConstant(4, MVT::i32));
17096
17097     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
17098                                 St->getPointerInfo(),
17099                                 St->isVolatile(), St->isNonTemporal(),
17100                                 St->getAlignment());
17101     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
17102                                 St->getPointerInfo().getWithOffset(4),
17103                                 St->isVolatile(),
17104                                 St->isNonTemporal(),
17105                                 MinAlign(St->getAlignment(), 4));
17106     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
17107   }
17108   return SDValue();
17109 }
17110
17111 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
17112 /// and return the operands for the horizontal operation in LHS and RHS.  A
17113 /// horizontal operation performs the binary operation on successive elements
17114 /// of its first operand, then on successive elements of its second operand,
17115 /// returning the resulting values in a vector.  For example, if
17116 ///   A = < float a0, float a1, float a2, float a3 >
17117 /// and
17118 ///   B = < float b0, float b1, float b2, float b3 >
17119 /// then the result of doing a horizontal operation on A and B is
17120 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
17121 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
17122 /// A horizontal-op B, for some already available A and B, and if so then LHS is
17123 /// set to A, RHS to B, and the routine returns 'true'.
17124 /// Note that the binary operation should have the property that if one of the
17125 /// operands is UNDEF then the result is UNDEF.
17126 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
17127   // Look for the following pattern: if
17128   //   A = < float a0, float a1, float a2, float a3 >
17129   //   B = < float b0, float b1, float b2, float b3 >
17130   // and
17131   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
17132   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
17133   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
17134   // which is A horizontal-op B.
17135
17136   // At least one of the operands should be a vector shuffle.
17137   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
17138       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
17139     return false;
17140
17141   EVT VT = LHS.getValueType();
17142
17143   assert((VT.is128BitVector() || VT.is256BitVector()) &&
17144          "Unsupported vector type for horizontal add/sub");
17145
17146   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
17147   // operate independently on 128-bit lanes.
17148   unsigned NumElts = VT.getVectorNumElements();
17149   unsigned NumLanes = VT.getSizeInBits()/128;
17150   unsigned NumLaneElts = NumElts / NumLanes;
17151   assert((NumLaneElts % 2 == 0) &&
17152          "Vector type should have an even number of elements in each lane");
17153   unsigned HalfLaneElts = NumLaneElts/2;
17154
17155   // View LHS in the form
17156   //   LHS = VECTOR_SHUFFLE A, B, LMask
17157   // If LHS is not a shuffle then pretend it is the shuffle
17158   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
17159   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
17160   // type VT.
17161   SDValue A, B;
17162   SmallVector<int, 16> LMask(NumElts);
17163   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
17164     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
17165       A = LHS.getOperand(0);
17166     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
17167       B = LHS.getOperand(1);
17168     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
17169     std::copy(Mask.begin(), Mask.end(), LMask.begin());
17170   } else {
17171     if (LHS.getOpcode() != ISD::UNDEF)
17172       A = LHS;
17173     for (unsigned i = 0; i != NumElts; ++i)
17174       LMask[i] = i;
17175   }
17176
17177   // Likewise, view RHS in the form
17178   //   RHS = VECTOR_SHUFFLE C, D, RMask
17179   SDValue C, D;
17180   SmallVector<int, 16> RMask(NumElts);
17181   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
17182     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
17183       C = RHS.getOperand(0);
17184     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
17185       D = RHS.getOperand(1);
17186     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
17187     std::copy(Mask.begin(), Mask.end(), RMask.begin());
17188   } else {
17189     if (RHS.getOpcode() != ISD::UNDEF)
17190       C = RHS;
17191     for (unsigned i = 0; i != NumElts; ++i)
17192       RMask[i] = i;
17193   }
17194
17195   // Check that the shuffles are both shuffling the same vectors.
17196   if (!(A == C && B == D) && !(A == D && B == C))
17197     return false;
17198
17199   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
17200   if (!A.getNode() && !B.getNode())
17201     return false;
17202
17203   // If A and B occur in reverse order in RHS, then "swap" them (which means
17204   // rewriting the mask).
17205   if (A != C)
17206     CommuteVectorShuffleMask(RMask, NumElts);
17207
17208   // At this point LHS and RHS are equivalent to
17209   //   LHS = VECTOR_SHUFFLE A, B, LMask
17210   //   RHS = VECTOR_SHUFFLE A, B, RMask
17211   // Check that the masks correspond to performing a horizontal operation.
17212   for (unsigned i = 0; i != NumElts; ++i) {
17213     int LIdx = LMask[i], RIdx = RMask[i];
17214
17215     // Ignore any UNDEF components.
17216     if (LIdx < 0 || RIdx < 0 ||
17217         (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
17218         (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
17219       continue;
17220
17221     // Check that successive elements are being operated on.  If not, this is
17222     // not a horizontal operation.
17223     unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
17224     unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
17225     int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
17226     if (!(LIdx == Index && RIdx == Index + 1) &&
17227         !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
17228       return false;
17229   }
17230
17231   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
17232   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
17233   return true;
17234 }
17235
17236 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
17237 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
17238                                   const X86Subtarget *Subtarget) {
17239   EVT VT = N->getValueType(0);
17240   SDValue LHS = N->getOperand(0);
17241   SDValue RHS = N->getOperand(1);
17242
17243   // Try to synthesize horizontal adds from adds of shuffles.
17244   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
17245        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
17246       isHorizontalBinOp(LHS, RHS, true))
17247     return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
17248   return SDValue();
17249 }
17250
17251 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
17252 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
17253                                   const X86Subtarget *Subtarget) {
17254   EVT VT = N->getValueType(0);
17255   SDValue LHS = N->getOperand(0);
17256   SDValue RHS = N->getOperand(1);
17257
17258   // Try to synthesize horizontal subs from subs of shuffles.
17259   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
17260        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
17261       isHorizontalBinOp(LHS, RHS, false))
17262     return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
17263   return SDValue();
17264 }
17265
17266 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
17267 /// X86ISD::FXOR nodes.
17268 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
17269   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
17270   // F[X]OR(0.0, x) -> x
17271   // F[X]OR(x, 0.0) -> x
17272   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
17273     if (C->getValueAPF().isPosZero())
17274       return N->getOperand(1);
17275   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
17276     if (C->getValueAPF().isPosZero())
17277       return N->getOperand(0);
17278   return SDValue();
17279 }
17280
17281 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
17282 /// X86ISD::FMAX nodes.
17283 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
17284   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
17285
17286   // Only perform optimizations if UnsafeMath is used.
17287   if (!DAG.getTarget().Options.UnsafeFPMath)
17288     return SDValue();
17289
17290   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
17291   // into FMINC and FMAXC, which are Commutative operations.
17292   unsigned NewOp = 0;
17293   switch (N->getOpcode()) {
17294     default: llvm_unreachable("unknown opcode");
17295     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
17296     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
17297   }
17298
17299   return DAG.getNode(NewOp, N->getDebugLoc(), N->getValueType(0),
17300                      N->getOperand(0), N->getOperand(1));
17301 }
17302
17303 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
17304 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
17305   // FAND(0.0, x) -> 0.0
17306   // FAND(x, 0.0) -> 0.0
17307   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
17308     if (C->getValueAPF().isPosZero())
17309       return N->getOperand(0);
17310   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
17311     if (C->getValueAPF().isPosZero())
17312       return N->getOperand(1);
17313   return SDValue();
17314 }
17315
17316 static SDValue PerformBTCombine(SDNode *N,
17317                                 SelectionDAG &DAG,
17318                                 TargetLowering::DAGCombinerInfo &DCI) {
17319   // BT ignores high bits in the bit index operand.
17320   SDValue Op1 = N->getOperand(1);
17321   if (Op1.hasOneUse()) {
17322     unsigned BitWidth = Op1.getValueSizeInBits();
17323     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
17324     APInt KnownZero, KnownOne;
17325     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
17326                                           !DCI.isBeforeLegalizeOps());
17327     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17328     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
17329         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
17330       DCI.CommitTargetLoweringOpt(TLO);
17331   }
17332   return SDValue();
17333 }
17334
17335 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
17336   SDValue Op = N->getOperand(0);
17337   if (Op.getOpcode() == ISD::BITCAST)
17338     Op = Op.getOperand(0);
17339   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
17340   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
17341       VT.getVectorElementType().getSizeInBits() ==
17342       OpVT.getVectorElementType().getSizeInBits()) {
17343     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
17344   }
17345   return SDValue();
17346 }
17347
17348 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG, 
17349                                                const X86Subtarget *Subtarget) {
17350   EVT VT = N->getValueType(0);
17351   if (!VT.isVector())
17352     return SDValue();
17353
17354   SDValue N0 = N->getOperand(0);
17355   SDValue N1 = N->getOperand(1);
17356   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
17357   DebugLoc dl = N->getDebugLoc();
17358
17359   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
17360   // both SSE and AVX2 since there is no sign-extended shift right
17361   // operation on a vector with 64-bit elements.
17362   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
17363   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
17364   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
17365       N0.getOpcode() == ISD::SIGN_EXTEND)) {
17366     SDValue N00 = N0.getOperand(0);
17367
17368     // EXTLOAD has a better solution on AVX2, 
17369     // it may be replaced with X86ISD::VSEXT node.
17370     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
17371       if (!ISD::isNormalLoad(N00.getNode()))
17372         return SDValue();
17373
17374     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
17375         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, 
17376                                   N00, N1);
17377       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
17378     }
17379   }
17380   return SDValue();
17381 }
17382
17383 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
17384                                   TargetLowering::DAGCombinerInfo &DCI,
17385                                   const X86Subtarget *Subtarget) {
17386   if (!DCI.isBeforeLegalizeOps())
17387     return SDValue();
17388
17389   if (!Subtarget->hasFp256())
17390     return SDValue();
17391
17392   EVT VT = N->getValueType(0);
17393   if (VT.isVector() && VT.getSizeInBits() == 256) {
17394     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
17395     if (R.getNode())
17396       return R;
17397   }
17398
17399   return SDValue();
17400 }
17401
17402 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
17403                                  const X86Subtarget* Subtarget) {
17404   DebugLoc dl = N->getDebugLoc();
17405   EVT VT = N->getValueType(0);
17406
17407   // Let legalize expand this if it isn't a legal type yet.
17408   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
17409     return SDValue();
17410
17411   EVT ScalarVT = VT.getScalarType();
17412   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
17413       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
17414     return SDValue();
17415
17416   SDValue A = N->getOperand(0);
17417   SDValue B = N->getOperand(1);
17418   SDValue C = N->getOperand(2);
17419
17420   bool NegA = (A.getOpcode() == ISD::FNEG);
17421   bool NegB = (B.getOpcode() == ISD::FNEG);
17422   bool NegC = (C.getOpcode() == ISD::FNEG);
17423
17424   // Negative multiplication when NegA xor NegB
17425   bool NegMul = (NegA != NegB);
17426   if (NegA)
17427     A = A.getOperand(0);
17428   if (NegB)
17429     B = B.getOperand(0);
17430   if (NegC)
17431     C = C.getOperand(0);
17432
17433   unsigned Opcode;
17434   if (!NegMul)
17435     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
17436   else
17437     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
17438
17439   return DAG.getNode(Opcode, dl, VT, A, B, C);
17440 }
17441
17442 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
17443                                   TargetLowering::DAGCombinerInfo &DCI,
17444                                   const X86Subtarget *Subtarget) {
17445   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
17446   //           (and (i32 x86isd::setcc_carry), 1)
17447   // This eliminates the zext. This transformation is necessary because
17448   // ISD::SETCC is always legalized to i8.
17449   DebugLoc dl = N->getDebugLoc();
17450   SDValue N0 = N->getOperand(0);
17451   EVT VT = N->getValueType(0);
17452
17453   if (N0.getOpcode() == ISD::AND &&
17454       N0.hasOneUse() &&
17455       N0.getOperand(0).hasOneUse()) {
17456     SDValue N00 = N0.getOperand(0);
17457     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
17458       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
17459       if (!C || C->getZExtValue() != 1)
17460         return SDValue();
17461       return DAG.getNode(ISD::AND, dl, VT,
17462                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
17463                                      N00.getOperand(0), N00.getOperand(1)),
17464                          DAG.getConstant(1, VT));
17465     }
17466   }
17467
17468   if (VT.is256BitVector()) {
17469     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
17470     if (R.getNode())
17471       return R;
17472   }
17473
17474   return SDValue();
17475 }
17476
17477 // Optimize x == -y --> x+y == 0
17478 //          x != -y --> x+y != 0
17479 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
17480   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
17481   SDValue LHS = N->getOperand(0);
17482   SDValue RHS = N->getOperand(1);
17483
17484   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
17485     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
17486       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
17487         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
17488                                    LHS.getValueType(), RHS, LHS.getOperand(1));
17489         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
17490                             addV, DAG.getConstant(0, addV.getValueType()), CC);
17491       }
17492   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
17493     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
17494       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
17495         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
17496                                    RHS.getValueType(), LHS, RHS.getOperand(1));
17497         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
17498                             addV, DAG.getConstant(0, addV.getValueType()), CC);
17499       }
17500   return SDValue();
17501 }
17502
17503 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
17504 // as "sbb reg,reg", since it can be extended without zext and produces
17505 // an all-ones bit which is more useful than 0/1 in some cases.
17506 static SDValue MaterializeSETB(DebugLoc DL, SDValue EFLAGS, SelectionDAG &DAG) {
17507   return DAG.getNode(ISD::AND, DL, MVT::i8,
17508                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
17509                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
17510                      DAG.getConstant(1, MVT::i8));
17511 }
17512
17513 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
17514 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
17515                                    TargetLowering::DAGCombinerInfo &DCI,
17516                                    const X86Subtarget *Subtarget) {
17517   DebugLoc DL = N->getDebugLoc();
17518   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
17519   SDValue EFLAGS = N->getOperand(1);
17520
17521   if (CC == X86::COND_A) {
17522     // Try to convert COND_A into COND_B in an attempt to facilitate
17523     // materializing "setb reg".
17524     //
17525     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
17526     // cannot take an immediate as its first operand.
17527     //
17528     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
17529         EFLAGS.getValueType().isInteger() &&
17530         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
17531       SDValue NewSub = DAG.getNode(X86ISD::SUB, EFLAGS.getDebugLoc(),
17532                                    EFLAGS.getNode()->getVTList(),
17533                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
17534       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
17535       return MaterializeSETB(DL, NewEFLAGS, DAG);
17536     }
17537   }
17538
17539   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
17540   // a zext and produces an all-ones bit which is more useful than 0/1 in some
17541   // cases.
17542   if (CC == X86::COND_B)
17543     return MaterializeSETB(DL, EFLAGS, DAG);
17544
17545   SDValue Flags;
17546
17547   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
17548   if (Flags.getNode()) {
17549     SDValue Cond = DAG.getConstant(CC, MVT::i8);
17550     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
17551   }
17552
17553   return SDValue();
17554 }
17555
17556 // Optimize branch condition evaluation.
17557 //
17558 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
17559                                     TargetLowering::DAGCombinerInfo &DCI,
17560                                     const X86Subtarget *Subtarget) {
17561   DebugLoc DL = N->getDebugLoc();
17562   SDValue Chain = N->getOperand(0);
17563   SDValue Dest = N->getOperand(1);
17564   SDValue EFLAGS = N->getOperand(3);
17565   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
17566
17567   SDValue Flags;
17568
17569   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
17570   if (Flags.getNode()) {
17571     SDValue Cond = DAG.getConstant(CC, MVT::i8);
17572     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
17573                        Flags);
17574   }
17575
17576   return SDValue();
17577 }
17578
17579 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
17580                                         const X86TargetLowering *XTLI) {
17581   SDValue Op0 = N->getOperand(0);
17582   EVT InVT = Op0->getValueType(0);
17583
17584   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
17585   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
17586     DebugLoc dl = N->getDebugLoc();
17587     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
17588     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
17589     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
17590   }
17591
17592   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
17593   // a 32-bit target where SSE doesn't support i64->FP operations.
17594   if (Op0.getOpcode() == ISD::LOAD) {
17595     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
17596     EVT VT = Ld->getValueType(0);
17597     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
17598         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
17599         !XTLI->getSubtarget()->is64Bit() &&
17600         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
17601       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
17602                                           Ld->getChain(), Op0, DAG);
17603       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
17604       return FILDChain;
17605     }
17606   }
17607   return SDValue();
17608 }
17609
17610 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
17611 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
17612                                  X86TargetLowering::DAGCombinerInfo &DCI) {
17613   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
17614   // the result is either zero or one (depending on the input carry bit).
17615   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
17616   if (X86::isZeroNode(N->getOperand(0)) &&
17617       X86::isZeroNode(N->getOperand(1)) &&
17618       // We don't have a good way to replace an EFLAGS use, so only do this when
17619       // dead right now.
17620       SDValue(N, 1).use_empty()) {
17621     DebugLoc DL = N->getDebugLoc();
17622     EVT VT = N->getValueType(0);
17623     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
17624     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
17625                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
17626                                            DAG.getConstant(X86::COND_B,MVT::i8),
17627                                            N->getOperand(2)),
17628                                DAG.getConstant(1, VT));
17629     return DCI.CombineTo(N, Res1, CarryOut);
17630   }
17631
17632   return SDValue();
17633 }
17634
17635 // fold (add Y, (sete  X, 0)) -> adc  0, Y
17636 //      (add Y, (setne X, 0)) -> sbb -1, Y
17637 //      (sub (sete  X, 0), Y) -> sbb  0, Y
17638 //      (sub (setne X, 0), Y) -> adc -1, Y
17639 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
17640   DebugLoc DL = N->getDebugLoc();
17641
17642   // Look through ZExts.
17643   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
17644   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
17645     return SDValue();
17646
17647   SDValue SetCC = Ext.getOperand(0);
17648   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
17649     return SDValue();
17650
17651   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
17652   if (CC != X86::COND_E && CC != X86::COND_NE)
17653     return SDValue();
17654
17655   SDValue Cmp = SetCC.getOperand(1);
17656   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
17657       !X86::isZeroNode(Cmp.getOperand(1)) ||
17658       !Cmp.getOperand(0).getValueType().isInteger())
17659     return SDValue();
17660
17661   SDValue CmpOp0 = Cmp.getOperand(0);
17662   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
17663                                DAG.getConstant(1, CmpOp0.getValueType()));
17664
17665   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
17666   if (CC == X86::COND_NE)
17667     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
17668                        DL, OtherVal.getValueType(), OtherVal,
17669                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
17670   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
17671                      DL, OtherVal.getValueType(), OtherVal,
17672                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
17673 }
17674
17675 /// PerformADDCombine - Do target-specific dag combines on integer adds.
17676 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
17677                                  const X86Subtarget *Subtarget) {
17678   EVT VT = N->getValueType(0);
17679   SDValue Op0 = N->getOperand(0);
17680   SDValue Op1 = N->getOperand(1);
17681
17682   // Try to synthesize horizontal adds from adds of shuffles.
17683   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
17684        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
17685       isHorizontalBinOp(Op0, Op1, true))
17686     return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
17687
17688   return OptimizeConditionalInDecrement(N, DAG);
17689 }
17690
17691 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
17692                                  const X86Subtarget *Subtarget) {
17693   SDValue Op0 = N->getOperand(0);
17694   SDValue Op1 = N->getOperand(1);
17695
17696   // X86 can't encode an immediate LHS of a sub. See if we can push the
17697   // negation into a preceding instruction.
17698   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
17699     // If the RHS of the sub is a XOR with one use and a constant, invert the
17700     // immediate. Then add one to the LHS of the sub so we can turn
17701     // X-Y -> X+~Y+1, saving one register.
17702     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
17703         isa<ConstantSDNode>(Op1.getOperand(1))) {
17704       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
17705       EVT VT = Op0.getValueType();
17706       SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
17707                                    Op1.getOperand(0),
17708                                    DAG.getConstant(~XorC, VT));
17709       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
17710                          DAG.getConstant(C->getAPIntValue()+1, VT));
17711     }
17712   }
17713
17714   // Try to synthesize horizontal adds from adds of shuffles.
17715   EVT VT = N->getValueType(0);
17716   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
17717        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
17718       isHorizontalBinOp(Op0, Op1, true))
17719     return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
17720
17721   return OptimizeConditionalInDecrement(N, DAG);
17722 }
17723
17724 /// performVZEXTCombine - Performs build vector combines
17725 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
17726                                         TargetLowering::DAGCombinerInfo &DCI,
17727                                         const X86Subtarget *Subtarget) {
17728   // (vzext (bitcast (vzext (x)) -> (vzext x)
17729   SDValue In = N->getOperand(0);
17730   while (In.getOpcode() == ISD::BITCAST)
17731     In = In.getOperand(0);
17732
17733   if (In.getOpcode() != X86ISD::VZEXT)
17734     return SDValue();
17735
17736   return DAG.getNode(X86ISD::VZEXT, N->getDebugLoc(), N->getValueType(0),
17737                      In.getOperand(0));
17738 }
17739
17740 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
17741                                              DAGCombinerInfo &DCI) const {
17742   SelectionDAG &DAG = DCI.DAG;
17743   switch (N->getOpcode()) {
17744   default: break;
17745   case ISD::EXTRACT_VECTOR_ELT:
17746     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
17747   case ISD::VSELECT:
17748   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
17749   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
17750   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
17751   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
17752   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
17753   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
17754   case ISD::SHL:
17755   case ISD::SRA:
17756   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
17757   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
17758   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
17759   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
17760   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
17761   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
17762   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
17763   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
17764   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
17765   case X86ISD::FXOR:
17766   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
17767   case X86ISD::FMIN:
17768   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
17769   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
17770   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
17771   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
17772   case ISD::ANY_EXTEND:
17773   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
17774   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
17775   case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
17776   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
17777   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG);
17778   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
17779   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
17780   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
17781   case X86ISD::SHUFP:       // Handle all target specific shuffles
17782   case X86ISD::PALIGNR:
17783   case X86ISD::UNPCKH:
17784   case X86ISD::UNPCKL:
17785   case X86ISD::MOVHLPS:
17786   case X86ISD::MOVLHPS:
17787   case X86ISD::PSHUFD:
17788   case X86ISD::PSHUFHW:
17789   case X86ISD::PSHUFLW:
17790   case X86ISD::MOVSS:
17791   case X86ISD::MOVSD:
17792   case X86ISD::VPERMILP:
17793   case X86ISD::VPERM2X128:
17794   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
17795   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
17796   }
17797
17798   return SDValue();
17799 }
17800
17801 /// isTypeDesirableForOp - Return true if the target has native support for
17802 /// the specified value type and it is 'desirable' to use the type for the
17803 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
17804 /// instruction encodings are longer and some i16 instructions are slow.
17805 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
17806   if (!isTypeLegal(VT))
17807     return false;
17808   if (VT != MVT::i16)
17809     return true;
17810
17811   switch (Opc) {
17812   default:
17813     return true;
17814   case ISD::LOAD:
17815   case ISD::SIGN_EXTEND:
17816   case ISD::ZERO_EXTEND:
17817   case ISD::ANY_EXTEND:
17818   case ISD::SHL:
17819   case ISD::SRL:
17820   case ISD::SUB:
17821   case ISD::ADD:
17822   case ISD::MUL:
17823   case ISD::AND:
17824   case ISD::OR:
17825   case ISD::XOR:
17826     return false;
17827   }
17828 }
17829
17830 /// IsDesirableToPromoteOp - This method query the target whether it is
17831 /// beneficial for dag combiner to promote the specified node. If true, it
17832 /// should return the desired promotion type by reference.
17833 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
17834   EVT VT = Op.getValueType();
17835   if (VT != MVT::i16)
17836     return false;
17837
17838   bool Promote = false;
17839   bool Commute = false;
17840   switch (Op.getOpcode()) {
17841   default: break;
17842   case ISD::LOAD: {
17843     LoadSDNode *LD = cast<LoadSDNode>(Op);
17844     // If the non-extending load has a single use and it's not live out, then it
17845     // might be folded.
17846     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
17847                                                      Op.hasOneUse()*/) {
17848       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
17849              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
17850         // The only case where we'd want to promote LOAD (rather then it being
17851         // promoted as an operand is when it's only use is liveout.
17852         if (UI->getOpcode() != ISD::CopyToReg)
17853           return false;
17854       }
17855     }
17856     Promote = true;
17857     break;
17858   }
17859   case ISD::SIGN_EXTEND:
17860   case ISD::ZERO_EXTEND:
17861   case ISD::ANY_EXTEND:
17862     Promote = true;
17863     break;
17864   case ISD::SHL:
17865   case ISD::SRL: {
17866     SDValue N0 = Op.getOperand(0);
17867     // Look out for (store (shl (load), x)).
17868     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
17869       return false;
17870     Promote = true;
17871     break;
17872   }
17873   case ISD::ADD:
17874   case ISD::MUL:
17875   case ISD::AND:
17876   case ISD::OR:
17877   case ISD::XOR:
17878     Commute = true;
17879     // fallthrough
17880   case ISD::SUB: {
17881     SDValue N0 = Op.getOperand(0);
17882     SDValue N1 = Op.getOperand(1);
17883     if (!Commute && MayFoldLoad(N1))
17884       return false;
17885     // Avoid disabling potential load folding opportunities.
17886     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
17887       return false;
17888     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
17889       return false;
17890     Promote = true;
17891   }
17892   }
17893
17894   PVT = MVT::i32;
17895   return Promote;
17896 }
17897
17898 //===----------------------------------------------------------------------===//
17899 //                           X86 Inline Assembly Support
17900 //===----------------------------------------------------------------------===//
17901
17902 namespace {
17903   // Helper to match a string separated by whitespace.
17904   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
17905     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
17906
17907     for (unsigned i = 0, e = args.size(); i != e; ++i) {
17908       StringRef piece(*args[i]);
17909       if (!s.startswith(piece)) // Check if the piece matches.
17910         return false;
17911
17912       s = s.substr(piece.size());
17913       StringRef::size_type pos = s.find_first_not_of(" \t");
17914       if (pos == 0) // We matched a prefix.
17915         return false;
17916
17917       s = s.substr(pos);
17918     }
17919
17920     return s.empty();
17921   }
17922   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
17923 }
17924
17925 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
17926   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
17927
17928   std::string AsmStr = IA->getAsmString();
17929
17930   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
17931   if (!Ty || Ty->getBitWidth() % 16 != 0)
17932     return false;
17933
17934   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
17935   SmallVector<StringRef, 4> AsmPieces;
17936   SplitString(AsmStr, AsmPieces, ";\n");
17937
17938   switch (AsmPieces.size()) {
17939   default: return false;
17940   case 1:
17941     // FIXME: this should verify that we are targeting a 486 or better.  If not,
17942     // we will turn this bswap into something that will be lowered to logical
17943     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
17944     // lower so don't worry about this.
17945     // bswap $0
17946     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
17947         matchAsm(AsmPieces[0], "bswapl", "$0") ||
17948         matchAsm(AsmPieces[0], "bswapq", "$0") ||
17949         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
17950         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
17951         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
17952       // No need to check constraints, nothing other than the equivalent of
17953       // "=r,0" would be valid here.
17954       return IntrinsicLowering::LowerToByteSwap(CI);
17955     }
17956
17957     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
17958     if (CI->getType()->isIntegerTy(16) &&
17959         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
17960         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
17961          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
17962       AsmPieces.clear();
17963       const std::string &ConstraintsStr = IA->getConstraintString();
17964       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
17965       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
17966       if (AsmPieces.size() == 4 &&
17967           AsmPieces[0] == "~{cc}" &&
17968           AsmPieces[1] == "~{dirflag}" &&
17969           AsmPieces[2] == "~{flags}" &&
17970           AsmPieces[3] == "~{fpsr}")
17971       return IntrinsicLowering::LowerToByteSwap(CI);
17972     }
17973     break;
17974   case 3:
17975     if (CI->getType()->isIntegerTy(32) &&
17976         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
17977         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
17978         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
17979         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
17980       AsmPieces.clear();
17981       const std::string &ConstraintsStr = IA->getConstraintString();
17982       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
17983       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
17984       if (AsmPieces.size() == 4 &&
17985           AsmPieces[0] == "~{cc}" &&
17986           AsmPieces[1] == "~{dirflag}" &&
17987           AsmPieces[2] == "~{flags}" &&
17988           AsmPieces[3] == "~{fpsr}")
17989         return IntrinsicLowering::LowerToByteSwap(CI);
17990     }
17991
17992     if (CI->getType()->isIntegerTy(64)) {
17993       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
17994       if (Constraints.size() >= 2 &&
17995           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
17996           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
17997         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
17998         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
17999             matchAsm(AsmPieces[1], "bswap", "%edx") &&
18000             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
18001           return IntrinsicLowering::LowerToByteSwap(CI);
18002       }
18003     }
18004     break;
18005   }
18006   return false;
18007 }
18008
18009 /// getConstraintType - Given a constraint letter, return the type of
18010 /// constraint it is for this target.
18011 X86TargetLowering::ConstraintType
18012 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
18013   if (Constraint.size() == 1) {
18014     switch (Constraint[0]) {
18015     case 'R':
18016     case 'q':
18017     case 'Q':
18018     case 'f':
18019     case 't':
18020     case 'u':
18021     case 'y':
18022     case 'x':
18023     case 'Y':
18024     case 'l':
18025       return C_RegisterClass;
18026     case 'a':
18027     case 'b':
18028     case 'c':
18029     case 'd':
18030     case 'S':
18031     case 'D':
18032     case 'A':
18033       return C_Register;
18034     case 'I':
18035     case 'J':
18036     case 'K':
18037     case 'L':
18038     case 'M':
18039     case 'N':
18040     case 'G':
18041     case 'C':
18042     case 'e':
18043     case 'Z':
18044       return C_Other;
18045     default:
18046       break;
18047     }
18048   }
18049   return TargetLowering::getConstraintType(Constraint);
18050 }
18051
18052 /// Examine constraint type and operand type and determine a weight value.
18053 /// This object must already have been set up with the operand type
18054 /// and the current alternative constraint selected.
18055 TargetLowering::ConstraintWeight
18056   X86TargetLowering::getSingleConstraintMatchWeight(
18057     AsmOperandInfo &info, const char *constraint) const {
18058   ConstraintWeight weight = CW_Invalid;
18059   Value *CallOperandVal = info.CallOperandVal;
18060     // If we don't have a value, we can't do a match,
18061     // but allow it at the lowest weight.
18062   if (CallOperandVal == NULL)
18063     return CW_Default;
18064   Type *type = CallOperandVal->getType();
18065   // Look at the constraint type.
18066   switch (*constraint) {
18067   default:
18068     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
18069   case 'R':
18070   case 'q':
18071   case 'Q':
18072   case 'a':
18073   case 'b':
18074   case 'c':
18075   case 'd':
18076   case 'S':
18077   case 'D':
18078   case 'A':
18079     if (CallOperandVal->getType()->isIntegerTy())
18080       weight = CW_SpecificReg;
18081     break;
18082   case 'f':
18083   case 't':
18084   case 'u':
18085     if (type->isFloatingPointTy())
18086       weight = CW_SpecificReg;
18087     break;
18088   case 'y':
18089     if (type->isX86_MMXTy() && Subtarget->hasMMX())
18090       weight = CW_SpecificReg;
18091     break;
18092   case 'x':
18093   case 'Y':
18094     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
18095         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
18096       weight = CW_Register;
18097     break;
18098   case 'I':
18099     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
18100       if (C->getZExtValue() <= 31)
18101         weight = CW_Constant;
18102     }
18103     break;
18104   case 'J':
18105     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18106       if (C->getZExtValue() <= 63)
18107         weight = CW_Constant;
18108     }
18109     break;
18110   case 'K':
18111     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18112       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
18113         weight = CW_Constant;
18114     }
18115     break;
18116   case 'L':
18117     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18118       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
18119         weight = CW_Constant;
18120     }
18121     break;
18122   case 'M':
18123     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18124       if (C->getZExtValue() <= 3)
18125         weight = CW_Constant;
18126     }
18127     break;
18128   case 'N':
18129     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18130       if (C->getZExtValue() <= 0xff)
18131         weight = CW_Constant;
18132     }
18133     break;
18134   case 'G':
18135   case 'C':
18136     if (dyn_cast<ConstantFP>(CallOperandVal)) {
18137       weight = CW_Constant;
18138     }
18139     break;
18140   case 'e':
18141     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18142       if ((C->getSExtValue() >= -0x80000000LL) &&
18143           (C->getSExtValue() <= 0x7fffffffLL))
18144         weight = CW_Constant;
18145     }
18146     break;
18147   case 'Z':
18148     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18149       if (C->getZExtValue() <= 0xffffffff)
18150         weight = CW_Constant;
18151     }
18152     break;
18153   }
18154   return weight;
18155 }
18156
18157 /// LowerXConstraint - try to replace an X constraint, which matches anything,
18158 /// with another that has more specific requirements based on the type of the
18159 /// corresponding operand.
18160 const char *X86TargetLowering::
18161 LowerXConstraint(EVT ConstraintVT) const {
18162   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
18163   // 'f' like normal targets.
18164   if (ConstraintVT.isFloatingPoint()) {
18165     if (Subtarget->hasSSE2())
18166       return "Y";
18167     if (Subtarget->hasSSE1())
18168       return "x";
18169   }
18170
18171   return TargetLowering::LowerXConstraint(ConstraintVT);
18172 }
18173
18174 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
18175 /// vector.  If it is invalid, don't add anything to Ops.
18176 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
18177                                                      std::string &Constraint,
18178                                                      std::vector<SDValue>&Ops,
18179                                                      SelectionDAG &DAG) const {
18180   SDValue Result(0, 0);
18181
18182   // Only support length 1 constraints for now.
18183   if (Constraint.length() > 1) return;
18184
18185   char ConstraintLetter = Constraint[0];
18186   switch (ConstraintLetter) {
18187   default: break;
18188   case 'I':
18189     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18190       if (C->getZExtValue() <= 31) {
18191         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18192         break;
18193       }
18194     }
18195     return;
18196   case 'J':
18197     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18198       if (C->getZExtValue() <= 63) {
18199         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18200         break;
18201       }
18202     }
18203     return;
18204   case 'K':
18205     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18206       if (isInt<8>(C->getSExtValue())) {
18207         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18208         break;
18209       }
18210     }
18211     return;
18212   case 'N':
18213     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18214       if (C->getZExtValue() <= 255) {
18215         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18216         break;
18217       }
18218     }
18219     return;
18220   case 'e': {
18221     // 32-bit signed value
18222     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18223       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
18224                                            C->getSExtValue())) {
18225         // Widen to 64 bits here to get it sign extended.
18226         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
18227         break;
18228       }
18229     // FIXME gcc accepts some relocatable values here too, but only in certain
18230     // memory models; it's complicated.
18231     }
18232     return;
18233   }
18234   case 'Z': {
18235     // 32-bit unsigned value
18236     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18237       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
18238                                            C->getZExtValue())) {
18239         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18240         break;
18241       }
18242     }
18243     // FIXME gcc accepts some relocatable values here too, but only in certain
18244     // memory models; it's complicated.
18245     return;
18246   }
18247   case 'i': {
18248     // Literal immediates are always ok.
18249     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
18250       // Widen to 64 bits here to get it sign extended.
18251       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
18252       break;
18253     }
18254
18255     // In any sort of PIC mode addresses need to be computed at runtime by
18256     // adding in a register or some sort of table lookup.  These can't
18257     // be used as immediates.
18258     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
18259       return;
18260
18261     // If we are in non-pic codegen mode, we allow the address of a global (with
18262     // an optional displacement) to be used with 'i'.
18263     GlobalAddressSDNode *GA = 0;
18264     int64_t Offset = 0;
18265
18266     // Match either (GA), (GA+C), (GA+C1+C2), etc.
18267     while (1) {
18268       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
18269         Offset += GA->getOffset();
18270         break;
18271       } else if (Op.getOpcode() == ISD::ADD) {
18272         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
18273           Offset += C->getZExtValue();
18274           Op = Op.getOperand(0);
18275           continue;
18276         }
18277       } else if (Op.getOpcode() == ISD::SUB) {
18278         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
18279           Offset += -C->getZExtValue();
18280           Op = Op.getOperand(0);
18281           continue;
18282         }
18283       }
18284
18285       // Otherwise, this isn't something we can handle, reject it.
18286       return;
18287     }
18288
18289     const GlobalValue *GV = GA->getGlobal();
18290     // If we require an extra load to get this address, as in PIC mode, we
18291     // can't accept it.
18292     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
18293                                                         getTargetMachine())))
18294       return;
18295
18296     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
18297                                         GA->getValueType(0), Offset);
18298     break;
18299   }
18300   }
18301
18302   if (Result.getNode()) {
18303     Ops.push_back(Result);
18304     return;
18305   }
18306   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
18307 }
18308
18309 std::pair<unsigned, const TargetRegisterClass*>
18310 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
18311                                                 EVT VT) const {
18312   // First, see if this is a constraint that directly corresponds to an LLVM
18313   // register class.
18314   if (Constraint.size() == 1) {
18315     // GCC Constraint Letters
18316     switch (Constraint[0]) {
18317     default: break;
18318       // TODO: Slight differences here in allocation order and leaving
18319       // RIP in the class. Do they matter any more here than they do
18320       // in the normal allocation?
18321     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
18322       if (Subtarget->is64Bit()) {
18323         if (VT == MVT::i32 || VT == MVT::f32)
18324           return std::make_pair(0U, &X86::GR32RegClass);
18325         if (VT == MVT::i16)
18326           return std::make_pair(0U, &X86::GR16RegClass);
18327         if (VT == MVT::i8 || VT == MVT::i1)
18328           return std::make_pair(0U, &X86::GR8RegClass);
18329         if (VT == MVT::i64 || VT == MVT::f64)
18330           return std::make_pair(0U, &X86::GR64RegClass);
18331         break;
18332       }
18333       // 32-bit fallthrough
18334     case 'Q':   // Q_REGS
18335       if (VT == MVT::i32 || VT == MVT::f32)
18336         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
18337       if (VT == MVT::i16)
18338         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
18339       if (VT == MVT::i8 || VT == MVT::i1)
18340         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
18341       if (VT == MVT::i64)
18342         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
18343       break;
18344     case 'r':   // GENERAL_REGS
18345     case 'l':   // INDEX_REGS
18346       if (VT == MVT::i8 || VT == MVT::i1)
18347         return std::make_pair(0U, &X86::GR8RegClass);
18348       if (VT == MVT::i16)
18349         return std::make_pair(0U, &X86::GR16RegClass);
18350       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
18351         return std::make_pair(0U, &X86::GR32RegClass);
18352       return std::make_pair(0U, &X86::GR64RegClass);
18353     case 'R':   // LEGACY_REGS
18354       if (VT == MVT::i8 || VT == MVT::i1)
18355         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
18356       if (VT == MVT::i16)
18357         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
18358       if (VT == MVT::i32 || !Subtarget->is64Bit())
18359         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
18360       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
18361     case 'f':  // FP Stack registers.
18362       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
18363       // value to the correct fpstack register class.
18364       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
18365         return std::make_pair(0U, &X86::RFP32RegClass);
18366       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
18367         return std::make_pair(0U, &X86::RFP64RegClass);
18368       return std::make_pair(0U, &X86::RFP80RegClass);
18369     case 'y':   // MMX_REGS if MMX allowed.
18370       if (!Subtarget->hasMMX()) break;
18371       return std::make_pair(0U, &X86::VR64RegClass);
18372     case 'Y':   // SSE_REGS if SSE2 allowed
18373       if (!Subtarget->hasSSE2()) break;
18374       // FALL THROUGH.
18375     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
18376       if (!Subtarget->hasSSE1()) break;
18377
18378       switch (VT.getSimpleVT().SimpleTy) {
18379       default: break;
18380       // Scalar SSE types.
18381       case MVT::f32:
18382       case MVT::i32:
18383         return std::make_pair(0U, &X86::FR32RegClass);
18384       case MVT::f64:
18385       case MVT::i64:
18386         return std::make_pair(0U, &X86::FR64RegClass);
18387       // Vector types.
18388       case MVT::v16i8:
18389       case MVT::v8i16:
18390       case MVT::v4i32:
18391       case MVT::v2i64:
18392       case MVT::v4f32:
18393       case MVT::v2f64:
18394         return std::make_pair(0U, &X86::VR128RegClass);
18395       // AVX types.
18396       case MVT::v32i8:
18397       case MVT::v16i16:
18398       case MVT::v8i32:
18399       case MVT::v4i64:
18400       case MVT::v8f32:
18401       case MVT::v4f64:
18402         return std::make_pair(0U, &X86::VR256RegClass);
18403       }
18404       break;
18405     }
18406   }
18407
18408   // Use the default implementation in TargetLowering to convert the register
18409   // constraint into a member of a register class.
18410   std::pair<unsigned, const TargetRegisterClass*> Res;
18411   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
18412
18413   // Not found as a standard register?
18414   if (Res.second == 0) {
18415     // Map st(0) -> st(7) -> ST0
18416     if (Constraint.size() == 7 && Constraint[0] == '{' &&
18417         tolower(Constraint[1]) == 's' &&
18418         tolower(Constraint[2]) == 't' &&
18419         Constraint[3] == '(' &&
18420         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
18421         Constraint[5] == ')' &&
18422         Constraint[6] == '}') {
18423
18424       Res.first = X86::ST0+Constraint[4]-'0';
18425       Res.second = &X86::RFP80RegClass;
18426       return Res;
18427     }
18428
18429     // GCC allows "st(0)" to be called just plain "st".
18430     if (StringRef("{st}").equals_lower(Constraint)) {
18431       Res.first = X86::ST0;
18432       Res.second = &X86::RFP80RegClass;
18433       return Res;
18434     }
18435
18436     // flags -> EFLAGS
18437     if (StringRef("{flags}").equals_lower(Constraint)) {
18438       Res.first = X86::EFLAGS;
18439       Res.second = &X86::CCRRegClass;
18440       return Res;
18441     }
18442
18443     // 'A' means EAX + EDX.
18444     if (Constraint == "A") {
18445       Res.first = X86::EAX;
18446       Res.second = &X86::GR32_ADRegClass;
18447       return Res;
18448     }
18449     return Res;
18450   }
18451
18452   // Otherwise, check to see if this is a register class of the wrong value
18453   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
18454   // turn into {ax},{dx}.
18455   if (Res.second->hasType(VT))
18456     return Res;   // Correct type already, nothing to do.
18457
18458   // All of the single-register GCC register classes map their values onto
18459   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
18460   // really want an 8-bit or 32-bit register, map to the appropriate register
18461   // class and return the appropriate register.
18462   if (Res.second == &X86::GR16RegClass) {
18463     if (VT == MVT::i8 || VT == MVT::i1) {
18464       unsigned DestReg = 0;
18465       switch (Res.first) {
18466       default: break;
18467       case X86::AX: DestReg = X86::AL; break;
18468       case X86::DX: DestReg = X86::DL; break;
18469       case X86::CX: DestReg = X86::CL; break;
18470       case X86::BX: DestReg = X86::BL; break;
18471       }
18472       if (DestReg) {
18473         Res.first = DestReg;
18474         Res.second = &X86::GR8RegClass;
18475       }
18476     } else if (VT == MVT::i32 || VT == MVT::f32) {
18477       unsigned DestReg = 0;
18478       switch (Res.first) {
18479       default: break;
18480       case X86::AX: DestReg = X86::EAX; break;
18481       case X86::DX: DestReg = X86::EDX; break;
18482       case X86::CX: DestReg = X86::ECX; break;
18483       case X86::BX: DestReg = X86::EBX; break;
18484       case X86::SI: DestReg = X86::ESI; break;
18485       case X86::DI: DestReg = X86::EDI; break;
18486       case X86::BP: DestReg = X86::EBP; break;
18487       case X86::SP: DestReg = X86::ESP; break;
18488       }
18489       if (DestReg) {
18490         Res.first = DestReg;
18491         Res.second = &X86::GR32RegClass;
18492       }
18493     } else if (VT == MVT::i64 || VT == MVT::f64) {
18494       unsigned DestReg = 0;
18495       switch (Res.first) {
18496       default: break;
18497       case X86::AX: DestReg = X86::RAX; break;
18498       case X86::DX: DestReg = X86::RDX; break;
18499       case X86::CX: DestReg = X86::RCX; break;
18500       case X86::BX: DestReg = X86::RBX; break;
18501       case X86::SI: DestReg = X86::RSI; break;
18502       case X86::DI: DestReg = X86::RDI; break;
18503       case X86::BP: DestReg = X86::RBP; break;
18504       case X86::SP: DestReg = X86::RSP; break;
18505       }
18506       if (DestReg) {
18507         Res.first = DestReg;
18508         Res.second = &X86::GR64RegClass;
18509       }
18510     }
18511   } else if (Res.second == &X86::FR32RegClass ||
18512              Res.second == &X86::FR64RegClass ||
18513              Res.second == &X86::VR128RegClass) {
18514     // Handle references to XMM physical registers that got mapped into the
18515     // wrong class.  This can happen with constraints like {xmm0} where the
18516     // target independent register mapper will just pick the first match it can
18517     // find, ignoring the required type.
18518
18519     if (VT == MVT::f32 || VT == MVT::i32)
18520       Res.second = &X86::FR32RegClass;
18521     else if (VT == MVT::f64 || VT == MVT::i64)
18522       Res.second = &X86::FR64RegClass;
18523     else if (X86::VR128RegClass.hasType(VT))
18524       Res.second = &X86::VR128RegClass;
18525     else if (X86::VR256RegClass.hasType(VT))
18526       Res.second = &X86::VR256RegClass;
18527   }
18528
18529   return Res;
18530 }