Add methods for querying minimum SSE version along with AVX. Simplifies all the place...
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "x86-isel"
16 #include "X86.h"
17 #include "X86InstrBuilder.h"
18 #include "X86ISelLowering.h"
19 #include "X86TargetMachine.h"
20 #include "X86TargetObjectFile.h"
21 #include "Utils/X86ShuffleDecode.h"
22 #include "llvm/CallingConv.h"
23 #include "llvm/Constants.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/GlobalAlias.h"
26 #include "llvm/GlobalVariable.h"
27 #include "llvm/Function.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/Intrinsics.h"
30 #include "llvm/LLVMContext.h"
31 #include "llvm/CodeGen/IntrinsicLowering.h"
32 #include "llvm/CodeGen/MachineFrameInfo.h"
33 #include "llvm/CodeGen/MachineFunction.h"
34 #include "llvm/CodeGen/MachineInstrBuilder.h"
35 #include "llvm/CodeGen/MachineJumpTableInfo.h"
36 #include "llvm/CodeGen/MachineModuleInfo.h"
37 #include "llvm/CodeGen/MachineRegisterInfo.h"
38 #include "llvm/MC/MCAsmInfo.h"
39 #include "llvm/MC/MCContext.h"
40 #include "llvm/MC/MCExpr.h"
41 #include "llvm/MC/MCSymbol.h"
42 #include "llvm/ADT/BitVector.h"
43 #include "llvm/ADT/SmallSet.h"
44 #include "llvm/ADT/Statistic.h"
45 #include "llvm/ADT/StringExtras.h"
46 #include "llvm/ADT/VectorExtras.h"
47 #include "llvm/Support/CallSite.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/Dwarf.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/MathExtras.h"
52 #include "llvm/Support/raw_ostream.h"
53 #include "llvm/Target/TargetOptions.h"
54 using namespace llvm;
55 using namespace dwarf;
56
57 STATISTIC(NumTailCalls, "Number of tail calls");
58
59 // Forward declarations.
60 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
61                        SDValue V2);
62
63 static SDValue Insert128BitVector(SDValue Result,
64                                   SDValue Vec,
65                                   SDValue Idx,
66                                   SelectionDAG &DAG,
67                                   DebugLoc dl);
68
69 static SDValue Extract128BitVector(SDValue Vec,
70                                    SDValue Idx,
71                                    SelectionDAG &DAG,
72                                    DebugLoc dl);
73
74 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
75 /// sets things up to match to an AVX VEXTRACTF128 instruction or a
76 /// simple subregister reference.  Idx is an index in the 128 bits we
77 /// want.  It need not be aligned to a 128-bit bounday.  That makes
78 /// lowering EXTRACT_VECTOR_ELT operations easier.
79 static SDValue Extract128BitVector(SDValue Vec,
80                                    SDValue Idx,
81                                    SelectionDAG &DAG,
82                                    DebugLoc dl) {
83   EVT VT = Vec.getValueType();
84   assert(VT.getSizeInBits() == 256 && "Unexpected vector size!");
85   EVT ElVT = VT.getVectorElementType();
86   int Factor = VT.getSizeInBits()/128;
87   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
88                                   VT.getVectorNumElements()/Factor);
89
90   // Extract from UNDEF is UNDEF.
91   if (Vec.getOpcode() == ISD::UNDEF)
92     return DAG.getNode(ISD::UNDEF, dl, ResultVT);
93
94   if (isa<ConstantSDNode>(Idx)) {
95     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
96
97     // Extract the relevant 128 bits.  Generate an EXTRACT_SUBVECTOR
98     // we can match to VEXTRACTF128.
99     unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
100
101     // This is the index of the first element of the 128-bit chunk
102     // we want.
103     unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
104                                  * ElemsPerChunk);
105
106     SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
107     SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
108                                  VecIdx);
109
110     return Result;
111   }
112
113   return SDValue();
114 }
115
116 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
117 /// sets things up to match to an AVX VINSERTF128 instruction or a
118 /// simple superregister reference.  Idx is an index in the 128 bits
119 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
120 /// lowering INSERT_VECTOR_ELT operations easier.
121 static SDValue Insert128BitVector(SDValue Result,
122                                   SDValue Vec,
123                                   SDValue Idx,
124                                   SelectionDAG &DAG,
125                                   DebugLoc dl) {
126   if (isa<ConstantSDNode>(Idx)) {
127     EVT VT = Vec.getValueType();
128     assert(VT.getSizeInBits() == 128 && "Unexpected vector size!");
129
130     EVT ElVT = VT.getVectorElementType();
131     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
132     EVT ResultVT = Result.getValueType();
133
134     // Insert the relevant 128 bits.
135     unsigned ElemsPerChunk = 128/ElVT.getSizeInBits();
136
137     // This is the index of the first element of the 128-bit chunk
138     // we want.
139     unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/128)
140                                  * ElemsPerChunk);
141
142     SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
143     Result = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
144                          VecIdx);
145     return Result;
146   }
147
148   return SDValue();
149 }
150
151 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
152   const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
153   bool is64Bit = Subtarget->is64Bit();
154
155   if (Subtarget->isTargetEnvMacho()) {
156     if (is64Bit)
157       return new X8664_MachoTargetObjectFile();
158     return new TargetLoweringObjectFileMachO();
159   }
160
161   if (Subtarget->isTargetELF())
162     return new TargetLoweringObjectFileELF();
163   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
164     return new TargetLoweringObjectFileCOFF();
165   llvm_unreachable("unknown subtarget type");
166 }
167
168 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
169   : TargetLowering(TM, createTLOF(TM)) {
170   Subtarget = &TM.getSubtarget<X86Subtarget>();
171   X86ScalarSSEf64 = Subtarget->hasXMMInt();
172   X86ScalarSSEf32 = Subtarget->hasXMM();
173   X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
174
175   RegInfo = TM.getRegisterInfo();
176   TD = getTargetData();
177
178   // Set up the TargetLowering object.
179   static MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
180
181   // X86 is weird, it always uses i8 for shift amounts and setcc results.
182   setBooleanContents(ZeroOrOneBooleanContent);
183   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
184   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
185
186   // For 64-bit since we have so many registers use the ILP scheduler, for
187   // 32-bit code use the register pressure specific scheduling.
188   if (Subtarget->is64Bit())
189     setSchedulingPreference(Sched::ILP);
190   else
191     setSchedulingPreference(Sched::RegPressure);
192   setStackPointerRegisterToSaveRestore(X86StackPtr);
193
194   if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
195     // Setup Windows compiler runtime calls.
196     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
197     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
198     setLibcallName(RTLIB::SREM_I64, "_allrem");
199     setLibcallName(RTLIB::UREM_I64, "_aullrem");
200     setLibcallName(RTLIB::MUL_I64, "_allmul");
201     setLibcallName(RTLIB::FPTOUINT_F64_I64, "_ftol2");
202     setLibcallName(RTLIB::FPTOUINT_F32_I64, "_ftol2");
203     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
204     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
205     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
206     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
207     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
208     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::C);
209     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::C);
210   }
211
212   if (Subtarget->isTargetDarwin()) {
213     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
214     setUseUnderscoreSetJmp(false);
215     setUseUnderscoreLongJmp(false);
216   } else if (Subtarget->isTargetMingw()) {
217     // MS runtime is weird: it exports _setjmp, but longjmp!
218     setUseUnderscoreSetJmp(true);
219     setUseUnderscoreLongJmp(false);
220   } else {
221     setUseUnderscoreSetJmp(true);
222     setUseUnderscoreLongJmp(true);
223   }
224
225   // Set up the register classes.
226   addRegisterClass(MVT::i8, X86::GR8RegisterClass);
227   addRegisterClass(MVT::i16, X86::GR16RegisterClass);
228   addRegisterClass(MVT::i32, X86::GR32RegisterClass);
229   if (Subtarget->is64Bit())
230     addRegisterClass(MVT::i64, X86::GR64RegisterClass);
231
232   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
233
234   // We don't accept any truncstore of integer registers.
235   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
236   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
237   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
238   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
239   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
240   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
241
242   // SETOEQ and SETUNE require checking two conditions.
243   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
244   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
245   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
246   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
247   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
248   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
249
250   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
251   // operation.
252   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
253   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
254   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
255
256   if (Subtarget->is64Bit()) {
257     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
258     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Expand);
259   } else if (!UseSoftFloat) {
260     // We have an algorithm for SSE2->double, and we turn this into a
261     // 64-bit FILD followed by conditional FADD for other targets.
262     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
263     // We have an algorithm for SSE2, and we turn this into a 64-bit
264     // FILD for other targets.
265     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
266   }
267
268   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
269   // this operation.
270   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
271   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
272
273   if (!UseSoftFloat) {
274     // SSE has no i16 to fp conversion, only i32
275     if (X86ScalarSSEf32) {
276       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
277       // f32 and f64 cases are Legal, f80 case is not
278       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
279     } else {
280       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
281       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
282     }
283   } else {
284     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
285     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
286   }
287
288   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
289   // are Legal, f80 is custom lowered.
290   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
291   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
292
293   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
294   // this operation.
295   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
296   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
297
298   if (X86ScalarSSEf32) {
299     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
300     // f32 and f64 cases are Legal, f80 case is not
301     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
302   } else {
303     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
304     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
305   }
306
307   // Handle FP_TO_UINT by promoting the destination to a larger signed
308   // conversion.
309   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
310   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
311   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
312
313   if (Subtarget->is64Bit()) {
314     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
315     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
316   } else if (!UseSoftFloat) {
317     // Since AVX is a superset of SSE3, only check for SSE here.
318     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
319       // Expand FP_TO_UINT into a select.
320       // FIXME: We would like to use a Custom expander here eventually to do
321       // the optimal thing for SSE vs. the default expansion in the legalizer.
322       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
323     else
324       // With SSE3 we can use fisttpll to convert to a signed i64; without
325       // SSE, we're stuck with a fistpll.
326       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
327   }
328
329   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
330   if (!X86ScalarSSEf64) {
331     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
332     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
333     if (Subtarget->is64Bit()) {
334       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
335       // Without SSE, i64->f64 goes through memory.
336       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
337     }
338   }
339
340   // Scalar integer divide and remainder are lowered to use operations that
341   // produce two results, to match the available instructions. This exposes
342   // the two-result form to trivial CSE, which is able to combine x/y and x%y
343   // into a single instruction.
344   //
345   // Scalar integer multiply-high is also lowered to use two-result
346   // operations, to match the available instructions. However, plain multiply
347   // (low) operations are left as Legal, as there are single-result
348   // instructions for this in x86. Using the two-result multiply instructions
349   // when both high and low results are needed must be arranged by dagcombine.
350   for (unsigned i = 0, e = 4; i != e; ++i) {
351     MVT VT = IntVTs[i];
352     setOperationAction(ISD::MULHS, VT, Expand);
353     setOperationAction(ISD::MULHU, VT, Expand);
354     setOperationAction(ISD::SDIV, VT, Expand);
355     setOperationAction(ISD::UDIV, VT, Expand);
356     setOperationAction(ISD::SREM, VT, Expand);
357     setOperationAction(ISD::UREM, VT, Expand);
358
359     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
360     setOperationAction(ISD::ADDC, VT, Custom);
361     setOperationAction(ISD::ADDE, VT, Custom);
362     setOperationAction(ISD::SUBC, VT, Custom);
363     setOperationAction(ISD::SUBE, VT, Custom);
364   }
365
366   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
367   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
368   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
369   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
370   if (Subtarget->is64Bit())
371     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
372   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
373   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
374   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
375   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
376   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
377   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
378   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
379   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
380
381   if (Subtarget->hasBMI()) {
382     setOperationAction(ISD::CTTZ           , MVT::i8   , Promote);
383   } else {
384     setOperationAction(ISD::CTTZ           , MVT::i8   , Custom);
385     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
386     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
387     if (Subtarget->is64Bit())
388       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
389   }
390
391   if (Subtarget->hasLZCNT()) {
392     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
393   } else {
394     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
395     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
396     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
397     if (Subtarget->is64Bit())
398       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
399   }
400
401   if (Subtarget->hasPOPCNT()) {
402     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
403   } else {
404     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
405     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
406     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
407     if (Subtarget->is64Bit())
408       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
409   }
410
411   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
412   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
413
414   // These should be promoted to a larger select which is supported.
415   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
416   // X86 wants to expand cmov itself.
417   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
418   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
419   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
420   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
421   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
422   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
423   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
424   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
425   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
426   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
427   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
428   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
429   if (Subtarget->is64Bit()) {
430     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
431     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
432   }
433   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
434
435   // Darwin ABI issue.
436   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
437   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
438   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
439   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
440   if (Subtarget->is64Bit())
441     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
442   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
443   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
444   if (Subtarget->is64Bit()) {
445     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
446     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
447     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
448     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
449     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
450   }
451   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
452   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
453   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
454   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
455   if (Subtarget->is64Bit()) {
456     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
457     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
458     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
459   }
460
461   if (Subtarget->hasXMM())
462     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
463
464   setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
465   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
466
467   // On X86 and X86-64, atomic operations are lowered to locked instructions.
468   // Locked instructions, in turn, have implicit fence semantics (all memory
469   // operations are flushed before issuing the locked instruction, and they
470   // are not buffered), so we can fold away the common pattern of
471   // fence-atomic-fence.
472   setShouldFoldAtomicFences(true);
473
474   // Expand certain atomics
475   for (unsigned i = 0, e = 4; i != e; ++i) {
476     MVT VT = IntVTs[i];
477     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
478     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
479     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
480   }
481
482   if (!Subtarget->is64Bit()) {
483     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
484     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
485     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
486     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
487     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
488     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
489     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
490     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
491   }
492
493   if (Subtarget->hasCmpxchg16b()) {
494     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
495   }
496
497   // FIXME - use subtarget debug flags
498   if (!Subtarget->isTargetDarwin() &&
499       !Subtarget->isTargetELF() &&
500       !Subtarget->isTargetCygMing()) {
501     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
502   }
503
504   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
505   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
506   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
507   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
508   if (Subtarget->is64Bit()) {
509     setExceptionPointerRegister(X86::RAX);
510     setExceptionSelectorRegister(X86::RDX);
511   } else {
512     setExceptionPointerRegister(X86::EAX);
513     setExceptionSelectorRegister(X86::EDX);
514   }
515   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
516   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
517
518   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
519   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
520
521   setOperationAction(ISD::TRAP, MVT::Other, Legal);
522
523   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
524   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
525   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
526   if (Subtarget->is64Bit()) {
527     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
528     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
529   } else {
530     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
531     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
532   }
533
534   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
535   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
536
537   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
538     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
539                        MVT::i64 : MVT::i32, Custom);
540   else if (EnableSegmentedStacks)
541     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
542                        MVT::i64 : MVT::i32, Custom);
543   else
544     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
545                        MVT::i64 : MVT::i32, Expand);
546
547   if (!UseSoftFloat && X86ScalarSSEf64) {
548     // f32 and f64 use SSE.
549     // Set up the FP register classes.
550     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
551     addRegisterClass(MVT::f64, X86::FR64RegisterClass);
552
553     // Use ANDPD to simulate FABS.
554     setOperationAction(ISD::FABS , MVT::f64, Custom);
555     setOperationAction(ISD::FABS , MVT::f32, Custom);
556
557     // Use XORP to simulate FNEG.
558     setOperationAction(ISD::FNEG , MVT::f64, Custom);
559     setOperationAction(ISD::FNEG , MVT::f32, Custom);
560
561     // Use ANDPD and ORPD to simulate FCOPYSIGN.
562     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
563     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
564
565     // Lower this to FGETSIGNx86 plus an AND.
566     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
567     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
568
569     // We don't support sin/cos/fmod
570     setOperationAction(ISD::FSIN , MVT::f64, Expand);
571     setOperationAction(ISD::FCOS , MVT::f64, Expand);
572     setOperationAction(ISD::FSIN , MVT::f32, Expand);
573     setOperationAction(ISD::FCOS , MVT::f32, Expand);
574
575     // Expand FP immediates into loads from the stack, except for the special
576     // cases we handle.
577     addLegalFPImmediate(APFloat(+0.0)); // xorpd
578     addLegalFPImmediate(APFloat(+0.0f)); // xorps
579   } else if (!UseSoftFloat && X86ScalarSSEf32) {
580     // Use SSE for f32, x87 for f64.
581     // Set up the FP register classes.
582     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
583     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
584
585     // Use ANDPS to simulate FABS.
586     setOperationAction(ISD::FABS , MVT::f32, Custom);
587
588     // Use XORP to simulate FNEG.
589     setOperationAction(ISD::FNEG , MVT::f32, Custom);
590
591     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
592
593     // Use ANDPS and ORPS to simulate FCOPYSIGN.
594     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
595     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
596
597     // We don't support sin/cos/fmod
598     setOperationAction(ISD::FSIN , MVT::f32, Expand);
599     setOperationAction(ISD::FCOS , MVT::f32, Expand);
600
601     // Special cases we handle for FP constants.
602     addLegalFPImmediate(APFloat(+0.0f)); // xorps
603     addLegalFPImmediate(APFloat(+0.0)); // FLD0
604     addLegalFPImmediate(APFloat(+1.0)); // FLD1
605     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
606     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
607
608     if (!UnsafeFPMath) {
609       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
610       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
611     }
612   } else if (!UseSoftFloat) {
613     // f32 and f64 in x87.
614     // Set up the FP register classes.
615     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
616     addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
617
618     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
619     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
620     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
621     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
622
623     if (!UnsafeFPMath) {
624       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
625       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
626     }
627     addLegalFPImmediate(APFloat(+0.0)); // FLD0
628     addLegalFPImmediate(APFloat(+1.0)); // FLD1
629     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
630     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
631     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
632     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
633     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
634     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
635   }
636
637   // We don't support FMA.
638   setOperationAction(ISD::FMA, MVT::f64, Expand);
639   setOperationAction(ISD::FMA, MVT::f32, Expand);
640
641   // Long double always uses X87.
642   if (!UseSoftFloat) {
643     addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
644     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
645     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
646     {
647       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
648       addLegalFPImmediate(TmpFlt);  // FLD0
649       TmpFlt.changeSign();
650       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
651
652       bool ignored;
653       APFloat TmpFlt2(+1.0);
654       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
655                       &ignored);
656       addLegalFPImmediate(TmpFlt2);  // FLD1
657       TmpFlt2.changeSign();
658       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
659     }
660
661     if (!UnsafeFPMath) {
662       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
663       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
664     }
665
666     setOperationAction(ISD::FMA, MVT::f80, Expand);
667   }
668
669   // Always use a library call for pow.
670   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
671   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
672   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
673
674   setOperationAction(ISD::FLOG, MVT::f80, Expand);
675   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
676   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
677   setOperationAction(ISD::FEXP, MVT::f80, Expand);
678   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
679
680   // First set operation action for all vector types to either promote
681   // (for widening) or expand (for scalarization). Then we will selectively
682   // turn on ones that can be effectively codegen'd.
683   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
684        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
685     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
686     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
687     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
688     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
689     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
690     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
691     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
692     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
693     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
694     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
695     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
696     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
697     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
698     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
699     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
700     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
701     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
702     setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
703     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
704     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
705     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
706     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
707     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
708     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
709     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
710     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
711     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
712     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
713     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
714     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
715     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
716     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
717     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
718     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
719     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
720     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
721     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
722     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
723     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
724     setOperationAction(ISD::SETCC, (MVT::SimpleValueType)VT, Expand);
725     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
726     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
727     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
728     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
729     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
730     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
731     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
732     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
733     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
734     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
735     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
736     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
737     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
738     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
739     setOperationAction(ISD::VSELECT,  (MVT::SimpleValueType)VT, Expand);
740     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
741          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
742       setTruncStoreAction((MVT::SimpleValueType)VT,
743                           (MVT::SimpleValueType)InnerVT, Expand);
744     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
745     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
746     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
747   }
748
749   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
750   // with -msoft-float, disable use of MMX as well.
751   if (!UseSoftFloat && Subtarget->hasMMX()) {
752     addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass);
753     // No operations on x86mmx supported, everything uses intrinsics.
754   }
755
756   // MMX-sized vectors (other than x86mmx) are expected to be expanded
757   // into smaller operations.
758   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
759   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
760   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
761   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
762   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
763   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
764   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
765   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
766   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
767   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
768   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
769   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
770   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
771   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
772   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
773   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
774   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
775   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
776   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
777   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
778   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
779   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
780   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
781   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
782   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
783   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
784   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
785   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
786   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
787
788   if (!UseSoftFloat && Subtarget->hasXMM()) {
789     addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
790
791     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
792     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
793     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
794     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
795     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
796     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
797     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
798     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
799     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
800     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
801     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
802     setOperationAction(ISD::SETCC,              MVT::v4f32, Custom);
803   }
804
805   if (!UseSoftFloat && Subtarget->hasXMMInt()) {
806     addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
807
808     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
809     // registers cannot be used even for integer operations.
810     addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
811     addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
812     addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
813     addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
814
815     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
816     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
817     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
818     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
819     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
820     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
821     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
822     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
823     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
824     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
825     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
826     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
827     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
828     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
829     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
830     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
831
832     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
833     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
834     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
835     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
836
837     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
838     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
839     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
840     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
841     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
842
843     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2f64, Custom);
844     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2i64, Custom);
845     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i8, Custom);
846     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i16, Custom);
847     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i32, Custom);
848
849     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
850     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
851       EVT VT = (MVT::SimpleValueType)i;
852       // Do not attempt to custom lower non-power-of-2 vectors
853       if (!isPowerOf2_32(VT.getVectorNumElements()))
854         continue;
855       // Do not attempt to custom lower non-128-bit vectors
856       if (!VT.is128BitVector())
857         continue;
858       setOperationAction(ISD::BUILD_VECTOR,
859                          VT.getSimpleVT().SimpleTy, Custom);
860       setOperationAction(ISD::VECTOR_SHUFFLE,
861                          VT.getSimpleVT().SimpleTy, Custom);
862       setOperationAction(ISD::EXTRACT_VECTOR_ELT,
863                          VT.getSimpleVT().SimpleTy, Custom);
864     }
865
866     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
867     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
868     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
869     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
870     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
871     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
872
873     if (Subtarget->is64Bit()) {
874       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
875       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
876     }
877
878     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
879     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
880       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
881       EVT VT = SVT;
882
883       // Do not attempt to promote non-128-bit vectors
884       if (!VT.is128BitVector())
885         continue;
886
887       setOperationAction(ISD::AND,    SVT, Promote);
888       AddPromotedToType (ISD::AND,    SVT, MVT::v2i64);
889       setOperationAction(ISD::OR,     SVT, Promote);
890       AddPromotedToType (ISD::OR,     SVT, MVT::v2i64);
891       setOperationAction(ISD::XOR,    SVT, Promote);
892       AddPromotedToType (ISD::XOR,    SVT, MVT::v2i64);
893       setOperationAction(ISD::LOAD,   SVT, Promote);
894       AddPromotedToType (ISD::LOAD,   SVT, MVT::v2i64);
895       setOperationAction(ISD::SELECT, SVT, Promote);
896       AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
897     }
898
899     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
900
901     // Custom lower v2i64 and v2f64 selects.
902     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
903     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
904     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
905     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
906
907     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
908     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
909   }
910
911   if (Subtarget->hasSSE41orAVX()) {
912     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
913     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
914     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
915     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
916     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
917     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
918     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
919     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
920     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
921     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
922
923     // FIXME: Do we need to handle scalar-to-vector here?
924     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
925
926     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
927     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
928     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
929     setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
930     setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
931
932     // i8 and i16 vectors are custom , because the source register and source
933     // source memory operand types are not the same width.  f32 vectors are
934     // custom since the immediate controlling the insert encodes additional
935     // information.
936     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
937     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
938     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
939     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
940
941     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
942     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
943     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
944     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
945
946     // FIXME: these should be Legal but thats only for the case where
947     // the index is constant.  For now custom expand to deal with that
948     if (Subtarget->is64Bit()) {
949       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
950       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
951     }
952   }
953
954   if (Subtarget->hasXMMInt()) {
955     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
956     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
957
958     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
959     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
960
961     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
962     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
963
964     if (Subtarget->hasAVX2()) {
965       setOperationAction(ISD::SRL,             MVT::v2i64, Legal);
966       setOperationAction(ISD::SRL,             MVT::v4i32, Legal);
967
968       setOperationAction(ISD::SHL,             MVT::v2i64, Legal);
969       setOperationAction(ISD::SHL,             MVT::v4i32, Legal);
970
971       setOperationAction(ISD::SRA,             MVT::v4i32, Legal);
972     } else {
973       setOperationAction(ISD::SRL,             MVT::v2i64, Custom);
974       setOperationAction(ISD::SRL,             MVT::v4i32, Custom);
975
976       setOperationAction(ISD::SHL,             MVT::v2i64, Custom);
977       setOperationAction(ISD::SHL,             MVT::v4i32, Custom);
978
979       setOperationAction(ISD::SRA,             MVT::v4i32, Custom);
980     }
981   }
982
983   if (Subtarget->hasSSE42orAVX())
984     setOperationAction(ISD::SETCC,             MVT::v2i64, Custom);
985
986   if (!UseSoftFloat && Subtarget->hasAVX()) {
987     addRegisterClass(MVT::v32i8,  X86::VR256RegisterClass);
988     addRegisterClass(MVT::v16i16, X86::VR256RegisterClass);
989     addRegisterClass(MVT::v8i32,  X86::VR256RegisterClass);
990     addRegisterClass(MVT::v8f32,  X86::VR256RegisterClass);
991     addRegisterClass(MVT::v4i64,  X86::VR256RegisterClass);
992     addRegisterClass(MVT::v4f64,  X86::VR256RegisterClass);
993
994     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
995     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
996     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
997
998     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
999     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1000     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1001     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1002     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1003     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1004
1005     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1006     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1007     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1008     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1009     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1010     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1011
1012     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1013     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1014     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1015
1016     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4f64,  Custom);
1017     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i64,  Custom);
1018     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f32,  Custom);
1019     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i32,  Custom);
1020     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i8,  Custom);
1021     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i16, Custom);
1022
1023     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1024     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1025
1026     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1027     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1028
1029     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1030     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1031
1032     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1033     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1034     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1035     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1036
1037     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1038     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1039     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1040
1041     setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1042     setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1043     setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1044     setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1045
1046     if (Subtarget->hasAVX2()) {
1047       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1048       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1049       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1050       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1051
1052       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1053       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1054       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1055       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1056
1057       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1058       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1059       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1060       // Don't lower v32i8 because there is no 128-bit byte mul
1061
1062       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1063
1064       setOperationAction(ISD::SRL,             MVT::v4i64, Legal);
1065       setOperationAction(ISD::SRL,             MVT::v8i32, Legal);
1066
1067       setOperationAction(ISD::SHL,             MVT::v4i64, Legal);
1068       setOperationAction(ISD::SHL,             MVT::v8i32, Legal);
1069
1070       setOperationAction(ISD::SRA,             MVT::v8i32, Legal);
1071     } else {
1072       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1073       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1074       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1075       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1076
1077       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1078       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1079       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1080       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1081
1082       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1083       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1084       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1085       // Don't lower v32i8 because there is no 128-bit byte mul
1086
1087       setOperationAction(ISD::SRL,             MVT::v4i64, Custom);
1088       setOperationAction(ISD::SRL,             MVT::v8i32, Custom);
1089
1090       setOperationAction(ISD::SHL,             MVT::v4i64, Custom);
1091       setOperationAction(ISD::SHL,             MVT::v8i32, Custom);
1092
1093       setOperationAction(ISD::SRA,             MVT::v8i32, Custom);
1094     }
1095
1096     // Custom lower several nodes for 256-bit types.
1097     for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1098                   i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
1099       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1100       EVT VT = SVT;
1101
1102       // Extract subvector is special because the value type
1103       // (result) is 128-bit but the source is 256-bit wide.
1104       if (VT.is128BitVector())
1105         setOperationAction(ISD::EXTRACT_SUBVECTOR, SVT, Custom);
1106
1107       // Do not attempt to custom lower other non-256-bit vectors
1108       if (!VT.is256BitVector())
1109         continue;
1110
1111       setOperationAction(ISD::BUILD_VECTOR,       SVT, Custom);
1112       setOperationAction(ISD::VECTOR_SHUFFLE,     SVT, Custom);
1113       setOperationAction(ISD::INSERT_VECTOR_ELT,  SVT, Custom);
1114       setOperationAction(ISD::EXTRACT_VECTOR_ELT, SVT, Custom);
1115       setOperationAction(ISD::SCALAR_TO_VECTOR,   SVT, Custom);
1116       setOperationAction(ISD::INSERT_SUBVECTOR,   SVT, Custom);
1117     }
1118
1119     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1120     for (unsigned i = (unsigned)MVT::v32i8; i != (unsigned)MVT::v4i64; ++i) {
1121       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1122       EVT VT = SVT;
1123
1124       // Do not attempt to promote non-256-bit vectors
1125       if (!VT.is256BitVector())
1126         continue;
1127
1128       setOperationAction(ISD::AND,    SVT, Promote);
1129       AddPromotedToType (ISD::AND,    SVT, MVT::v4i64);
1130       setOperationAction(ISD::OR,     SVT, Promote);
1131       AddPromotedToType (ISD::OR,     SVT, MVT::v4i64);
1132       setOperationAction(ISD::XOR,    SVT, Promote);
1133       AddPromotedToType (ISD::XOR,    SVT, MVT::v4i64);
1134       setOperationAction(ISD::LOAD,   SVT, Promote);
1135       AddPromotedToType (ISD::LOAD,   SVT, MVT::v4i64);
1136       setOperationAction(ISD::SELECT, SVT, Promote);
1137       AddPromotedToType (ISD::SELECT, SVT, MVT::v4i64);
1138     }
1139   }
1140
1141   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1142   // of this type with custom code.
1143   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1144          VT != (unsigned)MVT::LAST_VECTOR_VALUETYPE; VT++) {
1145     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT, Custom);
1146   }
1147
1148   // We want to custom lower some of our intrinsics.
1149   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1150
1151
1152   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1153   // handle type legalization for these operations here.
1154   //
1155   // FIXME: We really should do custom legalization for addition and
1156   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1157   // than generic legalization for 64-bit multiplication-with-overflow, though.
1158   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1159     // Add/Sub/Mul with overflow operations are custom lowered.
1160     MVT VT = IntVTs[i];
1161     setOperationAction(ISD::SADDO, VT, Custom);
1162     setOperationAction(ISD::UADDO, VT, Custom);
1163     setOperationAction(ISD::SSUBO, VT, Custom);
1164     setOperationAction(ISD::USUBO, VT, Custom);
1165     setOperationAction(ISD::SMULO, VT, Custom);
1166     setOperationAction(ISD::UMULO, VT, Custom);
1167   }
1168
1169   // There are no 8-bit 3-address imul/mul instructions
1170   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1171   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1172
1173   if (!Subtarget->is64Bit()) {
1174     // These libcalls are not available in 32-bit.
1175     setLibcallName(RTLIB::SHL_I128, 0);
1176     setLibcallName(RTLIB::SRL_I128, 0);
1177     setLibcallName(RTLIB::SRA_I128, 0);
1178   }
1179
1180   // We have target-specific dag combine patterns for the following nodes:
1181   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1182   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1183   setTargetDAGCombine(ISD::BUILD_VECTOR);
1184   setTargetDAGCombine(ISD::VSELECT);
1185   setTargetDAGCombine(ISD::SELECT);
1186   setTargetDAGCombine(ISD::SHL);
1187   setTargetDAGCombine(ISD::SRA);
1188   setTargetDAGCombine(ISD::SRL);
1189   setTargetDAGCombine(ISD::OR);
1190   setTargetDAGCombine(ISD::AND);
1191   setTargetDAGCombine(ISD::ADD);
1192   setTargetDAGCombine(ISD::FADD);
1193   setTargetDAGCombine(ISD::FSUB);
1194   setTargetDAGCombine(ISD::SUB);
1195   setTargetDAGCombine(ISD::LOAD);
1196   setTargetDAGCombine(ISD::STORE);
1197   setTargetDAGCombine(ISD::ZERO_EXTEND);
1198   setTargetDAGCombine(ISD::SINT_TO_FP);
1199   if (Subtarget->is64Bit())
1200     setTargetDAGCombine(ISD::MUL);
1201   if (Subtarget->hasBMI())
1202     setTargetDAGCombine(ISD::XOR);
1203
1204   computeRegisterProperties();
1205
1206   // On Darwin, -Os means optimize for size without hurting performance,
1207   // do not reduce the limit.
1208   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1209   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1210   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1211   maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1212   maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1213   maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1214   setPrefLoopAlignment(16);
1215   benefitFromCodePlacementOpt = true;
1216
1217   setPrefFunctionAlignment(4);
1218 }
1219
1220
1221 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1222   if (!VT.isVector()) return MVT::i8;
1223   return VT.changeVectorElementTypeToInteger();
1224 }
1225
1226
1227 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1228 /// the desired ByVal argument alignment.
1229 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1230   if (MaxAlign == 16)
1231     return;
1232   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1233     if (VTy->getBitWidth() == 128)
1234       MaxAlign = 16;
1235   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1236     unsigned EltAlign = 0;
1237     getMaxByValAlign(ATy->getElementType(), EltAlign);
1238     if (EltAlign > MaxAlign)
1239       MaxAlign = EltAlign;
1240   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1241     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1242       unsigned EltAlign = 0;
1243       getMaxByValAlign(STy->getElementType(i), EltAlign);
1244       if (EltAlign > MaxAlign)
1245         MaxAlign = EltAlign;
1246       if (MaxAlign == 16)
1247         break;
1248     }
1249   }
1250   return;
1251 }
1252
1253 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1254 /// function arguments in the caller parameter area. For X86, aggregates
1255 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1256 /// are at 4-byte boundaries.
1257 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1258   if (Subtarget->is64Bit()) {
1259     // Max of 8 and alignment of type.
1260     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1261     if (TyAlign > 8)
1262       return TyAlign;
1263     return 8;
1264   }
1265
1266   unsigned Align = 4;
1267   if (Subtarget->hasXMM())
1268     getMaxByValAlign(Ty, Align);
1269   return Align;
1270 }
1271
1272 /// getOptimalMemOpType - Returns the target specific optimal type for load
1273 /// and store operations as a result of memset, memcpy, and memmove
1274 /// lowering. If DstAlign is zero that means it's safe to destination
1275 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1276 /// means there isn't a need to check it against alignment requirement,
1277 /// probably because the source does not need to be loaded. If
1278 /// 'IsZeroVal' is true, that means it's safe to return a
1279 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1280 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1281 /// constant so it does not need to be loaded.
1282 /// It returns EVT::Other if the type should be determined using generic
1283 /// target-independent logic.
1284 EVT
1285 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1286                                        unsigned DstAlign, unsigned SrcAlign,
1287                                        bool IsZeroVal,
1288                                        bool MemcpyStrSrc,
1289                                        MachineFunction &MF) const {
1290   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1291   // linux.  This is because the stack realignment code can't handle certain
1292   // cases like PR2962.  This should be removed when PR2962 is fixed.
1293   const Function *F = MF.getFunction();
1294   if (IsZeroVal &&
1295       !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1296     if (Size >= 16 &&
1297         (Subtarget->isUnalignedMemAccessFast() ||
1298          ((DstAlign == 0 || DstAlign >= 16) &&
1299           (SrcAlign == 0 || SrcAlign >= 16))) &&
1300         Subtarget->getStackAlignment() >= 16) {
1301       if (Subtarget->hasAVX() &&
1302           Subtarget->getStackAlignment() >= 32)
1303         return MVT::v8f32;
1304       if (Subtarget->hasXMMInt())
1305         return MVT::v4i32;
1306       if (Subtarget->hasXMM())
1307         return MVT::v4f32;
1308     } else if (!MemcpyStrSrc && Size >= 8 &&
1309                !Subtarget->is64Bit() &&
1310                Subtarget->getStackAlignment() >= 8 &&
1311                Subtarget->hasXMMInt()) {
1312       // Do not use f64 to lower memcpy if source is string constant. It's
1313       // better to use i32 to avoid the loads.
1314       return MVT::f64;
1315     }
1316   }
1317   if (Subtarget->is64Bit() && Size >= 8)
1318     return MVT::i64;
1319   return MVT::i32;
1320 }
1321
1322 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1323 /// current function.  The returned value is a member of the
1324 /// MachineJumpTableInfo::JTEntryKind enum.
1325 unsigned X86TargetLowering::getJumpTableEncoding() const {
1326   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1327   // symbol.
1328   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1329       Subtarget->isPICStyleGOT())
1330     return MachineJumpTableInfo::EK_Custom32;
1331
1332   // Otherwise, use the normal jump table encoding heuristics.
1333   return TargetLowering::getJumpTableEncoding();
1334 }
1335
1336 const MCExpr *
1337 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1338                                              const MachineBasicBlock *MBB,
1339                                              unsigned uid,MCContext &Ctx) const{
1340   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1341          Subtarget->isPICStyleGOT());
1342   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1343   // entries.
1344   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1345                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1346 }
1347
1348 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1349 /// jumptable.
1350 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1351                                                     SelectionDAG &DAG) const {
1352   if (!Subtarget->is64Bit())
1353     // This doesn't have DebugLoc associated with it, but is not really the
1354     // same as a Register.
1355     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1356   return Table;
1357 }
1358
1359 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1360 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1361 /// MCExpr.
1362 const MCExpr *X86TargetLowering::
1363 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1364                              MCContext &Ctx) const {
1365   // X86-64 uses RIP relative addressing based on the jump table label.
1366   if (Subtarget->isPICStyleRIPRel())
1367     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1368
1369   // Otherwise, the reference is relative to the PIC base.
1370   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1371 }
1372
1373 // FIXME: Why this routine is here? Move to RegInfo!
1374 std::pair<const TargetRegisterClass*, uint8_t>
1375 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1376   const TargetRegisterClass *RRC = 0;
1377   uint8_t Cost = 1;
1378   switch (VT.getSimpleVT().SimpleTy) {
1379   default:
1380     return TargetLowering::findRepresentativeClass(VT);
1381   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1382     RRC = (Subtarget->is64Bit()
1383            ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1384     break;
1385   case MVT::x86mmx:
1386     RRC = X86::VR64RegisterClass;
1387     break;
1388   case MVT::f32: case MVT::f64:
1389   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1390   case MVT::v4f32: case MVT::v2f64:
1391   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1392   case MVT::v4f64:
1393     RRC = X86::VR128RegisterClass;
1394     break;
1395   }
1396   return std::make_pair(RRC, Cost);
1397 }
1398
1399 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1400                                                unsigned &Offset) const {
1401   if (!Subtarget->isTargetLinux())
1402     return false;
1403
1404   if (Subtarget->is64Bit()) {
1405     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1406     Offset = 0x28;
1407     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1408       AddressSpace = 256;
1409     else
1410       AddressSpace = 257;
1411   } else {
1412     // %gs:0x14 on i386
1413     Offset = 0x14;
1414     AddressSpace = 256;
1415   }
1416   return true;
1417 }
1418
1419
1420 //===----------------------------------------------------------------------===//
1421 //               Return Value Calling Convention Implementation
1422 //===----------------------------------------------------------------------===//
1423
1424 #include "X86GenCallingConv.inc"
1425
1426 bool
1427 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1428                                   MachineFunction &MF, bool isVarArg,
1429                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1430                         LLVMContext &Context) const {
1431   SmallVector<CCValAssign, 16> RVLocs;
1432   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1433                  RVLocs, Context);
1434   return CCInfo.CheckReturn(Outs, RetCC_X86);
1435 }
1436
1437 SDValue
1438 X86TargetLowering::LowerReturn(SDValue Chain,
1439                                CallingConv::ID CallConv, bool isVarArg,
1440                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1441                                const SmallVectorImpl<SDValue> &OutVals,
1442                                DebugLoc dl, SelectionDAG &DAG) const {
1443   MachineFunction &MF = DAG.getMachineFunction();
1444   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1445
1446   SmallVector<CCValAssign, 16> RVLocs;
1447   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1448                  RVLocs, *DAG.getContext());
1449   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1450
1451   // Add the regs to the liveout set for the function.
1452   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1453   for (unsigned i = 0; i != RVLocs.size(); ++i)
1454     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1455       MRI.addLiveOut(RVLocs[i].getLocReg());
1456
1457   SDValue Flag;
1458
1459   SmallVector<SDValue, 6> RetOps;
1460   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1461   // Operand #1 = Bytes To Pop
1462   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1463                    MVT::i16));
1464
1465   // Copy the result values into the output registers.
1466   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1467     CCValAssign &VA = RVLocs[i];
1468     assert(VA.isRegLoc() && "Can only return in registers!");
1469     SDValue ValToCopy = OutVals[i];
1470     EVT ValVT = ValToCopy.getValueType();
1471
1472     // If this is x86-64, and we disabled SSE, we can't return FP values,
1473     // or SSE or MMX vectors.
1474     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1475          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1476           (Subtarget->is64Bit() && !Subtarget->hasXMM())) {
1477       report_fatal_error("SSE register return with SSE disabled");
1478     }
1479     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1480     // llvm-gcc has never done it right and no one has noticed, so this
1481     // should be OK for now.
1482     if (ValVT == MVT::f64 &&
1483         (Subtarget->is64Bit() && !Subtarget->hasXMMInt()))
1484       report_fatal_error("SSE2 register return with SSE2 disabled");
1485
1486     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1487     // the RET instruction and handled by the FP Stackifier.
1488     if (VA.getLocReg() == X86::ST0 ||
1489         VA.getLocReg() == X86::ST1) {
1490       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1491       // change the value to the FP stack register class.
1492       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1493         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1494       RetOps.push_back(ValToCopy);
1495       // Don't emit a copytoreg.
1496       continue;
1497     }
1498
1499     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1500     // which is returned in RAX / RDX.
1501     if (Subtarget->is64Bit()) {
1502       if (ValVT == MVT::x86mmx) {
1503         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1504           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1505           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1506                                   ValToCopy);
1507           // If we don't have SSE2 available, convert to v4f32 so the generated
1508           // register is legal.
1509           if (!Subtarget->hasXMMInt())
1510             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1511         }
1512       }
1513     }
1514
1515     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1516     Flag = Chain.getValue(1);
1517   }
1518
1519   // The x86-64 ABI for returning structs by value requires that we copy
1520   // the sret argument into %rax for the return. We saved the argument into
1521   // a virtual register in the entry block, so now we copy the value out
1522   // and into %rax.
1523   if (Subtarget->is64Bit() &&
1524       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1525     MachineFunction &MF = DAG.getMachineFunction();
1526     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1527     unsigned Reg = FuncInfo->getSRetReturnReg();
1528     assert(Reg &&
1529            "SRetReturnReg should have been set in LowerFormalArguments().");
1530     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1531
1532     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1533     Flag = Chain.getValue(1);
1534
1535     // RAX now acts like a return value.
1536     MRI.addLiveOut(X86::RAX);
1537   }
1538
1539   RetOps[0] = Chain;  // Update chain.
1540
1541   // Add the flag if we have it.
1542   if (Flag.getNode())
1543     RetOps.push_back(Flag);
1544
1545   return DAG.getNode(X86ISD::RET_FLAG, dl,
1546                      MVT::Other, &RetOps[0], RetOps.size());
1547 }
1548
1549 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1550   if (N->getNumValues() != 1)
1551     return false;
1552   if (!N->hasNUsesOfValue(1, 0))
1553     return false;
1554
1555   SDNode *Copy = *N->use_begin();
1556   if (Copy->getOpcode() != ISD::CopyToReg &&
1557       Copy->getOpcode() != ISD::FP_EXTEND)
1558     return false;
1559
1560   bool HasRet = false;
1561   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1562        UI != UE; ++UI) {
1563     if (UI->getOpcode() != X86ISD::RET_FLAG)
1564       return false;
1565     HasRet = true;
1566   }
1567
1568   return HasRet;
1569 }
1570
1571 EVT
1572 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1573                                             ISD::NodeType ExtendKind) const {
1574   MVT ReturnMVT;
1575   // TODO: Is this also valid on 32-bit?
1576   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1577     ReturnMVT = MVT::i8;
1578   else
1579     ReturnMVT = MVT::i32;
1580
1581   EVT MinVT = getRegisterType(Context, ReturnMVT);
1582   return VT.bitsLT(MinVT) ? MinVT : VT;
1583 }
1584
1585 /// LowerCallResult - Lower the result values of a call into the
1586 /// appropriate copies out of appropriate physical registers.
1587 ///
1588 SDValue
1589 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1590                                    CallingConv::ID CallConv, bool isVarArg,
1591                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1592                                    DebugLoc dl, SelectionDAG &DAG,
1593                                    SmallVectorImpl<SDValue> &InVals) const {
1594
1595   // Assign locations to each value returned by this call.
1596   SmallVector<CCValAssign, 16> RVLocs;
1597   bool Is64Bit = Subtarget->is64Bit();
1598   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1599                  getTargetMachine(), RVLocs, *DAG.getContext());
1600   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1601
1602   // Copy all of the result registers out of their specified physreg.
1603   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1604     CCValAssign &VA = RVLocs[i];
1605     EVT CopyVT = VA.getValVT();
1606
1607     // If this is x86-64, and we disabled SSE, we can't return FP values
1608     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1609         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) {
1610       report_fatal_error("SSE register return with SSE disabled");
1611     }
1612
1613     SDValue Val;
1614
1615     // If this is a call to a function that returns an fp value on the floating
1616     // point stack, we must guarantee the the value is popped from the stack, so
1617     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1618     // if the return value is not used. We use the FpPOP_RETVAL instruction
1619     // instead.
1620     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1621       // If we prefer to use the value in xmm registers, copy it out as f80 and
1622       // use a truncate to move it from fp stack reg to xmm reg.
1623       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1624       SDValue Ops[] = { Chain, InFlag };
1625       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1626                                          MVT::Other, MVT::Glue, Ops, 2), 1);
1627       Val = Chain.getValue(0);
1628
1629       // Round the f80 to the right size, which also moves it to the appropriate
1630       // xmm register.
1631       if (CopyVT != VA.getValVT())
1632         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1633                           // This truncation won't change the value.
1634                           DAG.getIntPtrConstant(1));
1635     } else {
1636       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1637                                  CopyVT, InFlag).getValue(1);
1638       Val = Chain.getValue(0);
1639     }
1640     InFlag = Chain.getValue(2);
1641     InVals.push_back(Val);
1642   }
1643
1644   return Chain;
1645 }
1646
1647
1648 //===----------------------------------------------------------------------===//
1649 //                C & StdCall & Fast Calling Convention implementation
1650 //===----------------------------------------------------------------------===//
1651 //  StdCall calling convention seems to be standard for many Windows' API
1652 //  routines and around. It differs from C calling convention just a little:
1653 //  callee should clean up the stack, not caller. Symbols should be also
1654 //  decorated in some fancy way :) It doesn't support any vector arguments.
1655 //  For info on fast calling convention see Fast Calling Convention (tail call)
1656 //  implementation LowerX86_32FastCCCallTo.
1657
1658 /// CallIsStructReturn - Determines whether a call uses struct return
1659 /// semantics.
1660 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1661   if (Outs.empty())
1662     return false;
1663
1664   return Outs[0].Flags.isSRet();
1665 }
1666
1667 /// ArgsAreStructReturn - Determines whether a function uses struct
1668 /// return semantics.
1669 static bool
1670 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1671   if (Ins.empty())
1672     return false;
1673
1674   return Ins[0].Flags.isSRet();
1675 }
1676
1677 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1678 /// by "Src" to address "Dst" with size and alignment information specified by
1679 /// the specific parameter attribute. The copy will be passed as a byval
1680 /// function parameter.
1681 static SDValue
1682 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1683                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1684                           DebugLoc dl) {
1685   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1686
1687   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1688                        /*isVolatile*/false, /*AlwaysInline=*/true,
1689                        MachinePointerInfo(), MachinePointerInfo());
1690 }
1691
1692 /// IsTailCallConvention - Return true if the calling convention is one that
1693 /// supports tail call optimization.
1694 static bool IsTailCallConvention(CallingConv::ID CC) {
1695   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1696 }
1697
1698 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1699   if (!CI->isTailCall())
1700     return false;
1701
1702   CallSite CS(CI);
1703   CallingConv::ID CalleeCC = CS.getCallingConv();
1704   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1705     return false;
1706
1707   return true;
1708 }
1709
1710 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1711 /// a tailcall target by changing its ABI.
1712 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1713   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1714 }
1715
1716 SDValue
1717 X86TargetLowering::LowerMemArgument(SDValue Chain,
1718                                     CallingConv::ID CallConv,
1719                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1720                                     DebugLoc dl, SelectionDAG &DAG,
1721                                     const CCValAssign &VA,
1722                                     MachineFrameInfo *MFI,
1723                                     unsigned i) const {
1724   // Create the nodes corresponding to a load from this parameter slot.
1725   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1726   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1727   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1728   EVT ValVT;
1729
1730   // If value is passed by pointer we have address passed instead of the value
1731   // itself.
1732   if (VA.getLocInfo() == CCValAssign::Indirect)
1733     ValVT = VA.getLocVT();
1734   else
1735     ValVT = VA.getValVT();
1736
1737   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1738   // changed with more analysis.
1739   // In case of tail call optimization mark all arguments mutable. Since they
1740   // could be overwritten by lowering of arguments in case of a tail call.
1741   if (Flags.isByVal()) {
1742     unsigned Bytes = Flags.getByValSize();
1743     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1744     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1745     return DAG.getFrameIndex(FI, getPointerTy());
1746   } else {
1747     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1748                                     VA.getLocMemOffset(), isImmutable);
1749     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1750     return DAG.getLoad(ValVT, dl, Chain, FIN,
1751                        MachinePointerInfo::getFixedStack(FI),
1752                        false, false, false, 0);
1753   }
1754 }
1755
1756 SDValue
1757 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1758                                         CallingConv::ID CallConv,
1759                                         bool isVarArg,
1760                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1761                                         DebugLoc dl,
1762                                         SelectionDAG &DAG,
1763                                         SmallVectorImpl<SDValue> &InVals)
1764                                           const {
1765   MachineFunction &MF = DAG.getMachineFunction();
1766   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1767
1768   const Function* Fn = MF.getFunction();
1769   if (Fn->hasExternalLinkage() &&
1770       Subtarget->isTargetCygMing() &&
1771       Fn->getName() == "main")
1772     FuncInfo->setForceFramePointer(true);
1773
1774   MachineFrameInfo *MFI = MF.getFrameInfo();
1775   bool Is64Bit = Subtarget->is64Bit();
1776   bool IsWin64 = Subtarget->isTargetWin64();
1777
1778   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1779          "Var args not supported with calling convention fastcc or ghc");
1780
1781   // Assign locations to all of the incoming arguments.
1782   SmallVector<CCValAssign, 16> ArgLocs;
1783   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1784                  ArgLocs, *DAG.getContext());
1785
1786   // Allocate shadow area for Win64
1787   if (IsWin64) {
1788     CCInfo.AllocateStack(32, 8);
1789   }
1790
1791   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1792
1793   unsigned LastVal = ~0U;
1794   SDValue ArgValue;
1795   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1796     CCValAssign &VA = ArgLocs[i];
1797     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1798     // places.
1799     assert(VA.getValNo() != LastVal &&
1800            "Don't support value assigned to multiple locs yet");
1801     (void)LastVal;
1802     LastVal = VA.getValNo();
1803
1804     if (VA.isRegLoc()) {
1805       EVT RegVT = VA.getLocVT();
1806       TargetRegisterClass *RC = NULL;
1807       if (RegVT == MVT::i32)
1808         RC = X86::GR32RegisterClass;
1809       else if (Is64Bit && RegVT == MVT::i64)
1810         RC = X86::GR64RegisterClass;
1811       else if (RegVT == MVT::f32)
1812         RC = X86::FR32RegisterClass;
1813       else if (RegVT == MVT::f64)
1814         RC = X86::FR64RegisterClass;
1815       else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1816         RC = X86::VR256RegisterClass;
1817       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1818         RC = X86::VR128RegisterClass;
1819       else if (RegVT == MVT::x86mmx)
1820         RC = X86::VR64RegisterClass;
1821       else
1822         llvm_unreachable("Unknown argument type!");
1823
1824       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1825       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1826
1827       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1828       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1829       // right size.
1830       if (VA.getLocInfo() == CCValAssign::SExt)
1831         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1832                                DAG.getValueType(VA.getValVT()));
1833       else if (VA.getLocInfo() == CCValAssign::ZExt)
1834         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1835                                DAG.getValueType(VA.getValVT()));
1836       else if (VA.getLocInfo() == CCValAssign::BCvt)
1837         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1838
1839       if (VA.isExtInLoc()) {
1840         // Handle MMX values passed in XMM regs.
1841         if (RegVT.isVector()) {
1842           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1843                                  ArgValue);
1844         } else
1845           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1846       }
1847     } else {
1848       assert(VA.isMemLoc());
1849       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1850     }
1851
1852     // If value is passed via pointer - do a load.
1853     if (VA.getLocInfo() == CCValAssign::Indirect)
1854       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1855                              MachinePointerInfo(), false, false, false, 0);
1856
1857     InVals.push_back(ArgValue);
1858   }
1859
1860   // The x86-64 ABI for returning structs by value requires that we copy
1861   // the sret argument into %rax for the return. Save the argument into
1862   // a virtual register so that we can access it from the return points.
1863   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1864     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1865     unsigned Reg = FuncInfo->getSRetReturnReg();
1866     if (!Reg) {
1867       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1868       FuncInfo->setSRetReturnReg(Reg);
1869     }
1870     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1871     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1872   }
1873
1874   unsigned StackSize = CCInfo.getNextStackOffset();
1875   // Align stack specially for tail calls.
1876   if (FuncIsMadeTailCallSafe(CallConv))
1877     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1878
1879   // If the function takes variable number of arguments, make a frame index for
1880   // the start of the first vararg value... for expansion of llvm.va_start.
1881   if (isVarArg) {
1882     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1883                     CallConv != CallingConv::X86_ThisCall)) {
1884       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1885     }
1886     if (Is64Bit) {
1887       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1888
1889       // FIXME: We should really autogenerate these arrays
1890       static const unsigned GPR64ArgRegsWin64[] = {
1891         X86::RCX, X86::RDX, X86::R8,  X86::R9
1892       };
1893       static const unsigned GPR64ArgRegs64Bit[] = {
1894         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1895       };
1896       static const unsigned XMMArgRegs64Bit[] = {
1897         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1898         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1899       };
1900       const unsigned *GPR64ArgRegs;
1901       unsigned NumXMMRegs = 0;
1902
1903       if (IsWin64) {
1904         // The XMM registers which might contain var arg parameters are shadowed
1905         // in their paired GPR.  So we only need to save the GPR to their home
1906         // slots.
1907         TotalNumIntRegs = 4;
1908         GPR64ArgRegs = GPR64ArgRegsWin64;
1909       } else {
1910         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1911         GPR64ArgRegs = GPR64ArgRegs64Bit;
1912
1913         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1914       }
1915       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1916                                                        TotalNumIntRegs);
1917
1918       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1919       assert(!(NumXMMRegs && !Subtarget->hasXMM()) &&
1920              "SSE register cannot be used when SSE is disabled!");
1921       assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1922              "SSE register cannot be used when SSE is disabled!");
1923       if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasXMM())
1924         // Kernel mode asks for SSE to be disabled, so don't push them
1925         // on the stack.
1926         TotalNumXMMRegs = 0;
1927
1928       if (IsWin64) {
1929         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1930         // Get to the caller-allocated home save location.  Add 8 to account
1931         // for the return address.
1932         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1933         FuncInfo->setRegSaveFrameIndex(
1934           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1935         // Fixup to set vararg frame on shadow area (4 x i64).
1936         if (NumIntRegs < 4)
1937           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1938       } else {
1939         // For X86-64, if there are vararg parameters that are passed via
1940         // registers, then we must store them to their spots on the stack so they
1941         // may be loaded by deferencing the result of va_next.
1942         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1943         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1944         FuncInfo->setRegSaveFrameIndex(
1945           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1946                                false));
1947       }
1948
1949       // Store the integer parameter registers.
1950       SmallVector<SDValue, 8> MemOps;
1951       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1952                                         getPointerTy());
1953       unsigned Offset = FuncInfo->getVarArgsGPOffset();
1954       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1955         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1956                                   DAG.getIntPtrConstant(Offset));
1957         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1958                                      X86::GR64RegisterClass);
1959         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1960         SDValue Store =
1961           DAG.getStore(Val.getValue(1), dl, Val, FIN,
1962                        MachinePointerInfo::getFixedStack(
1963                          FuncInfo->getRegSaveFrameIndex(), Offset),
1964                        false, false, 0);
1965         MemOps.push_back(Store);
1966         Offset += 8;
1967       }
1968
1969       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1970         // Now store the XMM (fp + vector) parameter registers.
1971         SmallVector<SDValue, 11> SaveXMMOps;
1972         SaveXMMOps.push_back(Chain);
1973
1974         unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1975         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1976         SaveXMMOps.push_back(ALVal);
1977
1978         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1979                                FuncInfo->getRegSaveFrameIndex()));
1980         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1981                                FuncInfo->getVarArgsFPOffset()));
1982
1983         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1984           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
1985                                        X86::VR128RegisterClass);
1986           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1987           SaveXMMOps.push_back(Val);
1988         }
1989         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1990                                      MVT::Other,
1991                                      &SaveXMMOps[0], SaveXMMOps.size()));
1992       }
1993
1994       if (!MemOps.empty())
1995         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1996                             &MemOps[0], MemOps.size());
1997     }
1998   }
1999
2000   // Some CCs need callee pop.
2001   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt)) {
2002     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2003   } else {
2004     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2005     // If this is an sret function, the return should pop the hidden pointer.
2006     if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
2007       FuncInfo->setBytesToPopOnReturn(4);
2008   }
2009
2010   if (!Is64Bit) {
2011     // RegSaveFrameIndex is X86-64 only.
2012     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2013     if (CallConv == CallingConv::X86_FastCall ||
2014         CallConv == CallingConv::X86_ThisCall)
2015       // fastcc functions can't have varargs.
2016       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2017   }
2018
2019   FuncInfo->setArgumentStackSize(StackSize);
2020
2021   return Chain;
2022 }
2023
2024 SDValue
2025 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2026                                     SDValue StackPtr, SDValue Arg,
2027                                     DebugLoc dl, SelectionDAG &DAG,
2028                                     const CCValAssign &VA,
2029                                     ISD::ArgFlagsTy Flags) const {
2030   unsigned LocMemOffset = VA.getLocMemOffset();
2031   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2032   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2033   if (Flags.isByVal())
2034     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2035
2036   return DAG.getStore(Chain, dl, Arg, PtrOff,
2037                       MachinePointerInfo::getStack(LocMemOffset),
2038                       false, false, 0);
2039 }
2040
2041 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2042 /// optimization is performed and it is required.
2043 SDValue
2044 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2045                                            SDValue &OutRetAddr, SDValue Chain,
2046                                            bool IsTailCall, bool Is64Bit,
2047                                            int FPDiff, DebugLoc dl) const {
2048   // Adjust the Return address stack slot.
2049   EVT VT = getPointerTy();
2050   OutRetAddr = getReturnAddressFrameIndex(DAG);
2051
2052   // Load the "old" Return address.
2053   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2054                            false, false, false, 0);
2055   return SDValue(OutRetAddr.getNode(), 1);
2056 }
2057
2058 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2059 /// optimization is performed and it is required (FPDiff!=0).
2060 static SDValue
2061 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2062                          SDValue Chain, SDValue RetAddrFrIdx,
2063                          bool Is64Bit, int FPDiff, DebugLoc dl) {
2064   // Store the return address to the appropriate stack slot.
2065   if (!FPDiff) return Chain;
2066   // Calculate the new stack slot for the return address.
2067   int SlotSize = Is64Bit ? 8 : 4;
2068   int NewReturnAddrFI =
2069     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2070   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2071   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
2072   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2073                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2074                        false, false, 0);
2075   return Chain;
2076 }
2077
2078 SDValue
2079 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
2080                              CallingConv::ID CallConv, bool isVarArg,
2081                              bool &isTailCall,
2082                              const SmallVectorImpl<ISD::OutputArg> &Outs,
2083                              const SmallVectorImpl<SDValue> &OutVals,
2084                              const SmallVectorImpl<ISD::InputArg> &Ins,
2085                              DebugLoc dl, SelectionDAG &DAG,
2086                              SmallVectorImpl<SDValue> &InVals) const {
2087   MachineFunction &MF = DAG.getMachineFunction();
2088   bool Is64Bit        = Subtarget->is64Bit();
2089   bool IsWin64        = Subtarget->isTargetWin64();
2090   bool IsStructRet    = CallIsStructReturn(Outs);
2091   bool IsSibcall      = false;
2092
2093   if (isTailCall) {
2094     // Check if it's really possible to do a tail call.
2095     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2096                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
2097                                                    Outs, OutVals, Ins, DAG);
2098
2099     // Sibcalls are automatically detected tailcalls which do not require
2100     // ABI changes.
2101     if (!GuaranteedTailCallOpt && isTailCall)
2102       IsSibcall = true;
2103
2104     if (isTailCall)
2105       ++NumTailCalls;
2106   }
2107
2108   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2109          "Var args not supported with calling convention fastcc or ghc");
2110
2111   // Analyze operands of the call, assigning locations to each operand.
2112   SmallVector<CCValAssign, 16> ArgLocs;
2113   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2114                  ArgLocs, *DAG.getContext());
2115
2116   // Allocate shadow area for Win64
2117   if (IsWin64) {
2118     CCInfo.AllocateStack(32, 8);
2119   }
2120
2121   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2122
2123   // Get a count of how many bytes are to be pushed on the stack.
2124   unsigned NumBytes = CCInfo.getNextStackOffset();
2125   if (IsSibcall)
2126     // This is a sibcall. The memory operands are available in caller's
2127     // own caller's stack.
2128     NumBytes = 0;
2129   else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
2130     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2131
2132   int FPDiff = 0;
2133   if (isTailCall && !IsSibcall) {
2134     // Lower arguments at fp - stackoffset + fpdiff.
2135     unsigned NumBytesCallerPushed =
2136       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2137     FPDiff = NumBytesCallerPushed - NumBytes;
2138
2139     // Set the delta of movement of the returnaddr stackslot.
2140     // But only set if delta is greater than previous delta.
2141     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2142       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2143   }
2144
2145   if (!IsSibcall)
2146     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2147
2148   SDValue RetAddrFrIdx;
2149   // Load return address for tail calls.
2150   if (isTailCall && FPDiff)
2151     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2152                                     Is64Bit, FPDiff, dl);
2153
2154   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2155   SmallVector<SDValue, 8> MemOpChains;
2156   SDValue StackPtr;
2157
2158   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2159   // of tail call optimization arguments are handle later.
2160   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2161     CCValAssign &VA = ArgLocs[i];
2162     EVT RegVT = VA.getLocVT();
2163     SDValue Arg = OutVals[i];
2164     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2165     bool isByVal = Flags.isByVal();
2166
2167     // Promote the value if needed.
2168     switch (VA.getLocInfo()) {
2169     default: llvm_unreachable("Unknown loc info!");
2170     case CCValAssign::Full: break;
2171     case CCValAssign::SExt:
2172       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2173       break;
2174     case CCValAssign::ZExt:
2175       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2176       break;
2177     case CCValAssign::AExt:
2178       if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2179         // Special case: passing MMX values in XMM registers.
2180         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2181         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2182         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2183       } else
2184         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2185       break;
2186     case CCValAssign::BCvt:
2187       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2188       break;
2189     case CCValAssign::Indirect: {
2190       // Store the argument.
2191       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2192       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2193       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2194                            MachinePointerInfo::getFixedStack(FI),
2195                            false, false, 0);
2196       Arg = SpillSlot;
2197       break;
2198     }
2199     }
2200
2201     if (VA.isRegLoc()) {
2202       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2203       if (isVarArg && IsWin64) {
2204         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2205         // shadow reg if callee is a varargs function.
2206         unsigned ShadowReg = 0;
2207         switch (VA.getLocReg()) {
2208         case X86::XMM0: ShadowReg = X86::RCX; break;
2209         case X86::XMM1: ShadowReg = X86::RDX; break;
2210         case X86::XMM2: ShadowReg = X86::R8; break;
2211         case X86::XMM3: ShadowReg = X86::R9; break;
2212         }
2213         if (ShadowReg)
2214           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2215       }
2216     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2217       assert(VA.isMemLoc());
2218       if (StackPtr.getNode() == 0)
2219         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2220       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2221                                              dl, DAG, VA, Flags));
2222     }
2223   }
2224
2225   if (!MemOpChains.empty())
2226     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2227                         &MemOpChains[0], MemOpChains.size());
2228
2229   // Build a sequence of copy-to-reg nodes chained together with token chain
2230   // and flag operands which copy the outgoing args into registers.
2231   SDValue InFlag;
2232   // Tail call byval lowering might overwrite argument registers so in case of
2233   // tail call optimization the copies to registers are lowered later.
2234   if (!isTailCall)
2235     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2236       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2237                                RegsToPass[i].second, InFlag);
2238       InFlag = Chain.getValue(1);
2239     }
2240
2241   if (Subtarget->isPICStyleGOT()) {
2242     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2243     // GOT pointer.
2244     if (!isTailCall) {
2245       Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2246                                DAG.getNode(X86ISD::GlobalBaseReg,
2247                                            DebugLoc(), getPointerTy()),
2248                                InFlag);
2249       InFlag = Chain.getValue(1);
2250     } else {
2251       // If we are tail calling and generating PIC/GOT style code load the
2252       // address of the callee into ECX. The value in ecx is used as target of
2253       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2254       // for tail calls on PIC/GOT architectures. Normally we would just put the
2255       // address of GOT into ebx and then call target@PLT. But for tail calls
2256       // ebx would be restored (since ebx is callee saved) before jumping to the
2257       // target@PLT.
2258
2259       // Note: The actual moving to ECX is done further down.
2260       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2261       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2262           !G->getGlobal()->hasProtectedVisibility())
2263         Callee = LowerGlobalAddress(Callee, DAG);
2264       else if (isa<ExternalSymbolSDNode>(Callee))
2265         Callee = LowerExternalSymbol(Callee, DAG);
2266     }
2267   }
2268
2269   if (Is64Bit && isVarArg && !IsWin64) {
2270     // From AMD64 ABI document:
2271     // For calls that may call functions that use varargs or stdargs
2272     // (prototype-less calls or calls to functions containing ellipsis (...) in
2273     // the declaration) %al is used as hidden argument to specify the number
2274     // of SSE registers used. The contents of %al do not need to match exactly
2275     // the number of registers, but must be an ubound on the number of SSE
2276     // registers used and is in the range 0 - 8 inclusive.
2277
2278     // Count the number of XMM registers allocated.
2279     static const unsigned XMMArgRegs[] = {
2280       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2281       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2282     };
2283     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2284     assert((Subtarget->hasXMM() || !NumXMMRegs)
2285            && "SSE registers cannot be used when SSE is disabled");
2286
2287     Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2288                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2289     InFlag = Chain.getValue(1);
2290   }
2291
2292
2293   // For tail calls lower the arguments to the 'real' stack slot.
2294   if (isTailCall) {
2295     // Force all the incoming stack arguments to be loaded from the stack
2296     // before any new outgoing arguments are stored to the stack, because the
2297     // outgoing stack slots may alias the incoming argument stack slots, and
2298     // the alias isn't otherwise explicit. This is slightly more conservative
2299     // than necessary, because it means that each store effectively depends
2300     // on every argument instead of just those arguments it would clobber.
2301     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2302
2303     SmallVector<SDValue, 8> MemOpChains2;
2304     SDValue FIN;
2305     int FI = 0;
2306     // Do not flag preceding copytoreg stuff together with the following stuff.
2307     InFlag = SDValue();
2308     if (GuaranteedTailCallOpt) {
2309       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2310         CCValAssign &VA = ArgLocs[i];
2311         if (VA.isRegLoc())
2312           continue;
2313         assert(VA.isMemLoc());
2314         SDValue Arg = OutVals[i];
2315         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2316         // Create frame index.
2317         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2318         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2319         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2320         FIN = DAG.getFrameIndex(FI, getPointerTy());
2321
2322         if (Flags.isByVal()) {
2323           // Copy relative to framepointer.
2324           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2325           if (StackPtr.getNode() == 0)
2326             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2327                                           getPointerTy());
2328           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2329
2330           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2331                                                            ArgChain,
2332                                                            Flags, DAG, dl));
2333         } else {
2334           // Store relative to framepointer.
2335           MemOpChains2.push_back(
2336             DAG.getStore(ArgChain, dl, Arg, FIN,
2337                          MachinePointerInfo::getFixedStack(FI),
2338                          false, false, 0));
2339         }
2340       }
2341     }
2342
2343     if (!MemOpChains2.empty())
2344       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2345                           &MemOpChains2[0], MemOpChains2.size());
2346
2347     // Copy arguments to their registers.
2348     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2349       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2350                                RegsToPass[i].second, InFlag);
2351       InFlag = Chain.getValue(1);
2352     }
2353     InFlag =SDValue();
2354
2355     // Store the return address to the appropriate stack slot.
2356     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2357                                      FPDiff, dl);
2358   }
2359
2360   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2361     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2362     // In the 64-bit large code model, we have to make all calls
2363     // through a register, since the call instruction's 32-bit
2364     // pc-relative offset may not be large enough to hold the whole
2365     // address.
2366   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2367     // If the callee is a GlobalAddress node (quite common, every direct call
2368     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2369     // it.
2370
2371     // We should use extra load for direct calls to dllimported functions in
2372     // non-JIT mode.
2373     const GlobalValue *GV = G->getGlobal();
2374     if (!GV->hasDLLImportLinkage()) {
2375       unsigned char OpFlags = 0;
2376       bool ExtraLoad = false;
2377       unsigned WrapperKind = ISD::DELETED_NODE;
2378
2379       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2380       // external symbols most go through the PLT in PIC mode.  If the symbol
2381       // has hidden or protected visibility, or if it is static or local, then
2382       // we don't need to use the PLT - we can directly call it.
2383       if (Subtarget->isTargetELF() &&
2384           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2385           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2386         OpFlags = X86II::MO_PLT;
2387       } else if (Subtarget->isPICStyleStubAny() &&
2388                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2389                  (!Subtarget->getTargetTriple().isMacOSX() ||
2390                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2391         // PC-relative references to external symbols should go through $stub,
2392         // unless we're building with the leopard linker or later, which
2393         // automatically synthesizes these stubs.
2394         OpFlags = X86II::MO_DARWIN_STUB;
2395       } else if (Subtarget->isPICStyleRIPRel() &&
2396                  isa<Function>(GV) &&
2397                  cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2398         // If the function is marked as non-lazy, generate an indirect call
2399         // which loads from the GOT directly. This avoids runtime overhead
2400         // at the cost of eager binding (and one extra byte of encoding).
2401         OpFlags = X86II::MO_GOTPCREL;
2402         WrapperKind = X86ISD::WrapperRIP;
2403         ExtraLoad = true;
2404       }
2405
2406       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2407                                           G->getOffset(), OpFlags);
2408
2409       // Add a wrapper if needed.
2410       if (WrapperKind != ISD::DELETED_NODE)
2411         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2412       // Add extra indirection if needed.
2413       if (ExtraLoad)
2414         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2415                              MachinePointerInfo::getGOT(),
2416                              false, false, false, 0);
2417     }
2418   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2419     unsigned char OpFlags = 0;
2420
2421     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2422     // external symbols should go through the PLT.
2423     if (Subtarget->isTargetELF() &&
2424         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2425       OpFlags = X86II::MO_PLT;
2426     } else if (Subtarget->isPICStyleStubAny() &&
2427                (!Subtarget->getTargetTriple().isMacOSX() ||
2428                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2429       // PC-relative references to external symbols should go through $stub,
2430       // unless we're building with the leopard linker or later, which
2431       // automatically synthesizes these stubs.
2432       OpFlags = X86II::MO_DARWIN_STUB;
2433     }
2434
2435     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2436                                          OpFlags);
2437   }
2438
2439   // Returns a chain & a flag for retval copy to use.
2440   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2441   SmallVector<SDValue, 8> Ops;
2442
2443   if (!IsSibcall && isTailCall) {
2444     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2445                            DAG.getIntPtrConstant(0, true), InFlag);
2446     InFlag = Chain.getValue(1);
2447   }
2448
2449   Ops.push_back(Chain);
2450   Ops.push_back(Callee);
2451
2452   if (isTailCall)
2453     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2454
2455   // Add argument registers to the end of the list so that they are known live
2456   // into the call.
2457   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2458     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2459                                   RegsToPass[i].second.getValueType()));
2460
2461   // Add an implicit use GOT pointer in EBX.
2462   if (!isTailCall && Subtarget->isPICStyleGOT())
2463     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2464
2465   // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2466   if (Is64Bit && isVarArg && !IsWin64)
2467     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2468
2469   if (InFlag.getNode())
2470     Ops.push_back(InFlag);
2471
2472   if (isTailCall) {
2473     // We used to do:
2474     //// If this is the first return lowered for this function, add the regs
2475     //// to the liveout set for the function.
2476     // This isn't right, although it's probably harmless on x86; liveouts
2477     // should be computed from returns not tail calls.  Consider a void
2478     // function making a tail call to a function returning int.
2479     return DAG.getNode(X86ISD::TC_RETURN, dl,
2480                        NodeTys, &Ops[0], Ops.size());
2481   }
2482
2483   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2484   InFlag = Chain.getValue(1);
2485
2486   // Create the CALLSEQ_END node.
2487   unsigned NumBytesForCalleeToPush;
2488   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt))
2489     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2490   else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2491     // If this is a call to a struct-return function, the callee
2492     // pops the hidden struct pointer, so we have to push it back.
2493     // This is common for Darwin/X86, Linux & Mingw32 targets.
2494     NumBytesForCalleeToPush = 4;
2495   else
2496     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2497
2498   // Returns a flag for retval copy to use.
2499   if (!IsSibcall) {
2500     Chain = DAG.getCALLSEQ_END(Chain,
2501                                DAG.getIntPtrConstant(NumBytes, true),
2502                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2503                                                      true),
2504                                InFlag);
2505     InFlag = Chain.getValue(1);
2506   }
2507
2508   // Handle result values, copying them out of physregs into vregs that we
2509   // return.
2510   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2511                          Ins, dl, DAG, InVals);
2512 }
2513
2514
2515 //===----------------------------------------------------------------------===//
2516 //                Fast Calling Convention (tail call) implementation
2517 //===----------------------------------------------------------------------===//
2518
2519 //  Like std call, callee cleans arguments, convention except that ECX is
2520 //  reserved for storing the tail called function address. Only 2 registers are
2521 //  free for argument passing (inreg). Tail call optimization is performed
2522 //  provided:
2523 //                * tailcallopt is enabled
2524 //                * caller/callee are fastcc
2525 //  On X86_64 architecture with GOT-style position independent code only local
2526 //  (within module) calls are supported at the moment.
2527 //  To keep the stack aligned according to platform abi the function
2528 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2529 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2530 //  If a tail called function callee has more arguments than the caller the
2531 //  caller needs to make sure that there is room to move the RETADDR to. This is
2532 //  achieved by reserving an area the size of the argument delta right after the
2533 //  original REtADDR, but before the saved framepointer or the spilled registers
2534 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2535 //  stack layout:
2536 //    arg1
2537 //    arg2
2538 //    RETADDR
2539 //    [ new RETADDR
2540 //      move area ]
2541 //    (possible EBP)
2542 //    ESI
2543 //    EDI
2544 //    local1 ..
2545
2546 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2547 /// for a 16 byte align requirement.
2548 unsigned
2549 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2550                                                SelectionDAG& DAG) const {
2551   MachineFunction &MF = DAG.getMachineFunction();
2552   const TargetMachine &TM = MF.getTarget();
2553   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2554   unsigned StackAlignment = TFI.getStackAlignment();
2555   uint64_t AlignMask = StackAlignment - 1;
2556   int64_t Offset = StackSize;
2557   uint64_t SlotSize = TD->getPointerSize();
2558   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2559     // Number smaller than 12 so just add the difference.
2560     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2561   } else {
2562     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2563     Offset = ((~AlignMask) & Offset) + StackAlignment +
2564       (StackAlignment-SlotSize);
2565   }
2566   return Offset;
2567 }
2568
2569 /// MatchingStackOffset - Return true if the given stack call argument is
2570 /// already available in the same position (relatively) of the caller's
2571 /// incoming argument stack.
2572 static
2573 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2574                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2575                          const X86InstrInfo *TII) {
2576   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2577   int FI = INT_MAX;
2578   if (Arg.getOpcode() == ISD::CopyFromReg) {
2579     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2580     if (!TargetRegisterInfo::isVirtualRegister(VR))
2581       return false;
2582     MachineInstr *Def = MRI->getVRegDef(VR);
2583     if (!Def)
2584       return false;
2585     if (!Flags.isByVal()) {
2586       if (!TII->isLoadFromStackSlot(Def, FI))
2587         return false;
2588     } else {
2589       unsigned Opcode = Def->getOpcode();
2590       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2591           Def->getOperand(1).isFI()) {
2592         FI = Def->getOperand(1).getIndex();
2593         Bytes = Flags.getByValSize();
2594       } else
2595         return false;
2596     }
2597   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2598     if (Flags.isByVal())
2599       // ByVal argument is passed in as a pointer but it's now being
2600       // dereferenced. e.g.
2601       // define @foo(%struct.X* %A) {
2602       //   tail call @bar(%struct.X* byval %A)
2603       // }
2604       return false;
2605     SDValue Ptr = Ld->getBasePtr();
2606     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2607     if (!FINode)
2608       return false;
2609     FI = FINode->getIndex();
2610   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2611     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2612     FI = FINode->getIndex();
2613     Bytes = Flags.getByValSize();
2614   } else
2615     return false;
2616
2617   assert(FI != INT_MAX);
2618   if (!MFI->isFixedObjectIndex(FI))
2619     return false;
2620   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2621 }
2622
2623 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2624 /// for tail call optimization. Targets which want to do tail call
2625 /// optimization should implement this function.
2626 bool
2627 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2628                                                      CallingConv::ID CalleeCC,
2629                                                      bool isVarArg,
2630                                                      bool isCalleeStructRet,
2631                                                      bool isCallerStructRet,
2632                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2633                                     const SmallVectorImpl<SDValue> &OutVals,
2634                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2635                                                      SelectionDAG& DAG) const {
2636   if (!IsTailCallConvention(CalleeCC) &&
2637       CalleeCC != CallingConv::C)
2638     return false;
2639
2640   // If -tailcallopt is specified, make fastcc functions tail-callable.
2641   const MachineFunction &MF = DAG.getMachineFunction();
2642   const Function *CallerF = DAG.getMachineFunction().getFunction();
2643   CallingConv::ID CallerCC = CallerF->getCallingConv();
2644   bool CCMatch = CallerCC == CalleeCC;
2645
2646   if (GuaranteedTailCallOpt) {
2647     if (IsTailCallConvention(CalleeCC) && CCMatch)
2648       return true;
2649     return false;
2650   }
2651
2652   // Look for obvious safe cases to perform tail call optimization that do not
2653   // require ABI changes. This is what gcc calls sibcall.
2654
2655   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2656   // emit a special epilogue.
2657   if (RegInfo->needsStackRealignment(MF))
2658     return false;
2659
2660   // Also avoid sibcall optimization if either caller or callee uses struct
2661   // return semantics.
2662   if (isCalleeStructRet || isCallerStructRet)
2663     return false;
2664
2665   // An stdcall caller is expected to clean up its arguments; the callee
2666   // isn't going to do that.
2667   if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2668     return false;
2669
2670   // Do not sibcall optimize vararg calls unless all arguments are passed via
2671   // registers.
2672   if (isVarArg && !Outs.empty()) {
2673
2674     // Optimizing for varargs on Win64 is unlikely to be safe without
2675     // additional testing.
2676     if (Subtarget->isTargetWin64())
2677       return false;
2678
2679     SmallVector<CCValAssign, 16> ArgLocs;
2680     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2681                    getTargetMachine(), ArgLocs, *DAG.getContext());
2682
2683     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2684     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2685       if (!ArgLocs[i].isRegLoc())
2686         return false;
2687   }
2688
2689   // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2690   // Therefore if it's not used by the call it is not safe to optimize this into
2691   // a sibcall.
2692   bool Unused = false;
2693   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2694     if (!Ins[i].Used) {
2695       Unused = true;
2696       break;
2697     }
2698   }
2699   if (Unused) {
2700     SmallVector<CCValAssign, 16> RVLocs;
2701     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2702                    getTargetMachine(), RVLocs, *DAG.getContext());
2703     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2704     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2705       CCValAssign &VA = RVLocs[i];
2706       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2707         return false;
2708     }
2709   }
2710
2711   // If the calling conventions do not match, then we'd better make sure the
2712   // results are returned in the same way as what the caller expects.
2713   if (!CCMatch) {
2714     SmallVector<CCValAssign, 16> RVLocs1;
2715     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2716                     getTargetMachine(), RVLocs1, *DAG.getContext());
2717     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2718
2719     SmallVector<CCValAssign, 16> RVLocs2;
2720     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2721                     getTargetMachine(), RVLocs2, *DAG.getContext());
2722     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2723
2724     if (RVLocs1.size() != RVLocs2.size())
2725       return false;
2726     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2727       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2728         return false;
2729       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2730         return false;
2731       if (RVLocs1[i].isRegLoc()) {
2732         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2733           return false;
2734       } else {
2735         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2736           return false;
2737       }
2738     }
2739   }
2740
2741   // If the callee takes no arguments then go on to check the results of the
2742   // call.
2743   if (!Outs.empty()) {
2744     // Check if stack adjustment is needed. For now, do not do this if any
2745     // argument is passed on the stack.
2746     SmallVector<CCValAssign, 16> ArgLocs;
2747     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2748                    getTargetMachine(), ArgLocs, *DAG.getContext());
2749
2750     // Allocate shadow area for Win64
2751     if (Subtarget->isTargetWin64()) {
2752       CCInfo.AllocateStack(32, 8);
2753     }
2754
2755     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2756     if (CCInfo.getNextStackOffset()) {
2757       MachineFunction &MF = DAG.getMachineFunction();
2758       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2759         return false;
2760
2761       // Check if the arguments are already laid out in the right way as
2762       // the caller's fixed stack objects.
2763       MachineFrameInfo *MFI = MF.getFrameInfo();
2764       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2765       const X86InstrInfo *TII =
2766         ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2767       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2768         CCValAssign &VA = ArgLocs[i];
2769         SDValue Arg = OutVals[i];
2770         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2771         if (VA.getLocInfo() == CCValAssign::Indirect)
2772           return false;
2773         if (!VA.isRegLoc()) {
2774           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2775                                    MFI, MRI, TII))
2776             return false;
2777         }
2778       }
2779     }
2780
2781     // If the tailcall address may be in a register, then make sure it's
2782     // possible to register allocate for it. In 32-bit, the call address can
2783     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2784     // callee-saved registers are restored. These happen to be the same
2785     // registers used to pass 'inreg' arguments so watch out for those.
2786     if (!Subtarget->is64Bit() &&
2787         !isa<GlobalAddressSDNode>(Callee) &&
2788         !isa<ExternalSymbolSDNode>(Callee)) {
2789       unsigned NumInRegs = 0;
2790       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2791         CCValAssign &VA = ArgLocs[i];
2792         if (!VA.isRegLoc())
2793           continue;
2794         unsigned Reg = VA.getLocReg();
2795         switch (Reg) {
2796         default: break;
2797         case X86::EAX: case X86::EDX: case X86::ECX:
2798           if (++NumInRegs == 3)
2799             return false;
2800           break;
2801         }
2802       }
2803     }
2804   }
2805
2806   return true;
2807 }
2808
2809 FastISel *
2810 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2811   return X86::createFastISel(funcInfo);
2812 }
2813
2814
2815 //===----------------------------------------------------------------------===//
2816 //                           Other Lowering Hooks
2817 //===----------------------------------------------------------------------===//
2818
2819 static bool MayFoldLoad(SDValue Op) {
2820   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2821 }
2822
2823 static bool MayFoldIntoStore(SDValue Op) {
2824   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2825 }
2826
2827 static bool isTargetShuffle(unsigned Opcode) {
2828   switch(Opcode) {
2829   default: return false;
2830   case X86ISD::PSHUFD:
2831   case X86ISD::PSHUFHW:
2832   case X86ISD::PSHUFLW:
2833   case X86ISD::SHUFPD:
2834   case X86ISD::PALIGN:
2835   case X86ISD::SHUFPS:
2836   case X86ISD::MOVLHPS:
2837   case X86ISD::MOVLHPD:
2838   case X86ISD::MOVHLPS:
2839   case X86ISD::MOVLPS:
2840   case X86ISD::MOVLPD:
2841   case X86ISD::MOVSHDUP:
2842   case X86ISD::MOVSLDUP:
2843   case X86ISD::MOVDDUP:
2844   case X86ISD::MOVSS:
2845   case X86ISD::MOVSD:
2846   case X86ISD::UNPCKLPS:
2847   case X86ISD::UNPCKLPD:
2848   case X86ISD::VUNPCKLPSY:
2849   case X86ISD::VUNPCKLPDY:
2850   case X86ISD::PUNPCKLWD:
2851   case X86ISD::PUNPCKLBW:
2852   case X86ISD::PUNPCKLDQ:
2853   case X86ISD::PUNPCKLQDQ:
2854   case X86ISD::VPUNPCKLWDY:
2855   case X86ISD::VPUNPCKLBWY:
2856   case X86ISD::VPUNPCKLDQY:
2857   case X86ISD::VPUNPCKLQDQY:
2858   case X86ISD::UNPCKHPS:
2859   case X86ISD::UNPCKHPD:
2860   case X86ISD::VUNPCKHPSY:
2861   case X86ISD::VUNPCKHPDY:
2862   case X86ISD::PUNPCKHWD:
2863   case X86ISD::PUNPCKHBW:
2864   case X86ISD::PUNPCKHDQ:
2865   case X86ISD::PUNPCKHQDQ:
2866   case X86ISD::VPUNPCKHWDY:
2867   case X86ISD::VPUNPCKHBWY:
2868   case X86ISD::VPUNPCKHDQY:
2869   case X86ISD::VPUNPCKHQDQY:
2870   case X86ISD::VPERMILPS:
2871   case X86ISD::VPERMILPSY:
2872   case X86ISD::VPERMILPD:
2873   case X86ISD::VPERMILPDY:
2874   case X86ISD::VPERM2F128:
2875     return true;
2876   }
2877   return false;
2878 }
2879
2880 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2881                                                SDValue V1, SelectionDAG &DAG) {
2882   switch(Opc) {
2883   default: llvm_unreachable("Unknown x86 shuffle node");
2884   case X86ISD::MOVSHDUP:
2885   case X86ISD::MOVSLDUP:
2886   case X86ISD::MOVDDUP:
2887     return DAG.getNode(Opc, dl, VT, V1);
2888   }
2889
2890   return SDValue();
2891 }
2892
2893 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2894                           SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2895   switch(Opc) {
2896   default: llvm_unreachable("Unknown x86 shuffle node");
2897   case X86ISD::PSHUFD:
2898   case X86ISD::PSHUFHW:
2899   case X86ISD::PSHUFLW:
2900   case X86ISD::VPERMILPS:
2901   case X86ISD::VPERMILPSY:
2902   case X86ISD::VPERMILPD:
2903   case X86ISD::VPERMILPDY:
2904     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2905   }
2906
2907   return SDValue();
2908 }
2909
2910 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2911                SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2912   switch(Opc) {
2913   default: llvm_unreachable("Unknown x86 shuffle node");
2914   case X86ISD::PALIGN:
2915   case X86ISD::SHUFPD:
2916   case X86ISD::SHUFPS:
2917   case X86ISD::VPERM2F128:
2918     return DAG.getNode(Opc, dl, VT, V1, V2,
2919                        DAG.getConstant(TargetMask, MVT::i8));
2920   }
2921   return SDValue();
2922 }
2923
2924 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2925                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
2926   switch(Opc) {
2927   default: llvm_unreachable("Unknown x86 shuffle node");
2928   case X86ISD::MOVLHPS:
2929   case X86ISD::MOVLHPD:
2930   case X86ISD::MOVHLPS:
2931   case X86ISD::MOVLPS:
2932   case X86ISD::MOVLPD:
2933   case X86ISD::MOVSS:
2934   case X86ISD::MOVSD:
2935   case X86ISD::UNPCKLPS:
2936   case X86ISD::UNPCKLPD:
2937   case X86ISD::VUNPCKLPSY:
2938   case X86ISD::VUNPCKLPDY:
2939   case X86ISD::PUNPCKLWD:
2940   case X86ISD::PUNPCKLBW:
2941   case X86ISD::PUNPCKLDQ:
2942   case X86ISD::PUNPCKLQDQ:
2943   case X86ISD::VPUNPCKLWDY:
2944   case X86ISD::VPUNPCKLBWY:
2945   case X86ISD::VPUNPCKLDQY:
2946   case X86ISD::VPUNPCKLQDQY:
2947   case X86ISD::UNPCKHPS:
2948   case X86ISD::UNPCKHPD:
2949   case X86ISD::VUNPCKHPSY:
2950   case X86ISD::VUNPCKHPDY:
2951   case X86ISD::PUNPCKHWD:
2952   case X86ISD::PUNPCKHBW:
2953   case X86ISD::PUNPCKHDQ:
2954   case X86ISD::PUNPCKHQDQ:
2955   case X86ISD::VPUNPCKHWDY:
2956   case X86ISD::VPUNPCKHBWY:
2957   case X86ISD::VPUNPCKHDQY:
2958   case X86ISD::VPUNPCKHQDQY:
2959     return DAG.getNode(Opc, dl, VT, V1, V2);
2960   }
2961   return SDValue();
2962 }
2963
2964 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2965   MachineFunction &MF = DAG.getMachineFunction();
2966   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2967   int ReturnAddrIndex = FuncInfo->getRAIndex();
2968
2969   if (ReturnAddrIndex == 0) {
2970     // Set up a frame object for the return address.
2971     uint64_t SlotSize = TD->getPointerSize();
2972     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2973                                                            false);
2974     FuncInfo->setRAIndex(ReturnAddrIndex);
2975   }
2976
2977   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2978 }
2979
2980
2981 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2982                                        bool hasSymbolicDisplacement) {
2983   // Offset should fit into 32 bit immediate field.
2984   if (!isInt<32>(Offset))
2985     return false;
2986
2987   // If we don't have a symbolic displacement - we don't have any extra
2988   // restrictions.
2989   if (!hasSymbolicDisplacement)
2990     return true;
2991
2992   // FIXME: Some tweaks might be needed for medium code model.
2993   if (M != CodeModel::Small && M != CodeModel::Kernel)
2994     return false;
2995
2996   // For small code model we assume that latest object is 16MB before end of 31
2997   // bits boundary. We may also accept pretty large negative constants knowing
2998   // that all objects are in the positive half of address space.
2999   if (M == CodeModel::Small && Offset < 16*1024*1024)
3000     return true;
3001
3002   // For kernel code model we know that all object resist in the negative half
3003   // of 32bits address space. We may not accept negative offsets, since they may
3004   // be just off and we may accept pretty large positive ones.
3005   if (M == CodeModel::Kernel && Offset > 0)
3006     return true;
3007
3008   return false;
3009 }
3010
3011 /// isCalleePop - Determines whether the callee is required to pop its
3012 /// own arguments. Callee pop is necessary to support tail calls.
3013 bool X86::isCalleePop(CallingConv::ID CallingConv,
3014                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3015   if (IsVarArg)
3016     return false;
3017
3018   switch (CallingConv) {
3019   default:
3020     return false;
3021   case CallingConv::X86_StdCall:
3022     return !is64Bit;
3023   case CallingConv::X86_FastCall:
3024     return !is64Bit;
3025   case CallingConv::X86_ThisCall:
3026     return !is64Bit;
3027   case CallingConv::Fast:
3028     return TailCallOpt;
3029   case CallingConv::GHC:
3030     return TailCallOpt;
3031   }
3032 }
3033
3034 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3035 /// specific condition code, returning the condition code and the LHS/RHS of the
3036 /// comparison to make.
3037 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3038                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3039   if (!isFP) {
3040     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3041       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3042         // X > -1   -> X == 0, jump !sign.
3043         RHS = DAG.getConstant(0, RHS.getValueType());
3044         return X86::COND_NS;
3045       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3046         // X < 0   -> X == 0, jump on sign.
3047         return X86::COND_S;
3048       } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3049         // X < 1   -> X <= 0
3050         RHS = DAG.getConstant(0, RHS.getValueType());
3051         return X86::COND_LE;
3052       }
3053     }
3054
3055     switch (SetCCOpcode) {
3056     default: llvm_unreachable("Invalid integer condition!");
3057     case ISD::SETEQ:  return X86::COND_E;
3058     case ISD::SETGT:  return X86::COND_G;
3059     case ISD::SETGE:  return X86::COND_GE;
3060     case ISD::SETLT:  return X86::COND_L;
3061     case ISD::SETLE:  return X86::COND_LE;
3062     case ISD::SETNE:  return X86::COND_NE;
3063     case ISD::SETULT: return X86::COND_B;
3064     case ISD::SETUGT: return X86::COND_A;
3065     case ISD::SETULE: return X86::COND_BE;
3066     case ISD::SETUGE: return X86::COND_AE;
3067     }
3068   }
3069
3070   // First determine if it is required or is profitable to flip the operands.
3071
3072   // If LHS is a foldable load, but RHS is not, flip the condition.
3073   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3074       !ISD::isNON_EXTLoad(RHS.getNode())) {
3075     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3076     std::swap(LHS, RHS);
3077   }
3078
3079   switch (SetCCOpcode) {
3080   default: break;
3081   case ISD::SETOLT:
3082   case ISD::SETOLE:
3083   case ISD::SETUGT:
3084   case ISD::SETUGE:
3085     std::swap(LHS, RHS);
3086     break;
3087   }
3088
3089   // On a floating point condition, the flags are set as follows:
3090   // ZF  PF  CF   op
3091   //  0 | 0 | 0 | X > Y
3092   //  0 | 0 | 1 | X < Y
3093   //  1 | 0 | 0 | X == Y
3094   //  1 | 1 | 1 | unordered
3095   switch (SetCCOpcode) {
3096   default: llvm_unreachable("Condcode should be pre-legalized away");
3097   case ISD::SETUEQ:
3098   case ISD::SETEQ:   return X86::COND_E;
3099   case ISD::SETOLT:              // flipped
3100   case ISD::SETOGT:
3101   case ISD::SETGT:   return X86::COND_A;
3102   case ISD::SETOLE:              // flipped
3103   case ISD::SETOGE:
3104   case ISD::SETGE:   return X86::COND_AE;
3105   case ISD::SETUGT:              // flipped
3106   case ISD::SETULT:
3107   case ISD::SETLT:   return X86::COND_B;
3108   case ISD::SETUGE:              // flipped
3109   case ISD::SETULE:
3110   case ISD::SETLE:   return X86::COND_BE;
3111   case ISD::SETONE:
3112   case ISD::SETNE:   return X86::COND_NE;
3113   case ISD::SETUO:   return X86::COND_P;
3114   case ISD::SETO:    return X86::COND_NP;
3115   case ISD::SETOEQ:
3116   case ISD::SETUNE:  return X86::COND_INVALID;
3117   }
3118 }
3119
3120 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3121 /// code. Current x86 isa includes the following FP cmov instructions:
3122 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3123 static bool hasFPCMov(unsigned X86CC) {
3124   switch (X86CC) {
3125   default:
3126     return false;
3127   case X86::COND_B:
3128   case X86::COND_BE:
3129   case X86::COND_E:
3130   case X86::COND_P:
3131   case X86::COND_A:
3132   case X86::COND_AE:
3133   case X86::COND_NE:
3134   case X86::COND_NP:
3135     return true;
3136   }
3137 }
3138
3139 /// isFPImmLegal - Returns true if the target can instruction select the
3140 /// specified FP immediate natively. If false, the legalizer will
3141 /// materialize the FP immediate as a load from a constant pool.
3142 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3143   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3144     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3145       return true;
3146   }
3147   return false;
3148 }
3149
3150 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3151 /// the specified range (L, H].
3152 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3153   return (Val < 0) || (Val >= Low && Val < Hi);
3154 }
3155
3156 /// isUndefOrInRange - Return true if every element in Mask, begining
3157 /// from position Pos and ending in Pos+Size, falls within the specified
3158 /// range (L, L+Pos]. or is undef.
3159 static bool isUndefOrInRange(const SmallVectorImpl<int> &Mask,
3160                              int Pos, int Size, int Low, int Hi) {
3161   for (int i = Pos, e = Pos+Size; i != e; ++i)
3162     if (!isUndefOrInRange(Mask[i], Low, Hi))
3163       return false;
3164   return true;
3165 }
3166
3167 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3168 /// specified value.
3169 static bool isUndefOrEqual(int Val, int CmpVal) {
3170   if (Val < 0 || Val == CmpVal)
3171     return true;
3172   return false;
3173 }
3174
3175 /// isSequentialOrUndefInRange - Return true if every element in Mask, begining
3176 /// from position Pos and ending in Pos+Size, falls within the specified
3177 /// sequential range (L, L+Pos]. or is undef.
3178 static bool isSequentialOrUndefInRange(const SmallVectorImpl<int> &Mask,
3179                                        int Pos, int Size, int Low) {
3180   for (int i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3181     if (!isUndefOrEqual(Mask[i], Low))
3182       return false;
3183   return true;
3184 }
3185
3186 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3187 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3188 /// the second operand.
3189 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3190   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3191     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3192   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3193     return (Mask[0] < 2 && Mask[1] < 2);
3194   return false;
3195 }
3196
3197 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
3198   SmallVector<int, 8> M;
3199   N->getMask(M);
3200   return ::isPSHUFDMask(M, N->getValueType(0));
3201 }
3202
3203 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3204 /// is suitable for input to PSHUFHW.
3205 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3206   if (VT != MVT::v8i16)
3207     return false;
3208
3209   // Lower quadword copied in order or undef.
3210   for (int i = 0; i != 4; ++i)
3211     if (Mask[i] >= 0 && Mask[i] != i)
3212       return false;
3213
3214   // Upper quadword shuffled.
3215   for (int i = 4; i != 8; ++i)
3216     if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
3217       return false;
3218
3219   return true;
3220 }
3221
3222 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
3223   SmallVector<int, 8> M;
3224   N->getMask(M);
3225   return ::isPSHUFHWMask(M, N->getValueType(0));
3226 }
3227
3228 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3229 /// is suitable for input to PSHUFLW.
3230 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3231   if (VT != MVT::v8i16)
3232     return false;
3233
3234   // Upper quadword copied in order.
3235   for (int i = 4; i != 8; ++i)
3236     if (Mask[i] >= 0 && Mask[i] != i)
3237       return false;
3238
3239   // Lower quadword shuffled.
3240   for (int i = 0; i != 4; ++i)
3241     if (Mask[i] >= 4)
3242       return false;
3243
3244   return true;
3245 }
3246
3247 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
3248   SmallVector<int, 8> M;
3249   N->getMask(M);
3250   return ::isPSHUFLWMask(M, N->getValueType(0));
3251 }
3252
3253 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3254 /// is suitable for input to PALIGNR.
3255 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
3256                           bool hasSSSE3OrAVX) {
3257   int i, e = VT.getVectorNumElements();
3258   if (VT.getSizeInBits() != 128 && VT.getSizeInBits() != 64)
3259     return false;
3260
3261   // Do not handle v2i64 / v2f64 shuffles with palignr.
3262   if (e < 4 || !hasSSSE3OrAVX)
3263     return false;
3264
3265   for (i = 0; i != e; ++i)
3266     if (Mask[i] >= 0)
3267       break;
3268
3269   // All undef, not a palignr.
3270   if (i == e)
3271     return false;
3272
3273   // Make sure we're shifting in the right direction.
3274   if (Mask[i] <= i)
3275     return false;
3276
3277   int s = Mask[i] - i;
3278
3279   // Check the rest of the elements to see if they are consecutive.
3280   for (++i; i != e; ++i) {
3281     int m = Mask[i];
3282     if (m >= 0 && m != s+i)
3283       return false;
3284   }
3285   return true;
3286 }
3287
3288 /// isVSHUFPSYMask - Return true if the specified VECTOR_SHUFFLE operand
3289 /// specifies a shuffle of elements that is suitable for input to 256-bit
3290 /// VSHUFPSY.
3291 static bool isVSHUFPSYMask(const SmallVectorImpl<int> &Mask, EVT VT,
3292                           const X86Subtarget *Subtarget) {
3293   int NumElems = VT.getVectorNumElements();
3294
3295   if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256)
3296     return false;
3297
3298   if (NumElems != 8)
3299     return false;
3300
3301   // VSHUFPSY divides the resulting vector into 4 chunks.
3302   // The sources are also splitted into 4 chunks, and each destination
3303   // chunk must come from a different source chunk.
3304   //
3305   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3306   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3307   //
3308   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3309   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3310   //
3311   int QuarterSize = NumElems/4;
3312   int HalfSize = QuarterSize*2;
3313   for (int i = 0; i < QuarterSize; ++i)
3314     if (!isUndefOrInRange(Mask[i], 0, HalfSize))
3315       return false;
3316   for (int i = QuarterSize; i < QuarterSize*2; ++i)
3317     if (!isUndefOrInRange(Mask[i], NumElems, NumElems+HalfSize))
3318       return false;
3319
3320   // The mask of the second half must be the same as the first but with
3321   // the appropriate offsets. This works in the same way as VPERMILPS
3322   // works with masks.
3323   for (int i = QuarterSize*2; i < QuarterSize*3; ++i) {
3324     if (!isUndefOrInRange(Mask[i], HalfSize, NumElems))
3325       return false;
3326     int FstHalfIdx = i-HalfSize;
3327     if (Mask[FstHalfIdx] < 0)
3328       continue;
3329     if (!isUndefOrEqual(Mask[i], Mask[FstHalfIdx]+HalfSize))
3330       return false;
3331   }
3332   for (int i = QuarterSize*3; i < NumElems; ++i) {
3333     if (!isUndefOrInRange(Mask[i], NumElems+HalfSize, NumElems*2))
3334       return false;
3335     int FstHalfIdx = i-HalfSize;
3336     if (Mask[FstHalfIdx] < 0)
3337       continue;
3338     if (!isUndefOrEqual(Mask[i], Mask[FstHalfIdx]+HalfSize))
3339       return false;
3340
3341   }
3342
3343   return true;
3344 }
3345
3346 /// getShuffleVSHUFPSYImmediate - Return the appropriate immediate to shuffle
3347 /// the specified VECTOR_MASK mask with VSHUFPSY instruction.
3348 static unsigned getShuffleVSHUFPSYImmediate(SDNode *N) {
3349   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3350   EVT VT = SVOp->getValueType(0);
3351   int NumElems = VT.getVectorNumElements();
3352
3353   assert(NumElems == 8 && VT.getSizeInBits() == 256 &&
3354          "Only supports v8i32 and v8f32 types");
3355
3356   int HalfSize = NumElems/2;
3357   unsigned Mask = 0;
3358   for (int i = 0; i != NumElems ; ++i) {
3359     if (SVOp->getMaskElt(i) < 0)
3360       continue;
3361     // The mask of the first half must be equal to the second one.
3362     unsigned Shamt = (i%HalfSize)*2;
3363     unsigned Elt = SVOp->getMaskElt(i) % HalfSize;
3364     Mask |= Elt << Shamt;
3365   }
3366
3367   return Mask;
3368 }
3369
3370 /// isVSHUFPDYMask - Return true if the specified VECTOR_SHUFFLE operand
3371 /// specifies a shuffle of elements that is suitable for input to 256-bit
3372 /// VSHUFPDY. This shuffle doesn't have the same restriction as the PS
3373 /// version and the mask of the second half isn't binded with the first
3374 /// one.
3375 static bool isVSHUFPDYMask(const SmallVectorImpl<int> &Mask, EVT VT,
3376                            const X86Subtarget *Subtarget) {
3377   int NumElems = VT.getVectorNumElements();
3378
3379   if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256)
3380     return false;
3381
3382   if (NumElems != 4)
3383     return false;
3384
3385   // VSHUFPSY divides the resulting vector into 4 chunks.
3386   // The sources are also splitted into 4 chunks, and each destination
3387   // chunk must come from a different source chunk.
3388   //
3389   //  SRC1 =>      X3       X2       X1       X0
3390   //  SRC2 =>      Y3       Y2       Y1       Y0
3391   //
3392   //  DST  =>  Y2..Y3,  X2..X3,  Y1..Y0,  X1..X0
3393   //
3394   int QuarterSize = NumElems/4;
3395   int HalfSize = QuarterSize*2;
3396   for (int i = 0; i < QuarterSize; ++i)
3397     if (!isUndefOrInRange(Mask[i], 0, HalfSize))
3398       return false;
3399   for (int i = QuarterSize; i < QuarterSize*2; ++i)
3400     if (!isUndefOrInRange(Mask[i], NumElems, NumElems+HalfSize))
3401       return false;
3402   for (int i = QuarterSize*2; i < QuarterSize*3; ++i)
3403     if (!isUndefOrInRange(Mask[i], HalfSize, NumElems))
3404       return false;
3405   for (int i = QuarterSize*3; i < NumElems; ++i)
3406     if (!isUndefOrInRange(Mask[i], NumElems+HalfSize, NumElems*2))
3407       return false;
3408
3409   return true;
3410 }
3411
3412 /// getShuffleVSHUFPDYImmediate - Return the appropriate immediate to shuffle
3413 /// the specified VECTOR_MASK mask with VSHUFPDY instruction.
3414 static unsigned getShuffleVSHUFPDYImmediate(SDNode *N) {
3415   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3416   EVT VT = SVOp->getValueType(0);
3417   int NumElems = VT.getVectorNumElements();
3418
3419   assert(NumElems == 4 && VT.getSizeInBits() == 256 &&
3420          "Only supports v4i64 and v4f64 types");
3421
3422   int HalfSize = NumElems/2;
3423   unsigned Mask = 0;
3424   for (int i = 0; i != NumElems ; ++i) {
3425     if (SVOp->getMaskElt(i) < 0)
3426       continue;
3427     int Elt = SVOp->getMaskElt(i) % HalfSize;
3428     Mask |= Elt << i;
3429   }
3430
3431   return Mask;
3432 }
3433
3434 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3435 /// specifies a shuffle of elements that is suitable for input to 128-bit
3436 /// SHUFPS and SHUFPD.
3437 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3438   int NumElems = VT.getVectorNumElements();
3439
3440   if (VT.getSizeInBits() != 128)
3441     return false;
3442
3443   if (NumElems != 2 && NumElems != 4)
3444     return false;
3445
3446   int Half = NumElems / 2;
3447   for (int i = 0; i < Half; ++i)
3448     if (!isUndefOrInRange(Mask[i], 0, NumElems))
3449       return false;
3450   for (int i = Half; i < NumElems; ++i)
3451     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3452       return false;
3453
3454   return true;
3455 }
3456
3457 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
3458   SmallVector<int, 8> M;
3459   N->getMask(M);
3460   return ::isSHUFPMask(M, N->getValueType(0));
3461 }
3462
3463 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
3464 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
3465 /// half elements to come from vector 1 (which would equal the dest.) and
3466 /// the upper half to come from vector 2.
3467 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3468   int NumElems = VT.getVectorNumElements();
3469
3470   if (NumElems != 2 && NumElems != 4)
3471     return false;
3472
3473   int Half = NumElems / 2;
3474   for (int i = 0; i < Half; ++i)
3475     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3476       return false;
3477   for (int i = Half; i < NumElems; ++i)
3478     if (!isUndefOrInRange(Mask[i], 0, NumElems))
3479       return false;
3480   return true;
3481 }
3482
3483 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
3484   SmallVector<int, 8> M;
3485   N->getMask(M);
3486   return isCommutedSHUFPMask(M, N->getValueType(0));
3487 }
3488
3489 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3490 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3491 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3492   EVT VT = N->getValueType(0);
3493   unsigned NumElems = VT.getVectorNumElements();
3494
3495   if (VT.getSizeInBits() != 128)
3496     return false;
3497
3498   if (NumElems != 4)
3499     return false;
3500
3501   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3502   return isUndefOrEqual(N->getMaskElt(0), 6) &&
3503          isUndefOrEqual(N->getMaskElt(1), 7) &&
3504          isUndefOrEqual(N->getMaskElt(2), 2) &&
3505          isUndefOrEqual(N->getMaskElt(3), 3);
3506 }
3507
3508 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3509 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3510 /// <2, 3, 2, 3>
3511 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3512   EVT VT = N->getValueType(0);
3513   unsigned NumElems = VT.getVectorNumElements();
3514
3515   if (VT.getSizeInBits() != 128)
3516     return false;
3517
3518   if (NumElems != 4)
3519     return false;
3520
3521   return isUndefOrEqual(N->getMaskElt(0), 2) &&
3522          isUndefOrEqual(N->getMaskElt(1), 3) &&
3523          isUndefOrEqual(N->getMaskElt(2), 2) &&
3524          isUndefOrEqual(N->getMaskElt(3), 3);
3525 }
3526
3527 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3528 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3529 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3530   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3531
3532   if (NumElems != 2 && NumElems != 4)
3533     return false;
3534
3535   for (unsigned i = 0; i < NumElems/2; ++i)
3536     if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3537       return false;
3538
3539   for (unsigned i = NumElems/2; i < NumElems; ++i)
3540     if (!isUndefOrEqual(N->getMaskElt(i), i))
3541       return false;
3542
3543   return true;
3544 }
3545
3546 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3547 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3548 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3549   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3550
3551   if ((NumElems != 2 && NumElems != 4)
3552       || N->getValueType(0).getSizeInBits() > 128)
3553     return false;
3554
3555   for (unsigned i = 0; i < NumElems/2; ++i)
3556     if (!isUndefOrEqual(N->getMaskElt(i), i))
3557       return false;
3558
3559   for (unsigned i = 0; i < NumElems/2; ++i)
3560     if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3561       return false;
3562
3563   return true;
3564 }
3565
3566 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3567 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3568 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3569                          bool HasAVX2, bool V2IsSplat = false) {
3570   int NumElts = VT.getVectorNumElements();
3571
3572   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3573          "Unsupported vector type for unpckh");
3574
3575   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3576       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3577     return false;
3578
3579   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3580   // independently on 128-bit lanes.
3581   unsigned NumLanes = VT.getSizeInBits()/128;
3582   unsigned NumLaneElts = NumElts/NumLanes;
3583
3584   unsigned Start = 0;
3585   unsigned End = NumLaneElts;
3586   for (unsigned s = 0; s < NumLanes; ++s) {
3587     for (unsigned i = Start, j = s * NumLaneElts;
3588          i != End;
3589          i += 2, ++j) {
3590       int BitI  = Mask[i];
3591       int BitI1 = Mask[i+1];
3592       if (!isUndefOrEqual(BitI, j))
3593         return false;
3594       if (V2IsSplat) {
3595         if (!isUndefOrEqual(BitI1, NumElts))
3596           return false;
3597       } else {
3598         if (!isUndefOrEqual(BitI1, j + NumElts))
3599           return false;
3600       }
3601     }
3602     // Process the next 128 bits.
3603     Start += NumLaneElts;
3604     End += NumLaneElts;
3605   }
3606
3607   return true;
3608 }
3609
3610 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool HasAVX2, bool V2IsSplat) {
3611   SmallVector<int, 8> M;
3612   N->getMask(M);
3613   return ::isUNPCKLMask(M, N->getValueType(0), HasAVX2, V2IsSplat);
3614 }
3615
3616 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3617 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3618 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3619                          bool HasAVX2, bool V2IsSplat = false) {
3620   int NumElts = VT.getVectorNumElements();
3621
3622   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3623          "Unsupported vector type for unpckh");
3624
3625   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3626       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3627     return false;
3628
3629   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3630   // independently on 128-bit lanes.
3631   unsigned NumLanes = VT.getSizeInBits()/128;
3632   unsigned NumLaneElts = NumElts/NumLanes;
3633
3634   unsigned Start = 0;
3635   unsigned End = NumLaneElts;
3636   for (unsigned l = 0; l != NumLanes; ++l) {
3637     for (unsigned i = Start, j = (l*NumLaneElts)+NumLaneElts/2;
3638                              i != End; i += 2, ++j) {
3639       int BitI  = Mask[i];
3640       int BitI1 = Mask[i+1];
3641       if (!isUndefOrEqual(BitI, j))
3642         return false;
3643       if (V2IsSplat) {
3644         if (isUndefOrEqual(BitI1, NumElts))
3645           return false;
3646       } else {
3647         if (!isUndefOrEqual(BitI1, j+NumElts))
3648           return false;
3649       }
3650     }
3651     // Process the next 128 bits.
3652     Start += NumLaneElts;
3653     End += NumLaneElts;
3654   }
3655   return true;
3656 }
3657
3658 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool HasAVX2, bool V2IsSplat) {
3659   SmallVector<int, 8> M;
3660   N->getMask(M);
3661   return ::isUNPCKHMask(M, N->getValueType(0), HasAVX2, V2IsSplat);
3662 }
3663
3664 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3665 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3666 /// <0, 0, 1, 1>
3667 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3668   int NumElems = VT.getVectorNumElements();
3669   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3670     return false;
3671
3672   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3673   // FIXME: Need a better way to get rid of this, there's no latency difference
3674   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3675   // the former later. We should also remove the "_undef" special mask.
3676   if (NumElems == 4 && VT.getSizeInBits() == 256)
3677     return false;
3678
3679   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3680   // independently on 128-bit lanes.
3681   unsigned NumLanes = VT.getSizeInBits() / 128;
3682   unsigned NumLaneElts = NumElems / NumLanes;
3683
3684   for (unsigned s = 0; s < NumLanes; ++s) {
3685     for (unsigned i = s * NumLaneElts, j = s * NumLaneElts;
3686          i != NumLaneElts * (s + 1);
3687          i += 2, ++j) {
3688       int BitI  = Mask[i];
3689       int BitI1 = Mask[i+1];
3690
3691       if (!isUndefOrEqual(BitI, j))
3692         return false;
3693       if (!isUndefOrEqual(BitI1, j))
3694         return false;
3695     }
3696   }
3697
3698   return true;
3699 }
3700
3701 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3702   SmallVector<int, 8> M;
3703   N->getMask(M);
3704   return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3705 }
3706
3707 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3708 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3709 /// <2, 2, 3, 3>
3710 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3711   int NumElems = VT.getVectorNumElements();
3712   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3713     return false;
3714
3715   for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3716     int BitI  = Mask[i];
3717     int BitI1 = Mask[i+1];
3718     if (!isUndefOrEqual(BitI, j))
3719       return false;
3720     if (!isUndefOrEqual(BitI1, j))
3721       return false;
3722   }
3723   return true;
3724 }
3725
3726 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3727   SmallVector<int, 8> M;
3728   N->getMask(M);
3729   return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3730 }
3731
3732 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3733 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3734 /// MOVSD, and MOVD, i.e. setting the lowest element.
3735 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3736   if (VT.getVectorElementType().getSizeInBits() < 32)
3737     return false;
3738
3739   int NumElts = VT.getVectorNumElements();
3740
3741   if (!isUndefOrEqual(Mask[0], NumElts))
3742     return false;
3743
3744   for (int i = 1; i < NumElts; ++i)
3745     if (!isUndefOrEqual(Mask[i], i))
3746       return false;
3747
3748   return true;
3749 }
3750
3751 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3752   SmallVector<int, 8> M;
3753   N->getMask(M);
3754   return ::isMOVLMask(M, N->getValueType(0));
3755 }
3756
3757 /// isVPERM2F128Mask - Match 256-bit shuffles where the elements are considered
3758 /// as permutations between 128-bit chunks or halves. As an example: this
3759 /// shuffle bellow:
3760 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3761 /// The first half comes from the second half of V1 and the second half from the
3762 /// the second half of V2.
3763 static bool isVPERM2F128Mask(const SmallVectorImpl<int> &Mask, EVT VT,
3764                              const X86Subtarget *Subtarget) {
3765   if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256)
3766     return false;
3767
3768   // The shuffle result is divided into half A and half B. In total the two
3769   // sources have 4 halves, namely: C, D, E, F. The final values of A and
3770   // B must come from C, D, E or F.
3771   int HalfSize = VT.getVectorNumElements()/2;
3772   bool MatchA = false, MatchB = false;
3773
3774   // Check if A comes from one of C, D, E, F.
3775   for (int Half = 0; Half < 4; ++Half) {
3776     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3777       MatchA = true;
3778       break;
3779     }
3780   }
3781
3782   // Check if B comes from one of C, D, E, F.
3783   for (int Half = 0; Half < 4; ++Half) {
3784     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3785       MatchB = true;
3786       break;
3787     }
3788   }
3789
3790   return MatchA && MatchB;
3791 }
3792
3793 /// getShuffleVPERM2F128Immediate - Return the appropriate immediate to shuffle
3794 /// the specified VECTOR_MASK mask with VPERM2F128 instructions.
3795 static unsigned getShuffleVPERM2F128Immediate(SDNode *N) {
3796   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3797   EVT VT = SVOp->getValueType(0);
3798
3799   int HalfSize = VT.getVectorNumElements()/2;
3800
3801   int FstHalf = 0, SndHalf = 0;
3802   for (int i = 0; i < HalfSize; ++i) {
3803     if (SVOp->getMaskElt(i) > 0) {
3804       FstHalf = SVOp->getMaskElt(i)/HalfSize;
3805       break;
3806     }
3807   }
3808   for (int i = HalfSize; i < HalfSize*2; ++i) {
3809     if (SVOp->getMaskElt(i) > 0) {
3810       SndHalf = SVOp->getMaskElt(i)/HalfSize;
3811       break;
3812     }
3813   }
3814
3815   return (FstHalf | (SndHalf << 4));
3816 }
3817
3818 /// isVPERMILPDMask - Return true if the specified VECTOR_SHUFFLE operand
3819 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3820 /// Note that VPERMIL mask matching is different depending whether theunderlying
3821 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3822 /// to the same elements of the low, but to the higher half of the source.
3823 /// In VPERMILPD the two lanes could be shuffled independently of each other
3824 /// with the same restriction that lanes can't be crossed.
3825 static bool isVPERMILPDMask(const SmallVectorImpl<int> &Mask, EVT VT,
3826                             const X86Subtarget *Subtarget) {
3827   int NumElts = VT.getVectorNumElements();
3828   int NumLanes = VT.getSizeInBits()/128;
3829
3830   if (!Subtarget->hasAVX())
3831     return false;
3832
3833   // Only match 256-bit with 64-bit types
3834   if (VT.getSizeInBits() != 256 || NumElts != 4)
3835     return false;
3836
3837   // The mask on the high lane is independent of the low. Both can match
3838   // any element in inside its own lane, but can't cross.
3839   int LaneSize = NumElts/NumLanes;
3840   for (int l = 0; l < NumLanes; ++l)
3841     for (int i = l*LaneSize; i < LaneSize*(l+1); ++i) {
3842       int LaneStart = l*LaneSize;
3843       if (!isUndefOrInRange(Mask[i], LaneStart, LaneStart+LaneSize))
3844         return false;
3845     }
3846
3847   return true;
3848 }
3849
3850 /// isVPERMILPSMask - Return true if the specified VECTOR_SHUFFLE operand
3851 /// specifies a shuffle of elements that is suitable for input to VPERMILPS*.
3852 /// Note that VPERMIL mask matching is different depending whether theunderlying
3853 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3854 /// to the same elements of the low, but to the higher half of the source.
3855 /// In VPERMILPD the two lanes could be shuffled independently of each other
3856 /// with the same restriction that lanes can't be crossed.
3857 static bool isVPERMILPSMask(const SmallVectorImpl<int> &Mask, EVT VT,
3858                             const X86Subtarget *Subtarget) {
3859   unsigned NumElts = VT.getVectorNumElements();
3860   unsigned NumLanes = VT.getSizeInBits()/128;
3861
3862   if (!Subtarget->hasAVX())
3863     return false;
3864
3865   // Only match 256-bit with 32-bit types
3866   if (VT.getSizeInBits() != 256 || NumElts != 8)
3867     return false;
3868
3869   // The mask on the high lane should be the same as the low. Actually,
3870   // they can differ if any of the corresponding index in a lane is undef
3871   // and the other stays in range.
3872   int LaneSize = NumElts/NumLanes;
3873   for (int i = 0; i < LaneSize; ++i) {
3874     int HighElt = i+LaneSize;
3875     bool HighValid = isUndefOrInRange(Mask[HighElt], LaneSize, NumElts);
3876     bool LowValid = isUndefOrInRange(Mask[i], 0, LaneSize);
3877
3878     if (!HighValid || !LowValid)
3879       return false;
3880     if (Mask[i] < 0 || Mask[HighElt] < 0)
3881       continue;
3882     if (Mask[HighElt]-Mask[i] != LaneSize)
3883       return false;
3884   }
3885
3886   return true;
3887 }
3888
3889 /// getShuffleVPERMILPSImmediate - Return the appropriate immediate to shuffle
3890 /// the specified VECTOR_MASK mask with VPERMILPS* instructions.
3891 static unsigned getShuffleVPERMILPSImmediate(SDNode *N) {
3892   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3893   EVT VT = SVOp->getValueType(0);
3894
3895   int NumElts = VT.getVectorNumElements();
3896   int NumLanes = VT.getSizeInBits()/128;
3897   int LaneSize = NumElts/NumLanes;
3898
3899   // Although the mask is equal for both lanes do it twice to get the cases
3900   // where a mask will match because the same mask element is undef on the
3901   // first half but valid on the second. This would get pathological cases
3902   // such as: shuffle <u, 0, 1, 2, 4, 4, 5, 6>, which is completely valid.
3903   unsigned Mask = 0;
3904   for (int l = 0; l < NumLanes; ++l) {
3905     for (int i = 0; i < LaneSize; ++i) {
3906       int MaskElt = SVOp->getMaskElt(i+(l*LaneSize));
3907       if (MaskElt < 0)
3908         continue;
3909       if (MaskElt >= LaneSize)
3910         MaskElt -= LaneSize;
3911       Mask |= MaskElt << (i*2);
3912     }
3913   }
3914
3915   return Mask;
3916 }
3917
3918 /// getShuffleVPERMILPDImmediate - Return the appropriate immediate to shuffle
3919 /// the specified VECTOR_MASK mask with VPERMILPD* instructions.
3920 static unsigned getShuffleVPERMILPDImmediate(SDNode *N) {
3921   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3922   EVT VT = SVOp->getValueType(0);
3923
3924   int NumElts = VT.getVectorNumElements();
3925   int NumLanes = VT.getSizeInBits()/128;
3926
3927   unsigned Mask = 0;
3928   int LaneSize = NumElts/NumLanes;
3929   for (int l = 0; l < NumLanes; ++l)
3930     for (int i = l*LaneSize; i < LaneSize*(l+1); ++i) {
3931       int MaskElt = SVOp->getMaskElt(i);
3932       if (MaskElt < 0)
3933         continue;
3934       Mask |= (MaskElt-l*LaneSize) << i;
3935     }
3936
3937   return Mask;
3938 }
3939
3940 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3941 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3942 /// element of vector 2 and the other elements to come from vector 1 in order.
3943 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3944                                bool V2IsSplat = false, bool V2IsUndef = false) {
3945   int NumOps = VT.getVectorNumElements();
3946   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3947     return false;
3948
3949   if (!isUndefOrEqual(Mask[0], 0))
3950     return false;
3951
3952   for (int i = 1; i < NumOps; ++i)
3953     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3954           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3955           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3956       return false;
3957
3958   return true;
3959 }
3960
3961 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3962                            bool V2IsUndef = false) {
3963   SmallVector<int, 8> M;
3964   N->getMask(M);
3965   return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3966 }
3967
3968 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3969 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3970 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3971 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N,
3972                          const X86Subtarget *Subtarget) {
3973   if (!Subtarget->hasSSE3orAVX())
3974     return false;
3975
3976   // The second vector must be undef
3977   if (N->getOperand(1).getOpcode() != ISD::UNDEF)
3978     return false;
3979
3980   EVT VT = N->getValueType(0);
3981   unsigned NumElems = VT.getVectorNumElements();
3982
3983   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3984       (VT.getSizeInBits() == 256 && NumElems != 8))
3985     return false;
3986
3987   // "i+1" is the value the indexed mask element must have
3988   for (unsigned i = 0; i < NumElems; i += 2)
3989     if (!isUndefOrEqual(N->getMaskElt(i), i+1) ||
3990         !isUndefOrEqual(N->getMaskElt(i+1), i+1))
3991       return false;
3992
3993   return true;
3994 }
3995
3996 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3997 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3998 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3999 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N,
4000                          const X86Subtarget *Subtarget) {
4001   if (!Subtarget->hasSSE3orAVX())
4002     return false;
4003
4004   // The second vector must be undef
4005   if (N->getOperand(1).getOpcode() != ISD::UNDEF)
4006     return false;
4007
4008   EVT VT = N->getValueType(0);
4009   unsigned NumElems = VT.getVectorNumElements();
4010
4011   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
4012       (VT.getSizeInBits() == 256 && NumElems != 8))
4013     return false;
4014
4015   // "i" is the value the indexed mask element must have
4016   for (unsigned i = 0; i < NumElems; i += 2)
4017     if (!isUndefOrEqual(N->getMaskElt(i), i) ||
4018         !isUndefOrEqual(N->getMaskElt(i+1), i))
4019       return false;
4020
4021   return true;
4022 }
4023
4024 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4025 /// specifies a shuffle of elements that is suitable for input to 256-bit
4026 /// version of MOVDDUP.
4027 static bool isMOVDDUPYMask(ShuffleVectorSDNode *N,
4028                            const X86Subtarget *Subtarget) {
4029   EVT VT = N->getValueType(0);
4030   int NumElts = VT.getVectorNumElements();
4031   bool V2IsUndef = N->getOperand(1).getOpcode() == ISD::UNDEF;
4032
4033   if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256 ||
4034       !V2IsUndef || NumElts != 4)
4035     return false;
4036
4037   for (int i = 0; i != NumElts/2; ++i)
4038     if (!isUndefOrEqual(N->getMaskElt(i), 0))
4039       return false;
4040   for (int i = NumElts/2; i != NumElts; ++i)
4041     if (!isUndefOrEqual(N->getMaskElt(i), NumElts/2))
4042       return false;
4043   return true;
4044 }
4045
4046 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4047 /// specifies a shuffle of elements that is suitable for input to 128-bit
4048 /// version of MOVDDUP.
4049 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
4050   EVT VT = N->getValueType(0);
4051
4052   if (VT.getSizeInBits() != 128)
4053     return false;
4054
4055   int e = VT.getVectorNumElements() / 2;
4056   for (int i = 0; i < e; ++i)
4057     if (!isUndefOrEqual(N->getMaskElt(i), i))
4058       return false;
4059   for (int i = 0; i < e; ++i)
4060     if (!isUndefOrEqual(N->getMaskElt(e+i), i))
4061       return false;
4062   return true;
4063 }
4064
4065 /// isVEXTRACTF128Index - Return true if the specified
4066 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4067 /// suitable for input to VEXTRACTF128.
4068 bool X86::isVEXTRACTF128Index(SDNode *N) {
4069   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4070     return false;
4071
4072   // The index should be aligned on a 128-bit boundary.
4073   uint64_t Index =
4074     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4075
4076   unsigned VL = N->getValueType(0).getVectorNumElements();
4077   unsigned VBits = N->getValueType(0).getSizeInBits();
4078   unsigned ElSize = VBits / VL;
4079   bool Result = (Index * ElSize) % 128 == 0;
4080
4081   return Result;
4082 }
4083
4084 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
4085 /// operand specifies a subvector insert that is suitable for input to
4086 /// VINSERTF128.
4087 bool X86::isVINSERTF128Index(SDNode *N) {
4088   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4089     return false;
4090
4091   // The index should be aligned on a 128-bit boundary.
4092   uint64_t Index =
4093     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4094
4095   unsigned VL = N->getValueType(0).getVectorNumElements();
4096   unsigned VBits = N->getValueType(0).getSizeInBits();
4097   unsigned ElSize = VBits / VL;
4098   bool Result = (Index * ElSize) % 128 == 0;
4099
4100   return Result;
4101 }
4102
4103 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4104 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4105 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
4106   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4107   int NumOperands = SVOp->getValueType(0).getVectorNumElements();
4108
4109   unsigned Shift = (NumOperands == 4) ? 2 : 1;
4110   unsigned Mask = 0;
4111   for (int i = 0; i < NumOperands; ++i) {
4112     int Val = SVOp->getMaskElt(NumOperands-i-1);
4113     if (Val < 0) Val = 0;
4114     if (Val >= NumOperands) Val -= NumOperands;
4115     Mask |= Val;
4116     if (i != NumOperands - 1)
4117       Mask <<= Shift;
4118   }
4119   return Mask;
4120 }
4121
4122 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4123 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4124 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
4125   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4126   unsigned Mask = 0;
4127   // 8 nodes, but we only care about the last 4.
4128   for (unsigned i = 7; i >= 4; --i) {
4129     int Val = SVOp->getMaskElt(i);
4130     if (Val >= 0)
4131       Mask |= (Val - 4);
4132     if (i != 4)
4133       Mask <<= 2;
4134   }
4135   return Mask;
4136 }
4137
4138 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4139 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4140 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
4141   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4142   unsigned Mask = 0;
4143   // 8 nodes, but we only care about the first 4.
4144   for (int i = 3; i >= 0; --i) {
4145     int Val = SVOp->getMaskElt(i);
4146     if (Val >= 0)
4147       Mask |= Val;
4148     if (i != 0)
4149       Mask <<= 2;
4150   }
4151   return Mask;
4152 }
4153
4154 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4155 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4156 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
4157   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4158   EVT VVT = N->getValueType(0);
4159   unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
4160   int Val = 0;
4161
4162   unsigned i, e;
4163   for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
4164     Val = SVOp->getMaskElt(i);
4165     if (Val >= 0)
4166       break;
4167   }
4168   assert(Val - i > 0 && "PALIGNR imm should be positive");
4169   return (Val - i) * EltSize;
4170 }
4171
4172 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4173 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4174 /// instructions.
4175 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4176   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4177     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4178
4179   uint64_t Index =
4180     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4181
4182   EVT VecVT = N->getOperand(0).getValueType();
4183   EVT ElVT = VecVT.getVectorElementType();
4184
4185   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4186   return Index / NumElemsPerChunk;
4187 }
4188
4189 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4190 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4191 /// instructions.
4192 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4193   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4194     llvm_unreachable("Illegal insert subvector for VINSERTF128");
4195
4196   uint64_t Index =
4197     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4198
4199   EVT VecVT = N->getValueType(0);
4200   EVT ElVT = VecVT.getVectorElementType();
4201
4202   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4203   return Index / NumElemsPerChunk;
4204 }
4205
4206 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4207 /// constant +0.0.
4208 bool X86::isZeroNode(SDValue Elt) {
4209   return ((isa<ConstantSDNode>(Elt) &&
4210            cast<ConstantSDNode>(Elt)->isNullValue()) ||
4211           (isa<ConstantFPSDNode>(Elt) &&
4212            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4213 }
4214
4215 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4216 /// their permute mask.
4217 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4218                                     SelectionDAG &DAG) {
4219   EVT VT = SVOp->getValueType(0);
4220   unsigned NumElems = VT.getVectorNumElements();
4221   SmallVector<int, 8> MaskVec;
4222
4223   for (unsigned i = 0; i != NumElems; ++i) {
4224     int idx = SVOp->getMaskElt(i);
4225     if (idx < 0)
4226       MaskVec.push_back(idx);
4227     else if (idx < (int)NumElems)
4228       MaskVec.push_back(idx + NumElems);
4229     else
4230       MaskVec.push_back(idx - NumElems);
4231   }
4232   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4233                               SVOp->getOperand(0), &MaskVec[0]);
4234 }
4235
4236 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
4237 /// the two vector operands have swapped position.
4238 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
4239   unsigned NumElems = VT.getVectorNumElements();
4240   for (unsigned i = 0; i != NumElems; ++i) {
4241     int idx = Mask[i];
4242     if (idx < 0)
4243       continue;
4244     else if (idx < (int)NumElems)
4245       Mask[i] = idx + NumElems;
4246     else
4247       Mask[i] = idx - NumElems;
4248   }
4249 }
4250
4251 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4252 /// match movhlps. The lower half elements should come from upper half of
4253 /// V1 (and in order), and the upper half elements should come from the upper
4254 /// half of V2 (and in order).
4255 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
4256   EVT VT = Op->getValueType(0);
4257   if (VT.getSizeInBits() != 128)
4258     return false;
4259   if (VT.getVectorNumElements() != 4)
4260     return false;
4261   for (unsigned i = 0, e = 2; i != e; ++i)
4262     if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
4263       return false;
4264   for (unsigned i = 2; i != 4; ++i)
4265     if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
4266       return false;
4267   return true;
4268 }
4269
4270 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4271 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4272 /// required.
4273 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4274   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4275     return false;
4276   N = N->getOperand(0).getNode();
4277   if (!ISD::isNON_EXTLoad(N))
4278     return false;
4279   if (LD)
4280     *LD = cast<LoadSDNode>(N);
4281   return true;
4282 }
4283
4284 // Test whether the given value is a vector value which will be legalized
4285 // into a load.
4286 static bool WillBeConstantPoolLoad(SDNode *N) {
4287   if (N->getOpcode() != ISD::BUILD_VECTOR)
4288     return false;
4289
4290   // Check for any non-constant elements.
4291   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4292     switch (N->getOperand(i).getNode()->getOpcode()) {
4293     case ISD::UNDEF:
4294     case ISD::ConstantFP:
4295     case ISD::Constant:
4296       break;
4297     default:
4298       return false;
4299     }
4300
4301   // Vectors of all-zeros and all-ones are materialized with special
4302   // instructions rather than being loaded.
4303   return !ISD::isBuildVectorAllZeros(N) &&
4304          !ISD::isBuildVectorAllOnes(N);
4305 }
4306
4307 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4308 /// match movlp{s|d}. The lower half elements should come from lower half of
4309 /// V1 (and in order), and the upper half elements should come from the upper
4310 /// half of V2 (and in order). And since V1 will become the source of the
4311 /// MOVLP, it must be either a vector load or a scalar load to vector.
4312 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4313                                ShuffleVectorSDNode *Op) {
4314   EVT VT = Op->getValueType(0);
4315   if (VT.getSizeInBits() != 128)
4316     return false;
4317
4318   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4319     return false;
4320   // Is V2 is a vector load, don't do this transformation. We will try to use
4321   // load folding shufps op.
4322   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4323     return false;
4324
4325   unsigned NumElems = VT.getVectorNumElements();
4326
4327   if (NumElems != 2 && NumElems != 4)
4328     return false;
4329   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4330     if (!isUndefOrEqual(Op->getMaskElt(i), i))
4331       return false;
4332   for (unsigned i = NumElems/2; i != NumElems; ++i)
4333     if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
4334       return false;
4335   return true;
4336 }
4337
4338 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4339 /// all the same.
4340 static bool isSplatVector(SDNode *N) {
4341   if (N->getOpcode() != ISD::BUILD_VECTOR)
4342     return false;
4343
4344   SDValue SplatValue = N->getOperand(0);
4345   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4346     if (N->getOperand(i) != SplatValue)
4347       return false;
4348   return true;
4349 }
4350
4351 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4352 /// to an zero vector.
4353 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4354 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4355   SDValue V1 = N->getOperand(0);
4356   SDValue V2 = N->getOperand(1);
4357   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4358   for (unsigned i = 0; i != NumElems; ++i) {
4359     int Idx = N->getMaskElt(i);
4360     if (Idx >= (int)NumElems) {
4361       unsigned Opc = V2.getOpcode();
4362       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4363         continue;
4364       if (Opc != ISD::BUILD_VECTOR ||
4365           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4366         return false;
4367     } else if (Idx >= 0) {
4368       unsigned Opc = V1.getOpcode();
4369       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4370         continue;
4371       if (Opc != ISD::BUILD_VECTOR ||
4372           !X86::isZeroNode(V1.getOperand(Idx)))
4373         return false;
4374     }
4375   }
4376   return true;
4377 }
4378
4379 /// getZeroVector - Returns a vector of specified type with all zero elements.
4380 ///
4381 static SDValue getZeroVector(EVT VT, bool HasXMMInt, SelectionDAG &DAG,
4382                              DebugLoc dl) {
4383   assert(VT.isVector() && "Expected a vector type");
4384
4385   // Always build SSE zero vectors as <4 x i32> bitcasted
4386   // to their dest type. This ensures they get CSE'd.
4387   SDValue Vec;
4388   if (VT.getSizeInBits() == 128) {  // SSE
4389     if (HasXMMInt) {  // SSE2
4390       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4391       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4392     } else { // SSE1
4393       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4394       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4395     }
4396   } else if (VT.getSizeInBits() == 256) { // AVX
4397     // 256-bit logic and arithmetic instructions in AVX are
4398     // all floating-point, no support for integer ops. Default
4399     // to emitting fp zeroed vectors then.
4400     SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4401     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4402     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4403   }
4404   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4405 }
4406
4407 /// getOnesVector - Returns a vector of specified type with all bits set.
4408 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4409 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4410 /// Then bitcast to their original type, ensuring they get CSE'd.
4411 static SDValue getOnesVector(EVT VT, bool HasAVX2, SelectionDAG &DAG,
4412                              DebugLoc dl) {
4413   assert(VT.isVector() && "Expected a vector type");
4414   assert((VT.is128BitVector() || VT.is256BitVector())
4415          && "Expected a 128-bit or 256-bit vector type");
4416
4417   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4418   SDValue Vec;
4419   if (VT.getSizeInBits() == 256) {
4420     if (HasAVX2) { // AVX2
4421       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4422       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4423     } else { // AVX
4424       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4425       SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, MVT::v8i32),
4426                                 Vec, DAG.getConstant(0, MVT::i32), DAG, dl);
4427       Vec = Insert128BitVector(InsV, Vec,
4428                     DAG.getConstant(4 /* NumElems/2 */, MVT::i32), DAG, dl);
4429     }
4430   } else {
4431     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4432   }
4433
4434   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4435 }
4436
4437 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4438 /// that point to V2 points to its first element.
4439 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4440   EVT VT = SVOp->getValueType(0);
4441   unsigned NumElems = VT.getVectorNumElements();
4442
4443   bool Changed = false;
4444   SmallVector<int, 8> MaskVec;
4445   SVOp->getMask(MaskVec);
4446
4447   for (unsigned i = 0; i != NumElems; ++i) {
4448     if (MaskVec[i] > (int)NumElems) {
4449       MaskVec[i] = NumElems;
4450       Changed = true;
4451     }
4452   }
4453   if (Changed)
4454     return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
4455                                 SVOp->getOperand(1), &MaskVec[0]);
4456   return SDValue(SVOp, 0);
4457 }
4458
4459 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4460 /// operation of specified width.
4461 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4462                        SDValue V2) {
4463   unsigned NumElems = VT.getVectorNumElements();
4464   SmallVector<int, 8> Mask;
4465   Mask.push_back(NumElems);
4466   for (unsigned i = 1; i != NumElems; ++i)
4467     Mask.push_back(i);
4468   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4469 }
4470
4471 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4472 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4473                           SDValue V2) {
4474   unsigned NumElems = VT.getVectorNumElements();
4475   SmallVector<int, 8> Mask;
4476   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4477     Mask.push_back(i);
4478     Mask.push_back(i + NumElems);
4479   }
4480   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4481 }
4482
4483 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4484 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4485                           SDValue V2) {
4486   unsigned NumElems = VT.getVectorNumElements();
4487   unsigned Half = NumElems/2;
4488   SmallVector<int, 8> Mask;
4489   for (unsigned i = 0; i != Half; ++i) {
4490     Mask.push_back(i + Half);
4491     Mask.push_back(i + NumElems + Half);
4492   }
4493   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4494 }
4495
4496 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4497 // a generic shuffle instruction because the target has no such instructions.
4498 // Generate shuffles which repeat i16 and i8 several times until they can be
4499 // represented by v4f32 and then be manipulated by target suported shuffles.
4500 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4501   EVT VT = V.getValueType();
4502   int NumElems = VT.getVectorNumElements();
4503   DebugLoc dl = V.getDebugLoc();
4504
4505   while (NumElems > 4) {
4506     if (EltNo < NumElems/2) {
4507       V = getUnpackl(DAG, dl, VT, V, V);
4508     } else {
4509       V = getUnpackh(DAG, dl, VT, V, V);
4510       EltNo -= NumElems/2;
4511     }
4512     NumElems >>= 1;
4513   }
4514   return V;
4515 }
4516
4517 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4518 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4519   EVT VT = V.getValueType();
4520   DebugLoc dl = V.getDebugLoc();
4521   assert((VT.getSizeInBits() == 128 || VT.getSizeInBits() == 256)
4522          && "Vector size not supported");
4523
4524   if (VT.getSizeInBits() == 128) {
4525     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4526     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4527     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4528                              &SplatMask[0]);
4529   } else {
4530     // To use VPERMILPS to splat scalars, the second half of indicies must
4531     // refer to the higher part, which is a duplication of the lower one,
4532     // because VPERMILPS can only handle in-lane permutations.
4533     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4534                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4535
4536     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4537     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4538                              &SplatMask[0]);
4539   }
4540
4541   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4542 }
4543
4544 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4545 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4546   EVT SrcVT = SV->getValueType(0);
4547   SDValue V1 = SV->getOperand(0);
4548   DebugLoc dl = SV->getDebugLoc();
4549
4550   int EltNo = SV->getSplatIndex();
4551   int NumElems = SrcVT.getVectorNumElements();
4552   unsigned Size = SrcVT.getSizeInBits();
4553
4554   assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4555           "Unknown how to promote splat for type");
4556
4557   // Extract the 128-bit part containing the splat element and update
4558   // the splat element index when it refers to the higher register.
4559   if (Size == 256) {
4560     unsigned Idx = (EltNo > NumElems/2) ? NumElems/2 : 0;
4561     V1 = Extract128BitVector(V1, DAG.getConstant(Idx, MVT::i32), DAG, dl);
4562     if (Idx > 0)
4563       EltNo -= NumElems/2;
4564   }
4565
4566   // All i16 and i8 vector types can't be used directly by a generic shuffle
4567   // instruction because the target has no such instruction. Generate shuffles
4568   // which repeat i16 and i8 several times until they fit in i32, and then can
4569   // be manipulated by target suported shuffles.
4570   EVT EltVT = SrcVT.getVectorElementType();
4571   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4572     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4573
4574   // Recreate the 256-bit vector and place the same 128-bit vector
4575   // into the low and high part. This is necessary because we want
4576   // to use VPERM* to shuffle the vectors
4577   if (Size == 256) {
4578     SDValue InsV = Insert128BitVector(DAG.getUNDEF(SrcVT), V1,
4579                          DAG.getConstant(0, MVT::i32), DAG, dl);
4580     V1 = Insert128BitVector(InsV, V1,
4581                DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
4582   }
4583
4584   return getLegalSplat(DAG, V1, EltNo);
4585 }
4586
4587 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4588 /// vector of zero or undef vector.  This produces a shuffle where the low
4589 /// element of V2 is swizzled into the zero/undef vector, landing at element
4590 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4591 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4592                                            bool isZero, bool HasXMMInt,
4593                                            SelectionDAG &DAG) {
4594   EVT VT = V2.getValueType();
4595   SDValue V1 = isZero
4596     ? getZeroVector(VT, HasXMMInt, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4597   unsigned NumElems = VT.getVectorNumElements();
4598   SmallVector<int, 16> MaskVec;
4599   for (unsigned i = 0; i != NumElems; ++i)
4600     // If this is the insertion idx, put the low elt of V2 here.
4601     MaskVec.push_back(i == Idx ? NumElems : i);
4602   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4603 }
4604
4605 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4606 /// element of the result of the vector shuffle.
4607 static SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
4608                                    unsigned Depth) {
4609   if (Depth == 6)
4610     return SDValue();  // Limit search depth.
4611
4612   SDValue V = SDValue(N, 0);
4613   EVT VT = V.getValueType();
4614   unsigned Opcode = V.getOpcode();
4615
4616   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4617   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4618     Index = SV->getMaskElt(Index);
4619
4620     if (Index < 0)
4621       return DAG.getUNDEF(VT.getVectorElementType());
4622
4623     int NumElems = VT.getVectorNumElements();
4624     SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
4625     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
4626   }
4627
4628   // Recurse into target specific vector shuffles to find scalars.
4629   if (isTargetShuffle(Opcode)) {
4630     int NumElems = VT.getVectorNumElements();
4631     SmallVector<unsigned, 16> ShuffleMask;
4632     SDValue ImmN;
4633
4634     switch(Opcode) {
4635     case X86ISD::SHUFPS:
4636     case X86ISD::SHUFPD:
4637       ImmN = N->getOperand(N->getNumOperands()-1);
4638       DecodeSHUFPSMask(NumElems,
4639                        cast<ConstantSDNode>(ImmN)->getZExtValue(),
4640                        ShuffleMask);
4641       break;
4642     case X86ISD::PUNPCKHBW:
4643     case X86ISD::PUNPCKHWD:
4644     case X86ISD::PUNPCKHDQ:
4645     case X86ISD::PUNPCKHQDQ:
4646     case X86ISD::VPUNPCKHBWY:
4647     case X86ISD::VPUNPCKHWDY:
4648     case X86ISD::VPUNPCKHDQY:
4649     case X86ISD::VPUNPCKHQDQY:
4650       DecodePUNPCKHMask(NumElems, ShuffleMask);
4651       break;
4652     case X86ISD::UNPCKHPS:
4653     case X86ISD::UNPCKHPD:
4654     case X86ISD::VUNPCKHPSY:
4655     case X86ISD::VUNPCKHPDY:
4656       DecodeUNPCKHPMask(NumElems, ShuffleMask);
4657       break;
4658     case X86ISD::PUNPCKLBW:
4659     case X86ISD::PUNPCKLWD:
4660     case X86ISD::PUNPCKLDQ:
4661     case X86ISD::PUNPCKLQDQ:
4662     case X86ISD::VPUNPCKLBWY:
4663     case X86ISD::VPUNPCKLWDY:
4664     case X86ISD::VPUNPCKLDQY:
4665     case X86ISD::VPUNPCKLQDQY:
4666       DecodePUNPCKLMask(VT, ShuffleMask);
4667       break;
4668     case X86ISD::UNPCKLPS:
4669     case X86ISD::UNPCKLPD:
4670     case X86ISD::VUNPCKLPSY:
4671     case X86ISD::VUNPCKLPDY:
4672       DecodeUNPCKLPMask(VT, ShuffleMask);
4673       break;
4674     case X86ISD::MOVHLPS:
4675       DecodeMOVHLPSMask(NumElems, ShuffleMask);
4676       break;
4677     case X86ISD::MOVLHPS:
4678       DecodeMOVLHPSMask(NumElems, ShuffleMask);
4679       break;
4680     case X86ISD::PSHUFD:
4681       ImmN = N->getOperand(N->getNumOperands()-1);
4682       DecodePSHUFMask(NumElems,
4683                       cast<ConstantSDNode>(ImmN)->getZExtValue(),
4684                       ShuffleMask);
4685       break;
4686     case X86ISD::PSHUFHW:
4687       ImmN = N->getOperand(N->getNumOperands()-1);
4688       DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4689                         ShuffleMask);
4690       break;
4691     case X86ISD::PSHUFLW:
4692       ImmN = N->getOperand(N->getNumOperands()-1);
4693       DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4694                         ShuffleMask);
4695       break;
4696     case X86ISD::MOVSS:
4697     case X86ISD::MOVSD: {
4698       // The index 0 always comes from the first element of the second source,
4699       // this is why MOVSS and MOVSD are used in the first place. The other
4700       // elements come from the other positions of the first source vector.
4701       unsigned OpNum = (Index == 0) ? 1 : 0;
4702       return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
4703                                  Depth+1);
4704     }
4705     case X86ISD::VPERMILPS:
4706       ImmN = N->getOperand(N->getNumOperands()-1);
4707       DecodeVPERMILPSMask(4, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4708                         ShuffleMask);
4709       break;
4710     case X86ISD::VPERMILPSY:
4711       ImmN = N->getOperand(N->getNumOperands()-1);
4712       DecodeVPERMILPSMask(8, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4713                         ShuffleMask);
4714       break;
4715     case X86ISD::VPERMILPD:
4716       ImmN = N->getOperand(N->getNumOperands()-1);
4717       DecodeVPERMILPDMask(2, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4718                         ShuffleMask);
4719       break;
4720     case X86ISD::VPERMILPDY:
4721       ImmN = N->getOperand(N->getNumOperands()-1);
4722       DecodeVPERMILPDMask(4, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4723                         ShuffleMask);
4724       break;
4725     case X86ISD::VPERM2F128:
4726       ImmN = N->getOperand(N->getNumOperands()-1);
4727       DecodeVPERM2F128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4728                            ShuffleMask);
4729       break;
4730     case X86ISD::MOVDDUP:
4731     case X86ISD::MOVLHPD:
4732     case X86ISD::MOVLPD:
4733     case X86ISD::MOVLPS:
4734     case X86ISD::MOVSHDUP:
4735     case X86ISD::MOVSLDUP:
4736     case X86ISD::PALIGN:
4737       return SDValue(); // Not yet implemented.
4738     default:
4739       assert(0 && "unknown target shuffle node");
4740       return SDValue();
4741     }
4742
4743     Index = ShuffleMask[Index];
4744     if (Index < 0)
4745       return DAG.getUNDEF(VT.getVectorElementType());
4746
4747     SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
4748     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
4749                                Depth+1);
4750   }
4751
4752   // Actual nodes that may contain scalar elements
4753   if (Opcode == ISD::BITCAST) {
4754     V = V.getOperand(0);
4755     EVT SrcVT = V.getValueType();
4756     unsigned NumElems = VT.getVectorNumElements();
4757
4758     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4759       return SDValue();
4760   }
4761
4762   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4763     return (Index == 0) ? V.getOperand(0)
4764                           : DAG.getUNDEF(VT.getVectorElementType());
4765
4766   if (V.getOpcode() == ISD::BUILD_VECTOR)
4767     return V.getOperand(Index);
4768
4769   return SDValue();
4770 }
4771
4772 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4773 /// shuffle operation which come from a consecutively from a zero. The
4774 /// search can start in two different directions, from left or right.
4775 static
4776 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
4777                                   bool ZerosFromLeft, SelectionDAG &DAG) {
4778   int i = 0;
4779
4780   while (i < NumElems) {
4781     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4782     SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
4783     if (!(Elt.getNode() &&
4784          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4785       break;
4786     ++i;
4787   }
4788
4789   return i;
4790 }
4791
4792 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
4793 /// MaskE correspond consecutively to elements from one of the vector operands,
4794 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4795 static
4796 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
4797                               int OpIdx, int NumElems, unsigned &OpNum) {
4798   bool SeenV1 = false;
4799   bool SeenV2 = false;
4800
4801   for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
4802     int Idx = SVOp->getMaskElt(i);
4803     // Ignore undef indicies
4804     if (Idx < 0)
4805       continue;
4806
4807     if (Idx < NumElems)
4808       SeenV1 = true;
4809     else
4810       SeenV2 = true;
4811
4812     // Only accept consecutive elements from the same vector
4813     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4814       return false;
4815   }
4816
4817   OpNum = SeenV1 ? 0 : 1;
4818   return true;
4819 }
4820
4821 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4822 /// logical left shift of a vector.
4823 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4824                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4825   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4826   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4827               false /* check zeros from right */, DAG);
4828   unsigned OpSrc;
4829
4830   if (!NumZeros)
4831     return false;
4832
4833   // Considering the elements in the mask that are not consecutive zeros,
4834   // check if they consecutively come from only one of the source vectors.
4835   //
4836   //               V1 = {X, A, B, C}     0
4837   //                         \  \  \    /
4838   //   vector_shuffle V1, V2 <1, 2, 3, X>
4839   //
4840   if (!isShuffleMaskConsecutive(SVOp,
4841             0,                   // Mask Start Index
4842             NumElems-NumZeros-1, // Mask End Index
4843             NumZeros,            // Where to start looking in the src vector
4844             NumElems,            // Number of elements in vector
4845             OpSrc))              // Which source operand ?
4846     return false;
4847
4848   isLeft = false;
4849   ShAmt = NumZeros;
4850   ShVal = SVOp->getOperand(OpSrc);
4851   return true;
4852 }
4853
4854 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4855 /// logical left shift of a vector.
4856 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4857                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4858   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4859   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4860               true /* check zeros from left */, DAG);
4861   unsigned OpSrc;
4862
4863   if (!NumZeros)
4864     return false;
4865
4866   // Considering the elements in the mask that are not consecutive zeros,
4867   // check if they consecutively come from only one of the source vectors.
4868   //
4869   //                           0    { A, B, X, X } = V2
4870   //                          / \    /  /
4871   //   vector_shuffle V1, V2 <X, X, 4, 5>
4872   //
4873   if (!isShuffleMaskConsecutive(SVOp,
4874             NumZeros,     // Mask Start Index
4875             NumElems-1,   // Mask End Index
4876             0,            // Where to start looking in the src vector
4877             NumElems,     // Number of elements in vector
4878             OpSrc))       // Which source operand ?
4879     return false;
4880
4881   isLeft = true;
4882   ShAmt = NumZeros;
4883   ShVal = SVOp->getOperand(OpSrc);
4884   return true;
4885 }
4886
4887 /// isVectorShift - Returns true if the shuffle can be implemented as a
4888 /// logical left or right shift of a vector.
4889 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4890                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4891   // Although the logic below support any bitwidth size, there are no
4892   // shift instructions which handle more than 128-bit vectors.
4893   if (SVOp->getValueType(0).getSizeInBits() > 128)
4894     return false;
4895
4896   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4897       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4898     return true;
4899
4900   return false;
4901 }
4902
4903 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4904 ///
4905 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4906                                        unsigned NumNonZero, unsigned NumZero,
4907                                        SelectionDAG &DAG,
4908                                        const TargetLowering &TLI) {
4909   if (NumNonZero > 8)
4910     return SDValue();
4911
4912   DebugLoc dl = Op.getDebugLoc();
4913   SDValue V(0, 0);
4914   bool First = true;
4915   for (unsigned i = 0; i < 16; ++i) {
4916     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4917     if (ThisIsNonZero && First) {
4918       if (NumZero)
4919         V = getZeroVector(MVT::v8i16, true, DAG, dl);
4920       else
4921         V = DAG.getUNDEF(MVT::v8i16);
4922       First = false;
4923     }
4924
4925     if ((i & 1) != 0) {
4926       SDValue ThisElt(0, 0), LastElt(0, 0);
4927       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4928       if (LastIsNonZero) {
4929         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4930                               MVT::i16, Op.getOperand(i-1));
4931       }
4932       if (ThisIsNonZero) {
4933         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4934         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4935                               ThisElt, DAG.getConstant(8, MVT::i8));
4936         if (LastIsNonZero)
4937           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4938       } else
4939         ThisElt = LastElt;
4940
4941       if (ThisElt.getNode())
4942         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4943                         DAG.getIntPtrConstant(i/2));
4944     }
4945   }
4946
4947   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4948 }
4949
4950 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4951 ///
4952 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4953                                      unsigned NumNonZero, unsigned NumZero,
4954                                      SelectionDAG &DAG,
4955                                      const TargetLowering &TLI) {
4956   if (NumNonZero > 4)
4957     return SDValue();
4958
4959   DebugLoc dl = Op.getDebugLoc();
4960   SDValue V(0, 0);
4961   bool First = true;
4962   for (unsigned i = 0; i < 8; ++i) {
4963     bool isNonZero = (NonZeros & (1 << i)) != 0;
4964     if (isNonZero) {
4965       if (First) {
4966         if (NumZero)
4967           V = getZeroVector(MVT::v8i16, true, DAG, dl);
4968         else
4969           V = DAG.getUNDEF(MVT::v8i16);
4970         First = false;
4971       }
4972       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4973                       MVT::v8i16, V, Op.getOperand(i),
4974                       DAG.getIntPtrConstant(i));
4975     }
4976   }
4977
4978   return V;
4979 }
4980
4981 /// getVShift - Return a vector logical shift node.
4982 ///
4983 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4984                          unsigned NumBits, SelectionDAG &DAG,
4985                          const TargetLowering &TLI, DebugLoc dl) {
4986   assert(VT.getSizeInBits() == 128 && "Unknown type for VShift");
4987   EVT ShVT = MVT::v2i64;
4988   unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
4989   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4990   return DAG.getNode(ISD::BITCAST, dl, VT,
4991                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4992                              DAG.getConstant(NumBits,
4993                                   TLI.getShiftAmountTy(SrcOp.getValueType()))));
4994 }
4995
4996 SDValue
4997 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4998                                           SelectionDAG &DAG) const {
4999
5000   // Check if the scalar load can be widened into a vector load. And if
5001   // the address is "base + cst" see if the cst can be "absorbed" into
5002   // the shuffle mask.
5003   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5004     SDValue Ptr = LD->getBasePtr();
5005     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5006       return SDValue();
5007     EVT PVT = LD->getValueType(0);
5008     if (PVT != MVT::i32 && PVT != MVT::f32)
5009       return SDValue();
5010
5011     int FI = -1;
5012     int64_t Offset = 0;
5013     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5014       FI = FINode->getIndex();
5015       Offset = 0;
5016     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5017                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5018       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5019       Offset = Ptr.getConstantOperandVal(1);
5020       Ptr = Ptr.getOperand(0);
5021     } else {
5022       return SDValue();
5023     }
5024
5025     // FIXME: 256-bit vector instructions don't require a strict alignment,
5026     // improve this code to support it better.
5027     unsigned RequiredAlign = VT.getSizeInBits()/8;
5028     SDValue Chain = LD->getChain();
5029     // Make sure the stack object alignment is at least 16 or 32.
5030     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5031     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5032       if (MFI->isFixedObjectIndex(FI)) {
5033         // Can't change the alignment. FIXME: It's possible to compute
5034         // the exact stack offset and reference FI + adjust offset instead.
5035         // If someone *really* cares about this. That's the way to implement it.
5036         return SDValue();
5037       } else {
5038         MFI->setObjectAlignment(FI, RequiredAlign);
5039       }
5040     }
5041
5042     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5043     // Ptr + (Offset & ~15).
5044     if (Offset < 0)
5045       return SDValue();
5046     if ((Offset % RequiredAlign) & 3)
5047       return SDValue();
5048     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5049     if (StartOffset)
5050       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
5051                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5052
5053     int EltNo = (Offset - StartOffset) >> 2;
5054     int NumElems = VT.getVectorNumElements();
5055
5056     EVT CanonVT = VT.getSizeInBits() == 128 ? MVT::v4i32 : MVT::v8i32;
5057     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5058     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5059                              LD->getPointerInfo().getWithOffset(StartOffset),
5060                              false, false, false, 0);
5061
5062     // Canonicalize it to a v4i32 or v8i32 shuffle.
5063     SmallVector<int, 8> Mask;
5064     for (int i = 0; i < NumElems; ++i)
5065       Mask.push_back(EltNo);
5066
5067     V1 = DAG.getNode(ISD::BITCAST, dl, CanonVT, V1);
5068     return DAG.getNode(ISD::BITCAST, dl, NVT,
5069                        DAG.getVectorShuffle(CanonVT, dl, V1,
5070                                             DAG.getUNDEF(CanonVT),&Mask[0]));
5071   }
5072
5073   return SDValue();
5074 }
5075
5076 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5077 /// vector of type 'VT', see if the elements can be replaced by a single large
5078 /// load which has the same value as a build_vector whose operands are 'elts'.
5079 ///
5080 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5081 ///
5082 /// FIXME: we'd also like to handle the case where the last elements are zero
5083 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5084 /// There's even a handy isZeroNode for that purpose.
5085 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5086                                         DebugLoc &DL, SelectionDAG &DAG) {
5087   EVT EltVT = VT.getVectorElementType();
5088   unsigned NumElems = Elts.size();
5089
5090   LoadSDNode *LDBase = NULL;
5091   unsigned LastLoadedElt = -1U;
5092
5093   // For each element in the initializer, see if we've found a load or an undef.
5094   // If we don't find an initial load element, or later load elements are
5095   // non-consecutive, bail out.
5096   for (unsigned i = 0; i < NumElems; ++i) {
5097     SDValue Elt = Elts[i];
5098
5099     if (!Elt.getNode() ||
5100         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5101       return SDValue();
5102     if (!LDBase) {
5103       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5104         return SDValue();
5105       LDBase = cast<LoadSDNode>(Elt.getNode());
5106       LastLoadedElt = i;
5107       continue;
5108     }
5109     if (Elt.getOpcode() == ISD::UNDEF)
5110       continue;
5111
5112     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5113     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5114       return SDValue();
5115     LastLoadedElt = i;
5116   }
5117
5118   // If we have found an entire vector of loads and undefs, then return a large
5119   // load of the entire vector width starting at the base pointer.  If we found
5120   // consecutive loads for the low half, generate a vzext_load node.
5121   if (LastLoadedElt == NumElems - 1) {
5122     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5123       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5124                          LDBase->getPointerInfo(),
5125                          LDBase->isVolatile(), LDBase->isNonTemporal(),
5126                          LDBase->isInvariant(), 0);
5127     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5128                        LDBase->getPointerInfo(),
5129                        LDBase->isVolatile(), LDBase->isNonTemporal(),
5130                        LDBase->isInvariant(), LDBase->getAlignment());
5131   } else if (NumElems == 4 && LastLoadedElt == 1 &&
5132              DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5133     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5134     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5135     SDValue ResNode =
5136         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
5137                                 LDBase->getPointerInfo(),
5138                                 LDBase->getAlignment(),
5139                                 false/*isVolatile*/, true/*ReadMem*/,
5140                                 false/*WriteMem*/);
5141     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5142   }
5143   return SDValue();
5144 }
5145
5146 /// isVectorBroadcast - Check if the node chain is suitable to be xformed to
5147 /// a vbroadcast node. We support two patterns:
5148 /// 1. A splat BUILD_VECTOR which uses a single scalar load.
5149 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5150 /// a scalar load.
5151 /// The scalar load node is returned when a pattern is found,
5152 /// or SDValue() otherwise.
5153 static SDValue isVectorBroadcast(SDValue &Op, bool hasAVX2) {
5154   EVT VT = Op.getValueType();
5155   SDValue V = Op;
5156
5157   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5158     V = V.getOperand(0);
5159
5160   //A suspected load to be broadcasted.
5161   SDValue Ld;
5162
5163   switch (V.getOpcode()) {
5164     default:
5165       // Unknown pattern found.
5166       return SDValue();
5167
5168     case ISD::BUILD_VECTOR: {
5169       // The BUILD_VECTOR node must be a splat.
5170       if (!isSplatVector(V.getNode()))
5171         return SDValue();
5172
5173       Ld = V.getOperand(0);
5174
5175       // The suspected load node has several users. Make sure that all
5176       // of its users are from the BUILD_VECTOR node.
5177       if (!Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5178         return SDValue();
5179       break;
5180     }
5181
5182     case ISD::VECTOR_SHUFFLE: {
5183       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5184
5185       // Shuffles must have a splat mask where the first element is
5186       // broadcasted.
5187       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5188         return SDValue();
5189
5190       SDValue Sc = Op.getOperand(0);
5191       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR)
5192         return SDValue();
5193
5194       Ld = Sc.getOperand(0);
5195
5196       // The scalar_to_vector node and the suspected
5197       // load node must have exactly one user.
5198       if (!Sc.hasOneUse() || !Ld.hasOneUse())
5199         return SDValue();
5200       break;
5201     }
5202   }
5203
5204   // The scalar source must be a normal load.
5205   if (!ISD::isNormalLoad(Ld.getNode()))
5206     return SDValue();
5207
5208   bool Is256 = VT.getSizeInBits() == 256;
5209   bool Is128 = VT.getSizeInBits() == 128;
5210   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5211
5212   if (hasAVX2) {
5213     // VBroadcast to YMM
5214     if (Is256 && (ScalarSize == 8  || ScalarSize == 16 ||
5215                   ScalarSize == 32 || ScalarSize == 64 ))
5216       return Ld;
5217
5218     // VBroadcast to XMM
5219     if (Is128 && (ScalarSize ==  8 || ScalarSize == 32 ||
5220                   ScalarSize == 16 || ScalarSize == 64 ))
5221       return Ld;
5222   }
5223
5224   // VBroadcast to YMM
5225   if (Is256 && (ScalarSize == 32 || ScalarSize == 64))
5226     return Ld;
5227
5228   // VBroadcast to XMM
5229   if (Is128 && (ScalarSize == 32))
5230     return Ld;
5231
5232
5233   // Unsupported broadcast.
5234   return SDValue();
5235 }
5236
5237 SDValue
5238 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5239   DebugLoc dl = Op.getDebugLoc();
5240
5241   EVT VT = Op.getValueType();
5242   EVT ExtVT = VT.getVectorElementType();
5243   unsigned NumElems = Op.getNumOperands();
5244
5245   // Vectors containing all zeros can be matched by pxor and xorps later
5246   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5247     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5248     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5249     if (Op.getValueType() == MVT::v4i32 ||
5250         Op.getValueType() == MVT::v8i32)
5251       return Op;
5252
5253     return getZeroVector(Op.getValueType(), Subtarget->hasXMMInt(), DAG, dl);
5254   }
5255
5256   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5257   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5258   // vpcmpeqd on 256-bit vectors.
5259   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5260     if (Op.getValueType() == MVT::v4i32 ||
5261         (Op.getValueType() == MVT::v8i32 && Subtarget->hasAVX2()))
5262       return Op;
5263
5264     return getOnesVector(Op.getValueType(), Subtarget->hasAVX2(), DAG, dl);
5265   }
5266
5267   SDValue LD = isVectorBroadcast(Op, Subtarget->hasAVX2());
5268   if (Subtarget->hasAVX() && LD.getNode())
5269       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, LD);
5270
5271   unsigned EVTBits = ExtVT.getSizeInBits();
5272
5273   unsigned NumZero  = 0;
5274   unsigned NumNonZero = 0;
5275   unsigned NonZeros = 0;
5276   bool IsAllConstants = true;
5277   SmallSet<SDValue, 8> Values;
5278   for (unsigned i = 0; i < NumElems; ++i) {
5279     SDValue Elt = Op.getOperand(i);
5280     if (Elt.getOpcode() == ISD::UNDEF)
5281       continue;
5282     Values.insert(Elt);
5283     if (Elt.getOpcode() != ISD::Constant &&
5284         Elt.getOpcode() != ISD::ConstantFP)
5285       IsAllConstants = false;
5286     if (X86::isZeroNode(Elt))
5287       NumZero++;
5288     else {
5289       NonZeros |= (1 << i);
5290       NumNonZero++;
5291     }
5292   }
5293
5294   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5295   if (NumNonZero == 0)
5296     return DAG.getUNDEF(VT);
5297
5298   // Special case for single non-zero, non-undef, element.
5299   if (NumNonZero == 1) {
5300     unsigned Idx = CountTrailingZeros_32(NonZeros);
5301     SDValue Item = Op.getOperand(Idx);
5302
5303     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5304     // the value are obviously zero, truncate the value to i32 and do the
5305     // insertion that way.  Only do this if the value is non-constant or if the
5306     // value is a constant being inserted into element 0.  It is cheaper to do
5307     // a constant pool load than it is to do a movd + shuffle.
5308     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5309         (!IsAllConstants || Idx == 0)) {
5310       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5311         // Handle SSE only.
5312         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5313         EVT VecVT = MVT::v4i32;
5314         unsigned VecElts = 4;
5315
5316         // Truncate the value (which may itself be a constant) to i32, and
5317         // convert it to a vector with movd (S2V+shuffle to zero extend).
5318         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5319         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5320         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
5321                                            Subtarget->hasXMMInt(), DAG);
5322
5323         // Now we have our 32-bit value zero extended in the low element of
5324         // a vector.  If Idx != 0, swizzle it into place.
5325         if (Idx != 0) {
5326           SmallVector<int, 4> Mask;
5327           Mask.push_back(Idx);
5328           for (unsigned i = 1; i != VecElts; ++i)
5329             Mask.push_back(i);
5330           Item = DAG.getVectorShuffle(VecVT, dl, Item,
5331                                       DAG.getUNDEF(Item.getValueType()),
5332                                       &Mask[0]);
5333         }
5334         return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
5335       }
5336     }
5337
5338     // If we have a constant or non-constant insertion into the low element of
5339     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5340     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5341     // depending on what the source datatype is.
5342     if (Idx == 0) {
5343       if (NumZero == 0) {
5344         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5345       } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5346           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5347         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5348         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5349         return getShuffleVectorZeroOrUndef(Item, 0, true,Subtarget->hasXMMInt(),
5350                                            DAG);
5351       } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5352         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5353         assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
5354         EVT MiddleVT = MVT::v4i32;
5355         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
5356         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
5357                                            Subtarget->hasXMMInt(), DAG);
5358         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5359       }
5360     }
5361
5362     // Is it a vector logical left shift?
5363     if (NumElems == 2 && Idx == 1 &&
5364         X86::isZeroNode(Op.getOperand(0)) &&
5365         !X86::isZeroNode(Op.getOperand(1))) {
5366       unsigned NumBits = VT.getSizeInBits();
5367       return getVShift(true, VT,
5368                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5369                                    VT, Op.getOperand(1)),
5370                        NumBits/2, DAG, *this, dl);
5371     }
5372
5373     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5374       return SDValue();
5375
5376     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5377     // is a non-constant being inserted into an element other than the low one,
5378     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5379     // movd/movss) to move this into the low element, then shuffle it into
5380     // place.
5381     if (EVTBits == 32) {
5382       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5383
5384       // Turn it into a shuffle of zero and zero-extended scalar to vector.
5385       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
5386                                          Subtarget->hasXMMInt(), DAG);
5387       SmallVector<int, 8> MaskVec;
5388       for (unsigned i = 0; i < NumElems; i++)
5389         MaskVec.push_back(i == Idx ? 0 : 1);
5390       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5391     }
5392   }
5393
5394   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5395   if (Values.size() == 1) {
5396     if (EVTBits == 32) {
5397       // Instead of a shuffle like this:
5398       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5399       // Check if it's possible to issue this instead.
5400       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5401       unsigned Idx = CountTrailingZeros_32(NonZeros);
5402       SDValue Item = Op.getOperand(Idx);
5403       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5404         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5405     }
5406     return SDValue();
5407   }
5408
5409   // A vector full of immediates; various special cases are already
5410   // handled, so this is best done with a single constant-pool load.
5411   if (IsAllConstants)
5412     return SDValue();
5413
5414   // For AVX-length vectors, build the individual 128-bit pieces and use
5415   // shuffles to put them in place.
5416   if (VT.getSizeInBits() == 256 && !ISD::isBuildVectorAllZeros(Op.getNode())) {
5417     SmallVector<SDValue, 32> V;
5418     for (unsigned i = 0; i < NumElems; ++i)
5419       V.push_back(Op.getOperand(i));
5420
5421     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5422
5423     // Build both the lower and upper subvector.
5424     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5425     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5426                                 NumElems/2);
5427
5428     // Recreate the wider vector with the lower and upper part.
5429     SDValue Vec = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), Lower,
5430                                 DAG.getConstant(0, MVT::i32), DAG, dl);
5431     return Insert128BitVector(Vec, Upper, DAG.getConstant(NumElems/2, MVT::i32),
5432                               DAG, dl);
5433   }
5434
5435   // Let legalizer expand 2-wide build_vectors.
5436   if (EVTBits == 64) {
5437     if (NumNonZero == 1) {
5438       // One half is zero or undef.
5439       unsigned Idx = CountTrailingZeros_32(NonZeros);
5440       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5441                                  Op.getOperand(Idx));
5442       return getShuffleVectorZeroOrUndef(V2, Idx, true,
5443                                          Subtarget->hasXMMInt(), DAG);
5444     }
5445     return SDValue();
5446   }
5447
5448   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5449   if (EVTBits == 8 && NumElems == 16) {
5450     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5451                                         *this);
5452     if (V.getNode()) return V;
5453   }
5454
5455   if (EVTBits == 16 && NumElems == 8) {
5456     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5457                                       *this);
5458     if (V.getNode()) return V;
5459   }
5460
5461   // If element VT is == 32 bits, turn it into a number of shuffles.
5462   SmallVector<SDValue, 8> V;
5463   V.resize(NumElems);
5464   if (NumElems == 4 && NumZero > 0) {
5465     for (unsigned i = 0; i < 4; ++i) {
5466       bool isZero = !(NonZeros & (1 << i));
5467       if (isZero)
5468         V[i] = getZeroVector(VT, Subtarget->hasXMMInt(), DAG, dl);
5469       else
5470         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5471     }
5472
5473     for (unsigned i = 0; i < 2; ++i) {
5474       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5475         default: break;
5476         case 0:
5477           V[i] = V[i*2];  // Must be a zero vector.
5478           break;
5479         case 1:
5480           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5481           break;
5482         case 2:
5483           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5484           break;
5485         case 3:
5486           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5487           break;
5488       }
5489     }
5490
5491     SmallVector<int, 8> MaskVec;
5492     bool Reverse = (NonZeros & 0x3) == 2;
5493     for (unsigned i = 0; i < 2; ++i)
5494       MaskVec.push_back(Reverse ? 1-i : i);
5495     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5496     for (unsigned i = 0; i < 2; ++i)
5497       MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
5498     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5499   }
5500
5501   if (Values.size() > 1 && VT.getSizeInBits() == 128) {
5502     // Check for a build vector of consecutive loads.
5503     for (unsigned i = 0; i < NumElems; ++i)
5504       V[i] = Op.getOperand(i);
5505
5506     // Check for elements which are consecutive loads.
5507     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5508     if (LD.getNode())
5509       return LD;
5510
5511     // For SSE 4.1, use insertps to put the high elements into the low element.
5512     if (getSubtarget()->hasSSE41orAVX()) {
5513       SDValue Result;
5514       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5515         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5516       else
5517         Result = DAG.getUNDEF(VT);
5518
5519       for (unsigned i = 1; i < NumElems; ++i) {
5520         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5521         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5522                              Op.getOperand(i), DAG.getIntPtrConstant(i));
5523       }
5524       return Result;
5525     }
5526
5527     // Otherwise, expand into a number of unpckl*, start by extending each of
5528     // our (non-undef) elements to the full vector width with the element in the
5529     // bottom slot of the vector (which generates no code for SSE).
5530     for (unsigned i = 0; i < NumElems; ++i) {
5531       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5532         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5533       else
5534         V[i] = DAG.getUNDEF(VT);
5535     }
5536
5537     // Next, we iteratively mix elements, e.g. for v4f32:
5538     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5539     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5540     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5541     unsigned EltStride = NumElems >> 1;
5542     while (EltStride != 0) {
5543       for (unsigned i = 0; i < EltStride; ++i) {
5544         // If V[i+EltStride] is undef and this is the first round of mixing,
5545         // then it is safe to just drop this shuffle: V[i] is already in the
5546         // right place, the one element (since it's the first round) being
5547         // inserted as undef can be dropped.  This isn't safe for successive
5548         // rounds because they will permute elements within both vectors.
5549         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5550             EltStride == NumElems/2)
5551           continue;
5552
5553         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5554       }
5555       EltStride >>= 1;
5556     }
5557     return V[0];
5558   }
5559   return SDValue();
5560 }
5561
5562 // LowerMMXCONCAT_VECTORS - We support concatenate two MMX registers and place
5563 // them in a MMX register.  This is better than doing a stack convert.
5564 static SDValue LowerMMXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5565   DebugLoc dl = Op.getDebugLoc();
5566   EVT ResVT = Op.getValueType();
5567
5568   assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
5569          ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
5570   int Mask[2];
5571   SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
5572   SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5573   InVec = Op.getOperand(1);
5574   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5575     unsigned NumElts = ResVT.getVectorNumElements();
5576     VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5577     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
5578                        InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
5579   } else {
5580     InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
5581     SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5582     Mask[0] = 0; Mask[1] = 2;
5583     VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
5584   }
5585   return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5586 }
5587
5588 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5589 // to create 256-bit vectors from two other 128-bit ones.
5590 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5591   DebugLoc dl = Op.getDebugLoc();
5592   EVT ResVT = Op.getValueType();
5593
5594   assert(ResVT.getSizeInBits() == 256 && "Value type must be 256-bit wide");
5595
5596   SDValue V1 = Op.getOperand(0);
5597   SDValue V2 = Op.getOperand(1);
5598   unsigned NumElems = ResVT.getVectorNumElements();
5599
5600   SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, ResVT), V1,
5601                                  DAG.getConstant(0, MVT::i32), DAG, dl);
5602   return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32),
5603                             DAG, dl);
5604 }
5605
5606 SDValue
5607 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
5608   EVT ResVT = Op.getValueType();
5609
5610   assert(Op.getNumOperands() == 2);
5611   assert((ResVT.getSizeInBits() == 128 || ResVT.getSizeInBits() == 256) &&
5612          "Unsupported CONCAT_VECTORS for value type");
5613
5614   // We support concatenate two MMX registers and place them in a MMX register.
5615   // This is better than doing a stack convert.
5616   if (ResVT.is128BitVector())
5617     return LowerMMXCONCAT_VECTORS(Op, DAG);
5618
5619   // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5620   // from two other 128-bit ones.
5621   return LowerAVXCONCAT_VECTORS(Op, DAG);
5622 }
5623
5624 // v8i16 shuffles - Prefer shuffles in the following order:
5625 // 1. [all]   pshuflw, pshufhw, optional move
5626 // 2. [ssse3] 1 x pshufb
5627 // 3. [ssse3] 2 x pshufb + 1 x por
5628 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5629 SDValue
5630 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
5631                                             SelectionDAG &DAG) const {
5632   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5633   SDValue V1 = SVOp->getOperand(0);
5634   SDValue V2 = SVOp->getOperand(1);
5635   DebugLoc dl = SVOp->getDebugLoc();
5636   SmallVector<int, 8> MaskVals;
5637
5638   // Determine if more than 1 of the words in each of the low and high quadwords
5639   // of the result come from the same quadword of one of the two inputs.  Undef
5640   // mask values count as coming from any quadword, for better codegen.
5641   unsigned LoQuad[] = { 0, 0, 0, 0 };
5642   unsigned HiQuad[] = { 0, 0, 0, 0 };
5643   BitVector InputQuads(4);
5644   for (unsigned i = 0; i < 8; ++i) {
5645     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5646     int EltIdx = SVOp->getMaskElt(i);
5647     MaskVals.push_back(EltIdx);
5648     if (EltIdx < 0) {
5649       ++Quad[0];
5650       ++Quad[1];
5651       ++Quad[2];
5652       ++Quad[3];
5653       continue;
5654     }
5655     ++Quad[EltIdx / 4];
5656     InputQuads.set(EltIdx / 4);
5657   }
5658
5659   int BestLoQuad = -1;
5660   unsigned MaxQuad = 1;
5661   for (unsigned i = 0; i < 4; ++i) {
5662     if (LoQuad[i] > MaxQuad) {
5663       BestLoQuad = i;
5664       MaxQuad = LoQuad[i];
5665     }
5666   }
5667
5668   int BestHiQuad = -1;
5669   MaxQuad = 1;
5670   for (unsigned i = 0; i < 4; ++i) {
5671     if (HiQuad[i] > MaxQuad) {
5672       BestHiQuad = i;
5673       MaxQuad = HiQuad[i];
5674     }
5675   }
5676
5677   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5678   // of the two input vectors, shuffle them into one input vector so only a
5679   // single pshufb instruction is necessary. If There are more than 2 input
5680   // quads, disable the next transformation since it does not help SSSE3.
5681   bool V1Used = InputQuads[0] || InputQuads[1];
5682   bool V2Used = InputQuads[2] || InputQuads[3];
5683   if (Subtarget->hasSSSE3orAVX()) {
5684     if (InputQuads.count() == 2 && V1Used && V2Used) {
5685       BestLoQuad = InputQuads.find_first();
5686       BestHiQuad = InputQuads.find_next(BestLoQuad);
5687     }
5688     if (InputQuads.count() > 2) {
5689       BestLoQuad = -1;
5690       BestHiQuad = -1;
5691     }
5692   }
5693
5694   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5695   // the shuffle mask.  If a quad is scored as -1, that means that it contains
5696   // words from all 4 input quadwords.
5697   SDValue NewV;
5698   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5699     SmallVector<int, 8> MaskV;
5700     MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
5701     MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
5702     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5703                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5704                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5705     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5706
5707     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5708     // source words for the shuffle, to aid later transformations.
5709     bool AllWordsInNewV = true;
5710     bool InOrder[2] = { true, true };
5711     for (unsigned i = 0; i != 8; ++i) {
5712       int idx = MaskVals[i];
5713       if (idx != (int)i)
5714         InOrder[i/4] = false;
5715       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5716         continue;
5717       AllWordsInNewV = false;
5718       break;
5719     }
5720
5721     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5722     if (AllWordsInNewV) {
5723       for (int i = 0; i != 8; ++i) {
5724         int idx = MaskVals[i];
5725         if (idx < 0)
5726           continue;
5727         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5728         if ((idx != i) && idx < 4)
5729           pshufhw = false;
5730         if ((idx != i) && idx > 3)
5731           pshuflw = false;
5732       }
5733       V1 = NewV;
5734       V2Used = false;
5735       BestLoQuad = 0;
5736       BestHiQuad = 1;
5737     }
5738
5739     // If we've eliminated the use of V2, and the new mask is a pshuflw or
5740     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
5741     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5742       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5743       unsigned TargetMask = 0;
5744       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5745                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5746       TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
5747                              X86::getShufflePSHUFLWImmediate(NewV.getNode());
5748       V1 = NewV.getOperand(0);
5749       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5750     }
5751   }
5752
5753   // If we have SSSE3, and all words of the result are from 1 input vector,
5754   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5755   // is present, fall back to case 4.
5756   if (Subtarget->hasSSSE3orAVX()) {
5757     SmallVector<SDValue,16> pshufbMask;
5758
5759     // If we have elements from both input vectors, set the high bit of the
5760     // shuffle mask element to zero out elements that come from V2 in the V1
5761     // mask, and elements that come from V1 in the V2 mask, so that the two
5762     // results can be OR'd together.
5763     bool TwoInputs = V1Used && V2Used;
5764     for (unsigned i = 0; i != 8; ++i) {
5765       int EltIdx = MaskVals[i] * 2;
5766       if (TwoInputs && (EltIdx >= 16)) {
5767         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5768         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5769         continue;
5770       }
5771       pshufbMask.push_back(DAG.getConstant(EltIdx,   MVT::i8));
5772       pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
5773     }
5774     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5775     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5776                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5777                                  MVT::v16i8, &pshufbMask[0], 16));
5778     if (!TwoInputs)
5779       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5780
5781     // Calculate the shuffle mask for the second input, shuffle it, and
5782     // OR it with the first shuffled input.
5783     pshufbMask.clear();
5784     for (unsigned i = 0; i != 8; ++i) {
5785       int EltIdx = MaskVals[i] * 2;
5786       if (EltIdx < 16) {
5787         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5788         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5789         continue;
5790       }
5791       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5792       pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
5793     }
5794     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5795     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5796                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5797                                  MVT::v16i8, &pshufbMask[0], 16));
5798     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5799     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5800   }
5801
5802   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5803   // and update MaskVals with new element order.
5804   BitVector InOrder(8);
5805   if (BestLoQuad >= 0) {
5806     SmallVector<int, 8> MaskV;
5807     for (int i = 0; i != 4; ++i) {
5808       int idx = MaskVals[i];
5809       if (idx < 0) {
5810         MaskV.push_back(-1);
5811         InOrder.set(i);
5812       } else if ((idx / 4) == BestLoQuad) {
5813         MaskV.push_back(idx & 3);
5814         InOrder.set(i);
5815       } else {
5816         MaskV.push_back(-1);
5817       }
5818     }
5819     for (unsigned i = 4; i != 8; ++i)
5820       MaskV.push_back(i);
5821     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5822                                 &MaskV[0]);
5823
5824     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3orAVX())
5825       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5826                                NewV.getOperand(0),
5827                                X86::getShufflePSHUFLWImmediate(NewV.getNode()),
5828                                DAG);
5829   }
5830
5831   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5832   // and update MaskVals with the new element order.
5833   if (BestHiQuad >= 0) {
5834     SmallVector<int, 8> MaskV;
5835     for (unsigned i = 0; i != 4; ++i)
5836       MaskV.push_back(i);
5837     for (unsigned i = 4; i != 8; ++i) {
5838       int idx = MaskVals[i];
5839       if (idx < 0) {
5840         MaskV.push_back(-1);
5841         InOrder.set(i);
5842       } else if ((idx / 4) == BestHiQuad) {
5843         MaskV.push_back((idx & 3) + 4);
5844         InOrder.set(i);
5845       } else {
5846         MaskV.push_back(-1);
5847       }
5848     }
5849     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5850                                 &MaskV[0]);
5851
5852     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3orAVX())
5853       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5854                               NewV.getOperand(0),
5855                               X86::getShufflePSHUFHWImmediate(NewV.getNode()),
5856                               DAG);
5857   }
5858
5859   // In case BestHi & BestLo were both -1, which means each quadword has a word
5860   // from each of the four input quadwords, calculate the InOrder bitvector now
5861   // before falling through to the insert/extract cleanup.
5862   if (BestLoQuad == -1 && BestHiQuad == -1) {
5863     NewV = V1;
5864     for (int i = 0; i != 8; ++i)
5865       if (MaskVals[i] < 0 || MaskVals[i] == i)
5866         InOrder.set(i);
5867   }
5868
5869   // The other elements are put in the right place using pextrw and pinsrw.
5870   for (unsigned i = 0; i != 8; ++i) {
5871     if (InOrder[i])
5872       continue;
5873     int EltIdx = MaskVals[i];
5874     if (EltIdx < 0)
5875       continue;
5876     SDValue ExtOp = (EltIdx < 8)
5877     ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5878                   DAG.getIntPtrConstant(EltIdx))
5879     : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5880                   DAG.getIntPtrConstant(EltIdx - 8));
5881     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5882                        DAG.getIntPtrConstant(i));
5883   }
5884   return NewV;
5885 }
5886
5887 // v16i8 shuffles - Prefer shuffles in the following order:
5888 // 1. [ssse3] 1 x pshufb
5889 // 2. [ssse3] 2 x pshufb + 1 x por
5890 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
5891 static
5892 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5893                                  SelectionDAG &DAG,
5894                                  const X86TargetLowering &TLI) {
5895   SDValue V1 = SVOp->getOperand(0);
5896   SDValue V2 = SVOp->getOperand(1);
5897   DebugLoc dl = SVOp->getDebugLoc();
5898   SmallVector<int, 16> MaskVals;
5899   SVOp->getMask(MaskVals);
5900
5901   // If we have SSSE3, case 1 is generated when all result bytes come from
5902   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
5903   // present, fall back to case 3.
5904   // FIXME: kill V2Only once shuffles are canonizalized by getNode.
5905   bool V1Only = true;
5906   bool V2Only = true;
5907   for (unsigned i = 0; i < 16; ++i) {
5908     int EltIdx = MaskVals[i];
5909     if (EltIdx < 0)
5910       continue;
5911     if (EltIdx < 16)
5912       V2Only = false;
5913     else
5914       V1Only = false;
5915   }
5916
5917   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5918   if (TLI.getSubtarget()->hasSSSE3orAVX()) {
5919     SmallVector<SDValue,16> pshufbMask;
5920
5921     // If all result elements are from one input vector, then only translate
5922     // undef mask values to 0x80 (zero out result) in the pshufb mask.
5923     //
5924     // Otherwise, we have elements from both input vectors, and must zero out
5925     // elements that come from V2 in the first mask, and V1 in the second mask
5926     // so that we can OR them together.
5927     bool TwoInputs = !(V1Only || V2Only);
5928     for (unsigned i = 0; i != 16; ++i) {
5929       int EltIdx = MaskVals[i];
5930       if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
5931         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5932         continue;
5933       }
5934       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5935     }
5936     // If all the elements are from V2, assign it to V1 and return after
5937     // building the first pshufb.
5938     if (V2Only)
5939       V1 = V2;
5940     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5941                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5942                                  MVT::v16i8, &pshufbMask[0], 16));
5943     if (!TwoInputs)
5944       return V1;
5945
5946     // Calculate the shuffle mask for the second input, shuffle it, and
5947     // OR it with the first shuffled input.
5948     pshufbMask.clear();
5949     for (unsigned i = 0; i != 16; ++i) {
5950       int EltIdx = MaskVals[i];
5951       if (EltIdx < 16) {
5952         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5953         continue;
5954       }
5955       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5956     }
5957     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5958                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5959                                  MVT::v16i8, &pshufbMask[0], 16));
5960     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5961   }
5962
5963   // No SSSE3 - Calculate in place words and then fix all out of place words
5964   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
5965   // the 16 different words that comprise the two doublequadword input vectors.
5966   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5967   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5968   SDValue NewV = V2Only ? V2 : V1;
5969   for (int i = 0; i != 8; ++i) {
5970     int Elt0 = MaskVals[i*2];
5971     int Elt1 = MaskVals[i*2+1];
5972
5973     // This word of the result is all undef, skip it.
5974     if (Elt0 < 0 && Elt1 < 0)
5975       continue;
5976
5977     // This word of the result is already in the correct place, skip it.
5978     if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
5979       continue;
5980     if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
5981       continue;
5982
5983     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5984     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5985     SDValue InsElt;
5986
5987     // If Elt0 and Elt1 are defined, are consecutive, and can be load
5988     // using a single extract together, load it and store it.
5989     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5990       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5991                            DAG.getIntPtrConstant(Elt1 / 2));
5992       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5993                         DAG.getIntPtrConstant(i));
5994       continue;
5995     }
5996
5997     // If Elt1 is defined, extract it from the appropriate source.  If the
5998     // source byte is not also odd, shift the extracted word left 8 bits
5999     // otherwise clear the bottom 8 bits if we need to do an or.
6000     if (Elt1 >= 0) {
6001       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6002                            DAG.getIntPtrConstant(Elt1 / 2));
6003       if ((Elt1 & 1) == 0)
6004         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6005                              DAG.getConstant(8,
6006                                   TLI.getShiftAmountTy(InsElt.getValueType())));
6007       else if (Elt0 >= 0)
6008         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6009                              DAG.getConstant(0xFF00, MVT::i16));
6010     }
6011     // If Elt0 is defined, extract it from the appropriate source.  If the
6012     // source byte is not also even, shift the extracted word right 8 bits. If
6013     // Elt1 was also defined, OR the extracted values together before
6014     // inserting them in the result.
6015     if (Elt0 >= 0) {
6016       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6017                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6018       if ((Elt0 & 1) != 0)
6019         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6020                               DAG.getConstant(8,
6021                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
6022       else if (Elt1 >= 0)
6023         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6024                              DAG.getConstant(0x00FF, MVT::i16));
6025       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6026                          : InsElt0;
6027     }
6028     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6029                        DAG.getIntPtrConstant(i));
6030   }
6031   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6032 }
6033
6034 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6035 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6036 /// done when every pair / quad of shuffle mask elements point to elements in
6037 /// the right sequence. e.g.
6038 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6039 static
6040 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6041                                  SelectionDAG &DAG, DebugLoc dl) {
6042   EVT VT = SVOp->getValueType(0);
6043   SDValue V1 = SVOp->getOperand(0);
6044   SDValue V2 = SVOp->getOperand(1);
6045   unsigned NumElems = VT.getVectorNumElements();
6046   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
6047   EVT NewVT;
6048   switch (VT.getSimpleVT().SimpleTy) {
6049   default: assert(false && "Unexpected!");
6050   case MVT::v4f32: NewVT = MVT::v2f64; break;
6051   case MVT::v4i32: NewVT = MVT::v2i64; break;
6052   case MVT::v8i16: NewVT = MVT::v4i32; break;
6053   case MVT::v16i8: NewVT = MVT::v4i32; break;
6054   }
6055
6056   int Scale = NumElems / NewWidth;
6057   SmallVector<int, 8> MaskVec;
6058   for (unsigned i = 0; i < NumElems; i += Scale) {
6059     int StartIdx = -1;
6060     for (int j = 0; j < Scale; ++j) {
6061       int EltIdx = SVOp->getMaskElt(i+j);
6062       if (EltIdx < 0)
6063         continue;
6064       if (StartIdx == -1)
6065         StartIdx = EltIdx - (EltIdx % Scale);
6066       if (EltIdx != StartIdx + j)
6067         return SDValue();
6068     }
6069     if (StartIdx == -1)
6070       MaskVec.push_back(-1);
6071     else
6072       MaskVec.push_back(StartIdx / Scale);
6073   }
6074
6075   V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
6076   V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
6077   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6078 }
6079
6080 /// getVZextMovL - Return a zero-extending vector move low node.
6081 ///
6082 static SDValue getVZextMovL(EVT VT, EVT OpVT,
6083                             SDValue SrcOp, SelectionDAG &DAG,
6084                             const X86Subtarget *Subtarget, DebugLoc dl) {
6085   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6086     LoadSDNode *LD = NULL;
6087     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6088       LD = dyn_cast<LoadSDNode>(SrcOp);
6089     if (!LD) {
6090       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6091       // instead.
6092       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6093       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6094           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6095           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6096           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6097         // PR2108
6098         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6099         return DAG.getNode(ISD::BITCAST, dl, VT,
6100                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6101                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6102                                                    OpVT,
6103                                                    SrcOp.getOperand(0)
6104                                                           .getOperand(0))));
6105       }
6106     }
6107   }
6108
6109   return DAG.getNode(ISD::BITCAST, dl, VT,
6110                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6111                                  DAG.getNode(ISD::BITCAST, dl,
6112                                              OpVT, SrcOp)));
6113 }
6114
6115 /// areShuffleHalvesWithinDisjointLanes - Check whether each half of a vector
6116 /// shuffle node referes to only one lane in the sources.
6117 static bool areShuffleHalvesWithinDisjointLanes(ShuffleVectorSDNode *SVOp) {
6118   EVT VT = SVOp->getValueType(0);
6119   int NumElems = VT.getVectorNumElements();
6120   int HalfSize = NumElems/2;
6121   SmallVector<int, 16> M;
6122   SVOp->getMask(M);
6123   bool MatchA = false, MatchB = false;
6124
6125   for (int l = 0; l < NumElems*2; l += HalfSize) {
6126     if (isUndefOrInRange(M, 0, HalfSize, l, l+HalfSize)) {
6127       MatchA = true;
6128       break;
6129     }
6130   }
6131
6132   for (int l = 0; l < NumElems*2; l += HalfSize) {
6133     if (isUndefOrInRange(M, HalfSize, HalfSize, l, l+HalfSize)) {
6134       MatchB = true;
6135       break;
6136     }
6137   }
6138
6139   return MatchA && MatchB;
6140 }
6141
6142 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6143 /// which could not be matched by any known target speficic shuffle
6144 static SDValue
6145 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6146   if (areShuffleHalvesWithinDisjointLanes(SVOp)) {
6147     // If each half of a vector shuffle node referes to only one lane in the
6148     // source vectors, extract each used 128-bit lane and shuffle them using
6149     // 128-bit shuffles. Then, concatenate the results. Otherwise leave
6150     // the work to the legalizer.
6151     DebugLoc dl = SVOp->getDebugLoc();
6152     EVT VT = SVOp->getValueType(0);
6153     int NumElems = VT.getVectorNumElements();
6154     int HalfSize = NumElems/2;
6155
6156     // Extract the reference for each half
6157     int FstVecExtractIdx = 0, SndVecExtractIdx = 0;
6158     int FstVecOpNum = 0, SndVecOpNum = 0;
6159     for (int i = 0; i < HalfSize; ++i) {
6160       int Elt = SVOp->getMaskElt(i);
6161       if (SVOp->getMaskElt(i) < 0)
6162         continue;
6163       FstVecOpNum = Elt/NumElems;
6164       FstVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize;
6165       break;
6166     }
6167     for (int i = HalfSize; i < NumElems; ++i) {
6168       int Elt = SVOp->getMaskElt(i);
6169       if (SVOp->getMaskElt(i) < 0)
6170         continue;
6171       SndVecOpNum = Elt/NumElems;
6172       SndVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize;
6173       break;
6174     }
6175
6176     // Extract the subvectors
6177     SDValue V1 = Extract128BitVector(SVOp->getOperand(FstVecOpNum),
6178                       DAG.getConstant(FstVecExtractIdx, MVT::i32), DAG, dl);
6179     SDValue V2 = Extract128BitVector(SVOp->getOperand(SndVecOpNum),
6180                       DAG.getConstant(SndVecExtractIdx, MVT::i32), DAG, dl);
6181
6182     // Generate 128-bit shuffles
6183     SmallVector<int, 16> MaskV1, MaskV2;
6184     for (int i = 0; i < HalfSize; ++i) {
6185       int Elt = SVOp->getMaskElt(i);
6186       MaskV1.push_back(Elt < 0 ? Elt : Elt % HalfSize);
6187     }
6188     for (int i = HalfSize; i < NumElems; ++i) {
6189       int Elt = SVOp->getMaskElt(i);
6190       MaskV2.push_back(Elt < 0 ? Elt : Elt % HalfSize);
6191     }
6192
6193     EVT NVT = V1.getValueType();
6194     V1 = DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &MaskV1[0]);
6195     V2 = DAG.getVectorShuffle(NVT, dl, V2, DAG.getUNDEF(NVT), &MaskV2[0]);
6196
6197     // Concatenate the result back
6198     SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), V1,
6199                                    DAG.getConstant(0, MVT::i32), DAG, dl);
6200     return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32),
6201                               DAG, dl);
6202   }
6203
6204   return SDValue();
6205 }
6206
6207 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6208 /// 4 elements, and match them with several different shuffle types.
6209 static SDValue
6210 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6211   SDValue V1 = SVOp->getOperand(0);
6212   SDValue V2 = SVOp->getOperand(1);
6213   DebugLoc dl = SVOp->getDebugLoc();
6214   EVT VT = SVOp->getValueType(0);
6215
6216   assert(VT.getSizeInBits() == 128 && "Unsupported vector size");
6217
6218   SmallVector<std::pair<int, int>, 8> Locs;
6219   Locs.resize(4);
6220   SmallVector<int, 8> Mask1(4U, -1);
6221   SmallVector<int, 8> PermMask;
6222   SVOp->getMask(PermMask);
6223
6224   unsigned NumHi = 0;
6225   unsigned NumLo = 0;
6226   for (unsigned i = 0; i != 4; ++i) {
6227     int Idx = PermMask[i];
6228     if (Idx < 0) {
6229       Locs[i] = std::make_pair(-1, -1);
6230     } else {
6231       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6232       if (Idx < 4) {
6233         Locs[i] = std::make_pair(0, NumLo);
6234         Mask1[NumLo] = Idx;
6235         NumLo++;
6236       } else {
6237         Locs[i] = std::make_pair(1, NumHi);
6238         if (2+NumHi < 4)
6239           Mask1[2+NumHi] = Idx;
6240         NumHi++;
6241       }
6242     }
6243   }
6244
6245   if (NumLo <= 2 && NumHi <= 2) {
6246     // If no more than two elements come from either vector. This can be
6247     // implemented with two shuffles. First shuffle gather the elements.
6248     // The second shuffle, which takes the first shuffle as both of its
6249     // vector operands, put the elements into the right order.
6250     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6251
6252     SmallVector<int, 8> Mask2(4U, -1);
6253
6254     for (unsigned i = 0; i != 4; ++i) {
6255       if (Locs[i].first == -1)
6256         continue;
6257       else {
6258         unsigned Idx = (i < 2) ? 0 : 4;
6259         Idx += Locs[i].first * 2 + Locs[i].second;
6260         Mask2[i] = Idx;
6261       }
6262     }
6263
6264     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6265   } else if (NumLo == 3 || NumHi == 3) {
6266     // Otherwise, we must have three elements from one vector, call it X, and
6267     // one element from the other, call it Y.  First, use a shufps to build an
6268     // intermediate vector with the one element from Y and the element from X
6269     // that will be in the same half in the final destination (the indexes don't
6270     // matter). Then, use a shufps to build the final vector, taking the half
6271     // containing the element from Y from the intermediate, and the other half
6272     // from X.
6273     if (NumHi == 3) {
6274       // Normalize it so the 3 elements come from V1.
6275       CommuteVectorShuffleMask(PermMask, VT);
6276       std::swap(V1, V2);
6277     }
6278
6279     // Find the element from V2.
6280     unsigned HiIndex;
6281     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6282       int Val = PermMask[HiIndex];
6283       if (Val < 0)
6284         continue;
6285       if (Val >= 4)
6286         break;
6287     }
6288
6289     Mask1[0] = PermMask[HiIndex];
6290     Mask1[1] = -1;
6291     Mask1[2] = PermMask[HiIndex^1];
6292     Mask1[3] = -1;
6293     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6294
6295     if (HiIndex >= 2) {
6296       Mask1[0] = PermMask[0];
6297       Mask1[1] = PermMask[1];
6298       Mask1[2] = HiIndex & 1 ? 6 : 4;
6299       Mask1[3] = HiIndex & 1 ? 4 : 6;
6300       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6301     } else {
6302       Mask1[0] = HiIndex & 1 ? 2 : 0;
6303       Mask1[1] = HiIndex & 1 ? 0 : 2;
6304       Mask1[2] = PermMask[2];
6305       Mask1[3] = PermMask[3];
6306       if (Mask1[2] >= 0)
6307         Mask1[2] += 4;
6308       if (Mask1[3] >= 0)
6309         Mask1[3] += 4;
6310       return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6311     }
6312   }
6313
6314   // Break it into (shuffle shuffle_hi, shuffle_lo).
6315   Locs.clear();
6316   Locs.resize(4);
6317   SmallVector<int,8> LoMask(4U, -1);
6318   SmallVector<int,8> HiMask(4U, -1);
6319
6320   SmallVector<int,8> *MaskPtr = &LoMask;
6321   unsigned MaskIdx = 0;
6322   unsigned LoIdx = 0;
6323   unsigned HiIdx = 2;
6324   for (unsigned i = 0; i != 4; ++i) {
6325     if (i == 2) {
6326       MaskPtr = &HiMask;
6327       MaskIdx = 1;
6328       LoIdx = 0;
6329       HiIdx = 2;
6330     }
6331     int Idx = PermMask[i];
6332     if (Idx < 0) {
6333       Locs[i] = std::make_pair(-1, -1);
6334     } else if (Idx < 4) {
6335       Locs[i] = std::make_pair(MaskIdx, LoIdx);
6336       (*MaskPtr)[LoIdx] = Idx;
6337       LoIdx++;
6338     } else {
6339       Locs[i] = std::make_pair(MaskIdx, HiIdx);
6340       (*MaskPtr)[HiIdx] = Idx;
6341       HiIdx++;
6342     }
6343   }
6344
6345   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6346   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6347   SmallVector<int, 8> MaskOps;
6348   for (unsigned i = 0; i != 4; ++i) {
6349     if (Locs[i].first == -1) {
6350       MaskOps.push_back(-1);
6351     } else {
6352       unsigned Idx = Locs[i].first * 4 + Locs[i].second;
6353       MaskOps.push_back(Idx);
6354     }
6355   }
6356   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6357 }
6358
6359 static bool MayFoldVectorLoad(SDValue V) {
6360   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6361     V = V.getOperand(0);
6362   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6363     V = V.getOperand(0);
6364   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6365       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6366     // BUILD_VECTOR (load), undef
6367     V = V.getOperand(0);
6368   if (MayFoldLoad(V))
6369     return true;
6370   return false;
6371 }
6372
6373 // FIXME: the version above should always be used. Since there's
6374 // a bug where several vector shuffles can't be folded because the
6375 // DAG is not updated during lowering and a node claims to have two
6376 // uses while it only has one, use this version, and let isel match
6377 // another instruction if the load really happens to have more than
6378 // one use. Remove this version after this bug get fixed.
6379 // rdar://8434668, PR8156
6380 static bool RelaxedMayFoldVectorLoad(SDValue V) {
6381   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6382     V = V.getOperand(0);
6383   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6384     V = V.getOperand(0);
6385   if (ISD::isNormalLoad(V.getNode()))
6386     return true;
6387   return false;
6388 }
6389
6390 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
6391 /// a vector extract, and if both can be later optimized into a single load.
6392 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
6393 /// here because otherwise a target specific shuffle node is going to be
6394 /// emitted for this shuffle, and the optimization not done.
6395 /// FIXME: This is probably not the best approach, but fix the problem
6396 /// until the right path is decided.
6397 static
6398 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
6399                                          const TargetLowering &TLI) {
6400   EVT VT = V.getValueType();
6401   ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
6402
6403   // Be sure that the vector shuffle is present in a pattern like this:
6404   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
6405   if (!V.hasOneUse())
6406     return false;
6407
6408   SDNode *N = *V.getNode()->use_begin();
6409   if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
6410     return false;
6411
6412   SDValue EltNo = N->getOperand(1);
6413   if (!isa<ConstantSDNode>(EltNo))
6414     return false;
6415
6416   // If the bit convert changed the number of elements, it is unsafe
6417   // to examine the mask.
6418   bool HasShuffleIntoBitcast = false;
6419   if (V.getOpcode() == ISD::BITCAST) {
6420     EVT SrcVT = V.getOperand(0).getValueType();
6421     if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
6422       return false;
6423     V = V.getOperand(0);
6424     HasShuffleIntoBitcast = true;
6425   }
6426
6427   // Select the input vector, guarding against out of range extract vector.
6428   unsigned NumElems = VT.getVectorNumElements();
6429   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6430   int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
6431   V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
6432
6433   // Skip one more bit_convert if necessary
6434   if (V.getOpcode() == ISD::BITCAST)
6435     V = V.getOperand(0);
6436
6437   if (ISD::isNormalLoad(V.getNode())) {
6438     // Is the original load suitable?
6439     LoadSDNode *LN0 = cast<LoadSDNode>(V);
6440
6441     // FIXME: avoid the multi-use bug that is preventing lots of
6442     // of foldings to be detected, this is still wrong of course, but
6443     // give the temporary desired behavior, and if it happens that
6444     // the load has real more uses, during isel it will not fold, and
6445     // will generate poor code.
6446     if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
6447       return false;
6448
6449     if (!HasShuffleIntoBitcast)
6450       return true;
6451
6452     // If there's a bitcast before the shuffle, check if the load type and
6453     // alignment is valid.
6454     unsigned Align = LN0->getAlignment();
6455     unsigned NewAlign =
6456       TLI.getTargetData()->getABITypeAlignment(
6457                                     VT.getTypeForEVT(*DAG.getContext()));
6458
6459     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
6460       return false;
6461   }
6462
6463   return true;
6464 }
6465
6466 static
6467 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6468   EVT VT = Op.getValueType();
6469
6470   // Canonizalize to v2f64.
6471   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6472   return DAG.getNode(ISD::BITCAST, dl, VT,
6473                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6474                                           V1, DAG));
6475 }
6476
6477 static
6478 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6479                         bool HasXMMInt) {
6480   SDValue V1 = Op.getOperand(0);
6481   SDValue V2 = Op.getOperand(1);
6482   EVT VT = Op.getValueType();
6483
6484   assert(VT != MVT::v2i64 && "unsupported shuffle type");
6485
6486   if (HasXMMInt && VT == MVT::v2f64)
6487     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6488
6489   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6490   return DAG.getNode(ISD::BITCAST, dl, VT,
6491                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6492                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6493                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6494 }
6495
6496 static
6497 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6498   SDValue V1 = Op.getOperand(0);
6499   SDValue V2 = Op.getOperand(1);
6500   EVT VT = Op.getValueType();
6501
6502   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6503          "unsupported shuffle type");
6504
6505   if (V2.getOpcode() == ISD::UNDEF)
6506     V2 = V1;
6507
6508   // v4i32 or v4f32
6509   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6510 }
6511
6512 static inline unsigned getSHUFPOpcode(EVT VT) {
6513   switch(VT.getSimpleVT().SimpleTy) {
6514   case MVT::v8i32: // Use fp unit for int unpack.
6515   case MVT::v8f32:
6516   case MVT::v4i32: // Use fp unit for int unpack.
6517   case MVT::v4f32: return X86ISD::SHUFPS;
6518   case MVT::v4i64: // Use fp unit for int unpack.
6519   case MVT::v4f64:
6520   case MVT::v2i64: // Use fp unit for int unpack.
6521   case MVT::v2f64: return X86ISD::SHUFPD;
6522   default:
6523     llvm_unreachable("Unknown type for shufp*");
6524   }
6525   return 0;
6526 }
6527
6528 static
6529 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasXMMInt) {
6530   SDValue V1 = Op.getOperand(0);
6531   SDValue V2 = Op.getOperand(1);
6532   EVT VT = Op.getValueType();
6533   unsigned NumElems = VT.getVectorNumElements();
6534
6535   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6536   // operand of these instructions is only memory, so check if there's a
6537   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6538   // same masks.
6539   bool CanFoldLoad = false;
6540
6541   // Trivial case, when V2 comes from a load.
6542   if (MayFoldVectorLoad(V2))
6543     CanFoldLoad = true;
6544
6545   // When V1 is a load, it can be folded later into a store in isel, example:
6546   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6547   //    turns into:
6548   //  (MOVLPSmr addr:$src1, VR128:$src2)
6549   // So, recognize this potential and also use MOVLPS or MOVLPD
6550   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6551     CanFoldLoad = true;
6552
6553   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6554   if (CanFoldLoad) {
6555     if (HasXMMInt && NumElems == 2)
6556       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6557
6558     if (NumElems == 4)
6559       // If we don't care about the second element, procede to use movss.
6560       if (SVOp->getMaskElt(1) != -1)
6561         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6562   }
6563
6564   // movl and movlp will both match v2i64, but v2i64 is never matched by
6565   // movl earlier because we make it strict to avoid messing with the movlp load
6566   // folding logic (see the code above getMOVLP call). Match it here then,
6567   // this is horrible, but will stay like this until we move all shuffle
6568   // matching to x86 specific nodes. Note that for the 1st condition all
6569   // types are matched with movsd.
6570   if (HasXMMInt) {
6571     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6572     // as to remove this logic from here, as much as possible
6573     if (NumElems == 2 || !X86::isMOVLMask(SVOp))
6574       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6575     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6576   }
6577
6578   assert(VT != MVT::v4i32 && "unsupported shuffle type");
6579
6580   // Invert the operand order and use SHUFPS to match it.
6581   return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V2, V1,
6582                               X86::getShuffleSHUFImmediate(SVOp), DAG);
6583 }
6584
6585 static inline unsigned getUNPCKLOpcode(EVT VT, bool HasAVX2) {
6586   switch(VT.getSimpleVT().SimpleTy) {
6587   case MVT::v4i32: return X86ISD::PUNPCKLDQ;
6588   case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
6589   case MVT::v4f32: return X86ISD::UNPCKLPS;
6590   case MVT::v2f64: return X86ISD::UNPCKLPD;
6591   case MVT::v8i32:
6592     if (HasAVX2)   return X86ISD::VPUNPCKLDQY;
6593     // else use fp unit for int unpack.
6594   case MVT::v8f32: return X86ISD::VUNPCKLPSY;
6595   case MVT::v4i64:
6596     if (HasAVX2)   return X86ISD::VPUNPCKLQDQY;
6597     // else use fp unit for int unpack.
6598   case MVT::v4f64: return X86ISD::VUNPCKLPDY;
6599   case MVT::v16i8: return X86ISD::PUNPCKLBW;
6600   case MVT::v8i16: return X86ISD::PUNPCKLWD;
6601   case MVT::v16i16: return X86ISD::VPUNPCKLWDY;
6602   case MVT::v32i8: return X86ISD::VPUNPCKLBWY;
6603   default:
6604     llvm_unreachable("Unknown type for unpckl");
6605   }
6606   return 0;
6607 }
6608
6609 static inline unsigned getUNPCKHOpcode(EVT VT, bool HasAVX2) {
6610   switch(VT.getSimpleVT().SimpleTy) {
6611   case MVT::v4i32: return X86ISD::PUNPCKHDQ;
6612   case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
6613   case MVT::v4f32: return X86ISD::UNPCKHPS;
6614   case MVT::v2f64: return X86ISD::UNPCKHPD;
6615   case MVT::v8i32:
6616     if (HasAVX2)   return X86ISD::VPUNPCKHDQY;
6617     // else use fp unit for int unpack.
6618   case MVT::v8f32: return X86ISD::VUNPCKHPSY;
6619   case MVT::v4i64:
6620     if (HasAVX2)   return X86ISD::VPUNPCKHQDQY;
6621     // else use fp unit for int unpack.
6622   case MVT::v4f64: return X86ISD::VUNPCKHPDY;
6623   case MVT::v16i8: return X86ISD::PUNPCKHBW;
6624   case MVT::v8i16: return X86ISD::PUNPCKHWD;
6625   case MVT::v16i16: return X86ISD::VPUNPCKHWDY;
6626   case MVT::v32i8: return X86ISD::VPUNPCKHBWY;
6627   default:
6628     llvm_unreachable("Unknown type for unpckh");
6629   }
6630   return 0;
6631 }
6632
6633 static inline unsigned getVPERMILOpcode(EVT VT) {
6634   switch(VT.getSimpleVT().SimpleTy) {
6635   case MVT::v4i32:
6636   case MVT::v4f32: return X86ISD::VPERMILPS;
6637   case MVT::v2i64:
6638   case MVT::v2f64: return X86ISD::VPERMILPD;
6639   case MVT::v8i32:
6640   case MVT::v8f32: return X86ISD::VPERMILPSY;
6641   case MVT::v4i64:
6642   case MVT::v4f64: return X86ISD::VPERMILPDY;
6643   default:
6644     llvm_unreachable("Unknown type for vpermil");
6645   }
6646   return 0;
6647 }
6648
6649 static
6650 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
6651                                const TargetLowering &TLI,
6652                                const X86Subtarget *Subtarget) {
6653   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6654   EVT VT = Op.getValueType();
6655   DebugLoc dl = Op.getDebugLoc();
6656   SDValue V1 = Op.getOperand(0);
6657   SDValue V2 = Op.getOperand(1);
6658
6659   if (isZeroShuffle(SVOp))
6660     return getZeroVector(VT, Subtarget->hasXMMInt(), DAG, dl);
6661
6662   // Handle splat operations
6663   if (SVOp->isSplat()) {
6664     unsigned NumElem = VT.getVectorNumElements();
6665     int Size = VT.getSizeInBits();
6666     // Special case, this is the only place now where it's allowed to return
6667     // a vector_shuffle operation without using a target specific node, because
6668     // *hopefully* it will be optimized away by the dag combiner. FIXME: should
6669     // this be moved to DAGCombine instead?
6670     if (NumElem <= 4 && CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
6671       return Op;
6672
6673     // Use vbroadcast whenever the splat comes from a foldable load
6674     SDValue LD = isVectorBroadcast(Op, Subtarget->hasAVX2());
6675     if (Subtarget->hasAVX() && LD.getNode())
6676       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, LD);
6677
6678     // Handle splats by matching through known shuffle masks
6679     if ((Size == 128 && NumElem <= 4) ||
6680         (Size == 256 && NumElem < 8))
6681       return SDValue();
6682
6683     // All remaning splats are promoted to target supported vector shuffles.
6684     return PromoteSplat(SVOp, DAG);
6685   }
6686
6687   // If the shuffle can be profitably rewritten as a narrower shuffle, then
6688   // do it!
6689   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
6690     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6691     if (NewOp.getNode())
6692       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6693   } else if ((VT == MVT::v4i32 ||
6694              (VT == MVT::v4f32 && Subtarget->hasXMMInt()))) {
6695     // FIXME: Figure out a cleaner way to do this.
6696     // Try to make use of movq to zero out the top part.
6697     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6698       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6699       if (NewOp.getNode()) {
6700         if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
6701           return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
6702                               DAG, Subtarget, dl);
6703       }
6704     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6705       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6706       if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
6707         return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
6708                             DAG, Subtarget, dl);
6709     }
6710   }
6711   return SDValue();
6712 }
6713
6714 SDValue
6715 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6716   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6717   SDValue V1 = Op.getOperand(0);
6718   SDValue V2 = Op.getOperand(1);
6719   EVT VT = Op.getValueType();
6720   DebugLoc dl = Op.getDebugLoc();
6721   unsigned NumElems = VT.getVectorNumElements();
6722   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6723   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6724   bool V1IsSplat = false;
6725   bool V2IsSplat = false;
6726   bool HasXMMInt = Subtarget->hasXMMInt();
6727   bool HasAVX2   = Subtarget->hasAVX2();
6728   MachineFunction &MF = DAG.getMachineFunction();
6729   bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
6730
6731   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6732
6733   // Vector shuffle lowering takes 3 steps:
6734   //
6735   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6736   //    narrowing and commutation of operands should be handled.
6737   // 2) Matching of shuffles with known shuffle masks to x86 target specific
6738   //    shuffle nodes.
6739   // 3) Rewriting of unmatched masks into new generic shuffle operations,
6740   //    so the shuffle can be broken into other shuffles and the legalizer can
6741   //    try the lowering again.
6742   //
6743   // The general idea is that no vector_shuffle operation should be left to
6744   // be matched during isel, all of them must be converted to a target specific
6745   // node here.
6746
6747   // Normalize the input vectors. Here splats, zeroed vectors, profitable
6748   // narrowing and commutation of operands should be handled. The actual code
6749   // doesn't include all of those, work in progress...
6750   SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
6751   if (NewOp.getNode())
6752     return NewOp;
6753
6754   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6755   // unpckh_undef). Only use pshufd if speed is more important than size.
6756   if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
6757     return getTargetShuffleNode(getUNPCKLOpcode(VT, HasAVX2), dl, VT, V1, V1,
6758                                 DAG);
6759   if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
6760     return getTargetShuffleNode(getUNPCKHOpcode(VT, HasAVX2), dl, VT, V1, V1,
6761                                 DAG);
6762
6763   if (X86::isMOVDDUPMask(SVOp) && Subtarget->hasSSE3orAVX() &&
6764       V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6765     return getMOVDDup(Op, dl, V1, DAG);
6766
6767   if (X86::isMOVHLPS_v_undef_Mask(SVOp))
6768     return getMOVHighToLow(Op, dl, DAG);
6769
6770   // Use to match splats
6771   if (HasXMMInt && X86::isUNPCKHMask(SVOp, HasAVX2) && V2IsUndef &&
6772       (VT == MVT::v2f64 || VT == MVT::v2i64))
6773     return getTargetShuffleNode(getUNPCKHOpcode(VT, HasAVX2), dl, VT, V1, V1,
6774                                 DAG);
6775
6776   if (X86::isPSHUFDMask(SVOp)) {
6777     // The actual implementation will match the mask in the if above and then
6778     // during isel it can match several different instructions, not only pshufd
6779     // as its name says, sad but true, emulate the behavior for now...
6780     if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6781         return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6782
6783     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
6784
6785     if (HasXMMInt && (VT == MVT::v4f32 || VT == MVT::v4i32))
6786       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6787
6788     return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V1,
6789                                 TargetMask, DAG);
6790   }
6791
6792   // Check if this can be converted into a logical shift.
6793   bool isLeft = false;
6794   unsigned ShAmt = 0;
6795   SDValue ShVal;
6796   bool isShift = HasXMMInt && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6797   if (isShift && ShVal.hasOneUse()) {
6798     // If the shifted value has multiple uses, it may be cheaper to use
6799     // v_set0 + movlhps or movhlps, etc.
6800     EVT EltVT = VT.getVectorElementType();
6801     ShAmt *= EltVT.getSizeInBits();
6802     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6803   }
6804
6805   if (X86::isMOVLMask(SVOp)) {
6806     if (V1IsUndef)
6807       return V2;
6808     if (ISD::isBuildVectorAllZeros(V1.getNode()))
6809       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6810     if (!X86::isMOVLPMask(SVOp)) {
6811       if (HasXMMInt && (VT == MVT::v2i64 || VT == MVT::v2f64))
6812         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6813
6814       if (VT == MVT::v4i32 || VT == MVT::v4f32)
6815         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6816     }
6817   }
6818
6819   // FIXME: fold these into legal mask.
6820   if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp, HasAVX2))
6821     return getMOVLowToHigh(Op, dl, DAG, HasXMMInt);
6822
6823   if (X86::isMOVHLPSMask(SVOp))
6824     return getMOVHighToLow(Op, dl, DAG);
6825
6826   if (X86::isMOVSHDUPMask(SVOp, Subtarget))
6827     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6828
6829   if (X86::isMOVSLDUPMask(SVOp, Subtarget))
6830     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6831
6832   if (X86::isMOVLPMask(SVOp))
6833     return getMOVLP(Op, dl, DAG, HasXMMInt);
6834
6835   if (ShouldXformToMOVHLPS(SVOp) ||
6836       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
6837     return CommuteVectorShuffle(SVOp, DAG);
6838
6839   if (isShift) {
6840     // No better options. Use a vshl / vsrl.
6841     EVT EltVT = VT.getVectorElementType();
6842     ShAmt *= EltVT.getSizeInBits();
6843     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6844   }
6845
6846   bool Commuted = false;
6847   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
6848   // 1,1,1,1 -> v8i16 though.
6849   V1IsSplat = isSplatVector(V1.getNode());
6850   V2IsSplat = isSplatVector(V2.getNode());
6851
6852   // Canonicalize the splat or undef, if present, to be on the RHS.
6853   if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
6854     Op = CommuteVectorShuffle(SVOp, DAG);
6855     SVOp = cast<ShuffleVectorSDNode>(Op);
6856     V1 = SVOp->getOperand(0);
6857     V2 = SVOp->getOperand(1);
6858     std::swap(V1IsSplat, V2IsSplat);
6859     std::swap(V1IsUndef, V2IsUndef);
6860     Commuted = true;
6861   }
6862
6863   if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
6864     // Shuffling low element of v1 into undef, just return v1.
6865     if (V2IsUndef)
6866       return V1;
6867     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6868     // the instruction selector will not match, so get a canonical MOVL with
6869     // swapped operands to undo the commute.
6870     return getMOVL(DAG, dl, VT, V2, V1);
6871   }
6872
6873   if (X86::isUNPCKLMask(SVOp, HasAVX2))
6874     return getTargetShuffleNode(getUNPCKLOpcode(VT, HasAVX2), dl, VT, V1, V2,
6875                                 DAG);
6876
6877   if (X86::isUNPCKHMask(SVOp, HasAVX2))
6878     return getTargetShuffleNode(getUNPCKHOpcode(VT, HasAVX2), dl, VT, V1, V2,
6879                                 DAG);
6880
6881   if (V2IsSplat) {
6882     // Normalize mask so all entries that point to V2 points to its first
6883     // element then try to match unpck{h|l} again. If match, return a
6884     // new vector_shuffle with the corrected mask.
6885     SDValue NewMask = NormalizeMask(SVOp, DAG);
6886     ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
6887     if (NSVOp != SVOp) {
6888       if (X86::isUNPCKLMask(NSVOp, HasAVX2, true)) {
6889         return NewMask;
6890       } else if (X86::isUNPCKHMask(NSVOp, HasAVX2, true)) {
6891         return NewMask;
6892       }
6893     }
6894   }
6895
6896   if (Commuted) {
6897     // Commute is back and try unpck* again.
6898     // FIXME: this seems wrong.
6899     SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
6900     ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
6901
6902     if (X86::isUNPCKLMask(NewSVOp, HasAVX2))
6903       return getTargetShuffleNode(getUNPCKLOpcode(VT, HasAVX2), dl, VT, V2, V1,
6904                                   DAG);
6905
6906     if (X86::isUNPCKHMask(NewSVOp, HasAVX2))
6907       return getTargetShuffleNode(getUNPCKHOpcode(VT, HasAVX2), dl, VT, V2, V1,
6908                                   DAG);
6909   }
6910
6911   // Normalize the node to match x86 shuffle ops if needed
6912   if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
6913     return CommuteVectorShuffle(SVOp, DAG);
6914
6915   // The checks below are all present in isShuffleMaskLegal, but they are
6916   // inlined here right now to enable us to directly emit target specific
6917   // nodes, and remove one by one until they don't return Op anymore.
6918   SmallVector<int, 16> M;
6919   SVOp->getMask(M);
6920
6921   if (isPALIGNRMask(M, VT, Subtarget->hasSSSE3orAVX()))
6922     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6923                                 X86::getShufflePALIGNRImmediate(SVOp),
6924                                 DAG);
6925
6926   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6927       SVOp->getSplatIndex() == 0 && V2IsUndef) {
6928     if (VT == MVT::v2f64)
6929       return getTargetShuffleNode(X86ISD::UNPCKLPD, dl, VT, V1, V1, DAG);
6930     if (VT == MVT::v2i64)
6931       return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
6932   }
6933
6934   if (isPSHUFHWMask(M, VT))
6935     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6936                                 X86::getShufflePSHUFHWImmediate(SVOp),
6937                                 DAG);
6938
6939   if (isPSHUFLWMask(M, VT))
6940     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6941                                 X86::getShufflePSHUFLWImmediate(SVOp),
6942                                 DAG);
6943
6944   if (isSHUFPMask(M, VT))
6945     return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6946                                 X86::getShuffleSHUFImmediate(SVOp), DAG);
6947
6948   if (X86::isUNPCKL_v_undef_Mask(SVOp))
6949     return getTargetShuffleNode(getUNPCKLOpcode(VT, HasAVX2), dl, VT, V1, V1,
6950                                 DAG);
6951   if (X86::isUNPCKH_v_undef_Mask(SVOp))
6952     return getTargetShuffleNode(getUNPCKHOpcode(VT, HasAVX2), dl, VT, V1, V1,
6953                                 DAG);
6954
6955   //===--------------------------------------------------------------------===//
6956   // Generate target specific nodes for 128 or 256-bit shuffles only
6957   // supported in the AVX instruction set.
6958   //
6959
6960   // Handle VMOVDDUPY permutations
6961   if (isMOVDDUPYMask(SVOp, Subtarget))
6962     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6963
6964   // Handle VPERMILPS* permutations
6965   if (isVPERMILPSMask(M, VT, Subtarget))
6966     return getTargetShuffleNode(getVPERMILOpcode(VT), dl, VT, V1,
6967                                 getShuffleVPERMILPSImmediate(SVOp), DAG);
6968
6969   // Handle VPERMILPD* permutations
6970   if (isVPERMILPDMask(M, VT, Subtarget))
6971     return getTargetShuffleNode(getVPERMILOpcode(VT), dl, VT, V1,
6972                                 getShuffleVPERMILPDImmediate(SVOp), DAG);
6973
6974   // Handle VPERM2F128 permutations
6975   if (isVPERM2F128Mask(M, VT, Subtarget))
6976     return getTargetShuffleNode(X86ISD::VPERM2F128, dl, VT, V1, V2,
6977                                 getShuffleVPERM2F128Immediate(SVOp), DAG);
6978
6979   // Handle VSHUFPSY permutations
6980   if (isVSHUFPSYMask(M, VT, Subtarget))
6981     return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6982                                 getShuffleVSHUFPSYImmediate(SVOp), DAG);
6983
6984   // Handle VSHUFPDY permutations
6985   if (isVSHUFPDYMask(M, VT, Subtarget))
6986     return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6987                                 getShuffleVSHUFPDYImmediate(SVOp), DAG);
6988
6989   //===--------------------------------------------------------------------===//
6990   // Since no target specific shuffle was selected for this generic one,
6991   // lower it into other known shuffles. FIXME: this isn't true yet, but
6992   // this is the plan.
6993   //
6994
6995   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6996   if (VT == MVT::v8i16) {
6997     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
6998     if (NewOp.getNode())
6999       return NewOp;
7000   }
7001
7002   if (VT == MVT::v16i8) {
7003     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
7004     if (NewOp.getNode())
7005       return NewOp;
7006   }
7007
7008   // Handle all 128-bit wide vectors with 4 elements, and match them with
7009   // several different shuffle types.
7010   if (NumElems == 4 && VT.getSizeInBits() == 128)
7011     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7012
7013   // Handle general 256-bit shuffles
7014   if (VT.is256BitVector())
7015     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7016
7017   return SDValue();
7018 }
7019
7020 SDValue
7021 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
7022                                                 SelectionDAG &DAG) const {
7023   EVT VT = Op.getValueType();
7024   DebugLoc dl = Op.getDebugLoc();
7025
7026   if (Op.getOperand(0).getValueType().getSizeInBits() != 128)
7027     return SDValue();
7028
7029   if (VT.getSizeInBits() == 8) {
7030     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7031                                     Op.getOperand(0), Op.getOperand(1));
7032     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7033                                     DAG.getValueType(VT));
7034     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7035   } else if (VT.getSizeInBits() == 16) {
7036     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7037     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7038     if (Idx == 0)
7039       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7040                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7041                                      DAG.getNode(ISD::BITCAST, dl,
7042                                                  MVT::v4i32,
7043                                                  Op.getOperand(0)),
7044                                      Op.getOperand(1)));
7045     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7046                                     Op.getOperand(0), Op.getOperand(1));
7047     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7048                                     DAG.getValueType(VT));
7049     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7050   } else if (VT == MVT::f32) {
7051     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7052     // the result back to FR32 register. It's only worth matching if the
7053     // result has a single use which is a store or a bitcast to i32.  And in
7054     // the case of a store, it's not worth it if the index is a constant 0,
7055     // because a MOVSSmr can be used instead, which is smaller and faster.
7056     if (!Op.hasOneUse())
7057       return SDValue();
7058     SDNode *User = *Op.getNode()->use_begin();
7059     if ((User->getOpcode() != ISD::STORE ||
7060          (isa<ConstantSDNode>(Op.getOperand(1)) &&
7061           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7062         (User->getOpcode() != ISD::BITCAST ||
7063          User->getValueType(0) != MVT::i32))
7064       return SDValue();
7065     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7066                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7067                                               Op.getOperand(0)),
7068                                               Op.getOperand(1));
7069     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7070   } else if (VT == MVT::i32 || VT == MVT::i64) {
7071     // ExtractPS/pextrq works with constant index.
7072     if (isa<ConstantSDNode>(Op.getOperand(1)))
7073       return Op;
7074   }
7075   return SDValue();
7076 }
7077
7078
7079 SDValue
7080 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7081                                            SelectionDAG &DAG) const {
7082   if (!isa<ConstantSDNode>(Op.getOperand(1)))
7083     return SDValue();
7084
7085   SDValue Vec = Op.getOperand(0);
7086   EVT VecVT = Vec.getValueType();
7087
7088   // If this is a 256-bit vector result, first extract the 128-bit vector and
7089   // then extract the element from the 128-bit vector.
7090   if (VecVT.getSizeInBits() == 256) {
7091     DebugLoc dl = Op.getNode()->getDebugLoc();
7092     unsigned NumElems = VecVT.getVectorNumElements();
7093     SDValue Idx = Op.getOperand(1);
7094     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7095
7096     // Get the 128-bit vector.
7097     bool Upper = IdxVal >= NumElems/2;
7098     Vec = Extract128BitVector(Vec,
7099                     DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32), DAG, dl);
7100
7101     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7102                     Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : Idx);
7103   }
7104
7105   assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
7106
7107   if (Subtarget->hasSSE41orAVX()) {
7108     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7109     if (Res.getNode())
7110       return Res;
7111   }
7112
7113   EVT VT = Op.getValueType();
7114   DebugLoc dl = Op.getDebugLoc();
7115   // TODO: handle v16i8.
7116   if (VT.getSizeInBits() == 16) {
7117     SDValue Vec = Op.getOperand(0);
7118     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7119     if (Idx == 0)
7120       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7121                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7122                                      DAG.getNode(ISD::BITCAST, dl,
7123                                                  MVT::v4i32, Vec),
7124                                      Op.getOperand(1)));
7125     // Transform it so it match pextrw which produces a 32-bit result.
7126     EVT EltVT = MVT::i32;
7127     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7128                                     Op.getOperand(0), Op.getOperand(1));
7129     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7130                                     DAG.getValueType(VT));
7131     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7132   } else if (VT.getSizeInBits() == 32) {
7133     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7134     if (Idx == 0)
7135       return Op;
7136
7137     // SHUFPS the element to the lowest double word, then movss.
7138     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7139     EVT VVT = Op.getOperand(0).getValueType();
7140     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7141                                        DAG.getUNDEF(VVT), Mask);
7142     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7143                        DAG.getIntPtrConstant(0));
7144   } else if (VT.getSizeInBits() == 64) {
7145     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7146     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7147     //        to match extract_elt for f64.
7148     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7149     if (Idx == 0)
7150       return Op;
7151
7152     // UNPCKHPD the element to the lowest double word, then movsd.
7153     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7154     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7155     int Mask[2] = { 1, -1 };
7156     EVT VVT = Op.getOperand(0).getValueType();
7157     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7158                                        DAG.getUNDEF(VVT), Mask);
7159     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7160                        DAG.getIntPtrConstant(0));
7161   }
7162
7163   return SDValue();
7164 }
7165
7166 SDValue
7167 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
7168                                                SelectionDAG &DAG) const {
7169   EVT VT = Op.getValueType();
7170   EVT EltVT = VT.getVectorElementType();
7171   DebugLoc dl = Op.getDebugLoc();
7172
7173   SDValue N0 = Op.getOperand(0);
7174   SDValue N1 = Op.getOperand(1);
7175   SDValue N2 = Op.getOperand(2);
7176
7177   if (VT.getSizeInBits() == 256)
7178     return SDValue();
7179
7180   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7181       isa<ConstantSDNode>(N2)) {
7182     unsigned Opc;
7183     if (VT == MVT::v8i16)
7184       Opc = X86ISD::PINSRW;
7185     else if (VT == MVT::v16i8)
7186       Opc = X86ISD::PINSRB;
7187     else
7188       Opc = X86ISD::PINSRB;
7189
7190     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7191     // argument.
7192     if (N1.getValueType() != MVT::i32)
7193       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7194     if (N2.getValueType() != MVT::i32)
7195       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7196     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7197   } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7198     // Bits [7:6] of the constant are the source select.  This will always be
7199     //  zero here.  The DAG Combiner may combine an extract_elt index into these
7200     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
7201     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
7202     // Bits [5:4] of the constant are the destination select.  This is the
7203     //  value of the incoming immediate.
7204     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
7205     //   combine either bitwise AND or insert of float 0.0 to set these bits.
7206     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7207     // Create this as a scalar to vector..
7208     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7209     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7210   } else if ((EltVT == MVT::i32 || EltVT == MVT::i64) && 
7211              isa<ConstantSDNode>(N2)) {
7212     // PINSR* works with constant index.
7213     return Op;
7214   }
7215   return SDValue();
7216 }
7217
7218 SDValue
7219 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7220   EVT VT = Op.getValueType();
7221   EVT EltVT = VT.getVectorElementType();
7222
7223   DebugLoc dl = Op.getDebugLoc();
7224   SDValue N0 = Op.getOperand(0);
7225   SDValue N1 = Op.getOperand(1);
7226   SDValue N2 = Op.getOperand(2);
7227
7228   // If this is a 256-bit vector result, first extract the 128-bit vector,
7229   // insert the element into the extracted half and then place it back.
7230   if (VT.getSizeInBits() == 256) {
7231     if (!isa<ConstantSDNode>(N2))
7232       return SDValue();
7233
7234     // Get the desired 128-bit vector half.
7235     unsigned NumElems = VT.getVectorNumElements();
7236     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7237     bool Upper = IdxVal >= NumElems/2;
7238     SDValue Ins128Idx = DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32);
7239     SDValue V = Extract128BitVector(N0, Ins128Idx, DAG, dl);
7240
7241     // Insert the element into the desired half.
7242     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V,
7243                  N1, Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : N2);
7244
7245     // Insert the changed part back to the 256-bit vector
7246     return Insert128BitVector(N0, V, Ins128Idx, DAG, dl);
7247   }
7248
7249   if (Subtarget->hasSSE41orAVX())
7250     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7251
7252   if (EltVT == MVT::i8)
7253     return SDValue();
7254
7255   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7256     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7257     // as its second argument.
7258     if (N1.getValueType() != MVT::i32)
7259       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7260     if (N2.getValueType() != MVT::i32)
7261       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7262     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7263   }
7264   return SDValue();
7265 }
7266
7267 SDValue
7268 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
7269   LLVMContext *Context = DAG.getContext();
7270   DebugLoc dl = Op.getDebugLoc();
7271   EVT OpVT = Op.getValueType();
7272
7273   // If this is a 256-bit vector result, first insert into a 128-bit
7274   // vector and then insert into the 256-bit vector.
7275   if (OpVT.getSizeInBits() > 128) {
7276     // Insert into a 128-bit vector.
7277     EVT VT128 = EVT::getVectorVT(*Context,
7278                                  OpVT.getVectorElementType(),
7279                                  OpVT.getVectorNumElements() / 2);
7280
7281     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7282
7283     // Insert the 128-bit vector.
7284     return Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, OpVT), Op,
7285                               DAG.getConstant(0, MVT::i32),
7286                               DAG, dl);
7287   }
7288
7289   if (Op.getValueType() == MVT::v1i64 &&
7290       Op.getOperand(0).getValueType() == MVT::i64)
7291     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7292
7293   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7294   assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
7295          "Expected an SSE type!");
7296   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
7297                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7298 }
7299
7300 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7301 // a simple subregister reference or explicit instructions to grab
7302 // upper bits of a vector.
7303 SDValue
7304 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7305   if (Subtarget->hasAVX()) {
7306     DebugLoc dl = Op.getNode()->getDebugLoc();
7307     SDValue Vec = Op.getNode()->getOperand(0);
7308     SDValue Idx = Op.getNode()->getOperand(1);
7309
7310     if (Op.getNode()->getValueType(0).getSizeInBits() == 128
7311         && Vec.getNode()->getValueType(0).getSizeInBits() == 256) {
7312         return Extract128BitVector(Vec, Idx, DAG, dl);
7313     }
7314   }
7315   return SDValue();
7316 }
7317
7318 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7319 // simple superregister reference or explicit instructions to insert
7320 // the upper bits of a vector.
7321 SDValue
7322 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7323   if (Subtarget->hasAVX()) {
7324     DebugLoc dl = Op.getNode()->getDebugLoc();
7325     SDValue Vec = Op.getNode()->getOperand(0);
7326     SDValue SubVec = Op.getNode()->getOperand(1);
7327     SDValue Idx = Op.getNode()->getOperand(2);
7328
7329     if (Op.getNode()->getValueType(0).getSizeInBits() == 256
7330         && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) {
7331       return Insert128BitVector(Vec, SubVec, Idx, DAG, dl);
7332     }
7333   }
7334   return SDValue();
7335 }
7336
7337 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7338 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7339 // one of the above mentioned nodes. It has to be wrapped because otherwise
7340 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7341 // be used to form addressing mode. These wrapped nodes will be selected
7342 // into MOV32ri.
7343 SDValue
7344 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7345   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7346
7347   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7348   // global base reg.
7349   unsigned char OpFlag = 0;
7350   unsigned WrapperKind = X86ISD::Wrapper;
7351   CodeModel::Model M = getTargetMachine().getCodeModel();
7352
7353   if (Subtarget->isPICStyleRIPRel() &&
7354       (M == CodeModel::Small || M == CodeModel::Kernel))
7355     WrapperKind = X86ISD::WrapperRIP;
7356   else if (Subtarget->isPICStyleGOT())
7357     OpFlag = X86II::MO_GOTOFF;
7358   else if (Subtarget->isPICStyleStubPIC())
7359     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7360
7361   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7362                                              CP->getAlignment(),
7363                                              CP->getOffset(), OpFlag);
7364   DebugLoc DL = CP->getDebugLoc();
7365   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7366   // With PIC, the address is actually $g + Offset.
7367   if (OpFlag) {
7368     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7369                          DAG.getNode(X86ISD::GlobalBaseReg,
7370                                      DebugLoc(), getPointerTy()),
7371                          Result);
7372   }
7373
7374   return Result;
7375 }
7376
7377 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7378   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7379
7380   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7381   // global base reg.
7382   unsigned char OpFlag = 0;
7383   unsigned WrapperKind = X86ISD::Wrapper;
7384   CodeModel::Model M = getTargetMachine().getCodeModel();
7385
7386   if (Subtarget->isPICStyleRIPRel() &&
7387       (M == CodeModel::Small || M == CodeModel::Kernel))
7388     WrapperKind = X86ISD::WrapperRIP;
7389   else if (Subtarget->isPICStyleGOT())
7390     OpFlag = X86II::MO_GOTOFF;
7391   else if (Subtarget->isPICStyleStubPIC())
7392     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7393
7394   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7395                                           OpFlag);
7396   DebugLoc DL = JT->getDebugLoc();
7397   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7398
7399   // With PIC, the address is actually $g + Offset.
7400   if (OpFlag)
7401     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7402                          DAG.getNode(X86ISD::GlobalBaseReg,
7403                                      DebugLoc(), getPointerTy()),
7404                          Result);
7405
7406   return Result;
7407 }
7408
7409 SDValue
7410 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7411   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7412
7413   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7414   // global base reg.
7415   unsigned char OpFlag = 0;
7416   unsigned WrapperKind = X86ISD::Wrapper;
7417   CodeModel::Model M = getTargetMachine().getCodeModel();
7418
7419   if (Subtarget->isPICStyleRIPRel() &&
7420       (M == CodeModel::Small || M == CodeModel::Kernel)) {
7421     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7422       OpFlag = X86II::MO_GOTPCREL;
7423     WrapperKind = X86ISD::WrapperRIP;
7424   } else if (Subtarget->isPICStyleGOT()) {
7425     OpFlag = X86II::MO_GOT;
7426   } else if (Subtarget->isPICStyleStubPIC()) {
7427     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7428   } else if (Subtarget->isPICStyleStubNoDynamic()) {
7429     OpFlag = X86II::MO_DARWIN_NONLAZY;
7430   }
7431
7432   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7433
7434   DebugLoc DL = Op.getDebugLoc();
7435   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7436
7437
7438   // With PIC, the address is actually $g + Offset.
7439   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7440       !Subtarget->is64Bit()) {
7441     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7442                          DAG.getNode(X86ISD::GlobalBaseReg,
7443                                      DebugLoc(), getPointerTy()),
7444                          Result);
7445   }
7446
7447   // For symbols that require a load from a stub to get the address, emit the
7448   // load.
7449   if (isGlobalStubReference(OpFlag))
7450     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7451                          MachinePointerInfo::getGOT(), false, false, false, 0);
7452
7453   return Result;
7454 }
7455
7456 SDValue
7457 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7458   // Create the TargetBlockAddressAddress node.
7459   unsigned char OpFlags =
7460     Subtarget->ClassifyBlockAddressReference();
7461   CodeModel::Model M = getTargetMachine().getCodeModel();
7462   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7463   DebugLoc dl = Op.getDebugLoc();
7464   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
7465                                        /*isTarget=*/true, OpFlags);
7466
7467   if (Subtarget->isPICStyleRIPRel() &&
7468       (M == CodeModel::Small || M == CodeModel::Kernel))
7469     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7470   else
7471     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7472
7473   // With PIC, the address is actually $g + Offset.
7474   if (isGlobalRelativeToPICBase(OpFlags)) {
7475     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7476                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7477                          Result);
7478   }
7479
7480   return Result;
7481 }
7482
7483 SDValue
7484 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7485                                       int64_t Offset,
7486                                       SelectionDAG &DAG) const {
7487   // Create the TargetGlobalAddress node, folding in the constant
7488   // offset if it is legal.
7489   unsigned char OpFlags =
7490     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7491   CodeModel::Model M = getTargetMachine().getCodeModel();
7492   SDValue Result;
7493   if (OpFlags == X86II::MO_NO_FLAG &&
7494       X86::isOffsetSuitableForCodeModel(Offset, M)) {
7495     // A direct static reference to a global.
7496     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7497     Offset = 0;
7498   } else {
7499     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7500   }
7501
7502   if (Subtarget->isPICStyleRIPRel() &&
7503       (M == CodeModel::Small || M == CodeModel::Kernel))
7504     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7505   else
7506     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7507
7508   // With PIC, the address is actually $g + Offset.
7509   if (isGlobalRelativeToPICBase(OpFlags)) {
7510     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7511                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7512                          Result);
7513   }
7514
7515   // For globals that require a load from a stub to get the address, emit the
7516   // load.
7517   if (isGlobalStubReference(OpFlags))
7518     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7519                          MachinePointerInfo::getGOT(), false, false, false, 0);
7520
7521   // If there was a non-zero offset that we didn't fold, create an explicit
7522   // addition for it.
7523   if (Offset != 0)
7524     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7525                          DAG.getConstant(Offset, getPointerTy()));
7526
7527   return Result;
7528 }
7529
7530 SDValue
7531 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7532   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7533   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7534   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7535 }
7536
7537 static SDValue
7538 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7539            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7540            unsigned char OperandFlags) {
7541   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7542   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7543   DebugLoc dl = GA->getDebugLoc();
7544   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7545                                            GA->getValueType(0),
7546                                            GA->getOffset(),
7547                                            OperandFlags);
7548   if (InFlag) {
7549     SDValue Ops[] = { Chain,  TGA, *InFlag };
7550     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
7551   } else {
7552     SDValue Ops[]  = { Chain, TGA };
7553     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
7554   }
7555
7556   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7557   MFI->setAdjustsStack(true);
7558
7559   SDValue Flag = Chain.getValue(1);
7560   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7561 }
7562
7563 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7564 static SDValue
7565 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7566                                 const EVT PtrVT) {
7567   SDValue InFlag;
7568   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
7569   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7570                                      DAG.getNode(X86ISD::GlobalBaseReg,
7571                                                  DebugLoc(), PtrVT), InFlag);
7572   InFlag = Chain.getValue(1);
7573
7574   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7575 }
7576
7577 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7578 static SDValue
7579 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7580                                 const EVT PtrVT) {
7581   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7582                     X86::RAX, X86II::MO_TLSGD);
7583 }
7584
7585 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
7586 // "local exec" model.
7587 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7588                                    const EVT PtrVT, TLSModel::Model model,
7589                                    bool is64Bit) {
7590   DebugLoc dl = GA->getDebugLoc();
7591
7592   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7593   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7594                                                          is64Bit ? 257 : 256));
7595
7596   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7597                                       DAG.getIntPtrConstant(0),
7598                                       MachinePointerInfo(Ptr),
7599                                       false, false, false, 0);
7600
7601   unsigned char OperandFlags = 0;
7602   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
7603   // initialexec.
7604   unsigned WrapperKind = X86ISD::Wrapper;
7605   if (model == TLSModel::LocalExec) {
7606     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7607   } else if (is64Bit) {
7608     assert(model == TLSModel::InitialExec);
7609     OperandFlags = X86II::MO_GOTTPOFF;
7610     WrapperKind = X86ISD::WrapperRIP;
7611   } else {
7612     assert(model == TLSModel::InitialExec);
7613     OperandFlags = X86II::MO_INDNTPOFF;
7614   }
7615
7616   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
7617   // exec)
7618   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7619                                            GA->getValueType(0),
7620                                            GA->getOffset(), OperandFlags);
7621   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7622
7623   if (model == TLSModel::InitialExec)
7624     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7625                          MachinePointerInfo::getGOT(), false, false, false, 0);
7626
7627   // The address of the thread local variable is the add of the thread
7628   // pointer with the offset of the variable.
7629   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7630 }
7631
7632 SDValue
7633 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7634
7635   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7636   const GlobalValue *GV = GA->getGlobal();
7637
7638   if (Subtarget->isTargetELF()) {
7639     // TODO: implement the "local dynamic" model
7640     // TODO: implement the "initial exec"model for pic executables
7641
7642     // If GV is an alias then use the aliasee for determining
7643     // thread-localness.
7644     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7645       GV = GA->resolveAliasedGlobal(false);
7646
7647     TLSModel::Model model
7648       = getTLSModel(GV, getTargetMachine().getRelocationModel());
7649
7650     switch (model) {
7651       case TLSModel::GeneralDynamic:
7652       case TLSModel::LocalDynamic: // not implemented
7653         if (Subtarget->is64Bit())
7654           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7655         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7656
7657       case TLSModel::InitialExec:
7658       case TLSModel::LocalExec:
7659         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7660                                    Subtarget->is64Bit());
7661     }
7662   } else if (Subtarget->isTargetDarwin()) {
7663     // Darwin only has one model of TLS.  Lower to that.
7664     unsigned char OpFlag = 0;
7665     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7666                            X86ISD::WrapperRIP : X86ISD::Wrapper;
7667
7668     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7669     // global base reg.
7670     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7671                   !Subtarget->is64Bit();
7672     if (PIC32)
7673       OpFlag = X86II::MO_TLVP_PIC_BASE;
7674     else
7675       OpFlag = X86II::MO_TLVP;
7676     DebugLoc DL = Op.getDebugLoc();
7677     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7678                                                 GA->getValueType(0),
7679                                                 GA->getOffset(), OpFlag);
7680     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7681
7682     // With PIC32, the address is actually $g + Offset.
7683     if (PIC32)
7684       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7685                            DAG.getNode(X86ISD::GlobalBaseReg,
7686                                        DebugLoc(), getPointerTy()),
7687                            Offset);
7688
7689     // Lowering the machine isd will make sure everything is in the right
7690     // location.
7691     SDValue Chain = DAG.getEntryNode();
7692     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7693     SDValue Args[] = { Chain, Offset };
7694     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7695
7696     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7697     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7698     MFI->setAdjustsStack(true);
7699
7700     // And our return value (tls address) is in the standard call return value
7701     // location.
7702     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7703     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7704                               Chain.getValue(1));
7705   }
7706
7707   assert(false &&
7708          "TLS not implemented for this target.");
7709
7710   llvm_unreachable("Unreachable");
7711   return SDValue();
7712 }
7713
7714
7715 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values and
7716 /// take a 2 x i32 value to shift plus a shift amount.
7717 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const {
7718   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7719   EVT VT = Op.getValueType();
7720   unsigned VTBits = VT.getSizeInBits();
7721   DebugLoc dl = Op.getDebugLoc();
7722   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7723   SDValue ShOpLo = Op.getOperand(0);
7724   SDValue ShOpHi = Op.getOperand(1);
7725   SDValue ShAmt  = Op.getOperand(2);
7726   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7727                                      DAG.getConstant(VTBits - 1, MVT::i8))
7728                        : DAG.getConstant(0, VT);
7729
7730   SDValue Tmp2, Tmp3;
7731   if (Op.getOpcode() == ISD::SHL_PARTS) {
7732     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7733     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7734   } else {
7735     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7736     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7737   }
7738
7739   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7740                                 DAG.getConstant(VTBits, MVT::i8));
7741   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7742                              AndNode, DAG.getConstant(0, MVT::i8));
7743
7744   SDValue Hi, Lo;
7745   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7746   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7747   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7748
7749   if (Op.getOpcode() == ISD::SHL_PARTS) {
7750     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7751     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7752   } else {
7753     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7754     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7755   }
7756
7757   SDValue Ops[2] = { Lo, Hi };
7758   return DAG.getMergeValues(Ops, 2, dl);
7759 }
7760
7761 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7762                                            SelectionDAG &DAG) const {
7763   EVT SrcVT = Op.getOperand(0).getValueType();
7764
7765   if (SrcVT.isVector())
7766     return SDValue();
7767
7768   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7769          "Unknown SINT_TO_FP to lower!");
7770
7771   // These are really Legal; return the operand so the caller accepts it as
7772   // Legal.
7773   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7774     return Op;
7775   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7776       Subtarget->is64Bit()) {
7777     return Op;
7778   }
7779
7780   DebugLoc dl = Op.getDebugLoc();
7781   unsigned Size = SrcVT.getSizeInBits()/8;
7782   MachineFunction &MF = DAG.getMachineFunction();
7783   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7784   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7785   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7786                                StackSlot,
7787                                MachinePointerInfo::getFixedStack(SSFI),
7788                                false, false, 0);
7789   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7790 }
7791
7792 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7793                                      SDValue StackSlot,
7794                                      SelectionDAG &DAG) const {
7795   // Build the FILD
7796   DebugLoc DL = Op.getDebugLoc();
7797   SDVTList Tys;
7798   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7799   if (useSSE)
7800     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7801   else
7802     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7803
7804   unsigned ByteSize = SrcVT.getSizeInBits()/8;
7805
7806   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7807   MachineMemOperand *MMO;
7808   if (FI) {
7809     int SSFI = FI->getIndex();
7810     MMO =
7811       DAG.getMachineFunction()
7812       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7813                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
7814   } else {
7815     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7816     StackSlot = StackSlot.getOperand(1);
7817   }
7818   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7819   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7820                                            X86ISD::FILD, DL,
7821                                            Tys, Ops, array_lengthof(Ops),
7822                                            SrcVT, MMO);
7823
7824   if (useSSE) {
7825     Chain = Result.getValue(1);
7826     SDValue InFlag = Result.getValue(2);
7827
7828     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7829     // shouldn't be necessary except that RFP cannot be live across
7830     // multiple blocks. When stackifier is fixed, they can be uncoupled.
7831     MachineFunction &MF = DAG.getMachineFunction();
7832     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7833     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7834     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7835     Tys = DAG.getVTList(MVT::Other);
7836     SDValue Ops[] = {
7837       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7838     };
7839     MachineMemOperand *MMO =
7840       DAG.getMachineFunction()
7841       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7842                             MachineMemOperand::MOStore, SSFISize, SSFISize);
7843
7844     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7845                                     Ops, array_lengthof(Ops),
7846                                     Op.getValueType(), MMO);
7847     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7848                          MachinePointerInfo::getFixedStack(SSFI),
7849                          false, false, false, 0);
7850   }
7851
7852   return Result;
7853 }
7854
7855 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7856 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7857                                                SelectionDAG &DAG) const {
7858   // This algorithm is not obvious. Here it is in C code, more or less:
7859   /*
7860     double uint64_to_double( uint32_t hi, uint32_t lo ) {
7861       static const __m128i exp = { 0x4330000045300000ULL, 0 };
7862       static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
7863
7864       // Copy ints to xmm registers.
7865       __m128i xh = _mm_cvtsi32_si128( hi );
7866       __m128i xl = _mm_cvtsi32_si128( lo );
7867
7868       // Combine into low half of a single xmm register.
7869       __m128i x = _mm_unpacklo_epi32( xh, xl );
7870       __m128d d;
7871       double sd;
7872
7873       // Merge in appropriate exponents to give the integer bits the right
7874       // magnitude.
7875       x = _mm_unpacklo_epi32( x, exp );
7876
7877       // Subtract away the biases to deal with the IEEE-754 double precision
7878       // implicit 1.
7879       d = _mm_sub_pd( (__m128d) x, bias );
7880
7881       // All conversions up to here are exact. The correctly rounded result is
7882       // calculated using the current rounding mode using the following
7883       // horizontal add.
7884       d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
7885       _mm_store_sd( &sd, d );   // Because we are returning doubles in XMM, this
7886                                 // store doesn't really need to be here (except
7887                                 // maybe to zero the other double)
7888       return sd;
7889     }
7890   */
7891
7892   DebugLoc dl = Op.getDebugLoc();
7893   LLVMContext *Context = DAG.getContext();
7894
7895   // Build some magic constants.
7896   std::vector<Constant*> CV0;
7897   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
7898   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
7899   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7900   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7901   Constant *C0 = ConstantVector::get(CV0);
7902   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7903
7904   std::vector<Constant*> CV1;
7905   CV1.push_back(
7906     ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7907   CV1.push_back(
7908     ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7909   Constant *C1 = ConstantVector::get(CV1);
7910   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7911
7912   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7913                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7914                                         Op.getOperand(0),
7915                                         DAG.getIntPtrConstant(1)));
7916   SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7917                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7918                                         Op.getOperand(0),
7919                                         DAG.getIntPtrConstant(0)));
7920   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
7921   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7922                               MachinePointerInfo::getConstantPool(),
7923                               false, false, false, 16);
7924   SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
7925   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
7926   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7927                               MachinePointerInfo::getConstantPool(),
7928                               false, false, false, 16);
7929   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7930
7931   // Add the halves; easiest way is to swap them into another reg first.
7932   int ShufMask[2] = { 1, -1 };
7933   SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
7934                                       DAG.getUNDEF(MVT::v2f64), ShufMask);
7935   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
7936   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
7937                      DAG.getIntPtrConstant(0));
7938 }
7939
7940 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7941 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7942                                                SelectionDAG &DAG) const {
7943   DebugLoc dl = Op.getDebugLoc();
7944   // FP constant to bias correct the final result.
7945   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7946                                    MVT::f64);
7947
7948   // Load the 32-bit value into an XMM register.
7949   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7950                              Op.getOperand(0));
7951
7952   // Zero out the upper parts of the register.
7953   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget->hasXMMInt(),
7954                                      DAG);
7955
7956   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7957                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7958                      DAG.getIntPtrConstant(0));
7959
7960   // Or the load with the bias.
7961   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7962                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7963                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7964                                                    MVT::v2f64, Load)),
7965                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7966                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7967                                                    MVT::v2f64, Bias)));
7968   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7969                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7970                    DAG.getIntPtrConstant(0));
7971
7972   // Subtract the bias.
7973   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7974
7975   // Handle final rounding.
7976   EVT DestVT = Op.getValueType();
7977
7978   if (DestVT.bitsLT(MVT::f64)) {
7979     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7980                        DAG.getIntPtrConstant(0));
7981   } else if (DestVT.bitsGT(MVT::f64)) {
7982     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7983   }
7984
7985   // Handle final rounding.
7986   return Sub;
7987 }
7988
7989 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7990                                            SelectionDAG &DAG) const {
7991   SDValue N0 = Op.getOperand(0);
7992   DebugLoc dl = Op.getDebugLoc();
7993
7994   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
7995   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
7996   // the optimization here.
7997   if (DAG.SignBitIsZero(N0))
7998     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
7999
8000   EVT SrcVT = N0.getValueType();
8001   EVT DstVT = Op.getValueType();
8002   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8003     return LowerUINT_TO_FP_i64(Op, DAG);
8004   else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8005     return LowerUINT_TO_FP_i32(Op, DAG);
8006
8007   // Make a 64-bit buffer, and use it to build an FILD.
8008   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8009   if (SrcVT == MVT::i32) {
8010     SDValue WordOff = DAG.getConstant(4, getPointerTy());
8011     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8012                                      getPointerTy(), StackSlot, WordOff);
8013     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8014                                   StackSlot, MachinePointerInfo(),
8015                                   false, false, 0);
8016     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8017                                   OffsetSlot, MachinePointerInfo(),
8018                                   false, false, 0);
8019     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8020     return Fild;
8021   }
8022
8023   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8024   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8025                                 StackSlot, MachinePointerInfo(),
8026                                false, false, 0);
8027   // For i64 source, we need to add the appropriate power of 2 if the input
8028   // was negative.  This is the same as the optimization in
8029   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8030   // we must be careful to do the computation in x87 extended precision, not
8031   // in SSE. (The generic code can't know it's OK to do this, or how to.)
8032   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8033   MachineMemOperand *MMO =
8034     DAG.getMachineFunction()
8035     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8036                           MachineMemOperand::MOLoad, 8, 8);
8037
8038   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8039   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8040   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
8041                                          MVT::i64, MMO);
8042
8043   APInt FF(32, 0x5F800000ULL);
8044
8045   // Check whether the sign bit is set.
8046   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
8047                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8048                                  ISD::SETLT);
8049
8050   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8051   SDValue FudgePtr = DAG.getConstantPool(
8052                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8053                                          getPointerTy());
8054
8055   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8056   SDValue Zero = DAG.getIntPtrConstant(0);
8057   SDValue Four = DAG.getIntPtrConstant(4);
8058   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8059                                Zero, Four);
8060   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8061
8062   // Load the value out, extending it from f32 to f80.
8063   // FIXME: Avoid the extend by constructing the right constant pool?
8064   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8065                                  FudgePtr, MachinePointerInfo::getConstantPool(),
8066                                  MVT::f32, false, false, 4);
8067   // Extend everything to 80 bits to force it to be done on x87.
8068   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8069   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8070 }
8071
8072 std::pair<SDValue,SDValue> X86TargetLowering::
8073 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
8074   DebugLoc DL = Op.getDebugLoc();
8075
8076   EVT DstTy = Op.getValueType();
8077
8078   if (!IsSigned) {
8079     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8080     DstTy = MVT::i64;
8081   }
8082
8083   assert(DstTy.getSimpleVT() <= MVT::i64 &&
8084          DstTy.getSimpleVT() >= MVT::i16 &&
8085          "Unknown FP_TO_SINT to lower!");
8086
8087   // These are really Legal.
8088   if (DstTy == MVT::i32 &&
8089       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8090     return std::make_pair(SDValue(), SDValue());
8091   if (Subtarget->is64Bit() &&
8092       DstTy == MVT::i64 &&
8093       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8094     return std::make_pair(SDValue(), SDValue());
8095
8096   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
8097   // stack slot.
8098   MachineFunction &MF = DAG.getMachineFunction();
8099   unsigned MemSize = DstTy.getSizeInBits()/8;
8100   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8101   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8102
8103
8104
8105   unsigned Opc;
8106   switch (DstTy.getSimpleVT().SimpleTy) {
8107   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8108   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8109   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8110   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8111   }
8112
8113   SDValue Chain = DAG.getEntryNode();
8114   SDValue Value = Op.getOperand(0);
8115   EVT TheVT = Op.getOperand(0).getValueType();
8116   if (isScalarFPTypeInSSEReg(TheVT)) {
8117     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8118     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8119                          MachinePointerInfo::getFixedStack(SSFI),
8120                          false, false, 0);
8121     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8122     SDValue Ops[] = {
8123       Chain, StackSlot, DAG.getValueType(TheVT)
8124     };
8125
8126     MachineMemOperand *MMO =
8127       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8128                               MachineMemOperand::MOLoad, MemSize, MemSize);
8129     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
8130                                     DstTy, MMO);
8131     Chain = Value.getValue(1);
8132     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8133     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8134   }
8135
8136   MachineMemOperand *MMO =
8137     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8138                             MachineMemOperand::MOStore, MemSize, MemSize);
8139
8140   // Build the FP_TO_INT*_IN_MEM
8141   SDValue Ops[] = { Chain, Value, StackSlot };
8142   SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8143                                          Ops, 3, DstTy, MMO);
8144
8145   return std::make_pair(FIST, StackSlot);
8146 }
8147
8148 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8149                                            SelectionDAG &DAG) const {
8150   if (Op.getValueType().isVector())
8151     return SDValue();
8152
8153   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
8154   SDValue FIST = Vals.first, StackSlot = Vals.second;
8155   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8156   if (FIST.getNode() == 0) return Op;
8157
8158   // Load the result.
8159   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8160                      FIST, StackSlot, MachinePointerInfo(),
8161                      false, false, false, 0);
8162 }
8163
8164 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8165                                            SelectionDAG &DAG) const {
8166   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
8167   SDValue FIST = Vals.first, StackSlot = Vals.second;
8168   assert(FIST.getNode() && "Unexpected failure");
8169
8170   // Load the result.
8171   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8172                      FIST, StackSlot, MachinePointerInfo(),
8173                      false, false, false, 0);
8174 }
8175
8176 SDValue X86TargetLowering::LowerFABS(SDValue Op,
8177                                      SelectionDAG &DAG) const {
8178   LLVMContext *Context = DAG.getContext();
8179   DebugLoc dl = Op.getDebugLoc();
8180   EVT VT = Op.getValueType();
8181   EVT EltVT = VT;
8182   if (VT.isVector())
8183     EltVT = VT.getVectorElementType();
8184   std::vector<Constant*> CV;
8185   if (EltVT == MVT::f64) {
8186     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
8187     CV.push_back(C);
8188     CV.push_back(C);
8189   } else {
8190     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
8191     CV.push_back(C);
8192     CV.push_back(C);
8193     CV.push_back(C);
8194     CV.push_back(C);
8195   }
8196   Constant *C = ConstantVector::get(CV);
8197   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8198   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8199                              MachinePointerInfo::getConstantPool(),
8200                              false, false, false, 16);
8201   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8202 }
8203
8204 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8205   LLVMContext *Context = DAG.getContext();
8206   DebugLoc dl = Op.getDebugLoc();
8207   EVT VT = Op.getValueType();
8208   EVT EltVT = VT;
8209   if (VT.isVector())
8210     EltVT = VT.getVectorElementType();
8211   std::vector<Constant*> CV;
8212   if (EltVT == MVT::f64) {
8213     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8214     CV.push_back(C);
8215     CV.push_back(C);
8216   } else {
8217     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8218     CV.push_back(C);
8219     CV.push_back(C);
8220     CV.push_back(C);
8221     CV.push_back(C);
8222   }
8223   Constant *C = ConstantVector::get(CV);
8224   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8225   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8226                              MachinePointerInfo::getConstantPool(),
8227                              false, false, false, 16);
8228   if (VT.isVector()) {
8229     return DAG.getNode(ISD::BITCAST, dl, VT,
8230                        DAG.getNode(ISD::XOR, dl, MVT::v2i64,
8231                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8232                                 Op.getOperand(0)),
8233                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask)));
8234   } else {
8235     return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8236   }
8237 }
8238
8239 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8240   LLVMContext *Context = DAG.getContext();
8241   SDValue Op0 = Op.getOperand(0);
8242   SDValue Op1 = Op.getOperand(1);
8243   DebugLoc dl = Op.getDebugLoc();
8244   EVT VT = Op.getValueType();
8245   EVT SrcVT = Op1.getValueType();
8246
8247   // If second operand is smaller, extend it first.
8248   if (SrcVT.bitsLT(VT)) {
8249     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8250     SrcVT = VT;
8251   }
8252   // And if it is bigger, shrink it first.
8253   if (SrcVT.bitsGT(VT)) {
8254     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8255     SrcVT = VT;
8256   }
8257
8258   // At this point the operands and the result should have the same
8259   // type, and that won't be f80 since that is not custom lowered.
8260
8261   // First get the sign bit of second operand.
8262   std::vector<Constant*> CV;
8263   if (SrcVT == MVT::f64) {
8264     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8265     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8266   } else {
8267     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8268     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8269     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8270     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8271   }
8272   Constant *C = ConstantVector::get(CV);
8273   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8274   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8275                               MachinePointerInfo::getConstantPool(),
8276                               false, false, false, 16);
8277   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8278
8279   // Shift sign bit right or left if the two operands have different types.
8280   if (SrcVT.bitsGT(VT)) {
8281     // Op0 is MVT::f32, Op1 is MVT::f64.
8282     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8283     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8284                           DAG.getConstant(32, MVT::i32));
8285     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8286     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8287                           DAG.getIntPtrConstant(0));
8288   }
8289
8290   // Clear first operand sign bit.
8291   CV.clear();
8292   if (VT == MVT::f64) {
8293     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8294     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8295   } else {
8296     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8297     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8298     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8299     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8300   }
8301   C = ConstantVector::get(CV);
8302   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8303   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8304                               MachinePointerInfo::getConstantPool(),
8305                               false, false, false, 16);
8306   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8307
8308   // Or the value with the sign bit.
8309   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8310 }
8311
8312 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
8313   SDValue N0 = Op.getOperand(0);
8314   DebugLoc dl = Op.getDebugLoc();
8315   EVT VT = Op.getValueType();
8316
8317   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8318   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8319                                   DAG.getConstant(1, VT));
8320   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8321 }
8322
8323 /// Emit nodes that will be selected as "test Op0,Op0", or something
8324 /// equivalent.
8325 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8326                                     SelectionDAG &DAG) const {
8327   DebugLoc dl = Op.getDebugLoc();
8328
8329   // CF and OF aren't always set the way we want. Determine which
8330   // of these we need.
8331   bool NeedCF = false;
8332   bool NeedOF = false;
8333   switch (X86CC) {
8334   default: break;
8335   case X86::COND_A: case X86::COND_AE:
8336   case X86::COND_B: case X86::COND_BE:
8337     NeedCF = true;
8338     break;
8339   case X86::COND_G: case X86::COND_GE:
8340   case X86::COND_L: case X86::COND_LE:
8341   case X86::COND_O: case X86::COND_NO:
8342     NeedOF = true;
8343     break;
8344   }
8345
8346   // See if we can use the EFLAGS value from the operand instead of
8347   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8348   // we prove that the arithmetic won't overflow, we can't use OF or CF.
8349   if (Op.getResNo() != 0 || NeedOF || NeedCF)
8350     // Emit a CMP with 0, which is the TEST pattern.
8351     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8352                        DAG.getConstant(0, Op.getValueType()));
8353
8354   unsigned Opcode = 0;
8355   unsigned NumOperands = 0;
8356   switch (Op.getNode()->getOpcode()) {
8357   case ISD::ADD:
8358     // Due to an isel shortcoming, be conservative if this add is likely to be
8359     // selected as part of a load-modify-store instruction. When the root node
8360     // in a match is a store, isel doesn't know how to remap non-chain non-flag
8361     // uses of other nodes in the match, such as the ADD in this case. This
8362     // leads to the ADD being left around and reselected, with the result being
8363     // two adds in the output.  Alas, even if none our users are stores, that
8364     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
8365     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
8366     // climbing the DAG back to the root, and it doesn't seem to be worth the
8367     // effort.
8368     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8369          UE = Op.getNode()->use_end(); UI != UE; ++UI)
8370       if (UI->getOpcode() != ISD::CopyToReg &&
8371           UI->getOpcode() != ISD::SETCC &&
8372           UI->getOpcode() != ISD::STORE)
8373         goto default_case;
8374
8375     if (ConstantSDNode *C =
8376         dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
8377       // An add of one will be selected as an INC.
8378       if (C->getAPIntValue() == 1) {
8379         Opcode = X86ISD::INC;
8380         NumOperands = 1;
8381         break;
8382       }
8383
8384       // An add of negative one (subtract of one) will be selected as a DEC.
8385       if (C->getAPIntValue().isAllOnesValue()) {
8386         Opcode = X86ISD::DEC;
8387         NumOperands = 1;
8388         break;
8389       }
8390     }
8391
8392     // Otherwise use a regular EFLAGS-setting add.
8393     Opcode = X86ISD::ADD;
8394     NumOperands = 2;
8395     break;
8396   case ISD::AND: {
8397     // If the primary and result isn't used, don't bother using X86ISD::AND,
8398     // because a TEST instruction will be better.
8399     bool NonFlagUse = false;
8400     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8401            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8402       SDNode *User = *UI;
8403       unsigned UOpNo = UI.getOperandNo();
8404       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8405         // Look pass truncate.
8406         UOpNo = User->use_begin().getOperandNo();
8407         User = *User->use_begin();
8408       }
8409
8410       if (User->getOpcode() != ISD::BRCOND &&
8411           User->getOpcode() != ISD::SETCC &&
8412           (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
8413         NonFlagUse = true;
8414         break;
8415       }
8416     }
8417
8418     if (!NonFlagUse)
8419       break;
8420   }
8421     // FALL THROUGH
8422   case ISD::SUB:
8423   case ISD::OR:
8424   case ISD::XOR:
8425     // Due to the ISEL shortcoming noted above, be conservative if this op is
8426     // likely to be selected as part of a load-modify-store instruction.
8427     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8428            UE = Op.getNode()->use_end(); UI != UE; ++UI)
8429       if (UI->getOpcode() == ISD::STORE)
8430         goto default_case;
8431
8432     // Otherwise use a regular EFLAGS-setting instruction.
8433     switch (Op.getNode()->getOpcode()) {
8434     default: llvm_unreachable("unexpected operator!");
8435     case ISD::SUB: Opcode = X86ISD::SUB; break;
8436     case ISD::OR:  Opcode = X86ISD::OR;  break;
8437     case ISD::XOR: Opcode = X86ISD::XOR; break;
8438     case ISD::AND: Opcode = X86ISD::AND; break;
8439     }
8440
8441     NumOperands = 2;
8442     break;
8443   case X86ISD::ADD:
8444   case X86ISD::SUB:
8445   case X86ISD::INC:
8446   case X86ISD::DEC:
8447   case X86ISD::OR:
8448   case X86ISD::XOR:
8449   case X86ISD::AND:
8450     return SDValue(Op.getNode(), 1);
8451   default:
8452   default_case:
8453     break;
8454   }
8455
8456   if (Opcode == 0)
8457     // Emit a CMP with 0, which is the TEST pattern.
8458     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8459                        DAG.getConstant(0, Op.getValueType()));
8460
8461   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8462   SmallVector<SDValue, 4> Ops;
8463   for (unsigned i = 0; i != NumOperands; ++i)
8464     Ops.push_back(Op.getOperand(i));
8465
8466   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8467   DAG.ReplaceAllUsesWith(Op, New);
8468   return SDValue(New.getNode(), 1);
8469 }
8470
8471 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8472 /// equivalent.
8473 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8474                                    SelectionDAG &DAG) const {
8475   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8476     if (C->getAPIntValue() == 0)
8477       return EmitTest(Op0, X86CC, DAG);
8478
8479   DebugLoc dl = Op0.getDebugLoc();
8480   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8481 }
8482
8483 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8484 /// if it's possible.
8485 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8486                                      DebugLoc dl, SelectionDAG &DAG) const {
8487   SDValue Op0 = And.getOperand(0);
8488   SDValue Op1 = And.getOperand(1);
8489   if (Op0.getOpcode() == ISD::TRUNCATE)
8490     Op0 = Op0.getOperand(0);
8491   if (Op1.getOpcode() == ISD::TRUNCATE)
8492     Op1 = Op1.getOperand(0);
8493
8494   SDValue LHS, RHS;
8495   if (Op1.getOpcode() == ISD::SHL)
8496     std::swap(Op0, Op1);
8497   if (Op0.getOpcode() == ISD::SHL) {
8498     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8499       if (And00C->getZExtValue() == 1) {
8500         // If we looked past a truncate, check that it's only truncating away
8501         // known zeros.
8502         unsigned BitWidth = Op0.getValueSizeInBits();
8503         unsigned AndBitWidth = And.getValueSizeInBits();
8504         if (BitWidth > AndBitWidth) {
8505           APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
8506           DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
8507           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8508             return SDValue();
8509         }
8510         LHS = Op1;
8511         RHS = Op0.getOperand(1);
8512       }
8513   } else if (Op1.getOpcode() == ISD::Constant) {
8514     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8515     SDValue AndLHS = Op0;
8516     if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
8517       LHS = AndLHS.getOperand(0);
8518       RHS = AndLHS.getOperand(1);
8519     }
8520   }
8521
8522   if (LHS.getNode()) {
8523     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
8524     // instruction.  Since the shift amount is in-range-or-undefined, we know
8525     // that doing a bittest on the i32 value is ok.  We extend to i32 because
8526     // the encoding for the i16 version is larger than the i32 version.
8527     // Also promote i16 to i32 for performance / code size reason.
8528     if (LHS.getValueType() == MVT::i8 ||
8529         LHS.getValueType() == MVT::i16)
8530       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8531
8532     // If the operand types disagree, extend the shift amount to match.  Since
8533     // BT ignores high bits (like shifts) we can use anyextend.
8534     if (LHS.getValueType() != RHS.getValueType())
8535       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8536
8537     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8538     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8539     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8540                        DAG.getConstant(Cond, MVT::i8), BT);
8541   }
8542
8543   return SDValue();
8544 }
8545
8546 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8547
8548   if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8549
8550   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8551   SDValue Op0 = Op.getOperand(0);
8552   SDValue Op1 = Op.getOperand(1);
8553   DebugLoc dl = Op.getDebugLoc();
8554   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8555
8556   // Optimize to BT if possible.
8557   // Lower (X & (1 << N)) == 0 to BT(X, N).
8558   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8559   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8560   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8561       Op1.getOpcode() == ISD::Constant &&
8562       cast<ConstantSDNode>(Op1)->isNullValue() &&
8563       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8564     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8565     if (NewSetCC.getNode())
8566       return NewSetCC;
8567   }
8568
8569   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
8570   // these.
8571   if (Op1.getOpcode() == ISD::Constant &&
8572       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8573        cast<ConstantSDNode>(Op1)->isNullValue()) &&
8574       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8575
8576     // If the input is a setcc, then reuse the input setcc or use a new one with
8577     // the inverted condition.
8578     if (Op0.getOpcode() == X86ISD::SETCC) {
8579       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8580       bool Invert = (CC == ISD::SETNE) ^
8581         cast<ConstantSDNode>(Op1)->isNullValue();
8582       if (!Invert) return Op0;
8583
8584       CCode = X86::GetOppositeBranchCondition(CCode);
8585       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8586                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8587     }
8588   }
8589
8590   bool isFP = Op1.getValueType().isFloatingPoint();
8591   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8592   if (X86CC == X86::COND_INVALID)
8593     return SDValue();
8594
8595   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8596   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8597                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8598 }
8599
8600 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8601 // ones, and then concatenate the result back.
8602 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
8603   EVT VT = Op.getValueType();
8604
8605   assert(VT.getSizeInBits() == 256 && Op.getOpcode() == ISD::SETCC &&
8606          "Unsupported value type for operation");
8607
8608   int NumElems = VT.getVectorNumElements();
8609   DebugLoc dl = Op.getDebugLoc();
8610   SDValue CC = Op.getOperand(2);
8611   SDValue Idx0 = DAG.getConstant(0, MVT::i32);
8612   SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
8613
8614   // Extract the LHS vectors
8615   SDValue LHS = Op.getOperand(0);
8616   SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
8617   SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
8618
8619   // Extract the RHS vectors
8620   SDValue RHS = Op.getOperand(1);
8621   SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl);
8622   SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl);
8623
8624   // Issue the operation on the smaller types and concatenate the result back
8625   MVT EltVT = VT.getVectorElementType().getSimpleVT();
8626   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8627   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8628                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8629                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8630 }
8631
8632
8633 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8634   SDValue Cond;
8635   SDValue Op0 = Op.getOperand(0);
8636   SDValue Op1 = Op.getOperand(1);
8637   SDValue CC = Op.getOperand(2);
8638   EVT VT = Op.getValueType();
8639   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8640   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8641   DebugLoc dl = Op.getDebugLoc();
8642
8643   if (isFP) {
8644     unsigned SSECC = 8;
8645     EVT EltVT = Op0.getValueType().getVectorElementType();
8646     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
8647
8648     unsigned Opc = EltVT == MVT::f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
8649     bool Swap = false;
8650
8651     // SSE Condition code mapping:
8652     //  0 - EQ
8653     //  1 - LT
8654     //  2 - LE
8655     //  3 - UNORD
8656     //  4 - NEQ
8657     //  5 - NLT
8658     //  6 - NLE
8659     //  7 - ORD
8660     switch (SetCCOpcode) {
8661     default: break;
8662     case ISD::SETOEQ:
8663     case ISD::SETEQ:  SSECC = 0; break;
8664     case ISD::SETOGT:
8665     case ISD::SETGT: Swap = true; // Fallthrough
8666     case ISD::SETLT:
8667     case ISD::SETOLT: SSECC = 1; break;
8668     case ISD::SETOGE:
8669     case ISD::SETGE: Swap = true; // Fallthrough
8670     case ISD::SETLE:
8671     case ISD::SETOLE: SSECC = 2; break;
8672     case ISD::SETUO:  SSECC = 3; break;
8673     case ISD::SETUNE:
8674     case ISD::SETNE:  SSECC = 4; break;
8675     case ISD::SETULE: Swap = true;
8676     case ISD::SETUGE: SSECC = 5; break;
8677     case ISD::SETULT: Swap = true;
8678     case ISD::SETUGT: SSECC = 6; break;
8679     case ISD::SETO:   SSECC = 7; break;
8680     }
8681     if (Swap)
8682       std::swap(Op0, Op1);
8683
8684     // In the two special cases we can't handle, emit two comparisons.
8685     if (SSECC == 8) {
8686       if (SetCCOpcode == ISD::SETUEQ) {
8687         SDValue UNORD, EQ;
8688         UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
8689         EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
8690         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
8691       } else if (SetCCOpcode == ISD::SETONE) {
8692         SDValue ORD, NEQ;
8693         ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
8694         NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
8695         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
8696       }
8697       llvm_unreachable("Illegal FP comparison");
8698     }
8699     // Handle all other FP comparisons here.
8700     return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
8701   }
8702
8703   // Break 256-bit integer vector compare into smaller ones.
8704   if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2())
8705     return Lower256IntVSETCC(Op, DAG);
8706
8707   // We are handling one of the integer comparisons here.  Since SSE only has
8708   // GT and EQ comparisons for integer, swapping operands and multiple
8709   // operations may be required for some comparisons.
8710   unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
8711   bool Swap = false, Invert = false, FlipSigns = false;
8712
8713   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
8714   default: break;
8715   case MVT::i8:   EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
8716   case MVT::i16:  EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
8717   case MVT::i32:  EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
8718   case MVT::i64:  EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
8719   }
8720
8721   switch (SetCCOpcode) {
8722   default: break;
8723   case ISD::SETNE:  Invert = true;
8724   case ISD::SETEQ:  Opc = EQOpc; break;
8725   case ISD::SETLT:  Swap = true;
8726   case ISD::SETGT:  Opc = GTOpc; break;
8727   case ISD::SETGE:  Swap = true;
8728   case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
8729   case ISD::SETULT: Swap = true;
8730   case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
8731   case ISD::SETUGE: Swap = true;
8732   case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
8733   }
8734   if (Swap)
8735     std::swap(Op0, Op1);
8736
8737   // Check that the operation in question is available (most are plain SSE2,
8738   // but PCMPGTQ and PCMPEQQ have different requirements).
8739   if (Opc == X86ISD::PCMPGTQ && !Subtarget->hasSSE42orAVX())
8740     return SDValue();
8741   if (Opc == X86ISD::PCMPEQQ && !Subtarget->hasSSE41orAVX())
8742     return SDValue();
8743
8744   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
8745   // bits of the inputs before performing those operations.
8746   if (FlipSigns) {
8747     EVT EltVT = VT.getVectorElementType();
8748     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
8749                                       EltVT);
8750     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
8751     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
8752                                     SignBits.size());
8753     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
8754     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
8755   }
8756
8757   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
8758
8759   // If the logical-not of the result is required, perform that now.
8760   if (Invert)
8761     Result = DAG.getNOT(dl, Result, VT);
8762
8763   return Result;
8764 }
8765
8766 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
8767 static bool isX86LogicalCmp(SDValue Op) {
8768   unsigned Opc = Op.getNode()->getOpcode();
8769   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
8770     return true;
8771   if (Op.getResNo() == 1 &&
8772       (Opc == X86ISD::ADD ||
8773        Opc == X86ISD::SUB ||
8774        Opc == X86ISD::ADC ||
8775        Opc == X86ISD::SBB ||
8776        Opc == X86ISD::SMUL ||
8777        Opc == X86ISD::UMUL ||
8778        Opc == X86ISD::INC ||
8779        Opc == X86ISD::DEC ||
8780        Opc == X86ISD::OR ||
8781        Opc == X86ISD::XOR ||
8782        Opc == X86ISD::AND))
8783     return true;
8784
8785   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
8786     return true;
8787
8788   return false;
8789 }
8790
8791 static bool isZero(SDValue V) {
8792   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8793   return C && C->isNullValue();
8794 }
8795
8796 static bool isAllOnes(SDValue V) {
8797   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8798   return C && C->isAllOnesValue();
8799 }
8800
8801 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8802   bool addTest = true;
8803   SDValue Cond  = Op.getOperand(0);
8804   SDValue Op1 = Op.getOperand(1);
8805   SDValue Op2 = Op.getOperand(2);
8806   DebugLoc DL = Op.getDebugLoc();
8807   SDValue CC;
8808
8809   if (Cond.getOpcode() == ISD::SETCC) {
8810     SDValue NewCond = LowerSETCC(Cond, DAG);
8811     if (NewCond.getNode())
8812       Cond = NewCond;
8813   }
8814
8815   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
8816   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
8817   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
8818   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
8819   if (Cond.getOpcode() == X86ISD::SETCC &&
8820       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
8821       isZero(Cond.getOperand(1).getOperand(1))) {
8822     SDValue Cmp = Cond.getOperand(1);
8823
8824     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
8825
8826     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
8827         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
8828       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
8829
8830       SDValue CmpOp0 = Cmp.getOperand(0);
8831       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
8832                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
8833
8834       SDValue Res =   // Res = 0 or -1.
8835         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8836                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
8837
8838       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
8839         Res = DAG.getNOT(DL, Res, Res.getValueType());
8840
8841       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
8842       if (N2C == 0 || !N2C->isNullValue())
8843         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
8844       return Res;
8845     }
8846   }
8847
8848   // Look past (and (setcc_carry (cmp ...)), 1).
8849   if (Cond.getOpcode() == ISD::AND &&
8850       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8851     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8852     if (C && C->getAPIntValue() == 1)
8853       Cond = Cond.getOperand(0);
8854   }
8855
8856   // If condition flag is set by a X86ISD::CMP, then use it as the condition
8857   // setting operand in place of the X86ISD::SETCC.
8858   unsigned CondOpcode = Cond.getOpcode();
8859   if (CondOpcode == X86ISD::SETCC ||
8860       CondOpcode == X86ISD::SETCC_CARRY) {
8861     CC = Cond.getOperand(0);
8862
8863     SDValue Cmp = Cond.getOperand(1);
8864     unsigned Opc = Cmp.getOpcode();
8865     EVT VT = Op.getValueType();
8866
8867     bool IllegalFPCMov = false;
8868     if (VT.isFloatingPoint() && !VT.isVector() &&
8869         !isScalarFPTypeInSSEReg(VT))  // FPStack?
8870       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
8871
8872     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
8873         Opc == X86ISD::BT) { // FIXME
8874       Cond = Cmp;
8875       addTest = false;
8876     }
8877   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
8878              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
8879              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
8880               Cond.getOperand(0).getValueType() != MVT::i8)) {
8881     SDValue LHS = Cond.getOperand(0);
8882     SDValue RHS = Cond.getOperand(1);
8883     unsigned X86Opcode;
8884     unsigned X86Cond;
8885     SDVTList VTs;
8886     switch (CondOpcode) {
8887     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
8888     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
8889     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
8890     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
8891     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
8892     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
8893     default: llvm_unreachable("unexpected overflowing operator");
8894     }
8895     if (CondOpcode == ISD::UMULO)
8896       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
8897                           MVT::i32);
8898     else
8899       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
8900
8901     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
8902
8903     if (CondOpcode == ISD::UMULO)
8904       Cond = X86Op.getValue(2);
8905     else
8906       Cond = X86Op.getValue(1);
8907
8908     CC = DAG.getConstant(X86Cond, MVT::i8);
8909     addTest = false;
8910   }
8911
8912   if (addTest) {
8913     // Look pass the truncate.
8914     if (Cond.getOpcode() == ISD::TRUNCATE)
8915       Cond = Cond.getOperand(0);
8916
8917     // We know the result of AND is compared against zero. Try to match
8918     // it to BT.
8919     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8920       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
8921       if (NewSetCC.getNode()) {
8922         CC = NewSetCC.getOperand(0);
8923         Cond = NewSetCC.getOperand(1);
8924         addTest = false;
8925       }
8926     }
8927   }
8928
8929   if (addTest) {
8930     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8931     Cond = EmitTest(Cond, X86::COND_NE, DAG);
8932   }
8933
8934   // a <  b ? -1 :  0 -> RES = ~setcc_carry
8935   // a <  b ?  0 : -1 -> RES = setcc_carry
8936   // a >= b ? -1 :  0 -> RES = setcc_carry
8937   // a >= b ?  0 : -1 -> RES = ~setcc_carry
8938   if (Cond.getOpcode() == X86ISD::CMP) {
8939     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
8940
8941     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
8942         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
8943       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8944                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
8945       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
8946         return DAG.getNOT(DL, Res, Res.getValueType());
8947       return Res;
8948     }
8949   }
8950
8951   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
8952   // condition is true.
8953   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
8954   SDValue Ops[] = { Op2, Op1, CC, Cond };
8955   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
8956 }
8957
8958 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
8959 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
8960 // from the AND / OR.
8961 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
8962   Opc = Op.getOpcode();
8963   if (Opc != ISD::OR && Opc != ISD::AND)
8964     return false;
8965   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8966           Op.getOperand(0).hasOneUse() &&
8967           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
8968           Op.getOperand(1).hasOneUse());
8969 }
8970
8971 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
8972 // 1 and that the SETCC node has a single use.
8973 static bool isXor1OfSetCC(SDValue Op) {
8974   if (Op.getOpcode() != ISD::XOR)
8975     return false;
8976   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8977   if (N1C && N1C->getAPIntValue() == 1) {
8978     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8979       Op.getOperand(0).hasOneUse();
8980   }
8981   return false;
8982 }
8983
8984 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
8985   bool addTest = true;
8986   SDValue Chain = Op.getOperand(0);
8987   SDValue Cond  = Op.getOperand(1);
8988   SDValue Dest  = Op.getOperand(2);
8989   DebugLoc dl = Op.getDebugLoc();
8990   SDValue CC;
8991   bool Inverted = false;
8992
8993   if (Cond.getOpcode() == ISD::SETCC) {
8994     // Check for setcc([su]{add,sub,mul}o == 0).
8995     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
8996         isa<ConstantSDNode>(Cond.getOperand(1)) &&
8997         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
8998         Cond.getOperand(0).getResNo() == 1 &&
8999         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
9000          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
9001          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
9002          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
9003          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
9004          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
9005       Inverted = true;
9006       Cond = Cond.getOperand(0);
9007     } else {
9008       SDValue NewCond = LowerSETCC(Cond, DAG);
9009       if (NewCond.getNode())
9010         Cond = NewCond;
9011     }
9012   }
9013 #if 0
9014   // FIXME: LowerXALUO doesn't handle these!!
9015   else if (Cond.getOpcode() == X86ISD::ADD  ||
9016            Cond.getOpcode() == X86ISD::SUB  ||
9017            Cond.getOpcode() == X86ISD::SMUL ||
9018            Cond.getOpcode() == X86ISD::UMUL)
9019     Cond = LowerXALUO(Cond, DAG);
9020 #endif
9021
9022   // Look pass (and (setcc_carry (cmp ...)), 1).
9023   if (Cond.getOpcode() == ISD::AND &&
9024       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9025     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9026     if (C && C->getAPIntValue() == 1)
9027       Cond = Cond.getOperand(0);
9028   }
9029
9030   // If condition flag is set by a X86ISD::CMP, then use it as the condition
9031   // setting operand in place of the X86ISD::SETCC.
9032   unsigned CondOpcode = Cond.getOpcode();
9033   if (CondOpcode == X86ISD::SETCC ||
9034       CondOpcode == X86ISD::SETCC_CARRY) {
9035     CC = Cond.getOperand(0);
9036
9037     SDValue Cmp = Cond.getOperand(1);
9038     unsigned Opc = Cmp.getOpcode();
9039     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9040     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9041       Cond = Cmp;
9042       addTest = false;
9043     } else {
9044       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9045       default: break;
9046       case X86::COND_O:
9047       case X86::COND_B:
9048         // These can only come from an arithmetic instruction with overflow,
9049         // e.g. SADDO, UADDO.
9050         Cond = Cond.getNode()->getOperand(1);
9051         addTest = false;
9052         break;
9053       }
9054     }
9055   }
9056   CondOpcode = Cond.getOpcode();
9057   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9058       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9059       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9060        Cond.getOperand(0).getValueType() != MVT::i8)) {
9061     SDValue LHS = Cond.getOperand(0);
9062     SDValue RHS = Cond.getOperand(1);
9063     unsigned X86Opcode;
9064     unsigned X86Cond;
9065     SDVTList VTs;
9066     switch (CondOpcode) {
9067     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9068     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9069     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9070     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9071     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9072     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9073     default: llvm_unreachable("unexpected overflowing operator");
9074     }
9075     if (Inverted)
9076       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9077     if (CondOpcode == ISD::UMULO)
9078       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9079                           MVT::i32);
9080     else
9081       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9082
9083     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9084
9085     if (CondOpcode == ISD::UMULO)
9086       Cond = X86Op.getValue(2);
9087     else
9088       Cond = X86Op.getValue(1);
9089
9090     CC = DAG.getConstant(X86Cond, MVT::i8);
9091     addTest = false;
9092   } else {
9093     unsigned CondOpc;
9094     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9095       SDValue Cmp = Cond.getOperand(0).getOperand(1);
9096       if (CondOpc == ISD::OR) {
9097         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9098         // two branches instead of an explicit OR instruction with a
9099         // separate test.
9100         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9101             isX86LogicalCmp(Cmp)) {
9102           CC = Cond.getOperand(0).getOperand(0);
9103           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9104                               Chain, Dest, CC, Cmp);
9105           CC = Cond.getOperand(1).getOperand(0);
9106           Cond = Cmp;
9107           addTest = false;
9108         }
9109       } else { // ISD::AND
9110         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9111         // two branches instead of an explicit AND instruction with a
9112         // separate test. However, we only do this if this block doesn't
9113         // have a fall-through edge, because this requires an explicit
9114         // jmp when the condition is false.
9115         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9116             isX86LogicalCmp(Cmp) &&
9117             Op.getNode()->hasOneUse()) {
9118           X86::CondCode CCode =
9119             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9120           CCode = X86::GetOppositeBranchCondition(CCode);
9121           CC = DAG.getConstant(CCode, MVT::i8);
9122           SDNode *User = *Op.getNode()->use_begin();
9123           // Look for an unconditional branch following this conditional branch.
9124           // We need this because we need to reverse the successors in order
9125           // to implement FCMP_OEQ.
9126           if (User->getOpcode() == ISD::BR) {
9127             SDValue FalseBB = User->getOperand(1);
9128             SDNode *NewBR =
9129               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9130             assert(NewBR == User);
9131             (void)NewBR;
9132             Dest = FalseBB;
9133
9134             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9135                                 Chain, Dest, CC, Cmp);
9136             X86::CondCode CCode =
9137               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9138             CCode = X86::GetOppositeBranchCondition(CCode);
9139             CC = DAG.getConstant(CCode, MVT::i8);
9140             Cond = Cmp;
9141             addTest = false;
9142           }
9143         }
9144       }
9145     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9146       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9147       // It should be transformed during dag combiner except when the condition
9148       // is set by a arithmetics with overflow node.
9149       X86::CondCode CCode =
9150         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9151       CCode = X86::GetOppositeBranchCondition(CCode);
9152       CC = DAG.getConstant(CCode, MVT::i8);
9153       Cond = Cond.getOperand(0).getOperand(1);
9154       addTest = false;
9155     } else if (Cond.getOpcode() == ISD::SETCC &&
9156                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9157       // For FCMP_OEQ, we can emit
9158       // two branches instead of an explicit AND instruction with a
9159       // separate test. However, we only do this if this block doesn't
9160       // have a fall-through edge, because this requires an explicit
9161       // jmp when the condition is false.
9162       if (Op.getNode()->hasOneUse()) {
9163         SDNode *User = *Op.getNode()->use_begin();
9164         // Look for an unconditional branch following this conditional branch.
9165         // We need this because we need to reverse the successors in order
9166         // to implement FCMP_OEQ.
9167         if (User->getOpcode() == ISD::BR) {
9168           SDValue FalseBB = User->getOperand(1);
9169           SDNode *NewBR =
9170             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9171           assert(NewBR == User);
9172           (void)NewBR;
9173           Dest = FalseBB;
9174
9175           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9176                                     Cond.getOperand(0), Cond.getOperand(1));
9177           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9178           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9179                               Chain, Dest, CC, Cmp);
9180           CC = DAG.getConstant(X86::COND_P, MVT::i8);
9181           Cond = Cmp;
9182           addTest = false;
9183         }
9184       }
9185     } else if (Cond.getOpcode() == ISD::SETCC &&
9186                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9187       // For FCMP_UNE, we can emit
9188       // two branches instead of an explicit AND instruction with a
9189       // separate test. However, we only do this if this block doesn't
9190       // have a fall-through edge, because this requires an explicit
9191       // jmp when the condition is false.
9192       if (Op.getNode()->hasOneUse()) {
9193         SDNode *User = *Op.getNode()->use_begin();
9194         // Look for an unconditional branch following this conditional branch.
9195         // We need this because we need to reverse the successors in order
9196         // to implement FCMP_UNE.
9197         if (User->getOpcode() == ISD::BR) {
9198           SDValue FalseBB = User->getOperand(1);
9199           SDNode *NewBR =
9200             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9201           assert(NewBR == User);
9202           (void)NewBR;
9203
9204           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9205                                     Cond.getOperand(0), Cond.getOperand(1));
9206           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9207           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9208                               Chain, Dest, CC, Cmp);
9209           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9210           Cond = Cmp;
9211           addTest = false;
9212           Dest = FalseBB;
9213         }
9214       }
9215     }
9216   }
9217
9218   if (addTest) {
9219     // Look pass the truncate.
9220     if (Cond.getOpcode() == ISD::TRUNCATE)
9221       Cond = Cond.getOperand(0);
9222
9223     // We know the result of AND is compared against zero. Try to match
9224     // it to BT.
9225     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9226       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9227       if (NewSetCC.getNode()) {
9228         CC = NewSetCC.getOperand(0);
9229         Cond = NewSetCC.getOperand(1);
9230         addTest = false;
9231       }
9232     }
9233   }
9234
9235   if (addTest) {
9236     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9237     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9238   }
9239   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9240                      Chain, Dest, CC, Cond);
9241 }
9242
9243
9244 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
9245 // Calls to _alloca is needed to probe the stack when allocating more than 4k
9246 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
9247 // that the guard pages used by the OS virtual memory manager are allocated in
9248 // correct sequence.
9249 SDValue
9250 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9251                                            SelectionDAG &DAG) const {
9252   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
9253           EnableSegmentedStacks) &&
9254          "This should be used only on Windows targets or when segmented stacks "
9255          "are being used");
9256   assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
9257   DebugLoc dl = Op.getDebugLoc();
9258
9259   // Get the inputs.
9260   SDValue Chain = Op.getOperand(0);
9261   SDValue Size  = Op.getOperand(1);
9262   // FIXME: Ensure alignment here
9263
9264   bool Is64Bit = Subtarget->is64Bit();
9265   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
9266
9267   if (EnableSegmentedStacks) {
9268     MachineFunction &MF = DAG.getMachineFunction();
9269     MachineRegisterInfo &MRI = MF.getRegInfo();
9270
9271     if (Is64Bit) {
9272       // The 64 bit implementation of segmented stacks needs to clobber both r10
9273       // r11. This makes it impossible to use it along with nested parameters.
9274       const Function *F = MF.getFunction();
9275
9276       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9277            I != E; I++)
9278         if (I->hasNestAttr())
9279           report_fatal_error("Cannot use segmented stacks with functions that "
9280                              "have nested arguments.");
9281     }
9282
9283     const TargetRegisterClass *AddrRegClass =
9284       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9285     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9286     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9287     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9288                                 DAG.getRegister(Vreg, SPTy));
9289     SDValue Ops1[2] = { Value, Chain };
9290     return DAG.getMergeValues(Ops1, 2, dl);
9291   } else {
9292     SDValue Flag;
9293     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9294
9295     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9296     Flag = Chain.getValue(1);
9297     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9298
9299     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
9300     Flag = Chain.getValue(1);
9301
9302     Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
9303
9304     SDValue Ops1[2] = { Chain.getValue(0), Chain };
9305     return DAG.getMergeValues(Ops1, 2, dl);
9306   }
9307 }
9308
9309 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9310   MachineFunction &MF = DAG.getMachineFunction();
9311   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9312
9313   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9314   DebugLoc DL = Op.getDebugLoc();
9315
9316   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9317     // vastart just stores the address of the VarArgsFrameIndex slot into the
9318     // memory location argument.
9319     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9320                                    getPointerTy());
9321     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9322                         MachinePointerInfo(SV), false, false, 0);
9323   }
9324
9325   // __va_list_tag:
9326   //   gp_offset         (0 - 6 * 8)
9327   //   fp_offset         (48 - 48 + 8 * 16)
9328   //   overflow_arg_area (point to parameters coming in memory).
9329   //   reg_save_area
9330   SmallVector<SDValue, 8> MemOps;
9331   SDValue FIN = Op.getOperand(1);
9332   // Store gp_offset
9333   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9334                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9335                                                MVT::i32),
9336                                FIN, MachinePointerInfo(SV), false, false, 0);
9337   MemOps.push_back(Store);
9338
9339   // Store fp_offset
9340   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9341                     FIN, DAG.getIntPtrConstant(4));
9342   Store = DAG.getStore(Op.getOperand(0), DL,
9343                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9344                                        MVT::i32),
9345                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
9346   MemOps.push_back(Store);
9347
9348   // Store ptr to overflow_arg_area
9349   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9350                     FIN, DAG.getIntPtrConstant(4));
9351   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9352                                     getPointerTy());
9353   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9354                        MachinePointerInfo(SV, 8),
9355                        false, false, 0);
9356   MemOps.push_back(Store);
9357
9358   // Store ptr to reg_save_area.
9359   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9360                     FIN, DAG.getIntPtrConstant(8));
9361   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9362                                     getPointerTy());
9363   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9364                        MachinePointerInfo(SV, 16), false, false, 0);
9365   MemOps.push_back(Store);
9366   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9367                      &MemOps[0], MemOps.size());
9368 }
9369
9370 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9371   assert(Subtarget->is64Bit() &&
9372          "LowerVAARG only handles 64-bit va_arg!");
9373   assert((Subtarget->isTargetLinux() ||
9374           Subtarget->isTargetDarwin()) &&
9375           "Unhandled target in LowerVAARG");
9376   assert(Op.getNode()->getNumOperands() == 4);
9377   SDValue Chain = Op.getOperand(0);
9378   SDValue SrcPtr = Op.getOperand(1);
9379   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9380   unsigned Align = Op.getConstantOperandVal(3);
9381   DebugLoc dl = Op.getDebugLoc();
9382
9383   EVT ArgVT = Op.getNode()->getValueType(0);
9384   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9385   uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
9386   uint8_t ArgMode;
9387
9388   // Decide which area this value should be read from.
9389   // TODO: Implement the AMD64 ABI in its entirety. This simple
9390   // selection mechanism works only for the basic types.
9391   if (ArgVT == MVT::f80) {
9392     llvm_unreachable("va_arg for f80 not yet implemented");
9393   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9394     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
9395   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9396     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
9397   } else {
9398     llvm_unreachable("Unhandled argument type in LowerVAARG");
9399   }
9400
9401   if (ArgMode == 2) {
9402     // Sanity Check: Make sure using fp_offset makes sense.
9403     assert(!UseSoftFloat &&
9404            !(DAG.getMachineFunction()
9405                 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
9406            Subtarget->hasXMM());
9407   }
9408
9409   // Insert VAARG_64 node into the DAG
9410   // VAARG_64 returns two values: Variable Argument Address, Chain
9411   SmallVector<SDValue, 11> InstOps;
9412   InstOps.push_back(Chain);
9413   InstOps.push_back(SrcPtr);
9414   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9415   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9416   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9417   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9418   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9419                                           VTs, &InstOps[0], InstOps.size(),
9420                                           MVT::i64,
9421                                           MachinePointerInfo(SV),
9422                                           /*Align=*/0,
9423                                           /*Volatile=*/false,
9424                                           /*ReadMem=*/true,
9425                                           /*WriteMem=*/true);
9426   Chain = VAARG.getValue(1);
9427
9428   // Load the next argument and return it
9429   return DAG.getLoad(ArgVT, dl,
9430                      Chain,
9431                      VAARG,
9432                      MachinePointerInfo(),
9433                      false, false, false, 0);
9434 }
9435
9436 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
9437   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9438   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9439   SDValue Chain = Op.getOperand(0);
9440   SDValue DstPtr = Op.getOperand(1);
9441   SDValue SrcPtr = Op.getOperand(2);
9442   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9443   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9444   DebugLoc DL = Op.getDebugLoc();
9445
9446   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9447                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9448                        false,
9449                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9450 }
9451
9452 SDValue
9453 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
9454   DebugLoc dl = Op.getDebugLoc();
9455   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9456   switch (IntNo) {
9457   default: return SDValue();    // Don't custom lower most intrinsics.
9458   // Comparison intrinsics.
9459   case Intrinsic::x86_sse_comieq_ss:
9460   case Intrinsic::x86_sse_comilt_ss:
9461   case Intrinsic::x86_sse_comile_ss:
9462   case Intrinsic::x86_sse_comigt_ss:
9463   case Intrinsic::x86_sse_comige_ss:
9464   case Intrinsic::x86_sse_comineq_ss:
9465   case Intrinsic::x86_sse_ucomieq_ss:
9466   case Intrinsic::x86_sse_ucomilt_ss:
9467   case Intrinsic::x86_sse_ucomile_ss:
9468   case Intrinsic::x86_sse_ucomigt_ss:
9469   case Intrinsic::x86_sse_ucomige_ss:
9470   case Intrinsic::x86_sse_ucomineq_ss:
9471   case Intrinsic::x86_sse2_comieq_sd:
9472   case Intrinsic::x86_sse2_comilt_sd:
9473   case Intrinsic::x86_sse2_comile_sd:
9474   case Intrinsic::x86_sse2_comigt_sd:
9475   case Intrinsic::x86_sse2_comige_sd:
9476   case Intrinsic::x86_sse2_comineq_sd:
9477   case Intrinsic::x86_sse2_ucomieq_sd:
9478   case Intrinsic::x86_sse2_ucomilt_sd:
9479   case Intrinsic::x86_sse2_ucomile_sd:
9480   case Intrinsic::x86_sse2_ucomigt_sd:
9481   case Intrinsic::x86_sse2_ucomige_sd:
9482   case Intrinsic::x86_sse2_ucomineq_sd: {
9483     unsigned Opc = 0;
9484     ISD::CondCode CC = ISD::SETCC_INVALID;
9485     switch (IntNo) {
9486     default: break;
9487     case Intrinsic::x86_sse_comieq_ss:
9488     case Intrinsic::x86_sse2_comieq_sd:
9489       Opc = X86ISD::COMI;
9490       CC = ISD::SETEQ;
9491       break;
9492     case Intrinsic::x86_sse_comilt_ss:
9493     case Intrinsic::x86_sse2_comilt_sd:
9494       Opc = X86ISD::COMI;
9495       CC = ISD::SETLT;
9496       break;
9497     case Intrinsic::x86_sse_comile_ss:
9498     case Intrinsic::x86_sse2_comile_sd:
9499       Opc = X86ISD::COMI;
9500       CC = ISD::SETLE;
9501       break;
9502     case Intrinsic::x86_sse_comigt_ss:
9503     case Intrinsic::x86_sse2_comigt_sd:
9504       Opc = X86ISD::COMI;
9505       CC = ISD::SETGT;
9506       break;
9507     case Intrinsic::x86_sse_comige_ss:
9508     case Intrinsic::x86_sse2_comige_sd:
9509       Opc = X86ISD::COMI;
9510       CC = ISD::SETGE;
9511       break;
9512     case Intrinsic::x86_sse_comineq_ss:
9513     case Intrinsic::x86_sse2_comineq_sd:
9514       Opc = X86ISD::COMI;
9515       CC = ISD::SETNE;
9516       break;
9517     case Intrinsic::x86_sse_ucomieq_ss:
9518     case Intrinsic::x86_sse2_ucomieq_sd:
9519       Opc = X86ISD::UCOMI;
9520       CC = ISD::SETEQ;
9521       break;
9522     case Intrinsic::x86_sse_ucomilt_ss:
9523     case Intrinsic::x86_sse2_ucomilt_sd:
9524       Opc = X86ISD::UCOMI;
9525       CC = ISD::SETLT;
9526       break;
9527     case Intrinsic::x86_sse_ucomile_ss:
9528     case Intrinsic::x86_sse2_ucomile_sd:
9529       Opc = X86ISD::UCOMI;
9530       CC = ISD::SETLE;
9531       break;
9532     case Intrinsic::x86_sse_ucomigt_ss:
9533     case Intrinsic::x86_sse2_ucomigt_sd:
9534       Opc = X86ISD::UCOMI;
9535       CC = ISD::SETGT;
9536       break;
9537     case Intrinsic::x86_sse_ucomige_ss:
9538     case Intrinsic::x86_sse2_ucomige_sd:
9539       Opc = X86ISD::UCOMI;
9540       CC = ISD::SETGE;
9541       break;
9542     case Intrinsic::x86_sse_ucomineq_ss:
9543     case Intrinsic::x86_sse2_ucomineq_sd:
9544       Opc = X86ISD::UCOMI;
9545       CC = ISD::SETNE;
9546       break;
9547     }
9548
9549     SDValue LHS = Op.getOperand(1);
9550     SDValue RHS = Op.getOperand(2);
9551     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
9552     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
9553     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
9554     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9555                                 DAG.getConstant(X86CC, MVT::i8), Cond);
9556     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9557   }
9558   // Arithmetic intrinsics.
9559   case Intrinsic::x86_sse3_hadd_ps:
9560   case Intrinsic::x86_sse3_hadd_pd:
9561   case Intrinsic::x86_avx_hadd_ps_256:
9562   case Intrinsic::x86_avx_hadd_pd_256:
9563     return DAG.getNode(X86ISD::FHADD, dl, Op.getValueType(),
9564                        Op.getOperand(1), Op.getOperand(2));
9565   case Intrinsic::x86_sse3_hsub_ps:
9566   case Intrinsic::x86_sse3_hsub_pd:
9567   case Intrinsic::x86_avx_hsub_ps_256:
9568   case Intrinsic::x86_avx_hsub_pd_256:
9569     return DAG.getNode(X86ISD::FHSUB, dl, Op.getValueType(),
9570                        Op.getOperand(1), Op.getOperand(2));
9571   case Intrinsic::x86_avx2_psllv_d:
9572   case Intrinsic::x86_avx2_psllv_q:
9573   case Intrinsic::x86_avx2_psllv_d_256:
9574   case Intrinsic::x86_avx2_psllv_q_256:
9575     return DAG.getNode(ISD::SHL, dl, Op.getValueType(),
9576                       Op.getOperand(1), Op.getOperand(2));
9577   case Intrinsic::x86_avx2_psrlv_d:
9578   case Intrinsic::x86_avx2_psrlv_q:
9579   case Intrinsic::x86_avx2_psrlv_d_256:
9580   case Intrinsic::x86_avx2_psrlv_q_256:
9581     return DAG.getNode(ISD::SRL, dl, Op.getValueType(),
9582                       Op.getOperand(1), Op.getOperand(2));
9583   case Intrinsic::x86_avx2_psrav_d:
9584   case Intrinsic::x86_avx2_psrav_d_256:
9585     return DAG.getNode(ISD::SRA, dl, Op.getValueType(),
9586                       Op.getOperand(1), Op.getOperand(2));
9587
9588   // ptest and testp intrinsics. The intrinsic these come from are designed to
9589   // return an integer value, not just an instruction so lower it to the ptest
9590   // or testp pattern and a setcc for the result.
9591   case Intrinsic::x86_sse41_ptestz:
9592   case Intrinsic::x86_sse41_ptestc:
9593   case Intrinsic::x86_sse41_ptestnzc:
9594   case Intrinsic::x86_avx_ptestz_256:
9595   case Intrinsic::x86_avx_ptestc_256:
9596   case Intrinsic::x86_avx_ptestnzc_256:
9597   case Intrinsic::x86_avx_vtestz_ps:
9598   case Intrinsic::x86_avx_vtestc_ps:
9599   case Intrinsic::x86_avx_vtestnzc_ps:
9600   case Intrinsic::x86_avx_vtestz_pd:
9601   case Intrinsic::x86_avx_vtestc_pd:
9602   case Intrinsic::x86_avx_vtestnzc_pd:
9603   case Intrinsic::x86_avx_vtestz_ps_256:
9604   case Intrinsic::x86_avx_vtestc_ps_256:
9605   case Intrinsic::x86_avx_vtestnzc_ps_256:
9606   case Intrinsic::x86_avx_vtestz_pd_256:
9607   case Intrinsic::x86_avx_vtestc_pd_256:
9608   case Intrinsic::x86_avx_vtestnzc_pd_256: {
9609     bool IsTestPacked = false;
9610     unsigned X86CC = 0;
9611     switch (IntNo) {
9612     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
9613     case Intrinsic::x86_avx_vtestz_ps:
9614     case Intrinsic::x86_avx_vtestz_pd:
9615     case Intrinsic::x86_avx_vtestz_ps_256:
9616     case Intrinsic::x86_avx_vtestz_pd_256:
9617       IsTestPacked = true; // Fallthrough
9618     case Intrinsic::x86_sse41_ptestz:
9619     case Intrinsic::x86_avx_ptestz_256:
9620       // ZF = 1
9621       X86CC = X86::COND_E;
9622       break;
9623     case Intrinsic::x86_avx_vtestc_ps:
9624     case Intrinsic::x86_avx_vtestc_pd:
9625     case Intrinsic::x86_avx_vtestc_ps_256:
9626     case Intrinsic::x86_avx_vtestc_pd_256:
9627       IsTestPacked = true; // Fallthrough
9628     case Intrinsic::x86_sse41_ptestc:
9629     case Intrinsic::x86_avx_ptestc_256:
9630       // CF = 1
9631       X86CC = X86::COND_B;
9632       break;
9633     case Intrinsic::x86_avx_vtestnzc_ps:
9634     case Intrinsic::x86_avx_vtestnzc_pd:
9635     case Intrinsic::x86_avx_vtestnzc_ps_256:
9636     case Intrinsic::x86_avx_vtestnzc_pd_256:
9637       IsTestPacked = true; // Fallthrough
9638     case Intrinsic::x86_sse41_ptestnzc:
9639     case Intrinsic::x86_avx_ptestnzc_256:
9640       // ZF and CF = 0
9641       X86CC = X86::COND_A;
9642       break;
9643     }
9644
9645     SDValue LHS = Op.getOperand(1);
9646     SDValue RHS = Op.getOperand(2);
9647     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
9648     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
9649     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
9650     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
9651     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9652   }
9653
9654   // Fix vector shift instructions where the last operand is a non-immediate
9655   // i32 value.
9656   case Intrinsic::x86_avx2_pslli_w:
9657   case Intrinsic::x86_avx2_pslli_d:
9658   case Intrinsic::x86_avx2_pslli_q:
9659   case Intrinsic::x86_avx2_psrli_w:
9660   case Intrinsic::x86_avx2_psrli_d:
9661   case Intrinsic::x86_avx2_psrli_q:
9662   case Intrinsic::x86_avx2_psrai_w:
9663   case Intrinsic::x86_avx2_psrai_d:
9664   case Intrinsic::x86_sse2_pslli_w:
9665   case Intrinsic::x86_sse2_pslli_d:
9666   case Intrinsic::x86_sse2_pslli_q:
9667   case Intrinsic::x86_sse2_psrli_w:
9668   case Intrinsic::x86_sse2_psrli_d:
9669   case Intrinsic::x86_sse2_psrli_q:
9670   case Intrinsic::x86_sse2_psrai_w:
9671   case Intrinsic::x86_sse2_psrai_d:
9672   case Intrinsic::x86_mmx_pslli_w:
9673   case Intrinsic::x86_mmx_pslli_d:
9674   case Intrinsic::x86_mmx_pslli_q:
9675   case Intrinsic::x86_mmx_psrli_w:
9676   case Intrinsic::x86_mmx_psrli_d:
9677   case Intrinsic::x86_mmx_psrli_q:
9678   case Intrinsic::x86_mmx_psrai_w:
9679   case Intrinsic::x86_mmx_psrai_d: {
9680     SDValue ShAmt = Op.getOperand(2);
9681     if (isa<ConstantSDNode>(ShAmt))
9682       return SDValue();
9683
9684     unsigned NewIntNo = 0;
9685     EVT ShAmtVT = MVT::v4i32;
9686     switch (IntNo) {
9687     case Intrinsic::x86_sse2_pslli_w:
9688       NewIntNo = Intrinsic::x86_sse2_psll_w;
9689       break;
9690     case Intrinsic::x86_sse2_pslli_d:
9691       NewIntNo = Intrinsic::x86_sse2_psll_d;
9692       break;
9693     case Intrinsic::x86_sse2_pslli_q:
9694       NewIntNo = Intrinsic::x86_sse2_psll_q;
9695       break;
9696     case Intrinsic::x86_sse2_psrli_w:
9697       NewIntNo = Intrinsic::x86_sse2_psrl_w;
9698       break;
9699     case Intrinsic::x86_sse2_psrli_d:
9700       NewIntNo = Intrinsic::x86_sse2_psrl_d;
9701       break;
9702     case Intrinsic::x86_sse2_psrli_q:
9703       NewIntNo = Intrinsic::x86_sse2_psrl_q;
9704       break;
9705     case Intrinsic::x86_sse2_psrai_w:
9706       NewIntNo = Intrinsic::x86_sse2_psra_w;
9707       break;
9708     case Intrinsic::x86_sse2_psrai_d:
9709       NewIntNo = Intrinsic::x86_sse2_psra_d;
9710       break;
9711     case Intrinsic::x86_avx2_pslli_w:
9712       NewIntNo = Intrinsic::x86_avx2_psll_w;
9713       break;
9714     case Intrinsic::x86_avx2_pslli_d:
9715       NewIntNo = Intrinsic::x86_avx2_psll_d;
9716       break;
9717     case Intrinsic::x86_avx2_pslli_q:
9718       NewIntNo = Intrinsic::x86_avx2_psll_q;
9719       break;
9720     case Intrinsic::x86_avx2_psrli_w:
9721       NewIntNo = Intrinsic::x86_avx2_psrl_w;
9722       break;
9723     case Intrinsic::x86_avx2_psrli_d:
9724       NewIntNo = Intrinsic::x86_avx2_psrl_d;
9725       break;
9726     case Intrinsic::x86_avx2_psrli_q:
9727       NewIntNo = Intrinsic::x86_avx2_psrl_q;
9728       break;
9729     case Intrinsic::x86_avx2_psrai_w:
9730       NewIntNo = Intrinsic::x86_avx2_psra_w;
9731       break;
9732     case Intrinsic::x86_avx2_psrai_d:
9733       NewIntNo = Intrinsic::x86_avx2_psra_d;
9734       break;
9735     default: {
9736       ShAmtVT = MVT::v2i32;
9737       switch (IntNo) {
9738       case Intrinsic::x86_mmx_pslli_w:
9739         NewIntNo = Intrinsic::x86_mmx_psll_w;
9740         break;
9741       case Intrinsic::x86_mmx_pslli_d:
9742         NewIntNo = Intrinsic::x86_mmx_psll_d;
9743         break;
9744       case Intrinsic::x86_mmx_pslli_q:
9745         NewIntNo = Intrinsic::x86_mmx_psll_q;
9746         break;
9747       case Intrinsic::x86_mmx_psrli_w:
9748         NewIntNo = Intrinsic::x86_mmx_psrl_w;
9749         break;
9750       case Intrinsic::x86_mmx_psrli_d:
9751         NewIntNo = Intrinsic::x86_mmx_psrl_d;
9752         break;
9753       case Intrinsic::x86_mmx_psrli_q:
9754         NewIntNo = Intrinsic::x86_mmx_psrl_q;
9755         break;
9756       case Intrinsic::x86_mmx_psrai_w:
9757         NewIntNo = Intrinsic::x86_mmx_psra_w;
9758         break;
9759       case Intrinsic::x86_mmx_psrai_d:
9760         NewIntNo = Intrinsic::x86_mmx_psra_d;
9761         break;
9762       default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9763       }
9764       break;
9765     }
9766     }
9767
9768     // The vector shift intrinsics with scalars uses 32b shift amounts but
9769     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
9770     // to be zero.
9771     SDValue ShOps[4];
9772     ShOps[0] = ShAmt;
9773     ShOps[1] = DAG.getConstant(0, MVT::i32);
9774     if (ShAmtVT == MVT::v4i32) {
9775       ShOps[2] = DAG.getUNDEF(MVT::i32);
9776       ShOps[3] = DAG.getUNDEF(MVT::i32);
9777       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
9778     } else {
9779       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
9780 // FIXME this must be lowered to get rid of the invalid type.
9781     }
9782
9783     EVT VT = Op.getValueType();
9784     ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
9785     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9786                        DAG.getConstant(NewIntNo, MVT::i32),
9787                        Op.getOperand(1), ShAmt);
9788   }
9789   }
9790 }
9791
9792 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
9793                                            SelectionDAG &DAG) const {
9794   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9795   MFI->setReturnAddressIsTaken(true);
9796
9797   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9798   DebugLoc dl = Op.getDebugLoc();
9799
9800   if (Depth > 0) {
9801     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
9802     SDValue Offset =
9803       DAG.getConstant(TD->getPointerSize(),
9804                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
9805     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9806                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
9807                                    FrameAddr, Offset),
9808                        MachinePointerInfo(), false, false, false, 0);
9809   }
9810
9811   // Just load the return address.
9812   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
9813   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9814                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
9815 }
9816
9817 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
9818   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9819   MFI->setFrameAddressIsTaken(true);
9820
9821   EVT VT = Op.getValueType();
9822   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
9823   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9824   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
9825   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
9826   while (Depth--)
9827     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
9828                             MachinePointerInfo(),
9829                             false, false, false, 0);
9830   return FrameAddr;
9831 }
9832
9833 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
9834                                                      SelectionDAG &DAG) const {
9835   return DAG.getIntPtrConstant(2*TD->getPointerSize());
9836 }
9837
9838 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
9839   MachineFunction &MF = DAG.getMachineFunction();
9840   SDValue Chain     = Op.getOperand(0);
9841   SDValue Offset    = Op.getOperand(1);
9842   SDValue Handler   = Op.getOperand(2);
9843   DebugLoc dl       = Op.getDebugLoc();
9844
9845   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
9846                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
9847                                      getPointerTy());
9848   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
9849
9850   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
9851                                   DAG.getIntPtrConstant(TD->getPointerSize()));
9852   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
9853   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
9854                        false, false, 0);
9855   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
9856   MF.getRegInfo().addLiveOut(StoreAddrReg);
9857
9858   return DAG.getNode(X86ISD::EH_RETURN, dl,
9859                      MVT::Other,
9860                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
9861 }
9862
9863 SDValue X86TargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
9864                                                   SelectionDAG &DAG) const {
9865   return Op.getOperand(0);
9866 }
9867
9868 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
9869                                                 SelectionDAG &DAG) const {
9870   SDValue Root = Op.getOperand(0);
9871   SDValue Trmp = Op.getOperand(1); // trampoline
9872   SDValue FPtr = Op.getOperand(2); // nested function
9873   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
9874   DebugLoc dl  = Op.getDebugLoc();
9875
9876   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9877
9878   if (Subtarget->is64Bit()) {
9879     SDValue OutChains[6];
9880
9881     // Large code-model.
9882     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
9883     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
9884
9885     const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10);
9886     const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11);
9887
9888     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
9889
9890     // Load the pointer to the nested function into R11.
9891     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
9892     SDValue Addr = Trmp;
9893     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9894                                 Addr, MachinePointerInfo(TrmpAddr),
9895                                 false, false, 0);
9896
9897     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9898                        DAG.getConstant(2, MVT::i64));
9899     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
9900                                 MachinePointerInfo(TrmpAddr, 2),
9901                                 false, false, 2);
9902
9903     // Load the 'nest' parameter value into R10.
9904     // R10 is specified in X86CallingConv.td
9905     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
9906     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9907                        DAG.getConstant(10, MVT::i64));
9908     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9909                                 Addr, MachinePointerInfo(TrmpAddr, 10),
9910                                 false, false, 0);
9911
9912     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9913                        DAG.getConstant(12, MVT::i64));
9914     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
9915                                 MachinePointerInfo(TrmpAddr, 12),
9916                                 false, false, 2);
9917
9918     // Jump to the nested function.
9919     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
9920     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9921                        DAG.getConstant(20, MVT::i64));
9922     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9923                                 Addr, MachinePointerInfo(TrmpAddr, 20),
9924                                 false, false, 0);
9925
9926     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
9927     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9928                        DAG.getConstant(22, MVT::i64));
9929     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
9930                                 MachinePointerInfo(TrmpAddr, 22),
9931                                 false, false, 0);
9932
9933     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
9934   } else {
9935     const Function *Func =
9936       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
9937     CallingConv::ID CC = Func->getCallingConv();
9938     unsigned NestReg;
9939
9940     switch (CC) {
9941     default:
9942       llvm_unreachable("Unsupported calling convention");
9943     case CallingConv::C:
9944     case CallingConv::X86_StdCall: {
9945       // Pass 'nest' parameter in ECX.
9946       // Must be kept in sync with X86CallingConv.td
9947       NestReg = X86::ECX;
9948
9949       // Check that ECX wasn't needed by an 'inreg' parameter.
9950       FunctionType *FTy = Func->getFunctionType();
9951       const AttrListPtr &Attrs = Func->getAttributes();
9952
9953       if (!Attrs.isEmpty() && !Func->isVarArg()) {
9954         unsigned InRegCount = 0;
9955         unsigned Idx = 1;
9956
9957         for (FunctionType::param_iterator I = FTy->param_begin(),
9958              E = FTy->param_end(); I != E; ++I, ++Idx)
9959           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
9960             // FIXME: should only count parameters that are lowered to integers.
9961             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
9962
9963         if (InRegCount > 2) {
9964           report_fatal_error("Nest register in use - reduce number of inreg"
9965                              " parameters!");
9966         }
9967       }
9968       break;
9969     }
9970     case CallingConv::X86_FastCall:
9971     case CallingConv::X86_ThisCall:
9972     case CallingConv::Fast:
9973       // Pass 'nest' parameter in EAX.
9974       // Must be kept in sync with X86CallingConv.td
9975       NestReg = X86::EAX;
9976       break;
9977     }
9978
9979     SDValue OutChains[4];
9980     SDValue Addr, Disp;
9981
9982     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9983                        DAG.getConstant(10, MVT::i32));
9984     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
9985
9986     // This is storing the opcode for MOV32ri.
9987     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
9988     const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg);
9989     OutChains[0] = DAG.getStore(Root, dl,
9990                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
9991                                 Trmp, MachinePointerInfo(TrmpAddr),
9992                                 false, false, 0);
9993
9994     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9995                        DAG.getConstant(1, MVT::i32));
9996     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
9997                                 MachinePointerInfo(TrmpAddr, 1),
9998                                 false, false, 1);
9999
10000     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
10001     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10002                        DAG.getConstant(5, MVT::i32));
10003     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
10004                                 MachinePointerInfo(TrmpAddr, 5),
10005                                 false, false, 1);
10006
10007     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10008                        DAG.getConstant(6, MVT::i32));
10009     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
10010                                 MachinePointerInfo(TrmpAddr, 6),
10011                                 false, false, 1);
10012
10013     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
10014   }
10015 }
10016
10017 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
10018                                             SelectionDAG &DAG) const {
10019   /*
10020    The rounding mode is in bits 11:10 of FPSR, and has the following
10021    settings:
10022      00 Round to nearest
10023      01 Round to -inf
10024      10 Round to +inf
10025      11 Round to 0
10026
10027   FLT_ROUNDS, on the other hand, expects the following:
10028     -1 Undefined
10029      0 Round to 0
10030      1 Round to nearest
10031      2 Round to +inf
10032      3 Round to -inf
10033
10034   To perform the conversion, we do:
10035     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
10036   */
10037
10038   MachineFunction &MF = DAG.getMachineFunction();
10039   const TargetMachine &TM = MF.getTarget();
10040   const TargetFrameLowering &TFI = *TM.getFrameLowering();
10041   unsigned StackAlignment = TFI.getStackAlignment();
10042   EVT VT = Op.getValueType();
10043   DebugLoc DL = Op.getDebugLoc();
10044
10045   // Save FP Control Word to stack slot
10046   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
10047   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10048
10049
10050   MachineMemOperand *MMO =
10051    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10052                            MachineMemOperand::MOStore, 2, 2);
10053
10054   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
10055   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
10056                                           DAG.getVTList(MVT::Other),
10057                                           Ops, 2, MVT::i16, MMO);
10058
10059   // Load FP Control Word from stack slot
10060   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
10061                             MachinePointerInfo(), false, false, false, 0);
10062
10063   // Transform as necessary
10064   SDValue CWD1 =
10065     DAG.getNode(ISD::SRL, DL, MVT::i16,
10066                 DAG.getNode(ISD::AND, DL, MVT::i16,
10067                             CWD, DAG.getConstant(0x800, MVT::i16)),
10068                 DAG.getConstant(11, MVT::i8));
10069   SDValue CWD2 =
10070     DAG.getNode(ISD::SRL, DL, MVT::i16,
10071                 DAG.getNode(ISD::AND, DL, MVT::i16,
10072                             CWD, DAG.getConstant(0x400, MVT::i16)),
10073                 DAG.getConstant(9, MVT::i8));
10074
10075   SDValue RetVal =
10076     DAG.getNode(ISD::AND, DL, MVT::i16,
10077                 DAG.getNode(ISD::ADD, DL, MVT::i16,
10078                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
10079                             DAG.getConstant(1, MVT::i16)),
10080                 DAG.getConstant(3, MVT::i16));
10081
10082
10083   return DAG.getNode((VT.getSizeInBits() < 16 ?
10084                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
10085 }
10086
10087 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
10088   EVT VT = Op.getValueType();
10089   EVT OpVT = VT;
10090   unsigned NumBits = VT.getSizeInBits();
10091   DebugLoc dl = Op.getDebugLoc();
10092
10093   Op = Op.getOperand(0);
10094   if (VT == MVT::i8) {
10095     // Zero extend to i32 since there is not an i8 bsr.
10096     OpVT = MVT::i32;
10097     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10098   }
10099
10100   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
10101   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10102   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10103
10104   // If src is zero (i.e. bsr sets ZF), returns NumBits.
10105   SDValue Ops[] = {
10106     Op,
10107     DAG.getConstant(NumBits+NumBits-1, OpVT),
10108     DAG.getConstant(X86::COND_E, MVT::i8),
10109     Op.getValue(1)
10110   };
10111   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
10112
10113   // Finally xor with NumBits-1.
10114   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10115
10116   if (VT == MVT::i8)
10117     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10118   return Op;
10119 }
10120
10121 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
10122   EVT VT = Op.getValueType();
10123   EVT OpVT = VT;
10124   unsigned NumBits = VT.getSizeInBits();
10125   DebugLoc dl = Op.getDebugLoc();
10126
10127   Op = Op.getOperand(0);
10128   if (VT == MVT::i8) {
10129     OpVT = MVT::i32;
10130     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10131   }
10132
10133   // Issue a bsf (scan bits forward) which also sets EFLAGS.
10134   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10135   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
10136
10137   // If src is zero (i.e. bsf sets ZF), returns NumBits.
10138   SDValue Ops[] = {
10139     Op,
10140     DAG.getConstant(NumBits, OpVT),
10141     DAG.getConstant(X86::COND_E, MVT::i8),
10142     Op.getValue(1)
10143   };
10144   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
10145
10146   if (VT == MVT::i8)
10147     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10148   return Op;
10149 }
10150
10151 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
10152 // ones, and then concatenate the result back.
10153 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
10154   EVT VT = Op.getValueType();
10155
10156   assert(VT.getSizeInBits() == 256 && VT.isInteger() &&
10157          "Unsupported value type for operation");
10158
10159   int NumElems = VT.getVectorNumElements();
10160   DebugLoc dl = Op.getDebugLoc();
10161   SDValue Idx0 = DAG.getConstant(0, MVT::i32);
10162   SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
10163
10164   // Extract the LHS vectors
10165   SDValue LHS = Op.getOperand(0);
10166   SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
10167   SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
10168
10169   // Extract the RHS vectors
10170   SDValue RHS = Op.getOperand(1);
10171   SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl);
10172   SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl);
10173
10174   MVT EltVT = VT.getVectorElementType().getSimpleVT();
10175   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10176
10177   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10178                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
10179                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
10180 }
10181
10182 SDValue X86TargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const {
10183   assert(Op.getValueType().getSizeInBits() == 256 &&
10184          Op.getValueType().isInteger() &&
10185          "Only handle AVX 256-bit vector integer operation");
10186   return Lower256IntArith(Op, DAG);
10187 }
10188
10189 SDValue X86TargetLowering::LowerSUB(SDValue Op, SelectionDAG &DAG) const {
10190   assert(Op.getValueType().getSizeInBits() == 256 &&
10191          Op.getValueType().isInteger() &&
10192          "Only handle AVX 256-bit vector integer operation");
10193   return Lower256IntArith(Op, DAG);
10194 }
10195
10196 SDValue X86TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10197   EVT VT = Op.getValueType();
10198
10199   // Decompose 256-bit ops into smaller 128-bit ops.
10200   if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2())
10201     return Lower256IntArith(Op, DAG);
10202
10203   DebugLoc dl = Op.getDebugLoc();
10204
10205   SDValue A = Op.getOperand(0);
10206   SDValue B = Op.getOperand(1);
10207
10208   if (VT == MVT::v4i64) {
10209     assert(Subtarget->hasAVX2() && "Lowering v4i64 multiply requires AVX2");
10210
10211     //  ulong2 Ahi = __builtin_ia32_psrlqi256( a, 32);
10212     //  ulong2 Bhi = __builtin_ia32_psrlqi256( b, 32);
10213     //  ulong2 AloBlo = __builtin_ia32_pmuludq256( a, b );
10214     //  ulong2 AloBhi = __builtin_ia32_pmuludq256( a, Bhi );
10215     //  ulong2 AhiBlo = __builtin_ia32_pmuludq256( Ahi, b );
10216     //
10217     //  AloBhi = __builtin_ia32_psllqi256( AloBhi, 32 );
10218     //  AhiBlo = __builtin_ia32_psllqi256( AhiBlo, 32 );
10219     //  return AloBlo + AloBhi + AhiBlo;
10220
10221     SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10222                          DAG.getConstant(Intrinsic::x86_avx2_psrli_q, MVT::i32),
10223                          A, DAG.getConstant(32, MVT::i32));
10224     SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10225                          DAG.getConstant(Intrinsic::x86_avx2_psrli_q, MVT::i32),
10226                          B, DAG.getConstant(32, MVT::i32));
10227     SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10228                          DAG.getConstant(Intrinsic::x86_avx2_pmulu_dq, MVT::i32),
10229                          A, B);
10230     SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10231                          DAG.getConstant(Intrinsic::x86_avx2_pmulu_dq, MVT::i32),
10232                          A, Bhi);
10233     SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10234                          DAG.getConstant(Intrinsic::x86_avx2_pmulu_dq, MVT::i32),
10235                          Ahi, B);
10236     AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10237                          DAG.getConstant(Intrinsic::x86_avx2_pslli_q, MVT::i32),
10238                          AloBhi, DAG.getConstant(32, MVT::i32));
10239     AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10240                          DAG.getConstant(Intrinsic::x86_avx2_pslli_q, MVT::i32),
10241                          AhiBlo, DAG.getConstant(32, MVT::i32));
10242     SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
10243     Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10244     return Res;
10245   }
10246
10247   assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
10248
10249   //  ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
10250   //  ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
10251   //  ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
10252   //  ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
10253   //  ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
10254   //
10255   //  AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
10256   //  AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
10257   //  return AloBlo + AloBhi + AhiBlo;
10258
10259   SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10260                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
10261                        A, DAG.getConstant(32, MVT::i32));
10262   SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10263                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
10264                        B, DAG.getConstant(32, MVT::i32));
10265   SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10266                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
10267                        A, B);
10268   SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10269                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
10270                        A, Bhi);
10271   SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10272                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
10273                        Ahi, B);
10274   AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10275                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
10276                        AloBhi, DAG.getConstant(32, MVT::i32));
10277   AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10278                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
10279                        AhiBlo, DAG.getConstant(32, MVT::i32));
10280   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
10281   Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10282   return Res;
10283 }
10284
10285 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
10286
10287   EVT VT = Op.getValueType();
10288   DebugLoc dl = Op.getDebugLoc();
10289   SDValue R = Op.getOperand(0);
10290   SDValue Amt = Op.getOperand(1);
10291   LLVMContext *Context = DAG.getContext();
10292
10293   if (!Subtarget->hasXMMInt())
10294     return SDValue();
10295
10296   // Optimize shl/srl/sra with constant shift amount.
10297   if (isSplatVector(Amt.getNode())) {
10298     SDValue SclrAmt = Amt->getOperand(0);
10299     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
10300       uint64_t ShiftAmt = C->getZExtValue();
10301
10302       if (VT == MVT::v16i8 && Op.getOpcode() == ISD::SHL) {
10303         // Make a large shift.
10304         SDValue SHL =
10305           DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10306                       DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10307                       R, DAG.getConstant(ShiftAmt, MVT::i32));
10308         // Zero out the rightmost bits.
10309         SmallVector<SDValue, 16> V(16, DAG.getConstant(uint8_t(-1U << ShiftAmt),
10310                                                        MVT::i8));
10311         return DAG.getNode(ISD::AND, dl, VT, SHL,
10312                            DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10313       }
10314
10315       if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SHL)
10316        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10317                      DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
10318                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10319
10320       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SHL)
10321        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10322                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
10323                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10324
10325       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SHL)
10326        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10327                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10328                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10329
10330       if (VT == MVT::v16i8 && Op.getOpcode() == ISD::SRL) {
10331         // Make a large shift.
10332         SDValue SRL =
10333           DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10334                       DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
10335                       R, DAG.getConstant(ShiftAmt, MVT::i32));
10336         // Zero out the leftmost bits.
10337         SmallVector<SDValue, 16> V(16, DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10338                                                        MVT::i8));
10339         return DAG.getNode(ISD::AND, dl, VT, SRL,
10340                            DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10341       }
10342
10343       if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SRL)
10344        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10345                      DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
10346                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10347
10348       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRL)
10349        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10350                      DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
10351                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10352
10353       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRL)
10354        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10355                      DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
10356                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10357
10358       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRA)
10359        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10360                      DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
10361                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10362
10363       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRA)
10364        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10365                      DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
10366                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10367
10368       if (VT == MVT::v16i8 && Op.getOpcode() == ISD::SRA) {
10369         if (ShiftAmt == 7) {
10370           // R s>> 7  ===  R s< 0
10371           SDValue Zeros = getZeroVector(VT, true /* HasXMMInt */, DAG, dl);
10372           return DAG.getNode(X86ISD::PCMPGTB, dl, VT, Zeros, R);
10373         }
10374
10375         // R s>> a === ((R u>> a) ^ m) - m
10376         SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10377         SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
10378                                                        MVT::i8));
10379         SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
10380         Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10381         Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10382         return Res;
10383       }
10384
10385       if (Subtarget->hasAVX2() && VT == MVT::v32i8) {
10386         if (Op.getOpcode() == ISD::SHL) {
10387           // Make a large shift.
10388           SDValue SHL =
10389             DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10390                         DAG.getConstant(Intrinsic::x86_avx2_pslli_w, MVT::i32),
10391                         R, DAG.getConstant(ShiftAmt, MVT::i32));
10392           // Zero out the rightmost bits.
10393           SmallVector<SDValue, 32> V(32, DAG.getConstant(uint8_t(-1U << ShiftAmt),
10394                                                          MVT::i8));
10395           return DAG.getNode(ISD::AND, dl, VT, SHL,
10396                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10397         }
10398         if (Op.getOpcode() == ISD::SRL) {
10399           // Make a large shift.
10400           SDValue SRL =
10401             DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10402                         DAG.getConstant(Intrinsic::x86_avx2_psrli_w, MVT::i32),
10403                         R, DAG.getConstant(ShiftAmt, MVT::i32));
10404           // Zero out the leftmost bits.
10405           SmallVector<SDValue, 32> V(32, DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10406                                                          MVT::i8));
10407           return DAG.getNode(ISD::AND, dl, VT, SRL,
10408                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10409         }
10410         if (Op.getOpcode() == ISD::SRA) {
10411           if (ShiftAmt == 7) {
10412             // R s>> 7  ===  R s< 0
10413             SDValue Zeros = getZeroVector(VT, true /* HasXMMInt */, DAG, dl);
10414             return DAG.getNode(X86ISD::PCMPGTB, dl, VT, Zeros, R);
10415           }
10416
10417           // R s>> a === ((R u>> a) ^ m) - m
10418           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10419           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
10420                                                          MVT::i8));
10421           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
10422           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10423           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10424           return Res;
10425         }
10426       }
10427     }
10428   }
10429
10430   // Lower SHL with variable shift amount.
10431   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
10432     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10433                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
10434                      Op.getOperand(1), DAG.getConstant(23, MVT::i32));
10435
10436     ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
10437
10438     std::vector<Constant*> CV(4, CI);
10439     Constant *C = ConstantVector::get(CV);
10440     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10441     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10442                                  MachinePointerInfo::getConstantPool(),
10443                                  false, false, false, 16);
10444
10445     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
10446     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
10447     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
10448     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
10449   }
10450   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
10451     // a = a << 5;
10452     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10453                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10454                      Op.getOperand(1), DAG.getConstant(5, MVT::i32));
10455
10456     ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
10457     ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
10458
10459     std::vector<Constant*> CVM1(16, CM1);
10460     std::vector<Constant*> CVM2(16, CM2);
10461     Constant *C = ConstantVector::get(CVM1);
10462     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10463     SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10464                             MachinePointerInfo::getConstantPool(),
10465                             false, false, false, 16);
10466
10467     // r = pblendv(r, psllw(r & (char16)15, 4), a);
10468     M = DAG.getNode(ISD::AND, dl, VT, R, M);
10469     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10470                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
10471                     DAG.getConstant(4, MVT::i32));
10472     R = DAG.getNode(ISD::VSELECT, dl, VT, Op, R, M);
10473     // a += a
10474     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10475
10476     C = ConstantVector::get(CVM2);
10477     CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10478     M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10479                     MachinePointerInfo::getConstantPool(),
10480                     false, false, false, 16);
10481
10482     // r = pblendv(r, psllw(r & (char16)63, 2), a);
10483     M = DAG.getNode(ISD::AND, dl, VT, R, M);
10484     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10485                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
10486                     DAG.getConstant(2, MVT::i32));
10487     R = DAG.getNode(ISD::VSELECT, dl, VT, Op, R, M);
10488     // a += a
10489     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10490
10491     // return pblendv(r, r+r, a);
10492     R = DAG.getNode(ISD::VSELECT, dl, VT, Op,
10493                     R, DAG.getNode(ISD::ADD, dl, VT, R, R));
10494     return R;
10495   }
10496
10497   // Decompose 256-bit shifts into smaller 128-bit shifts.
10498   if (VT.getSizeInBits() == 256) {
10499     int NumElems = VT.getVectorNumElements();
10500     MVT EltVT = VT.getVectorElementType().getSimpleVT();
10501     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10502
10503     // Extract the two vectors
10504     SDValue V1 = Extract128BitVector(R, DAG.getConstant(0, MVT::i32), DAG, dl);
10505     SDValue V2 = Extract128BitVector(R, DAG.getConstant(NumElems/2, MVT::i32),
10506                                      DAG, dl);
10507
10508     // Recreate the shift amount vectors
10509     SDValue Amt1, Amt2;
10510     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
10511       // Constant shift amount
10512       SmallVector<SDValue, 4> Amt1Csts;
10513       SmallVector<SDValue, 4> Amt2Csts;
10514       for (int i = 0; i < NumElems/2; ++i)
10515         Amt1Csts.push_back(Amt->getOperand(i));
10516       for (int i = NumElems/2; i < NumElems; ++i)
10517         Amt2Csts.push_back(Amt->getOperand(i));
10518
10519       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10520                                  &Amt1Csts[0], NumElems/2);
10521       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10522                                  &Amt2Csts[0], NumElems/2);
10523     } else {
10524       // Variable shift amount
10525       Amt1 = Extract128BitVector(Amt, DAG.getConstant(0, MVT::i32), DAG, dl);
10526       Amt2 = Extract128BitVector(Amt, DAG.getConstant(NumElems/2, MVT::i32),
10527                                  DAG, dl);
10528     }
10529
10530     // Issue new vector shifts for the smaller types
10531     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
10532     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
10533
10534     // Concatenate the result back
10535     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
10536   }
10537
10538   return SDValue();
10539 }
10540
10541 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
10542   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
10543   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
10544   // looks for this combo and may remove the "setcc" instruction if the "setcc"
10545   // has only one use.
10546   SDNode *N = Op.getNode();
10547   SDValue LHS = N->getOperand(0);
10548   SDValue RHS = N->getOperand(1);
10549   unsigned BaseOp = 0;
10550   unsigned Cond = 0;
10551   DebugLoc DL = Op.getDebugLoc();
10552   switch (Op.getOpcode()) {
10553   default: llvm_unreachable("Unknown ovf instruction!");
10554   case ISD::SADDO:
10555     // A subtract of one will be selected as a INC. Note that INC doesn't
10556     // set CF, so we can't do this for UADDO.
10557     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10558       if (C->isOne()) {
10559         BaseOp = X86ISD::INC;
10560         Cond = X86::COND_O;
10561         break;
10562       }
10563     BaseOp = X86ISD::ADD;
10564     Cond = X86::COND_O;
10565     break;
10566   case ISD::UADDO:
10567     BaseOp = X86ISD::ADD;
10568     Cond = X86::COND_B;
10569     break;
10570   case ISD::SSUBO:
10571     // A subtract of one will be selected as a DEC. Note that DEC doesn't
10572     // set CF, so we can't do this for USUBO.
10573     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10574       if (C->isOne()) {
10575         BaseOp = X86ISD::DEC;
10576         Cond = X86::COND_O;
10577         break;
10578       }
10579     BaseOp = X86ISD::SUB;
10580     Cond = X86::COND_O;
10581     break;
10582   case ISD::USUBO:
10583     BaseOp = X86ISD::SUB;
10584     Cond = X86::COND_B;
10585     break;
10586   case ISD::SMULO:
10587     BaseOp = X86ISD::SMUL;
10588     Cond = X86::COND_O;
10589     break;
10590   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
10591     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
10592                                  MVT::i32);
10593     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
10594
10595     SDValue SetCC =
10596       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10597                   DAG.getConstant(X86::COND_O, MVT::i32),
10598                   SDValue(Sum.getNode(), 2));
10599
10600     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10601   }
10602   }
10603
10604   // Also sets EFLAGS.
10605   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
10606   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
10607
10608   SDValue SetCC =
10609     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
10610                 DAG.getConstant(Cond, MVT::i32),
10611                 SDValue(Sum.getNode(), 1));
10612
10613   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10614 }
10615
10616 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op, SelectionDAG &DAG) const{
10617   DebugLoc dl = Op.getDebugLoc();
10618   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
10619   EVT VT = Op.getValueType();
10620
10621   if (Subtarget->hasXMMInt() && VT.isVector()) {
10622     unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
10623                         ExtraVT.getScalarType().getSizeInBits();
10624     SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
10625
10626     unsigned SHLIntrinsicsID = 0;
10627     unsigned SRAIntrinsicsID = 0;
10628     switch (VT.getSimpleVT().SimpleTy) {
10629       default:
10630         return SDValue();
10631       case MVT::v4i32:
10632         SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_d;
10633         SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_d;
10634         break;
10635       case MVT::v8i16:
10636         SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_w;
10637         SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_w;
10638         break;
10639       case MVT::v8i32:
10640       case MVT::v16i16:
10641         if (!Subtarget->hasAVX())
10642           return SDValue();
10643         if (!Subtarget->hasAVX2()) {
10644           // needs to be split
10645           int NumElems = VT.getVectorNumElements();
10646           SDValue Idx0 = DAG.getConstant(0, MVT::i32);
10647           SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
10648
10649           // Extract the LHS vectors
10650           SDValue LHS = Op.getOperand(0);
10651           SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
10652           SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
10653
10654           MVT EltVT = VT.getVectorElementType().getSimpleVT();
10655           EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10656
10657           EVT ExtraEltVT = ExtraVT.getVectorElementType();
10658           int ExtraNumElems = ExtraVT.getVectorNumElements();
10659           ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
10660                                      ExtraNumElems/2);
10661           SDValue Extra = DAG.getValueType(ExtraVT);
10662
10663           LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
10664           LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
10665
10666           return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);;
10667         }
10668         if (VT == MVT::v8i32) {
10669           SHLIntrinsicsID = Intrinsic::x86_avx2_pslli_d;
10670           SRAIntrinsicsID = Intrinsic::x86_avx2_psrai_d;
10671         } else {
10672           SHLIntrinsicsID = Intrinsic::x86_avx2_pslli_w;
10673           SRAIntrinsicsID = Intrinsic::x86_avx2_psrai_w;
10674         }
10675     }
10676
10677     SDValue Tmp1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10678                          DAG.getConstant(SHLIntrinsicsID, MVT::i32),
10679                          Op.getOperand(0), ShAmt);
10680
10681     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10682                        DAG.getConstant(SRAIntrinsicsID, MVT::i32),
10683                        Tmp1, ShAmt);
10684   }
10685
10686   return SDValue();
10687 }
10688
10689
10690 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
10691   DebugLoc dl = Op.getDebugLoc();
10692
10693   // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
10694   // There isn't any reason to disable it if the target processor supports it.
10695   if (!Subtarget->hasXMMInt() && !Subtarget->is64Bit()) {
10696     SDValue Chain = Op.getOperand(0);
10697     SDValue Zero = DAG.getConstant(0, MVT::i32);
10698     SDValue Ops[] = {
10699       DAG.getRegister(X86::ESP, MVT::i32), // Base
10700       DAG.getTargetConstant(1, MVT::i8),   // Scale
10701       DAG.getRegister(0, MVT::i32),        // Index
10702       DAG.getTargetConstant(0, MVT::i32),  // Disp
10703       DAG.getRegister(0, MVT::i32),        // Segment.
10704       Zero,
10705       Chain
10706     };
10707     SDNode *Res =
10708       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10709                           array_lengthof(Ops));
10710     return SDValue(Res, 0);
10711   }
10712
10713   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
10714   if (!isDev)
10715     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10716
10717   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10718   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
10719   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
10720   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
10721
10722   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
10723   if (!Op1 && !Op2 && !Op3 && Op4)
10724     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
10725
10726   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
10727   if (Op1 && !Op2 && !Op3 && !Op4)
10728     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
10729
10730   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
10731   //           (MFENCE)>;
10732   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10733 }
10734
10735 SDValue X86TargetLowering::LowerATOMIC_FENCE(SDValue Op,
10736                                              SelectionDAG &DAG) const {
10737   DebugLoc dl = Op.getDebugLoc();
10738   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
10739     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
10740   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
10741     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
10742
10743   // The only fence that needs an instruction is a sequentially-consistent
10744   // cross-thread fence.
10745   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
10746     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
10747     // no-sse2). There isn't any reason to disable it if the target processor
10748     // supports it.
10749     if (Subtarget->hasXMMInt() || Subtarget->is64Bit())
10750       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10751
10752     SDValue Chain = Op.getOperand(0);
10753     SDValue Zero = DAG.getConstant(0, MVT::i32);
10754     SDValue Ops[] = {
10755       DAG.getRegister(X86::ESP, MVT::i32), // Base
10756       DAG.getTargetConstant(1, MVT::i8),   // Scale
10757       DAG.getRegister(0, MVT::i32),        // Index
10758       DAG.getTargetConstant(0, MVT::i32),  // Disp
10759       DAG.getRegister(0, MVT::i32),        // Segment.
10760       Zero,
10761       Chain
10762     };
10763     SDNode *Res =
10764       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10765                          array_lengthof(Ops));
10766     return SDValue(Res, 0);
10767   }
10768
10769   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
10770   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10771 }
10772
10773
10774 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
10775   EVT T = Op.getValueType();
10776   DebugLoc DL = Op.getDebugLoc();
10777   unsigned Reg = 0;
10778   unsigned size = 0;
10779   switch(T.getSimpleVT().SimpleTy) {
10780   default:
10781     assert(false && "Invalid value type!");
10782   case MVT::i8:  Reg = X86::AL;  size = 1; break;
10783   case MVT::i16: Reg = X86::AX;  size = 2; break;
10784   case MVT::i32: Reg = X86::EAX; size = 4; break;
10785   case MVT::i64:
10786     assert(Subtarget->is64Bit() && "Node not type legal!");
10787     Reg = X86::RAX; size = 8;
10788     break;
10789   }
10790   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
10791                                     Op.getOperand(2), SDValue());
10792   SDValue Ops[] = { cpIn.getValue(0),
10793                     Op.getOperand(1),
10794                     Op.getOperand(3),
10795                     DAG.getTargetConstant(size, MVT::i8),
10796                     cpIn.getValue(1) };
10797   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10798   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
10799   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
10800                                            Ops, 5, T, MMO);
10801   SDValue cpOut =
10802     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
10803   return cpOut;
10804 }
10805
10806 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
10807                                                  SelectionDAG &DAG) const {
10808   assert(Subtarget->is64Bit() && "Result not type legalized?");
10809   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10810   SDValue TheChain = Op.getOperand(0);
10811   DebugLoc dl = Op.getDebugLoc();
10812   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10813   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
10814   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
10815                                    rax.getValue(2));
10816   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
10817                             DAG.getConstant(32, MVT::i8));
10818   SDValue Ops[] = {
10819     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
10820     rdx.getValue(1)
10821   };
10822   return DAG.getMergeValues(Ops, 2, dl);
10823 }
10824
10825 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
10826                                             SelectionDAG &DAG) const {
10827   EVT SrcVT = Op.getOperand(0).getValueType();
10828   EVT DstVT = Op.getValueType();
10829   assert(Subtarget->is64Bit() && !Subtarget->hasXMMInt() &&
10830          Subtarget->hasMMX() && "Unexpected custom BITCAST");
10831   assert((DstVT == MVT::i64 ||
10832           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
10833          "Unexpected custom BITCAST");
10834   // i64 <=> MMX conversions are Legal.
10835   if (SrcVT==MVT::i64 && DstVT.isVector())
10836     return Op;
10837   if (DstVT==MVT::i64 && SrcVT.isVector())
10838     return Op;
10839   // MMX <=> MMX conversions are Legal.
10840   if (SrcVT.isVector() && DstVT.isVector())
10841     return Op;
10842   // All other conversions need to be expanded.
10843   return SDValue();
10844 }
10845
10846 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
10847   SDNode *Node = Op.getNode();
10848   DebugLoc dl = Node->getDebugLoc();
10849   EVT T = Node->getValueType(0);
10850   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
10851                               DAG.getConstant(0, T), Node->getOperand(2));
10852   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
10853                        cast<AtomicSDNode>(Node)->getMemoryVT(),
10854                        Node->getOperand(0),
10855                        Node->getOperand(1), negOp,
10856                        cast<AtomicSDNode>(Node)->getSrcValue(),
10857                        cast<AtomicSDNode>(Node)->getAlignment(),
10858                        cast<AtomicSDNode>(Node)->getOrdering(),
10859                        cast<AtomicSDNode>(Node)->getSynchScope());
10860 }
10861
10862 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
10863   SDNode *Node = Op.getNode();
10864   DebugLoc dl = Node->getDebugLoc();
10865   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10866
10867   // Convert seq_cst store -> xchg
10868   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
10869   // FIXME: On 32-bit, store -> fist or movq would be more efficient
10870   //        (The only way to get a 16-byte store is cmpxchg16b)
10871   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
10872   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
10873       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
10874     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
10875                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
10876                                  Node->getOperand(0),
10877                                  Node->getOperand(1), Node->getOperand(2),
10878                                  cast<AtomicSDNode>(Node)->getMemOperand(),
10879                                  cast<AtomicSDNode>(Node)->getOrdering(),
10880                                  cast<AtomicSDNode>(Node)->getSynchScope());
10881     return Swap.getValue(1);
10882   }
10883   // Other atomic stores have a simple pattern.
10884   return Op;
10885 }
10886
10887 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
10888   EVT VT = Op.getNode()->getValueType(0);
10889
10890   // Let legalize expand this if it isn't a legal type yet.
10891   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10892     return SDValue();
10893
10894   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10895
10896   unsigned Opc;
10897   bool ExtraOp = false;
10898   switch (Op.getOpcode()) {
10899   default: assert(0 && "Invalid code");
10900   case ISD::ADDC: Opc = X86ISD::ADD; break;
10901   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
10902   case ISD::SUBC: Opc = X86ISD::SUB; break;
10903   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
10904   }
10905
10906   if (!ExtraOp)
10907     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10908                        Op.getOperand(1));
10909   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10910                      Op.getOperand(1), Op.getOperand(2));
10911 }
10912
10913 /// LowerOperation - Provide custom lowering hooks for some operations.
10914 ///
10915 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10916   switch (Op.getOpcode()) {
10917   default: llvm_unreachable("Should not custom lower this!");
10918   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
10919   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op,DAG);
10920   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op,DAG);
10921   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
10922   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
10923   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
10924   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
10925   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
10926   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
10927   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
10928   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
10929   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op, DAG);
10930   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, DAG);
10931   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
10932   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
10933   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
10934   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
10935   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
10936   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
10937   case ISD::SHL_PARTS:
10938   case ISD::SRA_PARTS:
10939   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
10940   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
10941   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
10942   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
10943   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
10944   case ISD::FABS:               return LowerFABS(Op, DAG);
10945   case ISD::FNEG:               return LowerFNEG(Op, DAG);
10946   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
10947   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
10948   case ISD::SETCC:              return LowerSETCC(Op, DAG);
10949   case ISD::SELECT:             return LowerSELECT(Op, DAG);
10950   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
10951   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
10952   case ISD::VASTART:            return LowerVASTART(Op, DAG);
10953   case ISD::VAARG:              return LowerVAARG(Op, DAG);
10954   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
10955   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10956   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
10957   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
10958   case ISD::FRAME_TO_ARGS_OFFSET:
10959                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
10960   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10961   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
10962   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
10963   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
10964   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
10965   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
10966   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
10967   case ISD::MUL:                return LowerMUL(Op, DAG);
10968   case ISD::SRA:
10969   case ISD::SRL:
10970   case ISD::SHL:                return LowerShift(Op, DAG);
10971   case ISD::SADDO:
10972   case ISD::UADDO:
10973   case ISD::SSUBO:
10974   case ISD::USUBO:
10975   case ISD::SMULO:
10976   case ISD::UMULO:              return LowerXALUO(Op, DAG);
10977   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
10978   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
10979   case ISD::ADDC:
10980   case ISD::ADDE:
10981   case ISD::SUBC:
10982   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
10983   case ISD::ADD:                return LowerADD(Op, DAG);
10984   case ISD::SUB:                return LowerSUB(Op, DAG);
10985   }
10986 }
10987
10988 static void ReplaceATOMIC_LOAD(SDNode *Node,
10989                                   SmallVectorImpl<SDValue> &Results,
10990                                   SelectionDAG &DAG) {
10991   DebugLoc dl = Node->getDebugLoc();
10992   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10993
10994   // Convert wide load -> cmpxchg8b/cmpxchg16b
10995   // FIXME: On 32-bit, load -> fild or movq would be more efficient
10996   //        (The only way to get a 16-byte load is cmpxchg16b)
10997   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
10998   SDValue Zero = DAG.getConstant(0, VT);
10999   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
11000                                Node->getOperand(0),
11001                                Node->getOperand(1), Zero, Zero,
11002                                cast<AtomicSDNode>(Node)->getMemOperand(),
11003                                cast<AtomicSDNode>(Node)->getOrdering(),
11004                                cast<AtomicSDNode>(Node)->getSynchScope());
11005   Results.push_back(Swap.getValue(0));
11006   Results.push_back(Swap.getValue(1));
11007 }
11008
11009 void X86TargetLowering::
11010 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
11011                         SelectionDAG &DAG, unsigned NewOp) const {
11012   DebugLoc dl = Node->getDebugLoc();
11013   assert (Node->getValueType(0) == MVT::i64 &&
11014           "Only know how to expand i64 atomics");
11015
11016   SDValue Chain = Node->getOperand(0);
11017   SDValue In1 = Node->getOperand(1);
11018   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11019                              Node->getOperand(2), DAG.getIntPtrConstant(0));
11020   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11021                              Node->getOperand(2), DAG.getIntPtrConstant(1));
11022   SDValue Ops[] = { Chain, In1, In2L, In2H };
11023   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
11024   SDValue Result =
11025     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
11026                             cast<MemSDNode>(Node)->getMemOperand());
11027   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
11028   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
11029   Results.push_back(Result.getValue(2));
11030 }
11031
11032 /// ReplaceNodeResults - Replace a node with an illegal result type
11033 /// with a new node built out of custom code.
11034 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
11035                                            SmallVectorImpl<SDValue>&Results,
11036                                            SelectionDAG &DAG) const {
11037   DebugLoc dl = N->getDebugLoc();
11038   switch (N->getOpcode()) {
11039   default:
11040     assert(false && "Do not know how to custom type legalize this operation!");
11041     return;
11042   case ISD::SIGN_EXTEND_INREG:
11043   case ISD::ADDC:
11044   case ISD::ADDE:
11045   case ISD::SUBC:
11046   case ISD::SUBE:
11047     // We don't want to expand or promote these.
11048     return;
11049   case ISD::FP_TO_SINT: {
11050     std::pair<SDValue,SDValue> Vals =
11051         FP_TO_INTHelper(SDValue(N, 0), DAG, true);
11052     SDValue FIST = Vals.first, StackSlot = Vals.second;
11053     if (FIST.getNode() != 0) {
11054       EVT VT = N->getValueType(0);
11055       // Return a load from the stack slot.
11056       Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
11057                                     MachinePointerInfo(), 
11058                                     false, false, false, 0));
11059     }
11060     return;
11061   }
11062   case ISD::READCYCLECOUNTER: {
11063     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11064     SDValue TheChain = N->getOperand(0);
11065     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11066     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
11067                                      rd.getValue(1));
11068     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
11069                                      eax.getValue(2));
11070     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
11071     SDValue Ops[] = { eax, edx };
11072     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
11073     Results.push_back(edx.getValue(1));
11074     return;
11075   }
11076   case ISD::ATOMIC_CMP_SWAP: {
11077     EVT T = N->getValueType(0);
11078     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
11079     bool Regs64bit = T == MVT::i128;
11080     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
11081     SDValue cpInL, cpInH;
11082     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11083                         DAG.getConstant(0, HalfT));
11084     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11085                         DAG.getConstant(1, HalfT));
11086     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
11087                              Regs64bit ? X86::RAX : X86::EAX,
11088                              cpInL, SDValue());
11089     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
11090                              Regs64bit ? X86::RDX : X86::EDX,
11091                              cpInH, cpInL.getValue(1));
11092     SDValue swapInL, swapInH;
11093     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11094                           DAG.getConstant(0, HalfT));
11095     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11096                           DAG.getConstant(1, HalfT));
11097     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
11098                                Regs64bit ? X86::RBX : X86::EBX,
11099                                swapInL, cpInH.getValue(1));
11100     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
11101                                Regs64bit ? X86::RCX : X86::ECX, 
11102                                swapInH, swapInL.getValue(1));
11103     SDValue Ops[] = { swapInH.getValue(0),
11104                       N->getOperand(1),
11105                       swapInH.getValue(1) };
11106     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11107     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
11108     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
11109                                   X86ISD::LCMPXCHG8_DAG;
11110     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
11111                                              Ops, 3, T, MMO);
11112     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
11113                                         Regs64bit ? X86::RAX : X86::EAX,
11114                                         HalfT, Result.getValue(1));
11115     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
11116                                         Regs64bit ? X86::RDX : X86::EDX,
11117                                         HalfT, cpOutL.getValue(2));
11118     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
11119     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
11120     Results.push_back(cpOutH.getValue(1));
11121     return;
11122   }
11123   case ISD::ATOMIC_LOAD_ADD:
11124     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
11125     return;
11126   case ISD::ATOMIC_LOAD_AND:
11127     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
11128     return;
11129   case ISD::ATOMIC_LOAD_NAND:
11130     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
11131     return;
11132   case ISD::ATOMIC_LOAD_OR:
11133     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
11134     return;
11135   case ISD::ATOMIC_LOAD_SUB:
11136     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
11137     return;
11138   case ISD::ATOMIC_LOAD_XOR:
11139     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
11140     return;
11141   case ISD::ATOMIC_SWAP:
11142     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
11143     return;
11144   case ISD::ATOMIC_LOAD:
11145     ReplaceATOMIC_LOAD(N, Results, DAG);
11146   }
11147 }
11148
11149 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
11150   switch (Opcode) {
11151   default: return NULL;
11152   case X86ISD::BSF:                return "X86ISD::BSF";
11153   case X86ISD::BSR:                return "X86ISD::BSR";
11154   case X86ISD::SHLD:               return "X86ISD::SHLD";
11155   case X86ISD::SHRD:               return "X86ISD::SHRD";
11156   case X86ISD::FAND:               return "X86ISD::FAND";
11157   case X86ISD::FOR:                return "X86ISD::FOR";
11158   case X86ISD::FXOR:               return "X86ISD::FXOR";
11159   case X86ISD::FSRL:               return "X86ISD::FSRL";
11160   case X86ISD::FILD:               return "X86ISD::FILD";
11161   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
11162   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
11163   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
11164   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
11165   case X86ISD::FLD:                return "X86ISD::FLD";
11166   case X86ISD::FST:                return "X86ISD::FST";
11167   case X86ISD::CALL:               return "X86ISD::CALL";
11168   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
11169   case X86ISD::BT:                 return "X86ISD::BT";
11170   case X86ISD::CMP:                return "X86ISD::CMP";
11171   case X86ISD::COMI:               return "X86ISD::COMI";
11172   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
11173   case X86ISD::SETCC:              return "X86ISD::SETCC";
11174   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
11175   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
11176   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
11177   case X86ISD::CMOV:               return "X86ISD::CMOV";
11178   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
11179   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
11180   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
11181   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
11182   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
11183   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
11184   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
11185   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
11186   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
11187   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
11188   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
11189   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
11190   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
11191   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
11192   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
11193   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
11194   case X86ISD::FHADD:              return "X86ISD::FHADD";
11195   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
11196   case X86ISD::FMAX:               return "X86ISD::FMAX";
11197   case X86ISD::FMIN:               return "X86ISD::FMIN";
11198   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
11199   case X86ISD::FRCP:               return "X86ISD::FRCP";
11200   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
11201   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
11202   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
11203   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
11204   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
11205   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
11206   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
11207   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
11208   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
11209   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
11210   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
11211   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
11212   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
11213   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
11214   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
11215   case X86ISD::VSHL:               return "X86ISD::VSHL";
11216   case X86ISD::VSRL:               return "X86ISD::VSRL";
11217   case X86ISD::CMPPD:              return "X86ISD::CMPPD";
11218   case X86ISD::CMPPS:              return "X86ISD::CMPPS";
11219   case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
11220   case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
11221   case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
11222   case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
11223   case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
11224   case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
11225   case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
11226   case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
11227   case X86ISD::ADD:                return "X86ISD::ADD";
11228   case X86ISD::SUB:                return "X86ISD::SUB";
11229   case X86ISD::ADC:                return "X86ISD::ADC";
11230   case X86ISD::SBB:                return "X86ISD::SBB";
11231   case X86ISD::SMUL:               return "X86ISD::SMUL";
11232   case X86ISD::UMUL:               return "X86ISD::UMUL";
11233   case X86ISD::INC:                return "X86ISD::INC";
11234   case X86ISD::DEC:                return "X86ISD::DEC";
11235   case X86ISD::OR:                 return "X86ISD::OR";
11236   case X86ISD::XOR:                return "X86ISD::XOR";
11237   case X86ISD::AND:                return "X86ISD::AND";
11238   case X86ISD::ANDN:               return "X86ISD::ANDN";
11239   case X86ISD::BLSI:               return "X86ISD::BLSI";
11240   case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
11241   case X86ISD::BLSR:               return "X86ISD::BLSR";
11242   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
11243   case X86ISD::PTEST:              return "X86ISD::PTEST";
11244   case X86ISD::TESTP:              return "X86ISD::TESTP";
11245   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
11246   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
11247   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
11248   case X86ISD::PSHUFHW_LD:         return "X86ISD::PSHUFHW_LD";
11249   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
11250   case X86ISD::PSHUFLW_LD:         return "X86ISD::PSHUFLW_LD";
11251   case X86ISD::SHUFPS:             return "X86ISD::SHUFPS";
11252   case X86ISD::SHUFPD:             return "X86ISD::SHUFPD";
11253   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
11254   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
11255   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
11256   case X86ISD::MOVHLPD:            return "X86ISD::MOVHLPD";
11257   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
11258   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
11259   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
11260   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
11261   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
11262   case X86ISD::MOVSHDUP_LD:        return "X86ISD::MOVSHDUP_LD";
11263   case X86ISD::MOVSLDUP_LD:        return "X86ISD::MOVSLDUP_LD";
11264   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
11265   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
11266   case X86ISD::UNPCKLPS:           return "X86ISD::UNPCKLPS";
11267   case X86ISD::UNPCKLPD:           return "X86ISD::UNPCKLPD";
11268   case X86ISD::VUNPCKLPSY:         return "X86ISD::VUNPCKLPSY";
11269   case X86ISD::VUNPCKLPDY:         return "X86ISD::VUNPCKLPDY";
11270   case X86ISD::UNPCKHPS:           return "X86ISD::UNPCKHPS";
11271   case X86ISD::UNPCKHPD:           return "X86ISD::UNPCKHPD";
11272   case X86ISD::PUNPCKLBW:          return "X86ISD::PUNPCKLBW";
11273   case X86ISD::PUNPCKLWD:          return "X86ISD::PUNPCKLWD";
11274   case X86ISD::PUNPCKLDQ:          return "X86ISD::PUNPCKLDQ";
11275   case X86ISD::PUNPCKLQDQ:         return "X86ISD::PUNPCKLQDQ";
11276   case X86ISD::VPUNPCKLBWY:        return "X86ISD::VPUNPCKLBWY";
11277   case X86ISD::VPUNPCKLWDY:        return "X86ISD::VPUNPCKLWDY";
11278   case X86ISD::VPUNPCKLDQY:        return "X86ISD::VPUNPCKLDQY";
11279   case X86ISD::VPUNPCKLQDQY:       return "X86ISD::VPUNPCKLQDQY";
11280   case X86ISD::PUNPCKHBW:          return "X86ISD::PUNPCKHBW";
11281   case X86ISD::PUNPCKHWD:          return "X86ISD::PUNPCKHWD";
11282   case X86ISD::PUNPCKHDQ:          return "X86ISD::PUNPCKHDQ";
11283   case X86ISD::PUNPCKHQDQ:         return "X86ISD::PUNPCKHQDQ";
11284   case X86ISD::VPUNPCKHBWY:        return "X86ISD::VPUNPCKHBWY";
11285   case X86ISD::VPUNPCKHWDY:        return "X86ISD::VPUNPCKHWDY";
11286   case X86ISD::VPUNPCKHDQY:        return "X86ISD::VPUNPCKHDQY";
11287   case X86ISD::VPUNPCKHQDQY:       return "X86ISD::VPUNPCKHQDQY";
11288   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
11289   case X86ISD::VPERMILPS:          return "X86ISD::VPERMILPS";
11290   case X86ISD::VPERMILPSY:         return "X86ISD::VPERMILPSY";
11291   case X86ISD::VPERMILPD:          return "X86ISD::VPERMILPD";
11292   case X86ISD::VPERMILPDY:         return "X86ISD::VPERMILPDY";
11293   case X86ISD::VPERM2F128:         return "X86ISD::VPERM2F128";
11294   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
11295   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
11296   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
11297   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
11298   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
11299   }
11300 }
11301
11302 // isLegalAddressingMode - Return true if the addressing mode represented
11303 // by AM is legal for this target, for a load/store of the specified type.
11304 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
11305                                               Type *Ty) const {
11306   // X86 supports extremely general addressing modes.
11307   CodeModel::Model M = getTargetMachine().getCodeModel();
11308   Reloc::Model R = getTargetMachine().getRelocationModel();
11309
11310   // X86 allows a sign-extended 32-bit immediate field as a displacement.
11311   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
11312     return false;
11313
11314   if (AM.BaseGV) {
11315     unsigned GVFlags =
11316       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
11317
11318     // If a reference to this global requires an extra load, we can't fold it.
11319     if (isGlobalStubReference(GVFlags))
11320       return false;
11321
11322     // If BaseGV requires a register for the PIC base, we cannot also have a
11323     // BaseReg specified.
11324     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
11325       return false;
11326
11327     // If lower 4G is not available, then we must use rip-relative addressing.
11328     if ((M != CodeModel::Small || R != Reloc::Static) &&
11329         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
11330       return false;
11331   }
11332
11333   switch (AM.Scale) {
11334   case 0:
11335   case 1:
11336   case 2:
11337   case 4:
11338   case 8:
11339     // These scales always work.
11340     break;
11341   case 3:
11342   case 5:
11343   case 9:
11344     // These scales are formed with basereg+scalereg.  Only accept if there is
11345     // no basereg yet.
11346     if (AM.HasBaseReg)
11347       return false;
11348     break;
11349   default:  // Other stuff never works.
11350     return false;
11351   }
11352
11353   return true;
11354 }
11355
11356
11357 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11358   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11359     return false;
11360   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11361   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11362   if (NumBits1 <= NumBits2)
11363     return false;
11364   return true;
11365 }
11366
11367 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11368   if (!VT1.isInteger() || !VT2.isInteger())
11369     return false;
11370   unsigned NumBits1 = VT1.getSizeInBits();
11371   unsigned NumBits2 = VT2.getSizeInBits();
11372   if (NumBits1 <= NumBits2)
11373     return false;
11374   return true;
11375 }
11376
11377 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
11378   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11379   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
11380 }
11381
11382 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
11383   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11384   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
11385 }
11386
11387 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
11388   // i16 instructions are longer (0x66 prefix) and potentially slower.
11389   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
11390 }
11391
11392 /// isShuffleMaskLegal - Targets can use this to indicate that they only
11393 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
11394 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
11395 /// are assumed to be legal.
11396 bool
11397 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
11398                                       EVT VT) const {
11399   // Very little shuffling can be done for 64-bit vectors right now.
11400   if (VT.getSizeInBits() == 64)
11401     return isPALIGNRMask(M, VT, Subtarget->hasSSSE3orAVX());
11402
11403   // FIXME: pshufb, blends, shifts.
11404   return (VT.getVectorNumElements() == 2 ||
11405           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
11406           isMOVLMask(M, VT) ||
11407           isSHUFPMask(M, VT) ||
11408           isPSHUFDMask(M, VT) ||
11409           isPSHUFHWMask(M, VT) ||
11410           isPSHUFLWMask(M, VT) ||
11411           isPALIGNRMask(M, VT, Subtarget->hasSSSE3orAVX()) ||
11412           isUNPCKLMask(M, VT, Subtarget->hasAVX2()) ||
11413           isUNPCKHMask(M, VT, Subtarget->hasAVX2()) ||
11414           isUNPCKL_v_undef_Mask(M, VT) ||
11415           isUNPCKH_v_undef_Mask(M, VT));
11416 }
11417
11418 bool
11419 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
11420                                           EVT VT) const {
11421   unsigned NumElts = VT.getVectorNumElements();
11422   // FIXME: This collection of masks seems suspect.
11423   if (NumElts == 2)
11424     return true;
11425   if (NumElts == 4 && VT.getSizeInBits() == 128) {
11426     return (isMOVLMask(Mask, VT)  ||
11427             isCommutedMOVLMask(Mask, VT, true) ||
11428             isSHUFPMask(Mask, VT) ||
11429             isCommutedSHUFPMask(Mask, VT));
11430   }
11431   return false;
11432 }
11433
11434 //===----------------------------------------------------------------------===//
11435 //                           X86 Scheduler Hooks
11436 //===----------------------------------------------------------------------===//
11437
11438 // private utility function
11439 MachineBasicBlock *
11440 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
11441                                                        MachineBasicBlock *MBB,
11442                                                        unsigned regOpc,
11443                                                        unsigned immOpc,
11444                                                        unsigned LoadOpc,
11445                                                        unsigned CXchgOpc,
11446                                                        unsigned notOpc,
11447                                                        unsigned EAXreg,
11448                                                        TargetRegisterClass *RC,
11449                                                        bool invSrc) const {
11450   // For the atomic bitwise operator, we generate
11451   //   thisMBB:
11452   //   newMBB:
11453   //     ld  t1 = [bitinstr.addr]
11454   //     op  t2 = t1, [bitinstr.val]
11455   //     mov EAX = t1
11456   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
11457   //     bz  newMBB
11458   //     fallthrough -->nextMBB
11459   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11460   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11461   MachineFunction::iterator MBBIter = MBB;
11462   ++MBBIter;
11463
11464   /// First build the CFG
11465   MachineFunction *F = MBB->getParent();
11466   MachineBasicBlock *thisMBB = MBB;
11467   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11468   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11469   F->insert(MBBIter, newMBB);
11470   F->insert(MBBIter, nextMBB);
11471
11472   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11473   nextMBB->splice(nextMBB->begin(), thisMBB,
11474                   llvm::next(MachineBasicBlock::iterator(bInstr)),
11475                   thisMBB->end());
11476   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11477
11478   // Update thisMBB to fall through to newMBB
11479   thisMBB->addSuccessor(newMBB);
11480
11481   // newMBB jumps to itself and fall through to nextMBB
11482   newMBB->addSuccessor(nextMBB);
11483   newMBB->addSuccessor(newMBB);
11484
11485   // Insert instructions into newMBB based on incoming instruction
11486   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11487          "unexpected number of operands");
11488   DebugLoc dl = bInstr->getDebugLoc();
11489   MachineOperand& destOper = bInstr->getOperand(0);
11490   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11491   int numArgs = bInstr->getNumOperands() - 1;
11492   for (int i=0; i < numArgs; ++i)
11493     argOpers[i] = &bInstr->getOperand(i+1);
11494
11495   // x86 address has 4 operands: base, index, scale, and displacement
11496   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11497   int valArgIndx = lastAddrIndx + 1;
11498
11499   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11500   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
11501   for (int i=0; i <= lastAddrIndx; ++i)
11502     (*MIB).addOperand(*argOpers[i]);
11503
11504   unsigned tt = F->getRegInfo().createVirtualRegister(RC);
11505   if (invSrc) {
11506     MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
11507   }
11508   else
11509     tt = t1;
11510
11511   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11512   assert((argOpers[valArgIndx]->isReg() ||
11513           argOpers[valArgIndx]->isImm()) &&
11514          "invalid operand");
11515   if (argOpers[valArgIndx]->isReg())
11516     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
11517   else
11518     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
11519   MIB.addReg(tt);
11520   (*MIB).addOperand(*argOpers[valArgIndx]);
11521
11522   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
11523   MIB.addReg(t1);
11524
11525   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
11526   for (int i=0; i <= lastAddrIndx; ++i)
11527     (*MIB).addOperand(*argOpers[i]);
11528   MIB.addReg(t2);
11529   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11530   (*MIB).setMemRefs(bInstr->memoperands_begin(),
11531                     bInstr->memoperands_end());
11532
11533   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11534   MIB.addReg(EAXreg);
11535
11536   // insert branch
11537   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11538
11539   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
11540   return nextMBB;
11541 }
11542
11543 // private utility function:  64 bit atomics on 32 bit host.
11544 MachineBasicBlock *
11545 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
11546                                                        MachineBasicBlock *MBB,
11547                                                        unsigned regOpcL,
11548                                                        unsigned regOpcH,
11549                                                        unsigned immOpcL,
11550                                                        unsigned immOpcH,
11551                                                        bool invSrc) const {
11552   // For the atomic bitwise operator, we generate
11553   //   thisMBB (instructions are in pairs, except cmpxchg8b)
11554   //     ld t1,t2 = [bitinstr.addr]
11555   //   newMBB:
11556   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
11557   //     op  t5, t6 <- out1, out2, [bitinstr.val]
11558   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
11559   //     mov ECX, EBX <- t5, t6
11560   //     mov EAX, EDX <- t1, t2
11561   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
11562   //     mov t3, t4 <- EAX, EDX
11563   //     bz  newMBB
11564   //     result in out1, out2
11565   //     fallthrough -->nextMBB
11566
11567   const TargetRegisterClass *RC = X86::GR32RegisterClass;
11568   const unsigned LoadOpc = X86::MOV32rm;
11569   const unsigned NotOpc = X86::NOT32r;
11570   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11571   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11572   MachineFunction::iterator MBBIter = MBB;
11573   ++MBBIter;
11574
11575   /// First build the CFG
11576   MachineFunction *F = MBB->getParent();
11577   MachineBasicBlock *thisMBB = MBB;
11578   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11579   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11580   F->insert(MBBIter, newMBB);
11581   F->insert(MBBIter, nextMBB);
11582
11583   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11584   nextMBB->splice(nextMBB->begin(), thisMBB,
11585                   llvm::next(MachineBasicBlock::iterator(bInstr)),
11586                   thisMBB->end());
11587   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11588
11589   // Update thisMBB to fall through to newMBB
11590   thisMBB->addSuccessor(newMBB);
11591
11592   // newMBB jumps to itself and fall through to nextMBB
11593   newMBB->addSuccessor(nextMBB);
11594   newMBB->addSuccessor(newMBB);
11595
11596   DebugLoc dl = bInstr->getDebugLoc();
11597   // Insert instructions into newMBB based on incoming instruction
11598   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
11599   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
11600          "unexpected number of operands");
11601   MachineOperand& dest1Oper = bInstr->getOperand(0);
11602   MachineOperand& dest2Oper = bInstr->getOperand(1);
11603   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11604   for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
11605     argOpers[i] = &bInstr->getOperand(i+2);
11606
11607     // We use some of the operands multiple times, so conservatively just
11608     // clear any kill flags that might be present.
11609     if (argOpers[i]->isReg() && argOpers[i]->isUse())
11610       argOpers[i]->setIsKill(false);
11611   }
11612
11613   // x86 address has 5 operands: base, index, scale, displacement, and segment.
11614   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11615
11616   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11617   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
11618   for (int i=0; i <= lastAddrIndx; ++i)
11619     (*MIB).addOperand(*argOpers[i]);
11620   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11621   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
11622   // add 4 to displacement.
11623   for (int i=0; i <= lastAddrIndx-2; ++i)
11624     (*MIB).addOperand(*argOpers[i]);
11625   MachineOperand newOp3 = *(argOpers[3]);
11626   if (newOp3.isImm())
11627     newOp3.setImm(newOp3.getImm()+4);
11628   else
11629     newOp3.setOffset(newOp3.getOffset()+4);
11630   (*MIB).addOperand(newOp3);
11631   (*MIB).addOperand(*argOpers[lastAddrIndx]);
11632
11633   // t3/4 are defined later, at the bottom of the loop
11634   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11635   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
11636   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
11637     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
11638   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
11639     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
11640
11641   // The subsequent operations should be using the destination registers of
11642   //the PHI instructions.
11643   if (invSrc) {
11644     t1 = F->getRegInfo().createVirtualRegister(RC);
11645     t2 = F->getRegInfo().createVirtualRegister(RC);
11646     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
11647     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
11648   } else {
11649     t1 = dest1Oper.getReg();
11650     t2 = dest2Oper.getReg();
11651   }
11652
11653   int valArgIndx = lastAddrIndx + 1;
11654   assert((argOpers[valArgIndx]->isReg() ||
11655           argOpers[valArgIndx]->isImm()) &&
11656          "invalid operand");
11657   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
11658   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
11659   if (argOpers[valArgIndx]->isReg())
11660     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
11661   else
11662     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
11663   if (regOpcL != X86::MOV32rr)
11664     MIB.addReg(t1);
11665   (*MIB).addOperand(*argOpers[valArgIndx]);
11666   assert(argOpers[valArgIndx + 1]->isReg() ==
11667          argOpers[valArgIndx]->isReg());
11668   assert(argOpers[valArgIndx + 1]->isImm() ==
11669          argOpers[valArgIndx]->isImm());
11670   if (argOpers[valArgIndx + 1]->isReg())
11671     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
11672   else
11673     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
11674   if (regOpcH != X86::MOV32rr)
11675     MIB.addReg(t2);
11676   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
11677
11678   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11679   MIB.addReg(t1);
11680   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
11681   MIB.addReg(t2);
11682
11683   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
11684   MIB.addReg(t5);
11685   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
11686   MIB.addReg(t6);
11687
11688   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
11689   for (int i=0; i <= lastAddrIndx; ++i)
11690     (*MIB).addOperand(*argOpers[i]);
11691
11692   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11693   (*MIB).setMemRefs(bInstr->memoperands_begin(),
11694                     bInstr->memoperands_end());
11695
11696   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
11697   MIB.addReg(X86::EAX);
11698   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
11699   MIB.addReg(X86::EDX);
11700
11701   // insert branch
11702   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11703
11704   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
11705   return nextMBB;
11706 }
11707
11708 // private utility function
11709 MachineBasicBlock *
11710 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
11711                                                       MachineBasicBlock *MBB,
11712                                                       unsigned cmovOpc) const {
11713   // For the atomic min/max operator, we generate
11714   //   thisMBB:
11715   //   newMBB:
11716   //     ld t1 = [min/max.addr]
11717   //     mov t2 = [min/max.val]
11718   //     cmp  t1, t2
11719   //     cmov[cond] t2 = t1
11720   //     mov EAX = t1
11721   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
11722   //     bz   newMBB
11723   //     fallthrough -->nextMBB
11724   //
11725   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11726   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11727   MachineFunction::iterator MBBIter = MBB;
11728   ++MBBIter;
11729
11730   /// First build the CFG
11731   MachineFunction *F = MBB->getParent();
11732   MachineBasicBlock *thisMBB = MBB;
11733   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11734   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11735   F->insert(MBBIter, newMBB);
11736   F->insert(MBBIter, nextMBB);
11737
11738   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11739   nextMBB->splice(nextMBB->begin(), thisMBB,
11740                   llvm::next(MachineBasicBlock::iterator(mInstr)),
11741                   thisMBB->end());
11742   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11743
11744   // Update thisMBB to fall through to newMBB
11745   thisMBB->addSuccessor(newMBB);
11746
11747   // newMBB jumps to newMBB and fall through to nextMBB
11748   newMBB->addSuccessor(nextMBB);
11749   newMBB->addSuccessor(newMBB);
11750
11751   DebugLoc dl = mInstr->getDebugLoc();
11752   // Insert instructions into newMBB based on incoming instruction
11753   assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11754          "unexpected number of operands");
11755   MachineOperand& destOper = mInstr->getOperand(0);
11756   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11757   int numArgs = mInstr->getNumOperands() - 1;
11758   for (int i=0; i < numArgs; ++i)
11759     argOpers[i] = &mInstr->getOperand(i+1);
11760
11761   // x86 address has 4 operands: base, index, scale, and displacement
11762   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11763   int valArgIndx = lastAddrIndx + 1;
11764
11765   unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11766   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
11767   for (int i=0; i <= lastAddrIndx; ++i)
11768     (*MIB).addOperand(*argOpers[i]);
11769
11770   // We only support register and immediate values
11771   assert((argOpers[valArgIndx]->isReg() ||
11772           argOpers[valArgIndx]->isImm()) &&
11773          "invalid operand");
11774
11775   unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11776   if (argOpers[valArgIndx]->isReg())
11777     MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
11778   else
11779     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
11780   (*MIB).addOperand(*argOpers[valArgIndx]);
11781
11782   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11783   MIB.addReg(t1);
11784
11785   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
11786   MIB.addReg(t1);
11787   MIB.addReg(t2);
11788
11789   // Generate movc
11790   unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11791   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
11792   MIB.addReg(t2);
11793   MIB.addReg(t1);
11794
11795   // Cmp and exchange if none has modified the memory location
11796   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
11797   for (int i=0; i <= lastAddrIndx; ++i)
11798     (*MIB).addOperand(*argOpers[i]);
11799   MIB.addReg(t3);
11800   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11801   (*MIB).setMemRefs(mInstr->memoperands_begin(),
11802                     mInstr->memoperands_end());
11803
11804   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11805   MIB.addReg(X86::EAX);
11806
11807   // insert branch
11808   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11809
11810   mInstr->eraseFromParent();   // The pseudo instruction is gone now.
11811   return nextMBB;
11812 }
11813
11814 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
11815 // or XMM0_V32I8 in AVX all of this code can be replaced with that
11816 // in the .td file.
11817 MachineBasicBlock *
11818 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
11819                             unsigned numArgs, bool memArg) const {
11820   assert(Subtarget->hasSSE42orAVX() &&
11821          "Target must have SSE4.2 or AVX features enabled");
11822
11823   DebugLoc dl = MI->getDebugLoc();
11824   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11825   unsigned Opc;
11826   if (!Subtarget->hasAVX()) {
11827     if (memArg)
11828       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
11829     else
11830       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
11831   } else {
11832     if (memArg)
11833       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
11834     else
11835       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
11836   }
11837
11838   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
11839   for (unsigned i = 0; i < numArgs; ++i) {
11840     MachineOperand &Op = MI->getOperand(i+1);
11841     if (!(Op.isReg() && Op.isImplicit()))
11842       MIB.addOperand(Op);
11843   }
11844   BuildMI(*BB, MI, dl,
11845     TII->get(Subtarget->hasAVX() ? X86::VMOVAPSrr : X86::MOVAPSrr),
11846              MI->getOperand(0).getReg())
11847     .addReg(X86::XMM0);
11848
11849   MI->eraseFromParent();
11850   return BB;
11851 }
11852
11853 MachineBasicBlock *
11854 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
11855   DebugLoc dl = MI->getDebugLoc();
11856   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11857
11858   // Address into RAX/EAX, other two args into ECX, EDX.
11859   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
11860   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11861   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
11862   for (int i = 0; i < X86::AddrNumOperands; ++i)
11863     MIB.addOperand(MI->getOperand(i));
11864
11865   unsigned ValOps = X86::AddrNumOperands;
11866   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11867     .addReg(MI->getOperand(ValOps).getReg());
11868   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
11869     .addReg(MI->getOperand(ValOps+1).getReg());
11870
11871   // The instruction doesn't actually take any operands though.
11872   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
11873
11874   MI->eraseFromParent(); // The pseudo is gone now.
11875   return BB;
11876 }
11877
11878 MachineBasicBlock *
11879 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
11880   DebugLoc dl = MI->getDebugLoc();
11881   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11882
11883   // First arg in ECX, the second in EAX.
11884   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11885     .addReg(MI->getOperand(0).getReg());
11886   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
11887     .addReg(MI->getOperand(1).getReg());
11888
11889   // The instruction doesn't actually take any operands though.
11890   BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
11891
11892   MI->eraseFromParent(); // The pseudo is gone now.
11893   return BB;
11894 }
11895
11896 MachineBasicBlock *
11897 X86TargetLowering::EmitVAARG64WithCustomInserter(
11898                    MachineInstr *MI,
11899                    MachineBasicBlock *MBB) const {
11900   // Emit va_arg instruction on X86-64.
11901
11902   // Operands to this pseudo-instruction:
11903   // 0  ) Output        : destination address (reg)
11904   // 1-5) Input         : va_list address (addr, i64mem)
11905   // 6  ) ArgSize       : Size (in bytes) of vararg type
11906   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
11907   // 8  ) Align         : Alignment of type
11908   // 9  ) EFLAGS (implicit-def)
11909
11910   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
11911   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
11912
11913   unsigned DestReg = MI->getOperand(0).getReg();
11914   MachineOperand &Base = MI->getOperand(1);
11915   MachineOperand &Scale = MI->getOperand(2);
11916   MachineOperand &Index = MI->getOperand(3);
11917   MachineOperand &Disp = MI->getOperand(4);
11918   MachineOperand &Segment = MI->getOperand(5);
11919   unsigned ArgSize = MI->getOperand(6).getImm();
11920   unsigned ArgMode = MI->getOperand(7).getImm();
11921   unsigned Align = MI->getOperand(8).getImm();
11922
11923   // Memory Reference
11924   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
11925   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
11926   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
11927
11928   // Machine Information
11929   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11930   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
11931   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
11932   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
11933   DebugLoc DL = MI->getDebugLoc();
11934
11935   // struct va_list {
11936   //   i32   gp_offset
11937   //   i32   fp_offset
11938   //   i64   overflow_area (address)
11939   //   i64   reg_save_area (address)
11940   // }
11941   // sizeof(va_list) = 24
11942   // alignment(va_list) = 8
11943
11944   unsigned TotalNumIntRegs = 6;
11945   unsigned TotalNumXMMRegs = 8;
11946   bool UseGPOffset = (ArgMode == 1);
11947   bool UseFPOffset = (ArgMode == 2);
11948   unsigned MaxOffset = TotalNumIntRegs * 8 +
11949                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
11950
11951   /* Align ArgSize to a multiple of 8 */
11952   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
11953   bool NeedsAlign = (Align > 8);
11954
11955   MachineBasicBlock *thisMBB = MBB;
11956   MachineBasicBlock *overflowMBB;
11957   MachineBasicBlock *offsetMBB;
11958   MachineBasicBlock *endMBB;
11959
11960   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
11961   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
11962   unsigned OffsetReg = 0;
11963
11964   if (!UseGPOffset && !UseFPOffset) {
11965     // If we only pull from the overflow region, we don't create a branch.
11966     // We don't need to alter control flow.
11967     OffsetDestReg = 0; // unused
11968     OverflowDestReg = DestReg;
11969
11970     offsetMBB = NULL;
11971     overflowMBB = thisMBB;
11972     endMBB = thisMBB;
11973   } else {
11974     // First emit code to check if gp_offset (or fp_offset) is below the bound.
11975     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
11976     // If not, pull from overflow_area. (branch to overflowMBB)
11977     //
11978     //       thisMBB
11979     //         |     .
11980     //         |        .
11981     //     offsetMBB   overflowMBB
11982     //         |        .
11983     //         |     .
11984     //        endMBB
11985
11986     // Registers for the PHI in endMBB
11987     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
11988     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
11989
11990     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11991     MachineFunction *MF = MBB->getParent();
11992     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11993     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11994     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11995
11996     MachineFunction::iterator MBBIter = MBB;
11997     ++MBBIter;
11998
11999     // Insert the new basic blocks
12000     MF->insert(MBBIter, offsetMBB);
12001     MF->insert(MBBIter, overflowMBB);
12002     MF->insert(MBBIter, endMBB);
12003
12004     // Transfer the remainder of MBB and its successor edges to endMBB.
12005     endMBB->splice(endMBB->begin(), thisMBB,
12006                     llvm::next(MachineBasicBlock::iterator(MI)),
12007                     thisMBB->end());
12008     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
12009
12010     // Make offsetMBB and overflowMBB successors of thisMBB
12011     thisMBB->addSuccessor(offsetMBB);
12012     thisMBB->addSuccessor(overflowMBB);
12013
12014     // endMBB is a successor of both offsetMBB and overflowMBB
12015     offsetMBB->addSuccessor(endMBB);
12016     overflowMBB->addSuccessor(endMBB);
12017
12018     // Load the offset value into a register
12019     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12020     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
12021       .addOperand(Base)
12022       .addOperand(Scale)
12023       .addOperand(Index)
12024       .addDisp(Disp, UseFPOffset ? 4 : 0)
12025       .addOperand(Segment)
12026       .setMemRefs(MMOBegin, MMOEnd);
12027
12028     // Check if there is enough room left to pull this argument.
12029     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
12030       .addReg(OffsetReg)
12031       .addImm(MaxOffset + 8 - ArgSizeA8);
12032
12033     // Branch to "overflowMBB" if offset >= max
12034     // Fall through to "offsetMBB" otherwise
12035     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
12036       .addMBB(overflowMBB);
12037   }
12038
12039   // In offsetMBB, emit code to use the reg_save_area.
12040   if (offsetMBB) {
12041     assert(OffsetReg != 0);
12042
12043     // Read the reg_save_area address.
12044     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
12045     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
12046       .addOperand(Base)
12047       .addOperand(Scale)
12048       .addOperand(Index)
12049       .addDisp(Disp, 16)
12050       .addOperand(Segment)
12051       .setMemRefs(MMOBegin, MMOEnd);
12052
12053     // Zero-extend the offset
12054     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
12055       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
12056         .addImm(0)
12057         .addReg(OffsetReg)
12058         .addImm(X86::sub_32bit);
12059
12060     // Add the offset to the reg_save_area to get the final address.
12061     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
12062       .addReg(OffsetReg64)
12063       .addReg(RegSaveReg);
12064
12065     // Compute the offset for the next argument
12066     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12067     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
12068       .addReg(OffsetReg)
12069       .addImm(UseFPOffset ? 16 : 8);
12070
12071     // Store it back into the va_list.
12072     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
12073       .addOperand(Base)
12074       .addOperand(Scale)
12075       .addOperand(Index)
12076       .addDisp(Disp, UseFPOffset ? 4 : 0)
12077       .addOperand(Segment)
12078       .addReg(NextOffsetReg)
12079       .setMemRefs(MMOBegin, MMOEnd);
12080
12081     // Jump to endMBB
12082     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
12083       .addMBB(endMBB);
12084   }
12085
12086   //
12087   // Emit code to use overflow area
12088   //
12089
12090   // Load the overflow_area address into a register.
12091   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
12092   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
12093     .addOperand(Base)
12094     .addOperand(Scale)
12095     .addOperand(Index)
12096     .addDisp(Disp, 8)
12097     .addOperand(Segment)
12098     .setMemRefs(MMOBegin, MMOEnd);
12099
12100   // If we need to align it, do so. Otherwise, just copy the address
12101   // to OverflowDestReg.
12102   if (NeedsAlign) {
12103     // Align the overflow address
12104     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
12105     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
12106
12107     // aligned_addr = (addr + (align-1)) & ~(align-1)
12108     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
12109       .addReg(OverflowAddrReg)
12110       .addImm(Align-1);
12111
12112     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
12113       .addReg(TmpReg)
12114       .addImm(~(uint64_t)(Align-1));
12115   } else {
12116     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
12117       .addReg(OverflowAddrReg);
12118   }
12119
12120   // Compute the next overflow address after this argument.
12121   // (the overflow address should be kept 8-byte aligned)
12122   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
12123   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
12124     .addReg(OverflowDestReg)
12125     .addImm(ArgSizeA8);
12126
12127   // Store the new overflow address.
12128   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
12129     .addOperand(Base)
12130     .addOperand(Scale)
12131     .addOperand(Index)
12132     .addDisp(Disp, 8)
12133     .addOperand(Segment)
12134     .addReg(NextAddrReg)
12135     .setMemRefs(MMOBegin, MMOEnd);
12136
12137   // If we branched, emit the PHI to the front of endMBB.
12138   if (offsetMBB) {
12139     BuildMI(*endMBB, endMBB->begin(), DL,
12140             TII->get(X86::PHI), DestReg)
12141       .addReg(OffsetDestReg).addMBB(offsetMBB)
12142       .addReg(OverflowDestReg).addMBB(overflowMBB);
12143   }
12144
12145   // Erase the pseudo instruction
12146   MI->eraseFromParent();
12147
12148   return endMBB;
12149 }
12150
12151 MachineBasicBlock *
12152 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
12153                                                  MachineInstr *MI,
12154                                                  MachineBasicBlock *MBB) const {
12155   // Emit code to save XMM registers to the stack. The ABI says that the
12156   // number of registers to save is given in %al, so it's theoretically
12157   // possible to do an indirect jump trick to avoid saving all of them,
12158   // however this code takes a simpler approach and just executes all
12159   // of the stores if %al is non-zero. It's less code, and it's probably
12160   // easier on the hardware branch predictor, and stores aren't all that
12161   // expensive anyway.
12162
12163   // Create the new basic blocks. One block contains all the XMM stores,
12164   // and one block is the final destination regardless of whether any
12165   // stores were performed.
12166   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12167   MachineFunction *F = MBB->getParent();
12168   MachineFunction::iterator MBBIter = MBB;
12169   ++MBBIter;
12170   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
12171   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
12172   F->insert(MBBIter, XMMSaveMBB);
12173   F->insert(MBBIter, EndMBB);
12174
12175   // Transfer the remainder of MBB and its successor edges to EndMBB.
12176   EndMBB->splice(EndMBB->begin(), MBB,
12177                  llvm::next(MachineBasicBlock::iterator(MI)),
12178                  MBB->end());
12179   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
12180
12181   // The original block will now fall through to the XMM save block.
12182   MBB->addSuccessor(XMMSaveMBB);
12183   // The XMMSaveMBB will fall through to the end block.
12184   XMMSaveMBB->addSuccessor(EndMBB);
12185
12186   // Now add the instructions.
12187   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12188   DebugLoc DL = MI->getDebugLoc();
12189
12190   unsigned CountReg = MI->getOperand(0).getReg();
12191   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
12192   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
12193
12194   if (!Subtarget->isTargetWin64()) {
12195     // If %al is 0, branch around the XMM save block.
12196     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
12197     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
12198     MBB->addSuccessor(EndMBB);
12199   }
12200
12201   unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
12202   // In the XMM save block, save all the XMM argument registers.
12203   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
12204     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
12205     MachineMemOperand *MMO =
12206       F->getMachineMemOperand(
12207           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
12208         MachineMemOperand::MOStore,
12209         /*Size=*/16, /*Align=*/16);
12210     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
12211       .addFrameIndex(RegSaveFrameIndex)
12212       .addImm(/*Scale=*/1)
12213       .addReg(/*IndexReg=*/0)
12214       .addImm(/*Disp=*/Offset)
12215       .addReg(/*Segment=*/0)
12216       .addReg(MI->getOperand(i).getReg())
12217       .addMemOperand(MMO);
12218   }
12219
12220   MI->eraseFromParent();   // The pseudo instruction is gone now.
12221
12222   return EndMBB;
12223 }
12224
12225 MachineBasicBlock *
12226 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
12227                                      MachineBasicBlock *BB) const {
12228   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12229   DebugLoc DL = MI->getDebugLoc();
12230
12231   // To "insert" a SELECT_CC instruction, we actually have to insert the
12232   // diamond control-flow pattern.  The incoming instruction knows the
12233   // destination vreg to set, the condition code register to branch on, the
12234   // true/false values to select between, and a branch opcode to use.
12235   const BasicBlock *LLVM_BB = BB->getBasicBlock();
12236   MachineFunction::iterator It = BB;
12237   ++It;
12238
12239   //  thisMBB:
12240   //  ...
12241   //   TrueVal = ...
12242   //   cmpTY ccX, r1, r2
12243   //   bCC copy1MBB
12244   //   fallthrough --> copy0MBB
12245   MachineBasicBlock *thisMBB = BB;
12246   MachineFunction *F = BB->getParent();
12247   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
12248   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12249   F->insert(It, copy0MBB);
12250   F->insert(It, sinkMBB);
12251
12252   // If the EFLAGS register isn't dead in the terminator, then claim that it's
12253   // live into the sink and copy blocks.
12254   if (!MI->killsRegister(X86::EFLAGS)) {
12255     copy0MBB->addLiveIn(X86::EFLAGS);
12256     sinkMBB->addLiveIn(X86::EFLAGS);
12257   }
12258
12259   // Transfer the remainder of BB and its successor edges to sinkMBB.
12260   sinkMBB->splice(sinkMBB->begin(), BB,
12261                   llvm::next(MachineBasicBlock::iterator(MI)),
12262                   BB->end());
12263   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12264
12265   // Add the true and fallthrough blocks as its successors.
12266   BB->addSuccessor(copy0MBB);
12267   BB->addSuccessor(sinkMBB);
12268
12269   // Create the conditional branch instruction.
12270   unsigned Opc =
12271     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
12272   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
12273
12274   //  copy0MBB:
12275   //   %FalseValue = ...
12276   //   # fallthrough to sinkMBB
12277   copy0MBB->addSuccessor(sinkMBB);
12278
12279   //  sinkMBB:
12280   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
12281   //  ...
12282   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12283           TII->get(X86::PHI), MI->getOperand(0).getReg())
12284     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
12285     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
12286
12287   MI->eraseFromParent();   // The pseudo instruction is gone now.
12288   return sinkMBB;
12289 }
12290
12291 MachineBasicBlock *
12292 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
12293                                         bool Is64Bit) const {
12294   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12295   DebugLoc DL = MI->getDebugLoc();
12296   MachineFunction *MF = BB->getParent();
12297   const BasicBlock *LLVM_BB = BB->getBasicBlock();
12298
12299   assert(EnableSegmentedStacks);
12300
12301   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
12302   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
12303
12304   // BB:
12305   //  ... [Till the alloca]
12306   // If stacklet is not large enough, jump to mallocMBB
12307   //
12308   // bumpMBB:
12309   //  Allocate by subtracting from RSP
12310   //  Jump to continueMBB
12311   //
12312   // mallocMBB:
12313   //  Allocate by call to runtime
12314   //
12315   // continueMBB:
12316   //  ...
12317   //  [rest of original BB]
12318   //
12319
12320   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12321   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12322   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12323
12324   MachineRegisterInfo &MRI = MF->getRegInfo();
12325   const TargetRegisterClass *AddrRegClass =
12326     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
12327
12328   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12329     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12330     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
12331     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
12332     sizeVReg = MI->getOperand(1).getReg(),
12333     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
12334
12335   MachineFunction::iterator MBBIter = BB;
12336   ++MBBIter;
12337
12338   MF->insert(MBBIter, bumpMBB);
12339   MF->insert(MBBIter, mallocMBB);
12340   MF->insert(MBBIter, continueMBB);
12341
12342   continueMBB->splice(continueMBB->begin(), BB, llvm::next
12343                       (MachineBasicBlock::iterator(MI)), BB->end());
12344   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
12345
12346   // Add code to the main basic block to check if the stack limit has been hit,
12347   // and if so, jump to mallocMBB otherwise to bumpMBB.
12348   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
12349   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
12350     .addReg(tmpSPVReg).addReg(sizeVReg);
12351   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
12352     .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg)
12353     .addReg(SPLimitVReg);
12354   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
12355
12356   // bumpMBB simply decreases the stack pointer, since we know the current
12357   // stacklet has enough space.
12358   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
12359     .addReg(SPLimitVReg);
12360   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
12361     .addReg(SPLimitVReg);
12362   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12363
12364   // Calls into a routine in libgcc to allocate more space from the heap.
12365   if (Is64Bit) {
12366     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
12367       .addReg(sizeVReg);
12368     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
12369     .addExternalSymbol("__morestack_allocate_stack_space").addReg(X86::RDI);
12370   } else {
12371     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
12372       .addImm(12);
12373     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
12374     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
12375       .addExternalSymbol("__morestack_allocate_stack_space");
12376   }
12377
12378   if (!Is64Bit)
12379     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
12380       .addImm(16);
12381
12382   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
12383     .addReg(Is64Bit ? X86::RAX : X86::EAX);
12384   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12385
12386   // Set up the CFG correctly.
12387   BB->addSuccessor(bumpMBB);
12388   BB->addSuccessor(mallocMBB);
12389   mallocMBB->addSuccessor(continueMBB);
12390   bumpMBB->addSuccessor(continueMBB);
12391
12392   // Take care of the PHI nodes.
12393   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
12394           MI->getOperand(0).getReg())
12395     .addReg(mallocPtrVReg).addMBB(mallocMBB)
12396     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
12397
12398   // Delete the original pseudo instruction.
12399   MI->eraseFromParent();
12400
12401   // And we're done.
12402   return continueMBB;
12403 }
12404
12405 MachineBasicBlock *
12406 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
12407                                           MachineBasicBlock *BB) const {
12408   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12409   DebugLoc DL = MI->getDebugLoc();
12410
12411   assert(!Subtarget->isTargetEnvMacho());
12412
12413   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
12414   // non-trivial part is impdef of ESP.
12415
12416   if (Subtarget->isTargetWin64()) {
12417     if (Subtarget->isTargetCygMing()) {
12418       // ___chkstk(Mingw64):
12419       // Clobbers R10, R11, RAX and EFLAGS.
12420       // Updates RSP.
12421       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12422         .addExternalSymbol("___chkstk")
12423         .addReg(X86::RAX, RegState::Implicit)
12424         .addReg(X86::RSP, RegState::Implicit)
12425         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
12426         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
12427         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12428     } else {
12429       // __chkstk(MSVCRT): does not update stack pointer.
12430       // Clobbers R10, R11 and EFLAGS.
12431       // FIXME: RAX(allocated size) might be reused and not killed.
12432       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12433         .addExternalSymbol("__chkstk")
12434         .addReg(X86::RAX, RegState::Implicit)
12435         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12436       // RAX has the offset to subtracted from RSP.
12437       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
12438         .addReg(X86::RSP)
12439         .addReg(X86::RAX);
12440     }
12441   } else {
12442     const char *StackProbeSymbol =
12443       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
12444
12445     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
12446       .addExternalSymbol(StackProbeSymbol)
12447       .addReg(X86::EAX, RegState::Implicit)
12448       .addReg(X86::ESP, RegState::Implicit)
12449       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
12450       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
12451       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12452   }
12453
12454   MI->eraseFromParent();   // The pseudo instruction is gone now.
12455   return BB;
12456 }
12457
12458 MachineBasicBlock *
12459 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
12460                                       MachineBasicBlock *BB) const {
12461   // This is pretty easy.  We're taking the value that we received from
12462   // our load from the relocation, sticking it in either RDI (x86-64)
12463   // or EAX and doing an indirect call.  The return value will then
12464   // be in the normal return register.
12465   const X86InstrInfo *TII
12466     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
12467   DebugLoc DL = MI->getDebugLoc();
12468   MachineFunction *F = BB->getParent();
12469
12470   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
12471   assert(MI->getOperand(3).isGlobal() && "This should be a global");
12472
12473   if (Subtarget->is64Bit()) {
12474     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12475                                       TII->get(X86::MOV64rm), X86::RDI)
12476     .addReg(X86::RIP)
12477     .addImm(0).addReg(0)
12478     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12479                       MI->getOperand(3).getTargetFlags())
12480     .addReg(0);
12481     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
12482     addDirectMem(MIB, X86::RDI);
12483   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
12484     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12485                                       TII->get(X86::MOV32rm), X86::EAX)
12486     .addReg(0)
12487     .addImm(0).addReg(0)
12488     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12489                       MI->getOperand(3).getTargetFlags())
12490     .addReg(0);
12491     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12492     addDirectMem(MIB, X86::EAX);
12493   } else {
12494     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12495                                       TII->get(X86::MOV32rm), X86::EAX)
12496     .addReg(TII->getGlobalBaseReg(F))
12497     .addImm(0).addReg(0)
12498     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12499                       MI->getOperand(3).getTargetFlags())
12500     .addReg(0);
12501     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12502     addDirectMem(MIB, X86::EAX);
12503   }
12504
12505   MI->eraseFromParent(); // The pseudo instruction is gone now.
12506   return BB;
12507 }
12508
12509 MachineBasicBlock *
12510 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
12511                                                MachineBasicBlock *BB) const {
12512   switch (MI->getOpcode()) {
12513   default: assert(0 && "Unexpected instr type to insert");
12514   case X86::TAILJMPd64:
12515   case X86::TAILJMPr64:
12516   case X86::TAILJMPm64:
12517     assert(0 && "TAILJMP64 would not be touched here.");
12518   case X86::TCRETURNdi64:
12519   case X86::TCRETURNri64:
12520   case X86::TCRETURNmi64:
12521     // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset.
12522     // On AMD64, additional defs should be added before register allocation.
12523     if (!Subtarget->isTargetWin64()) {
12524       MI->addRegisterDefined(X86::RSI);
12525       MI->addRegisterDefined(X86::RDI);
12526       MI->addRegisterDefined(X86::XMM6);
12527       MI->addRegisterDefined(X86::XMM7);
12528       MI->addRegisterDefined(X86::XMM8);
12529       MI->addRegisterDefined(X86::XMM9);
12530       MI->addRegisterDefined(X86::XMM10);
12531       MI->addRegisterDefined(X86::XMM11);
12532       MI->addRegisterDefined(X86::XMM12);
12533       MI->addRegisterDefined(X86::XMM13);
12534       MI->addRegisterDefined(X86::XMM14);
12535       MI->addRegisterDefined(X86::XMM15);
12536     }
12537     return BB;
12538   case X86::WIN_ALLOCA:
12539     return EmitLoweredWinAlloca(MI, BB);
12540   case X86::SEG_ALLOCA_32:
12541     return EmitLoweredSegAlloca(MI, BB, false);
12542   case X86::SEG_ALLOCA_64:
12543     return EmitLoweredSegAlloca(MI, BB, true);
12544   case X86::TLSCall_32:
12545   case X86::TLSCall_64:
12546     return EmitLoweredTLSCall(MI, BB);
12547   case X86::CMOV_GR8:
12548   case X86::CMOV_FR32:
12549   case X86::CMOV_FR64:
12550   case X86::CMOV_V4F32:
12551   case X86::CMOV_V2F64:
12552   case X86::CMOV_V2I64:
12553   case X86::CMOV_V8F32:
12554   case X86::CMOV_V4F64:
12555   case X86::CMOV_V4I64:
12556   case X86::CMOV_GR16:
12557   case X86::CMOV_GR32:
12558   case X86::CMOV_RFP32:
12559   case X86::CMOV_RFP64:
12560   case X86::CMOV_RFP80:
12561     return EmitLoweredSelect(MI, BB);
12562
12563   case X86::FP32_TO_INT16_IN_MEM:
12564   case X86::FP32_TO_INT32_IN_MEM:
12565   case X86::FP32_TO_INT64_IN_MEM:
12566   case X86::FP64_TO_INT16_IN_MEM:
12567   case X86::FP64_TO_INT32_IN_MEM:
12568   case X86::FP64_TO_INT64_IN_MEM:
12569   case X86::FP80_TO_INT16_IN_MEM:
12570   case X86::FP80_TO_INT32_IN_MEM:
12571   case X86::FP80_TO_INT64_IN_MEM: {
12572     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12573     DebugLoc DL = MI->getDebugLoc();
12574
12575     // Change the floating point control register to use "round towards zero"
12576     // mode when truncating to an integer value.
12577     MachineFunction *F = BB->getParent();
12578     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
12579     addFrameReference(BuildMI(*BB, MI, DL,
12580                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
12581
12582     // Load the old value of the high byte of the control word...
12583     unsigned OldCW =
12584       F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
12585     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
12586                       CWFrameIdx);
12587
12588     // Set the high part to be round to zero...
12589     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
12590       .addImm(0xC7F);
12591
12592     // Reload the modified control word now...
12593     addFrameReference(BuildMI(*BB, MI, DL,
12594                               TII->get(X86::FLDCW16m)), CWFrameIdx);
12595
12596     // Restore the memory image of control word to original value
12597     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
12598       .addReg(OldCW);
12599
12600     // Get the X86 opcode to use.
12601     unsigned Opc;
12602     switch (MI->getOpcode()) {
12603     default: llvm_unreachable("illegal opcode!");
12604     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
12605     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
12606     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
12607     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
12608     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
12609     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
12610     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
12611     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
12612     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
12613     }
12614
12615     X86AddressMode AM;
12616     MachineOperand &Op = MI->getOperand(0);
12617     if (Op.isReg()) {
12618       AM.BaseType = X86AddressMode::RegBase;
12619       AM.Base.Reg = Op.getReg();
12620     } else {
12621       AM.BaseType = X86AddressMode::FrameIndexBase;
12622       AM.Base.FrameIndex = Op.getIndex();
12623     }
12624     Op = MI->getOperand(1);
12625     if (Op.isImm())
12626       AM.Scale = Op.getImm();
12627     Op = MI->getOperand(2);
12628     if (Op.isImm())
12629       AM.IndexReg = Op.getImm();
12630     Op = MI->getOperand(3);
12631     if (Op.isGlobal()) {
12632       AM.GV = Op.getGlobal();
12633     } else {
12634       AM.Disp = Op.getImm();
12635     }
12636     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
12637                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
12638
12639     // Reload the original control word now.
12640     addFrameReference(BuildMI(*BB, MI, DL,
12641                               TII->get(X86::FLDCW16m)), CWFrameIdx);
12642
12643     MI->eraseFromParent();   // The pseudo instruction is gone now.
12644     return BB;
12645   }
12646     // String/text processing lowering.
12647   case X86::PCMPISTRM128REG:
12648   case X86::VPCMPISTRM128REG:
12649     return EmitPCMP(MI, BB, 3, false /* in-mem */);
12650   case X86::PCMPISTRM128MEM:
12651   case X86::VPCMPISTRM128MEM:
12652     return EmitPCMP(MI, BB, 3, true /* in-mem */);
12653   case X86::PCMPESTRM128REG:
12654   case X86::VPCMPESTRM128REG:
12655     return EmitPCMP(MI, BB, 5, false /* in mem */);
12656   case X86::PCMPESTRM128MEM:
12657   case X86::VPCMPESTRM128MEM:
12658     return EmitPCMP(MI, BB, 5, true /* in mem */);
12659
12660     // Thread synchronization.
12661   case X86::MONITOR:
12662     return EmitMonitor(MI, BB);
12663   case X86::MWAIT:
12664     return EmitMwait(MI, BB);
12665
12666     // Atomic Lowering.
12667   case X86::ATOMAND32:
12668     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12669                                                X86::AND32ri, X86::MOV32rm,
12670                                                X86::LCMPXCHG32,
12671                                                X86::NOT32r, X86::EAX,
12672                                                X86::GR32RegisterClass);
12673   case X86::ATOMOR32:
12674     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
12675                                                X86::OR32ri, X86::MOV32rm,
12676                                                X86::LCMPXCHG32,
12677                                                X86::NOT32r, X86::EAX,
12678                                                X86::GR32RegisterClass);
12679   case X86::ATOMXOR32:
12680     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
12681                                                X86::XOR32ri, X86::MOV32rm,
12682                                                X86::LCMPXCHG32,
12683                                                X86::NOT32r, X86::EAX,
12684                                                X86::GR32RegisterClass);
12685   case X86::ATOMNAND32:
12686     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12687                                                X86::AND32ri, X86::MOV32rm,
12688                                                X86::LCMPXCHG32,
12689                                                X86::NOT32r, X86::EAX,
12690                                                X86::GR32RegisterClass, true);
12691   case X86::ATOMMIN32:
12692     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
12693   case X86::ATOMMAX32:
12694     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
12695   case X86::ATOMUMIN32:
12696     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
12697   case X86::ATOMUMAX32:
12698     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
12699
12700   case X86::ATOMAND16:
12701     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12702                                                X86::AND16ri, X86::MOV16rm,
12703                                                X86::LCMPXCHG16,
12704                                                X86::NOT16r, X86::AX,
12705                                                X86::GR16RegisterClass);
12706   case X86::ATOMOR16:
12707     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
12708                                                X86::OR16ri, X86::MOV16rm,
12709                                                X86::LCMPXCHG16,
12710                                                X86::NOT16r, X86::AX,
12711                                                X86::GR16RegisterClass);
12712   case X86::ATOMXOR16:
12713     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
12714                                                X86::XOR16ri, X86::MOV16rm,
12715                                                X86::LCMPXCHG16,
12716                                                X86::NOT16r, X86::AX,
12717                                                X86::GR16RegisterClass);
12718   case X86::ATOMNAND16:
12719     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12720                                                X86::AND16ri, X86::MOV16rm,
12721                                                X86::LCMPXCHG16,
12722                                                X86::NOT16r, X86::AX,
12723                                                X86::GR16RegisterClass, true);
12724   case X86::ATOMMIN16:
12725     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
12726   case X86::ATOMMAX16:
12727     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
12728   case X86::ATOMUMIN16:
12729     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
12730   case X86::ATOMUMAX16:
12731     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
12732
12733   case X86::ATOMAND8:
12734     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12735                                                X86::AND8ri, X86::MOV8rm,
12736                                                X86::LCMPXCHG8,
12737                                                X86::NOT8r, X86::AL,
12738                                                X86::GR8RegisterClass);
12739   case X86::ATOMOR8:
12740     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
12741                                                X86::OR8ri, X86::MOV8rm,
12742                                                X86::LCMPXCHG8,
12743                                                X86::NOT8r, X86::AL,
12744                                                X86::GR8RegisterClass);
12745   case X86::ATOMXOR8:
12746     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
12747                                                X86::XOR8ri, X86::MOV8rm,
12748                                                X86::LCMPXCHG8,
12749                                                X86::NOT8r, X86::AL,
12750                                                X86::GR8RegisterClass);
12751   case X86::ATOMNAND8:
12752     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12753                                                X86::AND8ri, X86::MOV8rm,
12754                                                X86::LCMPXCHG8,
12755                                                X86::NOT8r, X86::AL,
12756                                                X86::GR8RegisterClass, true);
12757   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
12758   // This group is for 64-bit host.
12759   case X86::ATOMAND64:
12760     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12761                                                X86::AND64ri32, X86::MOV64rm,
12762                                                X86::LCMPXCHG64,
12763                                                X86::NOT64r, X86::RAX,
12764                                                X86::GR64RegisterClass);
12765   case X86::ATOMOR64:
12766     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
12767                                                X86::OR64ri32, X86::MOV64rm,
12768                                                X86::LCMPXCHG64,
12769                                                X86::NOT64r, X86::RAX,
12770                                                X86::GR64RegisterClass);
12771   case X86::ATOMXOR64:
12772     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
12773                                                X86::XOR64ri32, X86::MOV64rm,
12774                                                X86::LCMPXCHG64,
12775                                                X86::NOT64r, X86::RAX,
12776                                                X86::GR64RegisterClass);
12777   case X86::ATOMNAND64:
12778     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12779                                                X86::AND64ri32, X86::MOV64rm,
12780                                                X86::LCMPXCHG64,
12781                                                X86::NOT64r, X86::RAX,
12782                                                X86::GR64RegisterClass, true);
12783   case X86::ATOMMIN64:
12784     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
12785   case X86::ATOMMAX64:
12786     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
12787   case X86::ATOMUMIN64:
12788     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
12789   case X86::ATOMUMAX64:
12790     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
12791
12792   // This group does 64-bit operations on a 32-bit host.
12793   case X86::ATOMAND6432:
12794     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12795                                                X86::AND32rr, X86::AND32rr,
12796                                                X86::AND32ri, X86::AND32ri,
12797                                                false);
12798   case X86::ATOMOR6432:
12799     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12800                                                X86::OR32rr, X86::OR32rr,
12801                                                X86::OR32ri, X86::OR32ri,
12802                                                false);
12803   case X86::ATOMXOR6432:
12804     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12805                                                X86::XOR32rr, X86::XOR32rr,
12806                                                X86::XOR32ri, X86::XOR32ri,
12807                                                false);
12808   case X86::ATOMNAND6432:
12809     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12810                                                X86::AND32rr, X86::AND32rr,
12811                                                X86::AND32ri, X86::AND32ri,
12812                                                true);
12813   case X86::ATOMADD6432:
12814     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12815                                                X86::ADD32rr, X86::ADC32rr,
12816                                                X86::ADD32ri, X86::ADC32ri,
12817                                                false);
12818   case X86::ATOMSUB6432:
12819     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12820                                                X86::SUB32rr, X86::SBB32rr,
12821                                                X86::SUB32ri, X86::SBB32ri,
12822                                                false);
12823   case X86::ATOMSWAP6432:
12824     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12825                                                X86::MOV32rr, X86::MOV32rr,
12826                                                X86::MOV32ri, X86::MOV32ri,
12827                                                false);
12828   case X86::VASTART_SAVE_XMM_REGS:
12829     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
12830
12831   case X86::VAARG_64:
12832     return EmitVAARG64WithCustomInserter(MI, BB);
12833   }
12834 }
12835
12836 //===----------------------------------------------------------------------===//
12837 //                           X86 Optimization Hooks
12838 //===----------------------------------------------------------------------===//
12839
12840 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
12841                                                        const APInt &Mask,
12842                                                        APInt &KnownZero,
12843                                                        APInt &KnownOne,
12844                                                        const SelectionDAG &DAG,
12845                                                        unsigned Depth) const {
12846   unsigned Opc = Op.getOpcode();
12847   assert((Opc >= ISD::BUILTIN_OP_END ||
12848           Opc == ISD::INTRINSIC_WO_CHAIN ||
12849           Opc == ISD::INTRINSIC_W_CHAIN ||
12850           Opc == ISD::INTRINSIC_VOID) &&
12851          "Should use MaskedValueIsZero if you don't know whether Op"
12852          " is a target node!");
12853
12854   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
12855   switch (Opc) {
12856   default: break;
12857   case X86ISD::ADD:
12858   case X86ISD::SUB:
12859   case X86ISD::ADC:
12860   case X86ISD::SBB:
12861   case X86ISD::SMUL:
12862   case X86ISD::UMUL:
12863   case X86ISD::INC:
12864   case X86ISD::DEC:
12865   case X86ISD::OR:
12866   case X86ISD::XOR:
12867   case X86ISD::AND:
12868     // These nodes' second result is a boolean.
12869     if (Op.getResNo() == 0)
12870       break;
12871     // Fallthrough
12872   case X86ISD::SETCC:
12873     KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
12874                                        Mask.getBitWidth() - 1);
12875     break;
12876   case ISD::INTRINSIC_WO_CHAIN: {
12877     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12878     unsigned NumLoBits = 0;
12879     switch (IntId) {
12880     default: break;
12881     case Intrinsic::x86_sse_movmsk_ps:
12882     case Intrinsic::x86_avx_movmsk_ps_256:
12883     case Intrinsic::x86_sse2_movmsk_pd:
12884     case Intrinsic::x86_avx_movmsk_pd_256:
12885     case Intrinsic::x86_mmx_pmovmskb:
12886     case Intrinsic::x86_sse2_pmovmskb_128: {
12887       // High bits of movmskp{s|d}, pmovmskb are known zero.
12888       switch (IntId) {
12889         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
12890         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
12891         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
12892         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
12893         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
12894         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
12895       }
12896       KnownZero = APInt::getHighBitsSet(Mask.getBitWidth(),
12897                                         Mask.getBitWidth() - NumLoBits);
12898       break;
12899     }
12900     }
12901     break;
12902   }
12903   }
12904 }
12905
12906 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
12907                                                          unsigned Depth) const {
12908   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
12909   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
12910     return Op.getValueType().getScalarType().getSizeInBits();
12911
12912   // Fallback case.
12913   return 1;
12914 }
12915
12916 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
12917 /// node is a GlobalAddress + offset.
12918 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
12919                                        const GlobalValue* &GA,
12920                                        int64_t &Offset) const {
12921   if (N->getOpcode() == X86ISD::Wrapper) {
12922     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
12923       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
12924       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
12925       return true;
12926     }
12927   }
12928   return TargetLowering::isGAPlusOffset(N, GA, Offset);
12929 }
12930
12931 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
12932 /// same as extracting the high 128-bit part of 256-bit vector and then
12933 /// inserting the result into the low part of a new 256-bit vector
12934 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
12935   EVT VT = SVOp->getValueType(0);
12936   int NumElems = VT.getVectorNumElements();
12937
12938   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
12939   for (int i = 0, j = NumElems/2; i < NumElems/2; ++i, ++j)
12940     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12941         SVOp->getMaskElt(j) >= 0)
12942       return false;
12943
12944   return true;
12945 }
12946
12947 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
12948 /// same as extracting the low 128-bit part of 256-bit vector and then
12949 /// inserting the result into the high part of a new 256-bit vector
12950 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
12951   EVT VT = SVOp->getValueType(0);
12952   int NumElems = VT.getVectorNumElements();
12953
12954   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
12955   for (int i = NumElems/2, j = 0; i < NumElems; ++i, ++j)
12956     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12957         SVOp->getMaskElt(j) >= 0)
12958       return false;
12959
12960   return true;
12961 }
12962
12963 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
12964 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
12965                                         TargetLowering::DAGCombinerInfo &DCI) {
12966   DebugLoc dl = N->getDebugLoc();
12967   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
12968   SDValue V1 = SVOp->getOperand(0);
12969   SDValue V2 = SVOp->getOperand(1);
12970   EVT VT = SVOp->getValueType(0);
12971   int NumElems = VT.getVectorNumElements();
12972
12973   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
12974       V2.getOpcode() == ISD::CONCAT_VECTORS) {
12975     //
12976     //                   0,0,0,...
12977     //                      |
12978     //    V      UNDEF    BUILD_VECTOR    UNDEF
12979     //     \      /           \           /
12980     //  CONCAT_VECTOR         CONCAT_VECTOR
12981     //         \                  /
12982     //          \                /
12983     //          RESULT: V + zero extended
12984     //
12985     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
12986         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
12987         V1.getOperand(1).getOpcode() != ISD::UNDEF)
12988       return SDValue();
12989
12990     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
12991       return SDValue();
12992
12993     // To match the shuffle mask, the first half of the mask should
12994     // be exactly the first vector, and all the rest a splat with the
12995     // first element of the second one.
12996     for (int i = 0; i < NumElems/2; ++i)
12997       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
12998           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
12999         return SDValue();
13000
13001     // Emit a zeroed vector and insert the desired subvector on its
13002     // first half.
13003     SDValue Zeros = getZeroVector(VT, true /* HasXMMInt */, DAG, dl);
13004     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0),
13005                          DAG.getConstant(0, MVT::i32), DAG, dl);
13006     return DCI.CombineTo(N, InsV);
13007   }
13008
13009   //===--------------------------------------------------------------------===//
13010   // Combine some shuffles into subvector extracts and inserts:
13011   //
13012
13013   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13014   if (isShuffleHigh128VectorInsertLow(SVOp)) {
13015     SDValue V = Extract128BitVector(V1, DAG.getConstant(NumElems/2, MVT::i32),
13016                                     DAG, dl);
13017     SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT),
13018                                       V, DAG.getConstant(0, MVT::i32), DAG, dl);
13019     return DCI.CombineTo(N, InsV);
13020   }
13021
13022   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13023   if (isShuffleLow128VectorInsertHigh(SVOp)) {
13024     SDValue V = Extract128BitVector(V1, DAG.getConstant(0, MVT::i32), DAG, dl);
13025     SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT),
13026                              V, DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
13027     return DCI.CombineTo(N, InsV);
13028   }
13029
13030   return SDValue();
13031 }
13032
13033 /// PerformShuffleCombine - Performs several different shuffle combines.
13034 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
13035                                      TargetLowering::DAGCombinerInfo &DCI,
13036                                      const X86Subtarget *Subtarget) {
13037   DebugLoc dl = N->getDebugLoc();
13038   EVT VT = N->getValueType(0);
13039
13040   // Don't create instructions with illegal types after legalize types has run.
13041   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13042   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
13043     return SDValue();
13044
13045   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
13046   if (Subtarget->hasAVX() && VT.getSizeInBits() == 256 &&
13047       N->getOpcode() == ISD::VECTOR_SHUFFLE)
13048     return PerformShuffleCombine256(N, DAG, DCI);
13049
13050   // Only handle 128 wide vector from here on.
13051   if (VT.getSizeInBits() != 128)
13052     return SDValue();
13053
13054   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
13055   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
13056   // consecutive, non-overlapping, and in the right order.
13057   SmallVector<SDValue, 16> Elts;
13058   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
13059     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
13060
13061   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
13062 }
13063
13064 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
13065 /// generation and convert it from being a bunch of shuffles and extracts
13066 /// to a simple store and scalar loads to extract the elements.
13067 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
13068                                                 const TargetLowering &TLI) {
13069   SDValue InputVector = N->getOperand(0);
13070
13071   // Only operate on vectors of 4 elements, where the alternative shuffling
13072   // gets to be more expensive.
13073   if (InputVector.getValueType() != MVT::v4i32)
13074     return SDValue();
13075
13076   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
13077   // single use which is a sign-extend or zero-extend, and all elements are
13078   // used.
13079   SmallVector<SDNode *, 4> Uses;
13080   unsigned ExtractedElements = 0;
13081   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
13082        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
13083     if (UI.getUse().getResNo() != InputVector.getResNo())
13084       return SDValue();
13085
13086     SDNode *Extract = *UI;
13087     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13088       return SDValue();
13089
13090     if (Extract->getValueType(0) != MVT::i32)
13091       return SDValue();
13092     if (!Extract->hasOneUse())
13093       return SDValue();
13094     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
13095         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
13096       return SDValue();
13097     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
13098       return SDValue();
13099
13100     // Record which element was extracted.
13101     ExtractedElements |=
13102       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
13103
13104     Uses.push_back(Extract);
13105   }
13106
13107   // If not all the elements were used, this may not be worthwhile.
13108   if (ExtractedElements != 15)
13109     return SDValue();
13110
13111   // Ok, we've now decided to do the transformation.
13112   DebugLoc dl = InputVector.getDebugLoc();
13113
13114   // Store the value to a temporary stack slot.
13115   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
13116   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
13117                             MachinePointerInfo(), false, false, 0);
13118
13119   // Replace each use (extract) with a load of the appropriate element.
13120   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
13121        UE = Uses.end(); UI != UE; ++UI) {
13122     SDNode *Extract = *UI;
13123
13124     // cOMpute the element's address.
13125     SDValue Idx = Extract->getOperand(1);
13126     unsigned EltSize =
13127         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
13128     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
13129     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
13130
13131     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
13132                                      StackPtr, OffsetVal);
13133
13134     // Load the scalar.
13135     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
13136                                      ScalarAddr, MachinePointerInfo(),
13137                                      false, false, false, 0);
13138
13139     // Replace the exact with the load.
13140     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
13141   }
13142
13143   // The replacement was made in place; don't return anything.
13144   return SDValue();
13145 }
13146
13147 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
13148 /// nodes.
13149 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
13150                                     const X86Subtarget *Subtarget) {
13151   DebugLoc DL = N->getDebugLoc();
13152   SDValue Cond = N->getOperand(0);
13153   // Get the LHS/RHS of the select.
13154   SDValue LHS = N->getOperand(1);
13155   SDValue RHS = N->getOperand(2);
13156   EVT VT = LHS.getValueType();
13157
13158   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
13159   // instructions match the semantics of the common C idiom x<y?x:y but not
13160   // x<=y?x:y, because of how they handle negative zero (which can be
13161   // ignored in unsafe-math mode).
13162   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
13163       VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
13164       (Subtarget->hasXMMInt() ||
13165        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
13166     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
13167
13168     unsigned Opcode = 0;
13169     // Check for x CC y ? x : y.
13170     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
13171         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
13172       switch (CC) {
13173       default: break;
13174       case ISD::SETULT:
13175         // Converting this to a min would handle NaNs incorrectly, and swapping
13176         // the operands would cause it to handle comparisons between positive
13177         // and negative zero incorrectly.
13178         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13179           if (!UnsafeFPMath &&
13180               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13181             break;
13182           std::swap(LHS, RHS);
13183         }
13184         Opcode = X86ISD::FMIN;
13185         break;
13186       case ISD::SETOLE:
13187         // Converting this to a min would handle comparisons between positive
13188         // and negative zero incorrectly.
13189         if (!UnsafeFPMath &&
13190             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13191           break;
13192         Opcode = X86ISD::FMIN;
13193         break;
13194       case ISD::SETULE:
13195         // Converting this to a min would handle both negative zeros and NaNs
13196         // incorrectly, but we can swap the operands to fix both.
13197         std::swap(LHS, RHS);
13198       case ISD::SETOLT:
13199       case ISD::SETLT:
13200       case ISD::SETLE:
13201         Opcode = X86ISD::FMIN;
13202         break;
13203
13204       case ISD::SETOGE:
13205         // Converting this to a max would handle comparisons between positive
13206         // and negative zero incorrectly.
13207         if (!UnsafeFPMath &&
13208             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13209           break;
13210         Opcode = X86ISD::FMAX;
13211         break;
13212       case ISD::SETUGT:
13213         // Converting this to a max would handle NaNs incorrectly, and swapping
13214         // the operands would cause it to handle comparisons between positive
13215         // and negative zero incorrectly.
13216         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13217           if (!UnsafeFPMath &&
13218               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13219             break;
13220           std::swap(LHS, RHS);
13221         }
13222         Opcode = X86ISD::FMAX;
13223         break;
13224       case ISD::SETUGE:
13225         // Converting this to a max would handle both negative zeros and NaNs
13226         // incorrectly, but we can swap the operands to fix both.
13227         std::swap(LHS, RHS);
13228       case ISD::SETOGT:
13229       case ISD::SETGT:
13230       case ISD::SETGE:
13231         Opcode = X86ISD::FMAX;
13232         break;
13233       }
13234     // Check for x CC y ? y : x -- a min/max with reversed arms.
13235     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
13236                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
13237       switch (CC) {
13238       default: break;
13239       case ISD::SETOGE:
13240         // Converting this to a min would handle comparisons between positive
13241         // and negative zero incorrectly, and swapping the operands would
13242         // cause it to handle NaNs incorrectly.
13243         if (!UnsafeFPMath &&
13244             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
13245           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13246             break;
13247           std::swap(LHS, RHS);
13248         }
13249         Opcode = X86ISD::FMIN;
13250         break;
13251       case ISD::SETUGT:
13252         // Converting this to a min would handle NaNs incorrectly.
13253         if (!UnsafeFPMath &&
13254             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
13255           break;
13256         Opcode = X86ISD::FMIN;
13257         break;
13258       case ISD::SETUGE:
13259         // Converting this to a min would handle both negative zeros and NaNs
13260         // incorrectly, but we can swap the operands to fix both.
13261         std::swap(LHS, RHS);
13262       case ISD::SETOGT:
13263       case ISD::SETGT:
13264       case ISD::SETGE:
13265         Opcode = X86ISD::FMIN;
13266         break;
13267
13268       case ISD::SETULT:
13269         // Converting this to a max would handle NaNs incorrectly.
13270         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13271           break;
13272         Opcode = X86ISD::FMAX;
13273         break;
13274       case ISD::SETOLE:
13275         // Converting this to a max would handle comparisons between positive
13276         // and negative zero incorrectly, and swapping the operands would
13277         // cause it to handle NaNs incorrectly.
13278         if (!UnsafeFPMath &&
13279             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
13280           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13281             break;
13282           std::swap(LHS, RHS);
13283         }
13284         Opcode = X86ISD::FMAX;
13285         break;
13286       case ISD::SETULE:
13287         // Converting this to a max would handle both negative zeros and NaNs
13288         // incorrectly, but we can swap the operands to fix both.
13289         std::swap(LHS, RHS);
13290       case ISD::SETOLT:
13291       case ISD::SETLT:
13292       case ISD::SETLE:
13293         Opcode = X86ISD::FMAX;
13294         break;
13295       }
13296     }
13297
13298     if (Opcode)
13299       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
13300   }
13301
13302   // If this is a select between two integer constants, try to do some
13303   // optimizations.
13304   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
13305     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
13306       // Don't do this for crazy integer types.
13307       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
13308         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
13309         // so that TrueC (the true value) is larger than FalseC.
13310         bool NeedsCondInvert = false;
13311
13312         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
13313             // Efficiently invertible.
13314             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
13315              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
13316               isa<ConstantSDNode>(Cond.getOperand(1))))) {
13317           NeedsCondInvert = true;
13318           std::swap(TrueC, FalseC);
13319         }
13320
13321         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
13322         if (FalseC->getAPIntValue() == 0 &&
13323             TrueC->getAPIntValue().isPowerOf2()) {
13324           if (NeedsCondInvert) // Invert the condition if needed.
13325             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13326                                DAG.getConstant(1, Cond.getValueType()));
13327
13328           // Zero extend the condition if needed.
13329           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
13330
13331           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13332           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
13333                              DAG.getConstant(ShAmt, MVT::i8));
13334         }
13335
13336         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
13337         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13338           if (NeedsCondInvert) // Invert the condition if needed.
13339             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13340                                DAG.getConstant(1, Cond.getValueType()));
13341
13342           // Zero extend the condition if needed.
13343           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13344                              FalseC->getValueType(0), Cond);
13345           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13346                              SDValue(FalseC, 0));
13347         }
13348
13349         // Optimize cases that will turn into an LEA instruction.  This requires
13350         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13351         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13352           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13353           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13354
13355           bool isFastMultiplier = false;
13356           if (Diff < 10) {
13357             switch ((unsigned char)Diff) {
13358               default: break;
13359               case 1:  // result = add base, cond
13360               case 2:  // result = lea base(    , cond*2)
13361               case 3:  // result = lea base(cond, cond*2)
13362               case 4:  // result = lea base(    , cond*4)
13363               case 5:  // result = lea base(cond, cond*4)
13364               case 8:  // result = lea base(    , cond*8)
13365               case 9:  // result = lea base(cond, cond*8)
13366                 isFastMultiplier = true;
13367                 break;
13368             }
13369           }
13370
13371           if (isFastMultiplier) {
13372             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13373             if (NeedsCondInvert) // Invert the condition if needed.
13374               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13375                                  DAG.getConstant(1, Cond.getValueType()));
13376
13377             // Zero extend the condition if needed.
13378             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13379                                Cond);
13380             // Scale the condition by the difference.
13381             if (Diff != 1)
13382               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13383                                  DAG.getConstant(Diff, Cond.getValueType()));
13384
13385             // Add the base if non-zero.
13386             if (FalseC->getAPIntValue() != 0)
13387               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13388                                  SDValue(FalseC, 0));
13389             return Cond;
13390           }
13391         }
13392       }
13393   }
13394
13395   return SDValue();
13396 }
13397
13398 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
13399 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
13400                                   TargetLowering::DAGCombinerInfo &DCI) {
13401   DebugLoc DL = N->getDebugLoc();
13402
13403   // If the flag operand isn't dead, don't touch this CMOV.
13404   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
13405     return SDValue();
13406
13407   SDValue FalseOp = N->getOperand(0);
13408   SDValue TrueOp = N->getOperand(1);
13409   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
13410   SDValue Cond = N->getOperand(3);
13411   if (CC == X86::COND_E || CC == X86::COND_NE) {
13412     switch (Cond.getOpcode()) {
13413     default: break;
13414     case X86ISD::BSR:
13415     case X86ISD::BSF:
13416       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
13417       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
13418         return (CC == X86::COND_E) ? FalseOp : TrueOp;
13419     }
13420   }
13421
13422   // If this is a select between two integer constants, try to do some
13423   // optimizations.  Note that the operands are ordered the opposite of SELECT
13424   // operands.
13425   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
13426     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
13427       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
13428       // larger than FalseC (the false value).
13429       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
13430         CC = X86::GetOppositeBranchCondition(CC);
13431         std::swap(TrueC, FalseC);
13432       }
13433
13434       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
13435       // This is efficient for any integer data type (including i8/i16) and
13436       // shift amount.
13437       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
13438         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13439                            DAG.getConstant(CC, MVT::i8), Cond);
13440
13441         // Zero extend the condition if needed.
13442         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
13443
13444         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13445         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
13446                            DAG.getConstant(ShAmt, MVT::i8));
13447         if (N->getNumValues() == 2)  // Dead flag value?
13448           return DCI.CombineTo(N, Cond, SDValue());
13449         return Cond;
13450       }
13451
13452       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
13453       // for any integer data type, including i8/i16.
13454       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13455         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13456                            DAG.getConstant(CC, MVT::i8), Cond);
13457
13458         // Zero extend the condition if needed.
13459         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13460                            FalseC->getValueType(0), Cond);
13461         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13462                            SDValue(FalseC, 0));
13463
13464         if (N->getNumValues() == 2)  // Dead flag value?
13465           return DCI.CombineTo(N, Cond, SDValue());
13466         return Cond;
13467       }
13468
13469       // Optimize cases that will turn into an LEA instruction.  This requires
13470       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13471       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13472         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13473         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13474
13475         bool isFastMultiplier = false;
13476         if (Diff < 10) {
13477           switch ((unsigned char)Diff) {
13478           default: break;
13479           case 1:  // result = add base, cond
13480           case 2:  // result = lea base(    , cond*2)
13481           case 3:  // result = lea base(cond, cond*2)
13482           case 4:  // result = lea base(    , cond*4)
13483           case 5:  // result = lea base(cond, cond*4)
13484           case 8:  // result = lea base(    , cond*8)
13485           case 9:  // result = lea base(cond, cond*8)
13486             isFastMultiplier = true;
13487             break;
13488           }
13489         }
13490
13491         if (isFastMultiplier) {
13492           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13493           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13494                              DAG.getConstant(CC, MVT::i8), Cond);
13495           // Zero extend the condition if needed.
13496           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13497                              Cond);
13498           // Scale the condition by the difference.
13499           if (Diff != 1)
13500             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13501                                DAG.getConstant(Diff, Cond.getValueType()));
13502
13503           // Add the base if non-zero.
13504           if (FalseC->getAPIntValue() != 0)
13505             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13506                                SDValue(FalseC, 0));
13507           if (N->getNumValues() == 2)  // Dead flag value?
13508             return DCI.CombineTo(N, Cond, SDValue());
13509           return Cond;
13510         }
13511       }
13512     }
13513   }
13514   return SDValue();
13515 }
13516
13517
13518 /// PerformMulCombine - Optimize a single multiply with constant into two
13519 /// in order to implement it with two cheaper instructions, e.g.
13520 /// LEA + SHL, LEA + LEA.
13521 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
13522                                  TargetLowering::DAGCombinerInfo &DCI) {
13523   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
13524     return SDValue();
13525
13526   EVT VT = N->getValueType(0);
13527   if (VT != MVT::i64)
13528     return SDValue();
13529
13530   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
13531   if (!C)
13532     return SDValue();
13533   uint64_t MulAmt = C->getZExtValue();
13534   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
13535     return SDValue();
13536
13537   uint64_t MulAmt1 = 0;
13538   uint64_t MulAmt2 = 0;
13539   if ((MulAmt % 9) == 0) {
13540     MulAmt1 = 9;
13541     MulAmt2 = MulAmt / 9;
13542   } else if ((MulAmt % 5) == 0) {
13543     MulAmt1 = 5;
13544     MulAmt2 = MulAmt / 5;
13545   } else if ((MulAmt % 3) == 0) {
13546     MulAmt1 = 3;
13547     MulAmt2 = MulAmt / 3;
13548   }
13549   if (MulAmt2 &&
13550       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
13551     DebugLoc DL = N->getDebugLoc();
13552
13553     if (isPowerOf2_64(MulAmt2) &&
13554         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
13555       // If second multiplifer is pow2, issue it first. We want the multiply by
13556       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
13557       // is an add.
13558       std::swap(MulAmt1, MulAmt2);
13559
13560     SDValue NewMul;
13561     if (isPowerOf2_64(MulAmt1))
13562       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
13563                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
13564     else
13565       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
13566                            DAG.getConstant(MulAmt1, VT));
13567
13568     if (isPowerOf2_64(MulAmt2))
13569       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
13570                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
13571     else
13572       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
13573                            DAG.getConstant(MulAmt2, VT));
13574
13575     // Do not add new nodes to DAG combiner worklist.
13576     DCI.CombineTo(N, NewMul, false);
13577   }
13578   return SDValue();
13579 }
13580
13581 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
13582   SDValue N0 = N->getOperand(0);
13583   SDValue N1 = N->getOperand(1);
13584   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
13585   EVT VT = N0.getValueType();
13586
13587   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
13588   // since the result of setcc_c is all zero's or all ones.
13589   if (VT.isInteger() && !VT.isVector() &&
13590       N1C && N0.getOpcode() == ISD::AND &&
13591       N0.getOperand(1).getOpcode() == ISD::Constant) {
13592     SDValue N00 = N0.getOperand(0);
13593     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
13594         ((N00.getOpcode() == ISD::ANY_EXTEND ||
13595           N00.getOpcode() == ISD::ZERO_EXTEND) &&
13596          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
13597       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
13598       APInt ShAmt = N1C->getAPIntValue();
13599       Mask = Mask.shl(ShAmt);
13600       if (Mask != 0)
13601         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
13602                            N00, DAG.getConstant(Mask, VT));
13603     }
13604   }
13605
13606
13607   // Hardware support for vector shifts is sparse which makes us scalarize the
13608   // vector operations in many cases. Also, on sandybridge ADD is faster than
13609   // shl.
13610   // (shl V, 1) -> add V,V
13611   if (isSplatVector(N1.getNode())) {
13612     assert(N0.getValueType().isVector() && "Invalid vector shift type");
13613     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
13614     // We shift all of the values by one. In many cases we do not have
13615     // hardware support for this operation. This is better expressed as an ADD
13616     // of two values.
13617     if (N1C && (1 == N1C->getZExtValue())) {
13618       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
13619     }
13620   }
13621
13622   return SDValue();
13623 }
13624
13625 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
13626 ///                       when possible.
13627 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
13628                                    const X86Subtarget *Subtarget) {
13629   EVT VT = N->getValueType(0);
13630   if (N->getOpcode() == ISD::SHL) {
13631     SDValue V = PerformSHLCombine(N, DAG);
13632     if (V.getNode()) return V;
13633   }
13634
13635   // On X86 with SSE2 support, we can transform this to a vector shift if
13636   // all elements are shifted by the same amount.  We can't do this in legalize
13637   // because the a constant vector is typically transformed to a constant pool
13638   // so we have no knowledge of the shift amount.
13639   if (!Subtarget->hasXMMInt())
13640     return SDValue();
13641
13642   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
13643       (!Subtarget->hasAVX2() ||
13644        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
13645     return SDValue();
13646
13647   SDValue ShAmtOp = N->getOperand(1);
13648   EVT EltVT = VT.getVectorElementType();
13649   DebugLoc DL = N->getDebugLoc();
13650   SDValue BaseShAmt = SDValue();
13651   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
13652     unsigned NumElts = VT.getVectorNumElements();
13653     unsigned i = 0;
13654     for (; i != NumElts; ++i) {
13655       SDValue Arg = ShAmtOp.getOperand(i);
13656       if (Arg.getOpcode() == ISD::UNDEF) continue;
13657       BaseShAmt = Arg;
13658       break;
13659     }
13660     for (; i != NumElts; ++i) {
13661       SDValue Arg = ShAmtOp.getOperand(i);
13662       if (Arg.getOpcode() == ISD::UNDEF) continue;
13663       if (Arg != BaseShAmt) {
13664         return SDValue();
13665       }
13666     }
13667   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
13668              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
13669     SDValue InVec = ShAmtOp.getOperand(0);
13670     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13671       unsigned NumElts = InVec.getValueType().getVectorNumElements();
13672       unsigned i = 0;
13673       for (; i != NumElts; ++i) {
13674         SDValue Arg = InVec.getOperand(i);
13675         if (Arg.getOpcode() == ISD::UNDEF) continue;
13676         BaseShAmt = Arg;
13677         break;
13678       }
13679     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13680        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13681          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
13682          if (C->getZExtValue() == SplatIdx)
13683            BaseShAmt = InVec.getOperand(1);
13684        }
13685     }
13686     if (BaseShAmt.getNode() == 0)
13687       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
13688                               DAG.getIntPtrConstant(0));
13689   } else
13690     return SDValue();
13691
13692   // The shift amount is an i32.
13693   if (EltVT.bitsGT(MVT::i32))
13694     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
13695   else if (EltVT.bitsLT(MVT::i32))
13696     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
13697
13698   // The shift amount is identical so we can do a vector shift.
13699   SDValue  ValOp = N->getOperand(0);
13700   switch (N->getOpcode()) {
13701   default:
13702     llvm_unreachable("Unknown shift opcode!");
13703     break;
13704   case ISD::SHL:
13705     if (VT == MVT::v2i64)
13706       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13707                          DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
13708                          ValOp, BaseShAmt);
13709     if (VT == MVT::v4i32)
13710       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13711                          DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
13712                          ValOp, BaseShAmt);
13713     if (VT == MVT::v8i16)
13714       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13715                          DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
13716                          ValOp, BaseShAmt);
13717     if (VT == MVT::v4i64)
13718       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13719                          DAG.getConstant(Intrinsic::x86_avx2_pslli_q, MVT::i32),
13720                          ValOp, BaseShAmt);
13721     if (VT == MVT::v8i32)
13722       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13723                          DAG.getConstant(Intrinsic::x86_avx2_pslli_d, MVT::i32),
13724                          ValOp, BaseShAmt);
13725     if (VT == MVT::v16i16)
13726       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13727                          DAG.getConstant(Intrinsic::x86_avx2_pslli_w, MVT::i32),
13728                          ValOp, BaseShAmt);
13729     break;
13730   case ISD::SRA:
13731     if (VT == MVT::v4i32)
13732       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13733                          DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
13734                          ValOp, BaseShAmt);
13735     if (VT == MVT::v8i16)
13736       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13737                          DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
13738                          ValOp, BaseShAmt);
13739     if (VT == MVT::v8i32)
13740       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13741                          DAG.getConstant(Intrinsic::x86_avx2_psrai_d, MVT::i32),
13742                          ValOp, BaseShAmt);
13743     if (VT == MVT::v16i16)
13744       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13745                          DAG.getConstant(Intrinsic::x86_avx2_psrai_w, MVT::i32),
13746                          ValOp, BaseShAmt);
13747     break;
13748   case ISD::SRL:
13749     if (VT == MVT::v2i64)
13750       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13751                          DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
13752                          ValOp, BaseShAmt);
13753     if (VT == MVT::v4i32)
13754       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13755                          DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
13756                          ValOp, BaseShAmt);
13757     if (VT ==  MVT::v8i16)
13758       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13759                          DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
13760                          ValOp, BaseShAmt);
13761     if (VT == MVT::v4i64)
13762       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13763                          DAG.getConstant(Intrinsic::x86_avx2_psrli_q, MVT::i32),
13764                          ValOp, BaseShAmt);
13765     if (VT == MVT::v8i32)
13766       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13767                          DAG.getConstant(Intrinsic::x86_avx2_psrli_d, MVT::i32),
13768                          ValOp, BaseShAmt);
13769     if (VT ==  MVT::v16i16)
13770       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13771                          DAG.getConstant(Intrinsic::x86_avx2_psrli_w, MVT::i32),
13772                          ValOp, BaseShAmt);
13773     break;
13774   }
13775   return SDValue();
13776 }
13777
13778
13779 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
13780 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
13781 // and friends.  Likewise for OR -> CMPNEQSS.
13782 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
13783                             TargetLowering::DAGCombinerInfo &DCI,
13784                             const X86Subtarget *Subtarget) {
13785   unsigned opcode;
13786
13787   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
13788   // we're requiring SSE2 for both.
13789   if (Subtarget->hasXMMInt() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
13790     SDValue N0 = N->getOperand(0);
13791     SDValue N1 = N->getOperand(1);
13792     SDValue CMP0 = N0->getOperand(1);
13793     SDValue CMP1 = N1->getOperand(1);
13794     DebugLoc DL = N->getDebugLoc();
13795
13796     // The SETCCs should both refer to the same CMP.
13797     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
13798       return SDValue();
13799
13800     SDValue CMP00 = CMP0->getOperand(0);
13801     SDValue CMP01 = CMP0->getOperand(1);
13802     EVT     VT    = CMP00.getValueType();
13803
13804     if (VT == MVT::f32 || VT == MVT::f64) {
13805       bool ExpectingFlags = false;
13806       // Check for any users that want flags:
13807       for (SDNode::use_iterator UI = N->use_begin(),
13808              UE = N->use_end();
13809            !ExpectingFlags && UI != UE; ++UI)
13810         switch (UI->getOpcode()) {
13811         default:
13812         case ISD::BR_CC:
13813         case ISD::BRCOND:
13814         case ISD::SELECT:
13815           ExpectingFlags = true;
13816           break;
13817         case ISD::CopyToReg:
13818         case ISD::SIGN_EXTEND:
13819         case ISD::ZERO_EXTEND:
13820         case ISD::ANY_EXTEND:
13821           break;
13822         }
13823
13824       if (!ExpectingFlags) {
13825         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
13826         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
13827
13828         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
13829           X86::CondCode tmp = cc0;
13830           cc0 = cc1;
13831           cc1 = tmp;
13832         }
13833
13834         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
13835             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
13836           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
13837           X86ISD::NodeType NTOperator = is64BitFP ?
13838             X86ISD::FSETCCsd : X86ISD::FSETCCss;
13839           // FIXME: need symbolic constants for these magic numbers.
13840           // See X86ATTInstPrinter.cpp:printSSECC().
13841           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
13842           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
13843                                               DAG.getConstant(x86cc, MVT::i8));
13844           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
13845                                               OnesOrZeroesF);
13846           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
13847                                       DAG.getConstant(1, MVT::i32));
13848           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
13849           return OneBitOfTruth;
13850         }
13851       }
13852     }
13853   }
13854   return SDValue();
13855 }
13856
13857 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
13858 /// so it can be folded inside ANDNP.
13859 static bool CanFoldXORWithAllOnes(const SDNode *N) {
13860   EVT VT = N->getValueType(0);
13861
13862   // Match direct AllOnes for 128 and 256-bit vectors
13863   if (ISD::isBuildVectorAllOnes(N))
13864     return true;
13865
13866   // Look through a bit convert.
13867   if (N->getOpcode() == ISD::BITCAST)
13868     N = N->getOperand(0).getNode();
13869
13870   // Sometimes the operand may come from a insert_subvector building a 256-bit
13871   // allones vector
13872   if (VT.getSizeInBits() == 256 &&
13873       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
13874     SDValue V1 = N->getOperand(0);
13875     SDValue V2 = N->getOperand(1);
13876
13877     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
13878         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
13879         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
13880         ISD::isBuildVectorAllOnes(V2.getNode()))
13881       return true;
13882   }
13883
13884   return false;
13885 }
13886
13887 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
13888                                  TargetLowering::DAGCombinerInfo &DCI,
13889                                  const X86Subtarget *Subtarget) {
13890   if (DCI.isBeforeLegalizeOps())
13891     return SDValue();
13892
13893   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
13894   if (R.getNode())
13895     return R;
13896
13897   EVT VT = N->getValueType(0);
13898
13899   // Create ANDN, BLSI, and BLSR instructions
13900   // BLSI is X & (-X)
13901   // BLSR is X & (X-1)
13902   if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
13903     SDValue N0 = N->getOperand(0);
13904     SDValue N1 = N->getOperand(1);
13905     DebugLoc DL = N->getDebugLoc();
13906
13907     // Check LHS for not
13908     if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1)))
13909       return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1);
13910     // Check RHS for not
13911     if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1)))
13912       return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
13913
13914     // Check LHS for neg
13915     if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
13916         isZero(N0.getOperand(0)))
13917       return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
13918
13919     // Check RHS for neg
13920     if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
13921         isZero(N1.getOperand(0)))
13922       return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
13923
13924     // Check LHS for X-1
13925     if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
13926         isAllOnes(N0.getOperand(1)))
13927       return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
13928
13929     // Check RHS for X-1
13930     if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
13931         isAllOnes(N1.getOperand(1)))
13932       return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
13933
13934     return SDValue();
13935   }
13936
13937   // Want to form ANDNP nodes:
13938   // 1) In the hopes of then easily combining them with OR and AND nodes
13939   //    to form PBLEND/PSIGN.
13940   // 2) To match ANDN packed intrinsics
13941   if (VT != MVT::v2i64 && VT != MVT::v4i64)
13942     return SDValue();
13943
13944   SDValue N0 = N->getOperand(0);
13945   SDValue N1 = N->getOperand(1);
13946   DebugLoc DL = N->getDebugLoc();
13947
13948   // Check LHS for vnot
13949   if (N0.getOpcode() == ISD::XOR &&
13950       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
13951       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
13952     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
13953
13954   // Check RHS for vnot
13955   if (N1.getOpcode() == ISD::XOR &&
13956       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
13957       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
13958     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
13959
13960   return SDValue();
13961 }
13962
13963 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
13964                                 TargetLowering::DAGCombinerInfo &DCI,
13965                                 const X86Subtarget *Subtarget) {
13966   if (DCI.isBeforeLegalizeOps())
13967     return SDValue();
13968
13969   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
13970   if (R.getNode())
13971     return R;
13972
13973   EVT VT = N->getValueType(0);
13974
13975   SDValue N0 = N->getOperand(0);
13976   SDValue N1 = N->getOperand(1);
13977
13978   // look for psign/blend
13979   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
13980     if (!Subtarget->hasSSSE3orAVX() ||
13981         (VT == MVT::v4i64 && !Subtarget->hasAVX2()))
13982       return SDValue();
13983
13984     // Canonicalize pandn to RHS
13985     if (N0.getOpcode() == X86ISD::ANDNP)
13986       std::swap(N0, N1);
13987     // or (and (m, x), (pandn m, y))
13988     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
13989       SDValue Mask = N1.getOperand(0);
13990       SDValue X    = N1.getOperand(1);
13991       SDValue Y;
13992       if (N0.getOperand(0) == Mask)
13993         Y = N0.getOperand(1);
13994       if (N0.getOperand(1) == Mask)
13995         Y = N0.getOperand(0);
13996
13997       // Check to see if the mask appeared in both the AND and ANDNP and
13998       if (!Y.getNode())
13999         return SDValue();
14000
14001       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
14002       if (Mask.getOpcode() != ISD::BITCAST ||
14003           X.getOpcode() != ISD::BITCAST ||
14004           Y.getOpcode() != ISD::BITCAST)
14005         return SDValue();
14006
14007       // Look through mask bitcast.
14008       Mask = Mask.getOperand(0);
14009       EVT MaskVT = Mask.getValueType();
14010
14011       // Validate that the Mask operand is a vector sra node.  The sra node
14012       // will be an intrinsic.
14013       if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
14014         return SDValue();
14015
14016       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
14017       // there is no psrai.b
14018       switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
14019       case Intrinsic::x86_sse2_psrai_w:
14020       case Intrinsic::x86_sse2_psrai_d:
14021       case Intrinsic::x86_avx2_psrai_w:
14022       case Intrinsic::x86_avx2_psrai_d:
14023         break;
14024       default: return SDValue();
14025       }
14026
14027       // Check that the SRA is all signbits.
14028       SDValue SraC = Mask.getOperand(2);
14029       unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
14030       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
14031       if ((SraAmt + 1) != EltBits)
14032         return SDValue();
14033
14034       DebugLoc DL = N->getDebugLoc();
14035
14036       // Now we know we at least have a plendvb with the mask val.  See if
14037       // we can form a psignb/w/d.
14038       // psign = x.type == y.type == mask.type && y = sub(0, x);
14039       X = X.getOperand(0);
14040       Y = Y.getOperand(0);
14041       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
14042           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
14043           X.getValueType() == MaskVT && X.getValueType() == Y.getValueType() &&
14044           (EltBits == 8 || EltBits == 16 || EltBits == 32)) {
14045         SDValue Sign = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X,
14046                                    Mask.getOperand(1));
14047         return DAG.getNode(ISD::BITCAST, DL, VT, Sign);
14048       }
14049       // PBLENDVB only available on SSE 4.1
14050       if (!Subtarget->hasSSE41orAVX())
14051         return SDValue();
14052
14053       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
14054
14055       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
14056       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
14057       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
14058       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, X, Y);
14059       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
14060     }
14061   }
14062
14063   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
14064     return SDValue();
14065
14066   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
14067   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
14068     std::swap(N0, N1);
14069   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
14070     return SDValue();
14071   if (!N0.hasOneUse() || !N1.hasOneUse())
14072     return SDValue();
14073
14074   SDValue ShAmt0 = N0.getOperand(1);
14075   if (ShAmt0.getValueType() != MVT::i8)
14076     return SDValue();
14077   SDValue ShAmt1 = N1.getOperand(1);
14078   if (ShAmt1.getValueType() != MVT::i8)
14079     return SDValue();
14080   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
14081     ShAmt0 = ShAmt0.getOperand(0);
14082   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
14083     ShAmt1 = ShAmt1.getOperand(0);
14084
14085   DebugLoc DL = N->getDebugLoc();
14086   unsigned Opc = X86ISD::SHLD;
14087   SDValue Op0 = N0.getOperand(0);
14088   SDValue Op1 = N1.getOperand(0);
14089   if (ShAmt0.getOpcode() == ISD::SUB) {
14090     Opc = X86ISD::SHRD;
14091     std::swap(Op0, Op1);
14092     std::swap(ShAmt0, ShAmt1);
14093   }
14094
14095   unsigned Bits = VT.getSizeInBits();
14096   if (ShAmt1.getOpcode() == ISD::SUB) {
14097     SDValue Sum = ShAmt1.getOperand(0);
14098     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
14099       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
14100       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
14101         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
14102       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
14103         return DAG.getNode(Opc, DL, VT,
14104                            Op0, Op1,
14105                            DAG.getNode(ISD::TRUNCATE, DL,
14106                                        MVT::i8, ShAmt0));
14107     }
14108   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
14109     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
14110     if (ShAmt0C &&
14111         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
14112       return DAG.getNode(Opc, DL, VT,
14113                          N0.getOperand(0), N1.getOperand(0),
14114                          DAG.getNode(ISD::TRUNCATE, DL,
14115                                        MVT::i8, ShAmt0));
14116   }
14117
14118   return SDValue();
14119 }
14120
14121 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
14122                                  TargetLowering::DAGCombinerInfo &DCI,
14123                                  const X86Subtarget *Subtarget) {
14124   if (DCI.isBeforeLegalizeOps())
14125     return SDValue();
14126
14127   EVT VT = N->getValueType(0);
14128
14129   if (VT != MVT::i32 && VT != MVT::i64)
14130     return SDValue();
14131
14132   // Create BLSMSK instructions by finding X ^ (X-1)
14133   SDValue N0 = N->getOperand(0);
14134   SDValue N1 = N->getOperand(1);
14135   DebugLoc DL = N->getDebugLoc();
14136
14137   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
14138       isAllOnes(N0.getOperand(1)))
14139     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
14140
14141   if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
14142       isAllOnes(N1.getOperand(1)))
14143     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
14144
14145   return SDValue();
14146 }
14147
14148 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
14149 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
14150                                    const X86Subtarget *Subtarget) {
14151   LoadSDNode *Ld = cast<LoadSDNode>(N);
14152   EVT RegVT = Ld->getValueType(0);
14153   EVT MemVT = Ld->getMemoryVT();
14154   DebugLoc dl = Ld->getDebugLoc();
14155   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14156
14157   ISD::LoadExtType Ext = Ld->getExtensionType();
14158
14159   // If this is a vector EXT Load then attempt to optimize it using a
14160   // shuffle. We need SSE4 for the shuffles.
14161   // TODO: It is possible to support ZExt by zeroing the undef values
14162   // during the shuffle phase or after the shuffle.
14163   if (RegVT.isVector() && Ext == ISD::EXTLOAD && Subtarget->hasSSE41()) {
14164     assert(MemVT != RegVT && "Cannot extend to the same type");
14165     assert(MemVT.isVector() && "Must load a vector from memory");
14166
14167     unsigned NumElems = RegVT.getVectorNumElements();
14168     unsigned RegSz = RegVT.getSizeInBits();
14169     unsigned MemSz = MemVT.getSizeInBits();
14170     assert(RegSz > MemSz && "Register size must be greater than the mem size");
14171     // All sizes must be a power of two
14172     if (!isPowerOf2_32(RegSz * MemSz * NumElems)) return SDValue();
14173
14174     // Attempt to load the original value using a single load op.
14175     // Find a scalar type which is equal to the loaded word size.
14176     MVT SclrLoadTy = MVT::i8;
14177     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
14178          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
14179       MVT Tp = (MVT::SimpleValueType)tp;
14180       if (TLI.isTypeLegal(Tp) &&  Tp.getSizeInBits() == MemSz) {
14181         SclrLoadTy = Tp;
14182         break;
14183       }
14184     }
14185
14186     // Proceed if a load word is found.
14187     if (SclrLoadTy.getSizeInBits() != MemSz) return SDValue();
14188
14189     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
14190       RegSz/SclrLoadTy.getSizeInBits());
14191
14192     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14193                                   RegSz/MemVT.getScalarType().getSizeInBits());
14194     // Can't shuffle using an illegal type.
14195     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
14196
14197     // Perform a single load.
14198     SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
14199                                   Ld->getBasePtr(),
14200                                   Ld->getPointerInfo(), Ld->isVolatile(),
14201                                   Ld->isNonTemporal(), Ld->isInvariant(),
14202                                   Ld->getAlignment());
14203
14204     // Insert the word loaded into a vector.
14205     SDValue ScalarInVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
14206       LoadUnitVecVT, ScalarLoad);
14207
14208     // Bitcast the loaded value to a vector of the original element type, in
14209     // the size of the target vector type.
14210     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, ScalarInVector);
14211     unsigned SizeRatio = RegSz/MemSz;
14212
14213     // Redistribute the loaded elements into the different locations.
14214     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
14215     for (unsigned i = 0; i < NumElems; i++) ShuffleVec[i*SizeRatio] = i;
14216
14217     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14218                                 DAG.getUNDEF(SlicedVec.getValueType()),
14219                                 ShuffleVec.data());
14220
14221     // Bitcast to the requested type.
14222     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
14223     // Replace the original load with the new sequence
14224     // and return the new chain.
14225     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Shuff);
14226     return SDValue(ScalarLoad.getNode(), 1);
14227   }
14228
14229   return SDValue();
14230 }
14231
14232 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
14233 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
14234                                    const X86Subtarget *Subtarget) {
14235   StoreSDNode *St = cast<StoreSDNode>(N);
14236   EVT VT = St->getValue().getValueType();
14237   EVT StVT = St->getMemoryVT();
14238   DebugLoc dl = St->getDebugLoc();
14239   SDValue StoredVal = St->getOperand(1);
14240   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14241
14242   // If we are saving a concatination of two XMM registers, perform two stores.
14243   // This is better in Sandy Bridge cause one 256-bit mem op is done via two
14244   // 128-bit ones. If in the future the cost becomes only one memory access the
14245   // first version would be better.
14246   if (VT.getSizeInBits() == 256 &&
14247     StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
14248     StoredVal.getNumOperands() == 2) {
14249
14250     SDValue Value0 = StoredVal.getOperand(0);
14251     SDValue Value1 = StoredVal.getOperand(1);
14252
14253     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
14254     SDValue Ptr0 = St->getBasePtr();
14255     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
14256
14257     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
14258                                 St->getPointerInfo(), St->isVolatile(),
14259                                 St->isNonTemporal(), St->getAlignment());
14260     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
14261                                 St->getPointerInfo(), St->isVolatile(),
14262                                 St->isNonTemporal(), St->getAlignment());
14263     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
14264   }
14265
14266   // Optimize trunc store (of multiple scalars) to shuffle and store.
14267   // First, pack all of the elements in one place. Next, store to memory
14268   // in fewer chunks.
14269   if (St->isTruncatingStore() && VT.isVector()) {
14270     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14271     unsigned NumElems = VT.getVectorNumElements();
14272     assert(StVT != VT && "Cannot truncate to the same type");
14273     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
14274     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
14275
14276     // From, To sizes and ElemCount must be pow of two
14277     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
14278     // We are going to use the original vector elt for storing.
14279     // Accumulated smaller vector elements must be a multiple of the store size.
14280     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
14281
14282     unsigned SizeRatio  = FromSz / ToSz;
14283
14284     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
14285
14286     // Create a type on which we perform the shuffle
14287     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
14288             StVT.getScalarType(), NumElems*SizeRatio);
14289
14290     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
14291
14292     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
14293     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
14294     for (unsigned i = 0; i < NumElems; i++ ) ShuffleVec[i] = i * SizeRatio;
14295
14296     // Can't shuffle using an illegal type
14297     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
14298
14299     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
14300                                 DAG.getUNDEF(WideVec.getValueType()),
14301                                 ShuffleVec.data());
14302     // At this point all of the data is stored at the bottom of the
14303     // register. We now need to save it to mem.
14304
14305     // Find the largest store unit
14306     MVT StoreType = MVT::i8;
14307     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
14308          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
14309       MVT Tp = (MVT::SimpleValueType)tp;
14310       if (TLI.isTypeLegal(Tp) && StoreType.getSizeInBits() < NumElems * ToSz)
14311         StoreType = Tp;
14312     }
14313
14314     // Bitcast the original vector into a vector of store-size units
14315     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
14316             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
14317     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
14318     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
14319     SmallVector<SDValue, 8> Chains;
14320     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
14321                                         TLI.getPointerTy());
14322     SDValue Ptr = St->getBasePtr();
14323
14324     // Perform one or more big stores into memory.
14325     for (unsigned i = 0; i < (ToSz*NumElems)/StoreType.getSizeInBits() ; i++) {
14326       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
14327                                    StoreType, ShuffWide,
14328                                    DAG.getIntPtrConstant(i));
14329       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
14330                                 St->getPointerInfo(), St->isVolatile(),
14331                                 St->isNonTemporal(), St->getAlignment());
14332       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14333       Chains.push_back(Ch);
14334     }
14335
14336     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
14337                                Chains.size());
14338   }
14339
14340
14341   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
14342   // the FP state in cases where an emms may be missing.
14343   // A preferable solution to the general problem is to figure out the right
14344   // places to insert EMMS.  This qualifies as a quick hack.
14345
14346   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
14347   if (VT.getSizeInBits() != 64)
14348     return SDValue();
14349
14350   const Function *F = DAG.getMachineFunction().getFunction();
14351   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
14352   bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
14353                      && Subtarget->hasXMMInt();
14354   if ((VT.isVector() ||
14355        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
14356       isa<LoadSDNode>(St->getValue()) &&
14357       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
14358       St->getChain().hasOneUse() && !St->isVolatile()) {
14359     SDNode* LdVal = St->getValue().getNode();
14360     LoadSDNode *Ld = 0;
14361     int TokenFactorIndex = -1;
14362     SmallVector<SDValue, 8> Ops;
14363     SDNode* ChainVal = St->getChain().getNode();
14364     // Must be a store of a load.  We currently handle two cases:  the load
14365     // is a direct child, and it's under an intervening TokenFactor.  It is
14366     // possible to dig deeper under nested TokenFactors.
14367     if (ChainVal == LdVal)
14368       Ld = cast<LoadSDNode>(St->getChain());
14369     else if (St->getValue().hasOneUse() &&
14370              ChainVal->getOpcode() == ISD::TokenFactor) {
14371       for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
14372         if (ChainVal->getOperand(i).getNode() == LdVal) {
14373           TokenFactorIndex = i;
14374           Ld = cast<LoadSDNode>(St->getValue());
14375         } else
14376           Ops.push_back(ChainVal->getOperand(i));
14377       }
14378     }
14379
14380     if (!Ld || !ISD::isNormalLoad(Ld))
14381       return SDValue();
14382
14383     // If this is not the MMX case, i.e. we are just turning i64 load/store
14384     // into f64 load/store, avoid the transformation if there are multiple
14385     // uses of the loaded value.
14386     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
14387       return SDValue();
14388
14389     DebugLoc LdDL = Ld->getDebugLoc();
14390     DebugLoc StDL = N->getDebugLoc();
14391     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
14392     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
14393     // pair instead.
14394     if (Subtarget->is64Bit() || F64IsLegal) {
14395       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
14396       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
14397                                   Ld->getPointerInfo(), Ld->isVolatile(),
14398                                   Ld->isNonTemporal(), Ld->isInvariant(),
14399                                   Ld->getAlignment());
14400       SDValue NewChain = NewLd.getValue(1);
14401       if (TokenFactorIndex != -1) {
14402         Ops.push_back(NewChain);
14403         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14404                                Ops.size());
14405       }
14406       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
14407                           St->getPointerInfo(),
14408                           St->isVolatile(), St->isNonTemporal(),
14409                           St->getAlignment());
14410     }
14411
14412     // Otherwise, lower to two pairs of 32-bit loads / stores.
14413     SDValue LoAddr = Ld->getBasePtr();
14414     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
14415                                  DAG.getConstant(4, MVT::i32));
14416
14417     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
14418                                Ld->getPointerInfo(),
14419                                Ld->isVolatile(), Ld->isNonTemporal(),
14420                                Ld->isInvariant(), Ld->getAlignment());
14421     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
14422                                Ld->getPointerInfo().getWithOffset(4),
14423                                Ld->isVolatile(), Ld->isNonTemporal(),
14424                                Ld->isInvariant(),
14425                                MinAlign(Ld->getAlignment(), 4));
14426
14427     SDValue NewChain = LoLd.getValue(1);
14428     if (TokenFactorIndex != -1) {
14429       Ops.push_back(LoLd);
14430       Ops.push_back(HiLd);
14431       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14432                              Ops.size());
14433     }
14434
14435     LoAddr = St->getBasePtr();
14436     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
14437                          DAG.getConstant(4, MVT::i32));
14438
14439     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
14440                                 St->getPointerInfo(),
14441                                 St->isVolatile(), St->isNonTemporal(),
14442                                 St->getAlignment());
14443     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
14444                                 St->getPointerInfo().getWithOffset(4),
14445                                 St->isVolatile(),
14446                                 St->isNonTemporal(),
14447                                 MinAlign(St->getAlignment(), 4));
14448     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
14449   }
14450   return SDValue();
14451 }
14452
14453 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
14454 /// and return the operands for the horizontal operation in LHS and RHS.  A
14455 /// horizontal operation performs the binary operation on successive elements
14456 /// of its first operand, then on successive elements of its second operand,
14457 /// returning the resulting values in a vector.  For example, if
14458 ///   A = < float a0, float a1, float a2, float a3 >
14459 /// and
14460 ///   B = < float b0, float b1, float b2, float b3 >
14461 /// then the result of doing a horizontal operation on A and B is
14462 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
14463 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
14464 /// A horizontal-op B, for some already available A and B, and if so then LHS is
14465 /// set to A, RHS to B, and the routine returns 'true'.
14466 /// Note that the binary operation should have the property that if one of the
14467 /// operands is UNDEF then the result is UNDEF.
14468 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool isCommutative) {
14469   // Look for the following pattern: if
14470   //   A = < float a0, float a1, float a2, float a3 >
14471   //   B = < float b0, float b1, float b2, float b3 >
14472   // and
14473   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
14474   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
14475   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
14476   // which is A horizontal-op B.
14477
14478   // At least one of the operands should be a vector shuffle.
14479   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
14480       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
14481     return false;
14482
14483   EVT VT = LHS.getValueType();
14484   unsigned N = VT.getVectorNumElements();
14485
14486   // View LHS in the form
14487   //   LHS = VECTOR_SHUFFLE A, B, LMask
14488   // If LHS is not a shuffle then pretend it is the shuffle
14489   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
14490   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
14491   // type VT.
14492   SDValue A, B;
14493   SmallVector<int, 8> LMask(N);
14494   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
14495     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
14496       A = LHS.getOperand(0);
14497     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
14498       B = LHS.getOperand(1);
14499     cast<ShuffleVectorSDNode>(LHS.getNode())->getMask(LMask);
14500   } else {
14501     if (LHS.getOpcode() != ISD::UNDEF)
14502       A = LHS;
14503     for (unsigned i = 0; i != N; ++i)
14504       LMask[i] = i;
14505   }
14506
14507   // Likewise, view RHS in the form
14508   //   RHS = VECTOR_SHUFFLE C, D, RMask
14509   SDValue C, D;
14510   SmallVector<int, 8> RMask(N);
14511   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
14512     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
14513       C = RHS.getOperand(0);
14514     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
14515       D = RHS.getOperand(1);
14516     cast<ShuffleVectorSDNode>(RHS.getNode())->getMask(RMask);
14517   } else {
14518     if (RHS.getOpcode() != ISD::UNDEF)
14519       C = RHS;
14520     for (unsigned i = 0; i != N; ++i)
14521       RMask[i] = i;
14522   }
14523
14524   // Check that the shuffles are both shuffling the same vectors.
14525   if (!(A == C && B == D) && !(A == D && B == C))
14526     return false;
14527
14528   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
14529   if (!A.getNode() && !B.getNode())
14530     return false;
14531
14532   // If A and B occur in reverse order in RHS, then "swap" them (which means
14533   // rewriting the mask).
14534   if (A != C)
14535     for (unsigned i = 0; i != N; ++i) {
14536       unsigned Idx = RMask[i];
14537       if (Idx < N)
14538         RMask[i] += N;
14539       else if (Idx < 2*N)
14540         RMask[i] -= N;
14541     }
14542
14543   // At this point LHS and RHS are equivalent to
14544   //   LHS = VECTOR_SHUFFLE A, B, LMask
14545   //   RHS = VECTOR_SHUFFLE A, B, RMask
14546   // Check that the masks correspond to performing a horizontal operation.
14547   for (unsigned i = 0; i != N; ++i) {
14548     unsigned LIdx = LMask[i], RIdx = RMask[i];
14549
14550     // Ignore any UNDEF components.
14551     if (LIdx >= 2*N || RIdx >= 2*N || (!A.getNode() && (LIdx < N || RIdx < N))
14552         || (!B.getNode() && (LIdx >= N || RIdx >= N)))
14553       continue;
14554
14555     // Check that successive elements are being operated on.  If not, this is
14556     // not a horizontal operation.
14557     if (!(LIdx == 2*i && RIdx == 2*i + 1) &&
14558         !(isCommutative && LIdx == 2*i + 1 && RIdx == 2*i))
14559       return false;
14560   }
14561
14562   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
14563   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
14564   return true;
14565 }
14566
14567 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
14568 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
14569                                   const X86Subtarget *Subtarget) {
14570   EVT VT = N->getValueType(0);
14571   SDValue LHS = N->getOperand(0);
14572   SDValue RHS = N->getOperand(1);
14573
14574   // Try to synthesize horizontal adds from adds of shuffles.
14575   if (Subtarget->hasSSE3orAVX() && (VT == MVT::v4f32 || VT == MVT::v2f64) &&
14576       isHorizontalBinOp(LHS, RHS, true))
14577     return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
14578   return SDValue();
14579 }
14580
14581 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
14582 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
14583                                   const X86Subtarget *Subtarget) {
14584   EVT VT = N->getValueType(0);
14585   SDValue LHS = N->getOperand(0);
14586   SDValue RHS = N->getOperand(1);
14587
14588   // Try to synthesize horizontal subs from subs of shuffles.
14589   if (Subtarget->hasSSE3orAVX() && (VT == MVT::v4f32 || VT == MVT::v2f64) &&
14590       isHorizontalBinOp(LHS, RHS, false))
14591     return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
14592   return SDValue();
14593 }
14594
14595 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
14596 /// X86ISD::FXOR nodes.
14597 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
14598   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
14599   // F[X]OR(0.0, x) -> x
14600   // F[X]OR(x, 0.0) -> x
14601   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
14602     if (C->getValueAPF().isPosZero())
14603       return N->getOperand(1);
14604   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
14605     if (C->getValueAPF().isPosZero())
14606       return N->getOperand(0);
14607   return SDValue();
14608 }
14609
14610 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
14611 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
14612   // FAND(0.0, x) -> 0.0
14613   // FAND(x, 0.0) -> 0.0
14614   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
14615     if (C->getValueAPF().isPosZero())
14616       return N->getOperand(0);
14617   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
14618     if (C->getValueAPF().isPosZero())
14619       return N->getOperand(1);
14620   return SDValue();
14621 }
14622
14623 static SDValue PerformBTCombine(SDNode *N,
14624                                 SelectionDAG &DAG,
14625                                 TargetLowering::DAGCombinerInfo &DCI) {
14626   // BT ignores high bits in the bit index operand.
14627   SDValue Op1 = N->getOperand(1);
14628   if (Op1.hasOneUse()) {
14629     unsigned BitWidth = Op1.getValueSizeInBits();
14630     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
14631     APInt KnownZero, KnownOne;
14632     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
14633                                           !DCI.isBeforeLegalizeOps());
14634     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14635     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
14636         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
14637       DCI.CommitTargetLoweringOpt(TLO);
14638   }
14639   return SDValue();
14640 }
14641
14642 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
14643   SDValue Op = N->getOperand(0);
14644   if (Op.getOpcode() == ISD::BITCAST)
14645     Op = Op.getOperand(0);
14646   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
14647   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
14648       VT.getVectorElementType().getSizeInBits() ==
14649       OpVT.getVectorElementType().getSizeInBits()) {
14650     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
14651   }
14652   return SDValue();
14653 }
14654
14655 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
14656   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
14657   //           (and (i32 x86isd::setcc_carry), 1)
14658   // This eliminates the zext. This transformation is necessary because
14659   // ISD::SETCC is always legalized to i8.
14660   DebugLoc dl = N->getDebugLoc();
14661   SDValue N0 = N->getOperand(0);
14662   EVT VT = N->getValueType(0);
14663   if (N0.getOpcode() == ISD::AND &&
14664       N0.hasOneUse() &&
14665       N0.getOperand(0).hasOneUse()) {
14666     SDValue N00 = N0.getOperand(0);
14667     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
14668       return SDValue();
14669     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
14670     if (!C || C->getZExtValue() != 1)
14671       return SDValue();
14672     return DAG.getNode(ISD::AND, dl, VT,
14673                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
14674                                    N00.getOperand(0), N00.getOperand(1)),
14675                        DAG.getConstant(1, VT));
14676   }
14677
14678   return SDValue();
14679 }
14680
14681 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
14682 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
14683   unsigned X86CC = N->getConstantOperandVal(0);
14684   SDValue EFLAG = N->getOperand(1);
14685   DebugLoc DL = N->getDebugLoc();
14686
14687   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
14688   // a zext and produces an all-ones bit which is more useful than 0/1 in some
14689   // cases.
14690   if (X86CC == X86::COND_B)
14691     return DAG.getNode(ISD::AND, DL, MVT::i8,
14692                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
14693                                    DAG.getConstant(X86CC, MVT::i8), EFLAG),
14694                        DAG.getConstant(1, MVT::i8));
14695
14696   return SDValue();
14697 }
14698
14699 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
14700                                         const X86TargetLowering *XTLI) {
14701   SDValue Op0 = N->getOperand(0);
14702   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
14703   // a 32-bit target where SSE doesn't support i64->FP operations.
14704   if (Op0.getOpcode() == ISD::LOAD) {
14705     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
14706     EVT VT = Ld->getValueType(0);
14707     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
14708         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
14709         !XTLI->getSubtarget()->is64Bit() &&
14710         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14711       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
14712                                           Ld->getChain(), Op0, DAG);
14713       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
14714       return FILDChain;
14715     }
14716   }
14717   return SDValue();
14718 }
14719
14720 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
14721 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
14722                                  X86TargetLowering::DAGCombinerInfo &DCI) {
14723   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
14724   // the result is either zero or one (depending on the input carry bit).
14725   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
14726   if (X86::isZeroNode(N->getOperand(0)) &&
14727       X86::isZeroNode(N->getOperand(1)) &&
14728       // We don't have a good way to replace an EFLAGS use, so only do this when
14729       // dead right now.
14730       SDValue(N, 1).use_empty()) {
14731     DebugLoc DL = N->getDebugLoc();
14732     EVT VT = N->getValueType(0);
14733     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
14734     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
14735                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
14736                                            DAG.getConstant(X86::COND_B,MVT::i8),
14737                                            N->getOperand(2)),
14738                                DAG.getConstant(1, VT));
14739     return DCI.CombineTo(N, Res1, CarryOut);
14740   }
14741
14742   return SDValue();
14743 }
14744
14745 // fold (add Y, (sete  X, 0)) -> adc  0, Y
14746 //      (add Y, (setne X, 0)) -> sbb -1, Y
14747 //      (sub (sete  X, 0), Y) -> sbb  0, Y
14748 //      (sub (setne X, 0), Y) -> adc -1, Y
14749 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
14750   DebugLoc DL = N->getDebugLoc();
14751
14752   // Look through ZExts.
14753   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
14754   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
14755     return SDValue();
14756
14757   SDValue SetCC = Ext.getOperand(0);
14758   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
14759     return SDValue();
14760
14761   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
14762   if (CC != X86::COND_E && CC != X86::COND_NE)
14763     return SDValue();
14764
14765   SDValue Cmp = SetCC.getOperand(1);
14766   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
14767       !X86::isZeroNode(Cmp.getOperand(1)) ||
14768       !Cmp.getOperand(0).getValueType().isInteger())
14769     return SDValue();
14770
14771   SDValue CmpOp0 = Cmp.getOperand(0);
14772   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
14773                                DAG.getConstant(1, CmpOp0.getValueType()));
14774
14775   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
14776   if (CC == X86::COND_NE)
14777     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
14778                        DL, OtherVal.getValueType(), OtherVal,
14779                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
14780   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
14781                      DL, OtherVal.getValueType(), OtherVal,
14782                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
14783 }
14784
14785 /// PerformADDCombine - Do target-specific dag combines on integer adds.
14786 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
14787                                  const X86Subtarget *Subtarget) {
14788   EVT VT = N->getValueType(0);
14789   SDValue Op0 = N->getOperand(0);
14790   SDValue Op1 = N->getOperand(1);
14791
14792   // Try to synthesize horizontal adds from adds of shuffles.
14793   if ((Subtarget->hasSSSE3orAVX()) && (VT == MVT::v8i16 || VT == MVT::v4i32) &&
14794       isHorizontalBinOp(Op0, Op1, true))
14795     return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
14796
14797   return OptimizeConditionalInDecrement(N, DAG);
14798 }
14799
14800 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
14801                                  const X86Subtarget *Subtarget) {
14802   SDValue Op0 = N->getOperand(0);
14803   SDValue Op1 = N->getOperand(1);
14804
14805   // X86 can't encode an immediate LHS of a sub. See if we can push the
14806   // negation into a preceding instruction.
14807   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
14808     // If the RHS of the sub is a XOR with one use and a constant, invert the
14809     // immediate. Then add one to the LHS of the sub so we can turn
14810     // X-Y -> X+~Y+1, saving one register.
14811     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
14812         isa<ConstantSDNode>(Op1.getOperand(1))) {
14813       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
14814       EVT VT = Op0.getValueType();
14815       SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
14816                                    Op1.getOperand(0),
14817                                    DAG.getConstant(~XorC, VT));
14818       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
14819                          DAG.getConstant(C->getAPIntValue()+1, VT));
14820     }
14821   }
14822
14823   // Try to synthesize horizontal adds from adds of shuffles.
14824   EVT VT = N->getValueType(0);
14825   if ((Subtarget->hasSSSE3orAVX()) && (VT == MVT::v8i16 || VT == MVT::v4i32) &&
14826       isHorizontalBinOp(Op0, Op1, false))
14827     return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
14828
14829   return OptimizeConditionalInDecrement(N, DAG);
14830 }
14831
14832 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
14833                                              DAGCombinerInfo &DCI) const {
14834   SelectionDAG &DAG = DCI.DAG;
14835   switch (N->getOpcode()) {
14836   default: break;
14837   case ISD::EXTRACT_VECTOR_ELT:
14838     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
14839   case ISD::VSELECT:
14840   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
14841   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
14842   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
14843   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
14844   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
14845   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
14846   case ISD::SHL:
14847   case ISD::SRA:
14848   case ISD::SRL:            return PerformShiftCombine(N, DAG, Subtarget);
14849   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
14850   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
14851   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
14852   case ISD::LOAD:           return PerformLOADCombine(N, DAG, Subtarget);
14853   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
14854   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
14855   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
14856   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
14857   case X86ISD::FXOR:
14858   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
14859   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
14860   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
14861   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
14862   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG);
14863   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG);
14864   case X86ISD::SHUFPS:      // Handle all target specific shuffles
14865   case X86ISD::SHUFPD:
14866   case X86ISD::PALIGN:
14867   case X86ISD::PUNPCKHBW:
14868   case X86ISD::PUNPCKHWD:
14869   case X86ISD::PUNPCKHDQ:
14870   case X86ISD::PUNPCKHQDQ:
14871   case X86ISD::VPUNPCKHBWY:
14872   case X86ISD::VPUNPCKHWDY:
14873   case X86ISD::VPUNPCKHDQY:
14874   case X86ISD::VPUNPCKHQDQY:
14875   case X86ISD::UNPCKHPS:
14876   case X86ISD::UNPCKHPD:
14877   case X86ISD::VUNPCKHPSY:
14878   case X86ISD::VUNPCKHPDY:
14879   case X86ISD::PUNPCKLBW:
14880   case X86ISD::PUNPCKLWD:
14881   case X86ISD::PUNPCKLDQ:
14882   case X86ISD::PUNPCKLQDQ:
14883   case X86ISD::VPUNPCKLBWY:
14884   case X86ISD::VPUNPCKLWDY:
14885   case X86ISD::VPUNPCKLDQY:
14886   case X86ISD::VPUNPCKLQDQY:
14887   case X86ISD::UNPCKLPS:
14888   case X86ISD::UNPCKLPD:
14889   case X86ISD::VUNPCKLPSY:
14890   case X86ISD::VUNPCKLPDY:
14891   case X86ISD::MOVHLPS:
14892   case X86ISD::MOVLHPS:
14893   case X86ISD::PSHUFD:
14894   case X86ISD::PSHUFHW:
14895   case X86ISD::PSHUFLW:
14896   case X86ISD::MOVSS:
14897   case X86ISD::MOVSD:
14898   case X86ISD::VPERMILPS:
14899   case X86ISD::VPERMILPSY:
14900   case X86ISD::VPERMILPD:
14901   case X86ISD::VPERMILPDY:
14902   case X86ISD::VPERM2F128:
14903   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
14904   }
14905
14906   return SDValue();
14907 }
14908
14909 /// isTypeDesirableForOp - Return true if the target has native support for
14910 /// the specified value type and it is 'desirable' to use the type for the
14911 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
14912 /// instruction encodings are longer and some i16 instructions are slow.
14913 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
14914   if (!isTypeLegal(VT))
14915     return false;
14916   if (VT != MVT::i16)
14917     return true;
14918
14919   switch (Opc) {
14920   default:
14921     return true;
14922   case ISD::LOAD:
14923   case ISD::SIGN_EXTEND:
14924   case ISD::ZERO_EXTEND:
14925   case ISD::ANY_EXTEND:
14926   case ISD::SHL:
14927   case ISD::SRL:
14928   case ISD::SUB:
14929   case ISD::ADD:
14930   case ISD::MUL:
14931   case ISD::AND:
14932   case ISD::OR:
14933   case ISD::XOR:
14934     return false;
14935   }
14936 }
14937
14938 /// IsDesirableToPromoteOp - This method query the target whether it is
14939 /// beneficial for dag combiner to promote the specified node. If true, it
14940 /// should return the desired promotion type by reference.
14941 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
14942   EVT VT = Op.getValueType();
14943   if (VT != MVT::i16)
14944     return false;
14945
14946   bool Promote = false;
14947   bool Commute = false;
14948   switch (Op.getOpcode()) {
14949   default: break;
14950   case ISD::LOAD: {
14951     LoadSDNode *LD = cast<LoadSDNode>(Op);
14952     // If the non-extending load has a single use and it's not live out, then it
14953     // might be folded.
14954     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
14955                                                      Op.hasOneUse()*/) {
14956       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
14957              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
14958         // The only case where we'd want to promote LOAD (rather then it being
14959         // promoted as an operand is when it's only use is liveout.
14960         if (UI->getOpcode() != ISD::CopyToReg)
14961           return false;
14962       }
14963     }
14964     Promote = true;
14965     break;
14966   }
14967   case ISD::SIGN_EXTEND:
14968   case ISD::ZERO_EXTEND:
14969   case ISD::ANY_EXTEND:
14970     Promote = true;
14971     break;
14972   case ISD::SHL:
14973   case ISD::SRL: {
14974     SDValue N0 = Op.getOperand(0);
14975     // Look out for (store (shl (load), x)).
14976     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
14977       return false;
14978     Promote = true;
14979     break;
14980   }
14981   case ISD::ADD:
14982   case ISD::MUL:
14983   case ISD::AND:
14984   case ISD::OR:
14985   case ISD::XOR:
14986     Commute = true;
14987     // fallthrough
14988   case ISD::SUB: {
14989     SDValue N0 = Op.getOperand(0);
14990     SDValue N1 = Op.getOperand(1);
14991     if (!Commute && MayFoldLoad(N1))
14992       return false;
14993     // Avoid disabling potential load folding opportunities.
14994     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
14995       return false;
14996     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
14997       return false;
14998     Promote = true;
14999   }
15000   }
15001
15002   PVT = MVT::i32;
15003   return Promote;
15004 }
15005
15006 //===----------------------------------------------------------------------===//
15007 //                           X86 Inline Assembly Support
15008 //===----------------------------------------------------------------------===//
15009
15010 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
15011   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
15012
15013   std::string AsmStr = IA->getAsmString();
15014
15015   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
15016   SmallVector<StringRef, 4> AsmPieces;
15017   SplitString(AsmStr, AsmPieces, ";\n");
15018
15019   switch (AsmPieces.size()) {
15020   default: return false;
15021   case 1:
15022     AsmStr = AsmPieces[0];
15023     AsmPieces.clear();
15024     SplitString(AsmStr, AsmPieces, " \t");  // Split with whitespace.
15025
15026     // FIXME: this should verify that we are targeting a 486 or better.  If not,
15027     // we will turn this bswap into something that will be lowered to logical ops
15028     // instead of emitting the bswap asm.  For now, we don't support 486 or lower
15029     // so don't worry about this.
15030     // bswap $0
15031     if (AsmPieces.size() == 2 &&
15032         (AsmPieces[0] == "bswap" ||
15033          AsmPieces[0] == "bswapq" ||
15034          AsmPieces[0] == "bswapl") &&
15035         (AsmPieces[1] == "$0" ||
15036          AsmPieces[1] == "${0:q}")) {
15037       // No need to check constraints, nothing other than the equivalent of
15038       // "=r,0" would be valid here.
15039       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
15040       if (!Ty || Ty->getBitWidth() % 16 != 0)
15041         return false;
15042       return IntrinsicLowering::LowerToByteSwap(CI);
15043     }
15044     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
15045     if (CI->getType()->isIntegerTy(16) &&
15046         AsmPieces.size() == 3 &&
15047         (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
15048         AsmPieces[1] == "$$8," &&
15049         AsmPieces[2] == "${0:w}" &&
15050         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
15051       AsmPieces.clear();
15052       const std::string &ConstraintsStr = IA->getConstraintString();
15053       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
15054       std::sort(AsmPieces.begin(), AsmPieces.end());
15055       if (AsmPieces.size() == 4 &&
15056           AsmPieces[0] == "~{cc}" &&
15057           AsmPieces[1] == "~{dirflag}" &&
15058           AsmPieces[2] == "~{flags}" &&
15059           AsmPieces[3] == "~{fpsr}") {
15060         IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
15061         if (!Ty || Ty->getBitWidth() % 16 != 0)
15062           return false;
15063         return IntrinsicLowering::LowerToByteSwap(CI);
15064       }
15065     }
15066     break;
15067   case 3:
15068     if (CI->getType()->isIntegerTy(32) &&
15069         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
15070       SmallVector<StringRef, 4> Words;
15071       SplitString(AsmPieces[0], Words, " \t,");
15072       if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
15073           Words[2] == "${0:w}") {
15074         Words.clear();
15075         SplitString(AsmPieces[1], Words, " \t,");
15076         if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" &&
15077             Words[2] == "$0") {
15078           Words.clear();
15079           SplitString(AsmPieces[2], Words, " \t,");
15080           if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
15081               Words[2] == "${0:w}") {
15082             AsmPieces.clear();
15083             const std::string &ConstraintsStr = IA->getConstraintString();
15084             SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
15085             std::sort(AsmPieces.begin(), AsmPieces.end());
15086             if (AsmPieces.size() == 4 &&
15087                 AsmPieces[0] == "~{cc}" &&
15088                 AsmPieces[1] == "~{dirflag}" &&
15089                 AsmPieces[2] == "~{flags}" &&
15090                 AsmPieces[3] == "~{fpsr}") {
15091               IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
15092               if (!Ty || Ty->getBitWidth() % 16 != 0)
15093                 return false;
15094               return IntrinsicLowering::LowerToByteSwap(CI);
15095             }
15096           }
15097         }
15098       }
15099     }
15100
15101     if (CI->getType()->isIntegerTy(64)) {
15102       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
15103       if (Constraints.size() >= 2 &&
15104           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
15105           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
15106         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
15107         SmallVector<StringRef, 4> Words;
15108         SplitString(AsmPieces[0], Words, " \t");
15109         if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
15110           Words.clear();
15111           SplitString(AsmPieces[1], Words, " \t");
15112           if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
15113             Words.clear();
15114             SplitString(AsmPieces[2], Words, " \t,");
15115             if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
15116                 Words[2] == "%edx") {
15117               IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
15118               if (!Ty || Ty->getBitWidth() % 16 != 0)
15119                 return false;
15120               return IntrinsicLowering::LowerToByteSwap(CI);
15121             }
15122           }
15123         }
15124       }
15125     }
15126     break;
15127   }
15128   return false;
15129 }
15130
15131
15132
15133 /// getConstraintType - Given a constraint letter, return the type of
15134 /// constraint it is for this target.
15135 X86TargetLowering::ConstraintType
15136 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
15137   if (Constraint.size() == 1) {
15138     switch (Constraint[0]) {
15139     case 'R':
15140     case 'q':
15141     case 'Q':
15142     case 'f':
15143     case 't':
15144     case 'u':
15145     case 'y':
15146     case 'x':
15147     case 'Y':
15148     case 'l':
15149       return C_RegisterClass;
15150     case 'a':
15151     case 'b':
15152     case 'c':
15153     case 'd':
15154     case 'S':
15155     case 'D':
15156     case 'A':
15157       return C_Register;
15158     case 'I':
15159     case 'J':
15160     case 'K':
15161     case 'L':
15162     case 'M':
15163     case 'N':
15164     case 'G':
15165     case 'C':
15166     case 'e':
15167     case 'Z':
15168       return C_Other;
15169     default:
15170       break;
15171     }
15172   }
15173   return TargetLowering::getConstraintType(Constraint);
15174 }
15175
15176 /// Examine constraint type and operand type and determine a weight value.
15177 /// This object must already have been set up with the operand type
15178 /// and the current alternative constraint selected.
15179 TargetLowering::ConstraintWeight
15180   X86TargetLowering::getSingleConstraintMatchWeight(
15181     AsmOperandInfo &info, const char *constraint) const {
15182   ConstraintWeight weight = CW_Invalid;
15183   Value *CallOperandVal = info.CallOperandVal;
15184     // If we don't have a value, we can't do a match,
15185     // but allow it at the lowest weight.
15186   if (CallOperandVal == NULL)
15187     return CW_Default;
15188   Type *type = CallOperandVal->getType();
15189   // Look at the constraint type.
15190   switch (*constraint) {
15191   default:
15192     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
15193   case 'R':
15194   case 'q':
15195   case 'Q':
15196   case 'a':
15197   case 'b':
15198   case 'c':
15199   case 'd':
15200   case 'S':
15201   case 'D':
15202   case 'A':
15203     if (CallOperandVal->getType()->isIntegerTy())
15204       weight = CW_SpecificReg;
15205     break;
15206   case 'f':
15207   case 't':
15208   case 'u':
15209       if (type->isFloatingPointTy())
15210         weight = CW_SpecificReg;
15211       break;
15212   case 'y':
15213       if (type->isX86_MMXTy() && Subtarget->hasMMX())
15214         weight = CW_SpecificReg;
15215       break;
15216   case 'x':
15217   case 'Y':
15218     if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
15219       weight = CW_Register;
15220     break;
15221   case 'I':
15222     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
15223       if (C->getZExtValue() <= 31)
15224         weight = CW_Constant;
15225     }
15226     break;
15227   case 'J':
15228     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15229       if (C->getZExtValue() <= 63)
15230         weight = CW_Constant;
15231     }
15232     break;
15233   case 'K':
15234     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15235       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
15236         weight = CW_Constant;
15237     }
15238     break;
15239   case 'L':
15240     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15241       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
15242         weight = CW_Constant;
15243     }
15244     break;
15245   case 'M':
15246     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15247       if (C->getZExtValue() <= 3)
15248         weight = CW_Constant;
15249     }
15250     break;
15251   case 'N':
15252     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15253       if (C->getZExtValue() <= 0xff)
15254         weight = CW_Constant;
15255     }
15256     break;
15257   case 'G':
15258   case 'C':
15259     if (dyn_cast<ConstantFP>(CallOperandVal)) {
15260       weight = CW_Constant;
15261     }
15262     break;
15263   case 'e':
15264     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15265       if ((C->getSExtValue() >= -0x80000000LL) &&
15266           (C->getSExtValue() <= 0x7fffffffLL))
15267         weight = CW_Constant;
15268     }
15269     break;
15270   case 'Z':
15271     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15272       if (C->getZExtValue() <= 0xffffffff)
15273         weight = CW_Constant;
15274     }
15275     break;
15276   }
15277   return weight;
15278 }
15279
15280 /// LowerXConstraint - try to replace an X constraint, which matches anything,
15281 /// with another that has more specific requirements based on the type of the
15282 /// corresponding operand.
15283 const char *X86TargetLowering::
15284 LowerXConstraint(EVT ConstraintVT) const {
15285   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
15286   // 'f' like normal targets.
15287   if (ConstraintVT.isFloatingPoint()) {
15288     if (Subtarget->hasXMMInt())
15289       return "Y";
15290     if (Subtarget->hasXMM())
15291       return "x";
15292   }
15293
15294   return TargetLowering::LowerXConstraint(ConstraintVT);
15295 }
15296
15297 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
15298 /// vector.  If it is invalid, don't add anything to Ops.
15299 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
15300                                                      std::string &Constraint,
15301                                                      std::vector<SDValue>&Ops,
15302                                                      SelectionDAG &DAG) const {
15303   SDValue Result(0, 0);
15304
15305   // Only support length 1 constraints for now.
15306   if (Constraint.length() > 1) return;
15307
15308   char ConstraintLetter = Constraint[0];
15309   switch (ConstraintLetter) {
15310   default: break;
15311   case 'I':
15312     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15313       if (C->getZExtValue() <= 31) {
15314         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15315         break;
15316       }
15317     }
15318     return;
15319   case 'J':
15320     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15321       if (C->getZExtValue() <= 63) {
15322         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15323         break;
15324       }
15325     }
15326     return;
15327   case 'K':
15328     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15329       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
15330         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15331         break;
15332       }
15333     }
15334     return;
15335   case 'N':
15336     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15337       if (C->getZExtValue() <= 255) {
15338         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15339         break;
15340       }
15341     }
15342     return;
15343   case 'e': {
15344     // 32-bit signed value
15345     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15346       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
15347                                            C->getSExtValue())) {
15348         // Widen to 64 bits here to get it sign extended.
15349         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
15350         break;
15351       }
15352     // FIXME gcc accepts some relocatable values here too, but only in certain
15353     // memory models; it's complicated.
15354     }
15355     return;
15356   }
15357   case 'Z': {
15358     // 32-bit unsigned value
15359     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15360       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
15361                                            C->getZExtValue())) {
15362         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15363         break;
15364       }
15365     }
15366     // FIXME gcc accepts some relocatable values here too, but only in certain
15367     // memory models; it's complicated.
15368     return;
15369   }
15370   case 'i': {
15371     // Literal immediates are always ok.
15372     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
15373       // Widen to 64 bits here to get it sign extended.
15374       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
15375       break;
15376     }
15377
15378     // In any sort of PIC mode addresses need to be computed at runtime by
15379     // adding in a register or some sort of table lookup.  These can't
15380     // be used as immediates.
15381     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
15382       return;
15383
15384     // If we are in non-pic codegen mode, we allow the address of a global (with
15385     // an optional displacement) to be used with 'i'.
15386     GlobalAddressSDNode *GA = 0;
15387     int64_t Offset = 0;
15388
15389     // Match either (GA), (GA+C), (GA+C1+C2), etc.
15390     while (1) {
15391       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
15392         Offset += GA->getOffset();
15393         break;
15394       } else if (Op.getOpcode() == ISD::ADD) {
15395         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
15396           Offset += C->getZExtValue();
15397           Op = Op.getOperand(0);
15398           continue;
15399         }
15400       } else if (Op.getOpcode() == ISD::SUB) {
15401         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
15402           Offset += -C->getZExtValue();
15403           Op = Op.getOperand(0);
15404           continue;
15405         }
15406       }
15407
15408       // Otherwise, this isn't something we can handle, reject it.
15409       return;
15410     }
15411
15412     const GlobalValue *GV = GA->getGlobal();
15413     // If we require an extra load to get this address, as in PIC mode, we
15414     // can't accept it.
15415     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
15416                                                         getTargetMachine())))
15417       return;
15418
15419     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
15420                                         GA->getValueType(0), Offset);
15421     break;
15422   }
15423   }
15424
15425   if (Result.getNode()) {
15426     Ops.push_back(Result);
15427     return;
15428   }
15429   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
15430 }
15431
15432 std::pair<unsigned, const TargetRegisterClass*>
15433 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
15434                                                 EVT VT) const {
15435   // First, see if this is a constraint that directly corresponds to an LLVM
15436   // register class.
15437   if (Constraint.size() == 1) {
15438     // GCC Constraint Letters
15439     switch (Constraint[0]) {
15440     default: break;
15441       // TODO: Slight differences here in allocation order and leaving
15442       // RIP in the class. Do they matter any more here than they do
15443       // in the normal allocation?
15444     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
15445       if (Subtarget->is64Bit()) {
15446         if (VT == MVT::i32 || VT == MVT::f32)
15447           return std::make_pair(0U, X86::GR32RegisterClass);
15448         else if (VT == MVT::i16)
15449           return std::make_pair(0U, X86::GR16RegisterClass);
15450         else if (VT == MVT::i8 || VT == MVT::i1)
15451           return std::make_pair(0U, X86::GR8RegisterClass);
15452         else if (VT == MVT::i64 || VT == MVT::f64)
15453           return std::make_pair(0U, X86::GR64RegisterClass);
15454         break;
15455       }
15456       // 32-bit fallthrough
15457     case 'Q':   // Q_REGS
15458       if (VT == MVT::i32 || VT == MVT::f32)
15459         return std::make_pair(0U, X86::GR32_ABCDRegisterClass);
15460       else if (VT == MVT::i16)
15461         return std::make_pair(0U, X86::GR16_ABCDRegisterClass);
15462       else if (VT == MVT::i8 || VT == MVT::i1)
15463         return std::make_pair(0U, X86::GR8_ABCD_LRegisterClass);
15464       else if (VT == MVT::i64)
15465         return std::make_pair(0U, X86::GR64_ABCDRegisterClass);
15466       break;
15467     case 'r':   // GENERAL_REGS
15468     case 'l':   // INDEX_REGS
15469       if (VT == MVT::i8 || VT == MVT::i1)
15470         return std::make_pair(0U, X86::GR8RegisterClass);
15471       if (VT == MVT::i16)
15472         return std::make_pair(0U, X86::GR16RegisterClass);
15473       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
15474         return std::make_pair(0U, X86::GR32RegisterClass);
15475       return std::make_pair(0U, X86::GR64RegisterClass);
15476     case 'R':   // LEGACY_REGS
15477       if (VT == MVT::i8 || VT == MVT::i1)
15478         return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
15479       if (VT == MVT::i16)
15480         return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
15481       if (VT == MVT::i32 || !Subtarget->is64Bit())
15482         return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
15483       return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
15484     case 'f':  // FP Stack registers.
15485       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
15486       // value to the correct fpstack register class.
15487       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
15488         return std::make_pair(0U, X86::RFP32RegisterClass);
15489       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
15490         return std::make_pair(0U, X86::RFP64RegisterClass);
15491       return std::make_pair(0U, X86::RFP80RegisterClass);
15492     case 'y':   // MMX_REGS if MMX allowed.
15493       if (!Subtarget->hasMMX()) break;
15494       return std::make_pair(0U, X86::VR64RegisterClass);
15495     case 'Y':   // SSE_REGS if SSE2 allowed
15496       if (!Subtarget->hasXMMInt()) break;
15497       // FALL THROUGH.
15498     case 'x':   // SSE_REGS if SSE1 allowed
15499       if (!Subtarget->hasXMM()) break;
15500
15501       switch (VT.getSimpleVT().SimpleTy) {
15502       default: break;
15503       // Scalar SSE types.
15504       case MVT::f32:
15505       case MVT::i32:
15506         return std::make_pair(0U, X86::FR32RegisterClass);
15507       case MVT::f64:
15508       case MVT::i64:
15509         return std::make_pair(0U, X86::FR64RegisterClass);
15510       // Vector types.
15511       case MVT::v16i8:
15512       case MVT::v8i16:
15513       case MVT::v4i32:
15514       case MVT::v2i64:
15515       case MVT::v4f32:
15516       case MVT::v2f64:
15517         return std::make_pair(0U, X86::VR128RegisterClass);
15518       }
15519       break;
15520     }
15521   }
15522
15523   // Use the default implementation in TargetLowering to convert the register
15524   // constraint into a member of a register class.
15525   std::pair<unsigned, const TargetRegisterClass*> Res;
15526   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
15527
15528   // Not found as a standard register?
15529   if (Res.second == 0) {
15530     // Map st(0) -> st(7) -> ST0
15531     if (Constraint.size() == 7 && Constraint[0] == '{' &&
15532         tolower(Constraint[1]) == 's' &&
15533         tolower(Constraint[2]) == 't' &&
15534         Constraint[3] == '(' &&
15535         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
15536         Constraint[5] == ')' &&
15537         Constraint[6] == '}') {
15538
15539       Res.first = X86::ST0+Constraint[4]-'0';
15540       Res.second = X86::RFP80RegisterClass;
15541       return Res;
15542     }
15543
15544     // GCC allows "st(0)" to be called just plain "st".
15545     if (StringRef("{st}").equals_lower(Constraint)) {
15546       Res.first = X86::ST0;
15547       Res.second = X86::RFP80RegisterClass;
15548       return Res;
15549     }
15550
15551     // flags -> EFLAGS
15552     if (StringRef("{flags}").equals_lower(Constraint)) {
15553       Res.first = X86::EFLAGS;
15554       Res.second = X86::CCRRegisterClass;
15555       return Res;
15556     }
15557
15558     // 'A' means EAX + EDX.
15559     if (Constraint == "A") {
15560       Res.first = X86::EAX;
15561       Res.second = X86::GR32_ADRegisterClass;
15562       return Res;
15563     }
15564     return Res;
15565   }
15566
15567   // Otherwise, check to see if this is a register class of the wrong value
15568   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
15569   // turn into {ax},{dx}.
15570   if (Res.second->hasType(VT))
15571     return Res;   // Correct type already, nothing to do.
15572
15573   // All of the single-register GCC register classes map their values onto
15574   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
15575   // really want an 8-bit or 32-bit register, map to the appropriate register
15576   // class and return the appropriate register.
15577   if (Res.second == X86::GR16RegisterClass) {
15578     if (VT == MVT::i8) {
15579       unsigned DestReg = 0;
15580       switch (Res.first) {
15581       default: break;
15582       case X86::AX: DestReg = X86::AL; break;
15583       case X86::DX: DestReg = X86::DL; break;
15584       case X86::CX: DestReg = X86::CL; break;
15585       case X86::BX: DestReg = X86::BL; break;
15586       }
15587       if (DestReg) {
15588         Res.first = DestReg;
15589         Res.second = X86::GR8RegisterClass;
15590       }
15591     } else if (VT == MVT::i32) {
15592       unsigned DestReg = 0;
15593       switch (Res.first) {
15594       default: break;
15595       case X86::AX: DestReg = X86::EAX; break;
15596       case X86::DX: DestReg = X86::EDX; break;
15597       case X86::CX: DestReg = X86::ECX; break;
15598       case X86::BX: DestReg = X86::EBX; break;
15599       case X86::SI: DestReg = X86::ESI; break;
15600       case X86::DI: DestReg = X86::EDI; break;
15601       case X86::BP: DestReg = X86::EBP; break;
15602       case X86::SP: DestReg = X86::ESP; break;
15603       }
15604       if (DestReg) {
15605         Res.first = DestReg;
15606         Res.second = X86::GR32RegisterClass;
15607       }
15608     } else if (VT == MVT::i64) {
15609       unsigned DestReg = 0;
15610       switch (Res.first) {
15611       default: break;
15612       case X86::AX: DestReg = X86::RAX; break;
15613       case X86::DX: DestReg = X86::RDX; break;
15614       case X86::CX: DestReg = X86::RCX; break;
15615       case X86::BX: DestReg = X86::RBX; break;
15616       case X86::SI: DestReg = X86::RSI; break;
15617       case X86::DI: DestReg = X86::RDI; break;
15618       case X86::BP: DestReg = X86::RBP; break;
15619       case X86::SP: DestReg = X86::RSP; break;
15620       }
15621       if (DestReg) {
15622         Res.first = DestReg;
15623         Res.second = X86::GR64RegisterClass;
15624       }
15625     }
15626   } else if (Res.second == X86::FR32RegisterClass ||
15627              Res.second == X86::FR64RegisterClass ||
15628              Res.second == X86::VR128RegisterClass) {
15629     // Handle references to XMM physical registers that got mapped into the
15630     // wrong class.  This can happen with constraints like {xmm0} where the
15631     // target independent register mapper will just pick the first match it can
15632     // find, ignoring the required type.
15633     if (VT == MVT::f32)
15634       Res.second = X86::FR32RegisterClass;
15635     else if (VT == MVT::f64)
15636       Res.second = X86::FR64RegisterClass;
15637     else if (X86::VR128RegisterClass->hasType(VT))
15638       Res.second = X86::VR128RegisterClass;
15639   }
15640
15641   return Res;
15642 }