No case stmt for BUILD_VECTOR in PerformDAGCombine(), so I assume this isn't
[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/VariadicFunction.h"
47 #include "llvm/ADT/VectorExtras.h"
48 #include "llvm/Support/CallSite.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/Dwarf.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Support/raw_ostream.h"
54 #include "llvm/Target/TargetOptions.h"
55 using namespace llvm;
56 using namespace dwarf;
57
58 STATISTIC(NumTailCalls, "Number of tail calls");
59
60 // Forward declarations.
61 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
62                        SDValue V2);
63
64 static SDValue Insert128BitVector(SDValue Result,
65                                   SDValue Vec,
66                                   SDValue Idx,
67                                   SelectionDAG &DAG,
68                                   DebugLoc dl);
69
70 static SDValue Extract128BitVector(SDValue Vec,
71                                    SDValue Idx,
72                                    SelectionDAG &DAG,
73                                    DebugLoc dl);
74
75 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
76 /// sets things up to match to an AVX VEXTRACTF128 instruction or a
77 /// simple subregister reference.  Idx is an index in the 128 bits we
78 /// want.  It need not be aligned to a 128-bit bounday.  That makes
79 /// lowering EXTRACT_VECTOR_ELT operations easier.
80 static SDValue Extract128BitVector(SDValue Vec,
81                                    SDValue Idx,
82                                    SelectionDAG &DAG,
83                                    DebugLoc dl) {
84   EVT VT = Vec.getValueType();
85   assert(VT.getSizeInBits() == 256 && "Unexpected vector size!");
86   EVT ElVT = VT.getVectorElementType();
87   int Factor = VT.getSizeInBits()/128;
88   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
89                                   VT.getVectorNumElements()/Factor);
90
91   // Extract from UNDEF is UNDEF.
92   if (Vec.getOpcode() == ISD::UNDEF)
93     return DAG.getNode(ISD::UNDEF, dl, ResultVT);
94
95   if (isa<ConstantSDNode>(Idx)) {
96     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
97
98     // Extract the relevant 128 bits.  Generate an EXTRACT_SUBVECTOR
99     // we can match to VEXTRACTF128.
100     unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
101
102     // This is the index of the first element of the 128-bit chunk
103     // we want.
104     unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
105                                  * ElemsPerChunk);
106
107     SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
108     SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
109                                  VecIdx);
110
111     return Result;
112   }
113
114   return SDValue();
115 }
116
117 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
118 /// sets things up to match to an AVX VINSERTF128 instruction or a
119 /// simple superregister reference.  Idx is an index in the 128 bits
120 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
121 /// lowering INSERT_VECTOR_ELT operations easier.
122 static SDValue Insert128BitVector(SDValue Result,
123                                   SDValue Vec,
124                                   SDValue Idx,
125                                   SelectionDAG &DAG,
126                                   DebugLoc dl) {
127   if (isa<ConstantSDNode>(Idx)) {
128     EVT VT = Vec.getValueType();
129     assert(VT.getSizeInBits() == 128 && "Unexpected vector size!");
130
131     EVT ElVT = VT.getVectorElementType();
132     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
133     EVT ResultVT = Result.getValueType();
134
135     // Insert the relevant 128 bits.
136     unsigned ElemsPerChunk = 128/ElVT.getSizeInBits();
137
138     // This is the index of the first element of the 128-bit chunk
139     // we want.
140     unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/128)
141                                  * ElemsPerChunk);
142
143     SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
144     Result = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
145                          VecIdx);
146     return Result;
147   }
148
149   return SDValue();
150 }
151
152 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
153   const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
154   bool is64Bit = Subtarget->is64Bit();
155
156   if (Subtarget->isTargetEnvMacho()) {
157     if (is64Bit)
158       return new X8664_MachoTargetObjectFile();
159     return new TargetLoweringObjectFileMachO();
160   }
161
162   if (Subtarget->isTargetELF())
163     return new TargetLoweringObjectFileELF();
164   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
165     return new TargetLoweringObjectFileCOFF();
166   llvm_unreachable("unknown subtarget type");
167 }
168
169 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
170   : TargetLowering(TM, createTLOF(TM)) {
171   Subtarget = &TM.getSubtarget<X86Subtarget>();
172   X86ScalarSSEf64 = Subtarget->hasXMMInt();
173   X86ScalarSSEf32 = Subtarget->hasXMM();
174   X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
175
176   RegInfo = TM.getRegisterInfo();
177   TD = getTargetData();
178
179   // Set up the TargetLowering object.
180   static MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
181
182   // X86 is weird, it always uses i8 for shift amounts and setcc results.
183   setBooleanContents(ZeroOrOneBooleanContent);
184   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
185   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
186
187   // For 64-bit since we have so many registers use the ILP scheduler, for
188   // 32-bit code use the register pressure specific scheduling.
189   if (Subtarget->is64Bit())
190     setSchedulingPreference(Sched::ILP);
191   else
192     setSchedulingPreference(Sched::RegPressure);
193   setStackPointerRegisterToSaveRestore(X86StackPtr);
194
195   if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
196     // Setup Windows compiler runtime calls.
197     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
198     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
199     setLibcallName(RTLIB::SREM_I64, "_allrem");
200     setLibcallName(RTLIB::UREM_I64, "_aullrem");
201     setLibcallName(RTLIB::MUL_I64, "_allmul");
202     setLibcallName(RTLIB::FPTOUINT_F64_I64, "_ftol2");
203     setLibcallName(RTLIB::FPTOUINT_F32_I64, "_ftol2");
204     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
205     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
206     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
207     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
208     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
209     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::C);
210     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::C);
211   }
212
213   if (Subtarget->isTargetDarwin()) {
214     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
215     setUseUnderscoreSetJmp(false);
216     setUseUnderscoreLongJmp(false);
217   } else if (Subtarget->isTargetMingw()) {
218     // MS runtime is weird: it exports _setjmp, but longjmp!
219     setUseUnderscoreSetJmp(true);
220     setUseUnderscoreLongJmp(false);
221   } else {
222     setUseUnderscoreSetJmp(true);
223     setUseUnderscoreLongJmp(true);
224   }
225
226   // Set up the register classes.
227   addRegisterClass(MVT::i8, X86::GR8RegisterClass);
228   addRegisterClass(MVT::i16, X86::GR16RegisterClass);
229   addRegisterClass(MVT::i32, X86::GR32RegisterClass);
230   if (Subtarget->is64Bit())
231     addRegisterClass(MVT::i64, X86::GR64RegisterClass);
232
233   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
234
235   // We don't accept any truncstore of integer registers.
236   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
237   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
238   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
239   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
240   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
241   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
242
243   // SETOEQ and SETUNE require checking two conditions.
244   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
245   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
246   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
247   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
248   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
249   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
250
251   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
252   // operation.
253   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
254   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
255   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
256
257   if (Subtarget->is64Bit()) {
258     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
259     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Expand);
260   } else if (!TM.Options.UseSoftFloat) {
261     // We have an algorithm for SSE2->double, and we turn this into a
262     // 64-bit FILD followed by conditional FADD for other targets.
263     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
264     // We have an algorithm for SSE2, and we turn this into a 64-bit
265     // FILD for other targets.
266     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
267   }
268
269   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
270   // this operation.
271   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
272   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
273
274   if (!TM.Options.UseSoftFloat) {
275     // SSE has no i16 to fp conversion, only i32
276     if (X86ScalarSSEf32) {
277       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
278       // f32 and f64 cases are Legal, f80 case is not
279       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
280     } else {
281       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
282       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
283     }
284   } else {
285     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
286     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
287   }
288
289   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
290   // are Legal, f80 is custom lowered.
291   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
292   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
293
294   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
295   // this operation.
296   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
297   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
298
299   if (X86ScalarSSEf32) {
300     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
301     // f32 and f64 cases are Legal, f80 case is not
302     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
303   } else {
304     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
305     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
306   }
307
308   // Handle FP_TO_UINT by promoting the destination to a larger signed
309   // conversion.
310   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
311   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
312   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
313
314   if (Subtarget->is64Bit()) {
315     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
316     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
317   } else if (!TM.Options.UseSoftFloat) {
318     // Since AVX is a superset of SSE3, only check for SSE here.
319     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
320       // Expand FP_TO_UINT into a select.
321       // FIXME: We would like to use a Custom expander here eventually to do
322       // the optimal thing for SSE vs. the default expansion in the legalizer.
323       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
324     else
325       // With SSE3 we can use fisttpll to convert to a signed i64; without
326       // SSE, we're stuck with a fistpll.
327       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
328   }
329
330   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
331   if (!X86ScalarSSEf64) {
332     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
333     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
334     if (Subtarget->is64Bit()) {
335       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
336       // Without SSE, i64->f64 goes through memory.
337       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
338     }
339   }
340
341   // Scalar integer divide and remainder are lowered to use operations that
342   // produce two results, to match the available instructions. This exposes
343   // the two-result form to trivial CSE, which is able to combine x/y and x%y
344   // into a single instruction.
345   //
346   // Scalar integer multiply-high is also lowered to use two-result
347   // operations, to match the available instructions. However, plain multiply
348   // (low) operations are left as Legal, as there are single-result
349   // instructions for this in x86. Using the two-result multiply instructions
350   // when both high and low results are needed must be arranged by dagcombine.
351   for (unsigned i = 0, e = 4; i != e; ++i) {
352     MVT VT = IntVTs[i];
353     setOperationAction(ISD::MULHS, VT, Expand);
354     setOperationAction(ISD::MULHU, VT, Expand);
355     setOperationAction(ISD::SDIV, VT, Expand);
356     setOperationAction(ISD::UDIV, VT, Expand);
357     setOperationAction(ISD::SREM, VT, Expand);
358     setOperationAction(ISD::UREM, VT, Expand);
359
360     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
361     setOperationAction(ISD::ADDC, VT, Custom);
362     setOperationAction(ISD::ADDE, VT, Custom);
363     setOperationAction(ISD::SUBC, VT, Custom);
364     setOperationAction(ISD::SUBE, VT, Custom);
365   }
366
367   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
368   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
369   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
370   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
371   if (Subtarget->is64Bit())
372     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
373   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
374   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
375   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
376   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
377   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
378   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
379   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
380   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
381
382   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Expand);
383   if (Subtarget->hasBMI()) {
384     setOperationAction(ISD::CTTZ           , MVT::i8   , Promote);
385   } else {
386     setOperationAction(ISD::CTTZ           , MVT::i8   , Custom);
387     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
388     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
389     if (Subtarget->is64Bit())
390       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
391   }
392
393   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i8   , Expand);
394   if (Subtarget->hasLZCNT()) {
395     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
396   } else {
397     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
398     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
399     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
400     if (Subtarget->is64Bit())
401       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
402   }
403
404   if (Subtarget->hasPOPCNT()) {
405     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
406   } else {
407     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
408     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
409     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
410     if (Subtarget->is64Bit())
411       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
412   }
413
414   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
415   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
416
417   // These should be promoted to a larger select which is supported.
418   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
419   // X86 wants to expand cmov itself.
420   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
421   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
422   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
423   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
424   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
425   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
426   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
427   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
428   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
429   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
430   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
431   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
432   if (Subtarget->is64Bit()) {
433     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
434     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
435   }
436   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
437
438   // Darwin ABI issue.
439   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
440   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
441   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
442   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
443   if (Subtarget->is64Bit())
444     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
445   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
446   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
447   if (Subtarget->is64Bit()) {
448     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
449     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
450     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
451     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
452     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
453   }
454   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
455   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
456   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
457   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
458   if (Subtarget->is64Bit()) {
459     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
460     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
461     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
462   }
463
464   if (Subtarget->hasXMM())
465     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
466
467   setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
468   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
469
470   // On X86 and X86-64, atomic operations are lowered to locked instructions.
471   // Locked instructions, in turn, have implicit fence semantics (all memory
472   // operations are flushed before issuing the locked instruction, and they
473   // are not buffered), so we can fold away the common pattern of
474   // fence-atomic-fence.
475   setShouldFoldAtomicFences(true);
476
477   // Expand certain atomics
478   for (unsigned i = 0, e = 4; i != e; ++i) {
479     MVT VT = IntVTs[i];
480     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
481     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
482     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
483   }
484
485   if (!Subtarget->is64Bit()) {
486     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
487     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
488     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
489     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
490     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
491     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
492     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
493     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
494   }
495
496   if (Subtarget->hasCmpxchg16b()) {
497     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
498   }
499
500   // FIXME - use subtarget debug flags
501   if (!Subtarget->isTargetDarwin() &&
502       !Subtarget->isTargetELF() &&
503       !Subtarget->isTargetCygMing()) {
504     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
505   }
506
507   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
508   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
509   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
510   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
511   if (Subtarget->is64Bit()) {
512     setExceptionPointerRegister(X86::RAX);
513     setExceptionSelectorRegister(X86::RDX);
514   } else {
515     setExceptionPointerRegister(X86::EAX);
516     setExceptionSelectorRegister(X86::EDX);
517   }
518   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
519   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
520
521   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
522   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
523
524   setOperationAction(ISD::TRAP, MVT::Other, Legal);
525
526   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
527   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
528   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
529   if (Subtarget->is64Bit()) {
530     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
531     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
532   } else {
533     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
534     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
535   }
536
537   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
538   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
539
540   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
541     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
542                        MVT::i64 : MVT::i32, Custom);
543   else if (TM.Options.EnableSegmentedStacks)
544     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
545                        MVT::i64 : MVT::i32, Custom);
546   else
547     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
548                        MVT::i64 : MVT::i32, Expand);
549
550   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
551     // f32 and f64 use SSE.
552     // Set up the FP register classes.
553     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
554     addRegisterClass(MVT::f64, X86::FR64RegisterClass);
555
556     // Use ANDPD to simulate FABS.
557     setOperationAction(ISD::FABS , MVT::f64, Custom);
558     setOperationAction(ISD::FABS , MVT::f32, Custom);
559
560     // Use XORP to simulate FNEG.
561     setOperationAction(ISD::FNEG , MVT::f64, Custom);
562     setOperationAction(ISD::FNEG , MVT::f32, Custom);
563
564     // Use ANDPD and ORPD to simulate FCOPYSIGN.
565     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
566     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
567
568     // Lower this to FGETSIGNx86 plus an AND.
569     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
570     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
571
572     // We don't support sin/cos/fmod
573     setOperationAction(ISD::FSIN , MVT::f64, Expand);
574     setOperationAction(ISD::FCOS , MVT::f64, Expand);
575     setOperationAction(ISD::FSIN , MVT::f32, Expand);
576     setOperationAction(ISD::FCOS , MVT::f32, Expand);
577
578     // Expand FP immediates into loads from the stack, except for the special
579     // cases we handle.
580     addLegalFPImmediate(APFloat(+0.0)); // xorpd
581     addLegalFPImmediate(APFloat(+0.0f)); // xorps
582   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
583     // Use SSE for f32, x87 for f64.
584     // Set up the FP register classes.
585     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
586     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
587
588     // Use ANDPS to simulate FABS.
589     setOperationAction(ISD::FABS , MVT::f32, Custom);
590
591     // Use XORP to simulate FNEG.
592     setOperationAction(ISD::FNEG , MVT::f32, Custom);
593
594     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
595
596     // Use ANDPS and ORPS to simulate FCOPYSIGN.
597     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
598     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
599
600     // We don't support sin/cos/fmod
601     setOperationAction(ISD::FSIN , MVT::f32, Expand);
602     setOperationAction(ISD::FCOS , MVT::f32, Expand);
603
604     // Special cases we handle for FP constants.
605     addLegalFPImmediate(APFloat(+0.0f)); // xorps
606     addLegalFPImmediate(APFloat(+0.0)); // FLD0
607     addLegalFPImmediate(APFloat(+1.0)); // FLD1
608     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
609     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
610
611     if (!TM.Options.UnsafeFPMath) {
612       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
613       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
614     }
615   } else if (!TM.Options.UseSoftFloat) {
616     // f32 and f64 in x87.
617     // Set up the FP register classes.
618     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
619     addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
620
621     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
622     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
623     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
624     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
625
626     if (!TM.Options.UnsafeFPMath) {
627       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
628       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
629     }
630     addLegalFPImmediate(APFloat(+0.0)); // FLD0
631     addLegalFPImmediate(APFloat(+1.0)); // FLD1
632     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
633     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
634     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
635     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
636     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
637     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
638   }
639
640   // We don't support FMA.
641   setOperationAction(ISD::FMA, MVT::f64, Expand);
642   setOperationAction(ISD::FMA, MVT::f32, Expand);
643
644   // Long double always uses X87.
645   if (!TM.Options.UseSoftFloat) {
646     addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
647     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
648     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
649     {
650       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
651       addLegalFPImmediate(TmpFlt);  // FLD0
652       TmpFlt.changeSign();
653       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
654
655       bool ignored;
656       APFloat TmpFlt2(+1.0);
657       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
658                       &ignored);
659       addLegalFPImmediate(TmpFlt2);  // FLD1
660       TmpFlt2.changeSign();
661       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
662     }
663
664     if (!TM.Options.UnsafeFPMath) {
665       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
666       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
667     }
668
669     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
670     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
671     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
672     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
673     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
674     setOperationAction(ISD::FMA, MVT::f80, Expand);
675   }
676
677   // Always use a library call for pow.
678   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
679   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
680   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
681
682   setOperationAction(ISD::FLOG, MVT::f80, Expand);
683   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
684   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
685   setOperationAction(ISD::FEXP, MVT::f80, Expand);
686   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
687
688   // First set operation action for all vector types to either promote
689   // (for widening) or expand (for scalarization). Then we will selectively
690   // turn on ones that can be effectively codegen'd.
691   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
692        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
693     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
694     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
695     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
696     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
697     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
698     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
699     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
700     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
701     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
702     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
703     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
704     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
705     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
706     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
707     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
708     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
709     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
710     setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
711     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
712     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
713     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
714     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
715     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
716     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
717     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
718     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
719     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
720     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
721     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
722     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
723     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
724     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
725     setOperationAction(ISD::CTTZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
726     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
727     setOperationAction(ISD::CTLZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
728     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
729     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
730     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
731     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
732     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
733     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
734     setOperationAction(ISD::SETCC, (MVT::SimpleValueType)VT, Expand);
735     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
736     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
737     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
738     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
739     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
740     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
741     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
742     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
743     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
744     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
745     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
746     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
747     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
748     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
749     setOperationAction(ISD::VSELECT,  (MVT::SimpleValueType)VT, Expand);
750     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
751          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
752       setTruncStoreAction((MVT::SimpleValueType)VT,
753                           (MVT::SimpleValueType)InnerVT, Expand);
754     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
755     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
756     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
757   }
758
759   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
760   // with -msoft-float, disable use of MMX as well.
761   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
762     addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass);
763     // No operations on x86mmx supported, everything uses intrinsics.
764   }
765
766   // MMX-sized vectors (other than x86mmx) are expected to be expanded
767   // into smaller operations.
768   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
769   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
770   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
771   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
772   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
773   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
774   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
775   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
776   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
777   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
778   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
779   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
780   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
781   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
782   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
783   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
784   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
785   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
786   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
787   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
788   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
789   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
790   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
791   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
792   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
793   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
794   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
795   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
796   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
797
798   if (!TM.Options.UseSoftFloat && Subtarget->hasXMM()) {
799     addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
800
801     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
802     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
803     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
804     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
805     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
806     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
807     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
808     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
809     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
810     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
811     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
812     setOperationAction(ISD::SETCC,              MVT::v4f32, Custom);
813   }
814
815   if (!TM.Options.UseSoftFloat && Subtarget->hasXMMInt()) {
816     addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
817
818     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
819     // registers cannot be used even for integer operations.
820     addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
821     addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
822     addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
823     addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
824
825     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
826     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
827     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
828     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
829     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
830     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
831     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
832     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
833     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
834     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
835     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
836     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
837     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
838     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
839     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
840     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
841
842     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
843     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
844     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
845     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
846
847     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
848     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
849     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
850     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
851     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
852
853     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2f64, Custom);
854     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2i64, Custom);
855     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i8, Custom);
856     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i16, Custom);
857     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i32, Custom);
858
859     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
860     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
861       EVT VT = (MVT::SimpleValueType)i;
862       // Do not attempt to custom lower non-power-of-2 vectors
863       if (!isPowerOf2_32(VT.getVectorNumElements()))
864         continue;
865       // Do not attempt to custom lower non-128-bit vectors
866       if (!VT.is128BitVector())
867         continue;
868       setOperationAction(ISD::BUILD_VECTOR,
869                          VT.getSimpleVT().SimpleTy, Custom);
870       setOperationAction(ISD::VECTOR_SHUFFLE,
871                          VT.getSimpleVT().SimpleTy, Custom);
872       setOperationAction(ISD::EXTRACT_VECTOR_ELT,
873                          VT.getSimpleVT().SimpleTy, Custom);
874     }
875
876     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
877     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
878     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
879     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
880     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
881     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
882
883     if (Subtarget->is64Bit()) {
884       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
885       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
886     }
887
888     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
889     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
890       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
891       EVT VT = SVT;
892
893       // Do not attempt to promote non-128-bit vectors
894       if (!VT.is128BitVector())
895         continue;
896
897       setOperationAction(ISD::AND,    SVT, Promote);
898       AddPromotedToType (ISD::AND,    SVT, MVT::v2i64);
899       setOperationAction(ISD::OR,     SVT, Promote);
900       AddPromotedToType (ISD::OR,     SVT, MVT::v2i64);
901       setOperationAction(ISD::XOR,    SVT, Promote);
902       AddPromotedToType (ISD::XOR,    SVT, MVT::v2i64);
903       setOperationAction(ISD::LOAD,   SVT, Promote);
904       AddPromotedToType (ISD::LOAD,   SVT, MVT::v2i64);
905       setOperationAction(ISD::SELECT, SVT, Promote);
906       AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
907     }
908
909     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
910
911     // Custom lower v2i64 and v2f64 selects.
912     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
913     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
914     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
915     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
916
917     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
918     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
919   }
920
921   if (Subtarget->hasSSE41orAVX()) {
922     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
923     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
924     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
925     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
926     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
927     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
928     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
929     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
930     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
931     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
932
933     // FIXME: Do we need to handle scalar-to-vector here?
934     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
935
936     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
937     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
938     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
939     setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
940     setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
941
942     // i8 and i16 vectors are custom , because the source register and source
943     // source memory operand types are not the same width.  f32 vectors are
944     // custom since the immediate controlling the insert encodes additional
945     // information.
946     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
947     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
948     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
949     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
950
951     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
952     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
953     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
954     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
955
956     // FIXME: these should be Legal but thats only for the case where
957     // the index is constant.  For now custom expand to deal with that
958     if (Subtarget->is64Bit()) {
959       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
960       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
961     }
962   }
963
964   if (Subtarget->hasXMMInt()) {
965     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
966     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
967
968     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
969     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
970
971     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
972     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
973
974     if (Subtarget->hasAVX2()) {
975       setOperationAction(ISD::SRL,             MVT::v2i64, Legal);
976       setOperationAction(ISD::SRL,             MVT::v4i32, Legal);
977
978       setOperationAction(ISD::SHL,             MVT::v2i64, Legal);
979       setOperationAction(ISD::SHL,             MVT::v4i32, Legal);
980
981       setOperationAction(ISD::SRA,             MVT::v4i32, Legal);
982     } else {
983       setOperationAction(ISD::SRL,             MVT::v2i64, Custom);
984       setOperationAction(ISD::SRL,             MVT::v4i32, Custom);
985
986       setOperationAction(ISD::SHL,             MVT::v2i64, Custom);
987       setOperationAction(ISD::SHL,             MVT::v4i32, Custom);
988
989       setOperationAction(ISD::SRA,             MVT::v4i32, Custom);
990     }
991   }
992
993   if (Subtarget->hasSSE42orAVX())
994     setOperationAction(ISD::SETCC,             MVT::v2i64, Custom);
995
996   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX()) {
997     addRegisterClass(MVT::v32i8,  X86::VR256RegisterClass);
998     addRegisterClass(MVT::v16i16, X86::VR256RegisterClass);
999     addRegisterClass(MVT::v8i32,  X86::VR256RegisterClass);
1000     addRegisterClass(MVT::v8f32,  X86::VR256RegisterClass);
1001     addRegisterClass(MVT::v4i64,  X86::VR256RegisterClass);
1002     addRegisterClass(MVT::v4f64,  X86::VR256RegisterClass);
1003
1004     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1005     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1006     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1007
1008     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1009     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1010     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1011     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1012     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1013     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1014
1015     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1016     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1017     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1018     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1019     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1020     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1021
1022     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1023     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1024     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1025
1026     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4f64,  Custom);
1027     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i64,  Custom);
1028     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f32,  Custom);
1029     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i32,  Custom);
1030     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i8,  Custom);
1031     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i16, Custom);
1032
1033     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1034     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1035
1036     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1037     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1038
1039     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1040     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1041
1042     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1043     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1044     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1045     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1046
1047     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1048     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1049     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1050
1051     setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1052     setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1053     setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1054     setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1055
1056     if (Subtarget->hasAVX2()) {
1057       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1058       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1059       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1060       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1061
1062       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1063       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1064       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1065       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1066
1067       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1068       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1069       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1070       // Don't lower v32i8 because there is no 128-bit byte mul
1071
1072       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1073
1074       setOperationAction(ISD::SRL,             MVT::v4i64, Legal);
1075       setOperationAction(ISD::SRL,             MVT::v8i32, Legal);
1076
1077       setOperationAction(ISD::SHL,             MVT::v4i64, Legal);
1078       setOperationAction(ISD::SHL,             MVT::v8i32, Legal);
1079
1080       setOperationAction(ISD::SRA,             MVT::v8i32, Legal);
1081     } else {
1082       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1083       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1084       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1085       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1086
1087       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1088       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1089       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1090       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1091
1092       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1093       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1094       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1095       // Don't lower v32i8 because there is no 128-bit byte mul
1096
1097       setOperationAction(ISD::SRL,             MVT::v4i64, Custom);
1098       setOperationAction(ISD::SRL,             MVT::v8i32, Custom);
1099
1100       setOperationAction(ISD::SHL,             MVT::v4i64, Custom);
1101       setOperationAction(ISD::SHL,             MVT::v8i32, Custom);
1102
1103       setOperationAction(ISD::SRA,             MVT::v8i32, Custom);
1104     }
1105
1106     // Custom lower several nodes for 256-bit types.
1107     for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1108                   i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
1109       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1110       EVT VT = SVT;
1111
1112       // Extract subvector is special because the value type
1113       // (result) is 128-bit but the source is 256-bit wide.
1114       if (VT.is128BitVector())
1115         setOperationAction(ISD::EXTRACT_SUBVECTOR, SVT, Custom);
1116
1117       // Do not attempt to custom lower other non-256-bit vectors
1118       if (!VT.is256BitVector())
1119         continue;
1120
1121       setOperationAction(ISD::BUILD_VECTOR,       SVT, Custom);
1122       setOperationAction(ISD::VECTOR_SHUFFLE,     SVT, Custom);
1123       setOperationAction(ISD::INSERT_VECTOR_ELT,  SVT, Custom);
1124       setOperationAction(ISD::EXTRACT_VECTOR_ELT, SVT, Custom);
1125       setOperationAction(ISD::SCALAR_TO_VECTOR,   SVT, Custom);
1126       setOperationAction(ISD::INSERT_SUBVECTOR,   SVT, Custom);
1127     }
1128
1129     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1130     for (unsigned i = (unsigned)MVT::v32i8; i != (unsigned)MVT::v4i64; ++i) {
1131       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1132       EVT VT = SVT;
1133
1134       // Do not attempt to promote non-256-bit vectors
1135       if (!VT.is256BitVector())
1136         continue;
1137
1138       setOperationAction(ISD::AND,    SVT, Promote);
1139       AddPromotedToType (ISD::AND,    SVT, MVT::v4i64);
1140       setOperationAction(ISD::OR,     SVT, Promote);
1141       AddPromotedToType (ISD::OR,     SVT, MVT::v4i64);
1142       setOperationAction(ISD::XOR,    SVT, Promote);
1143       AddPromotedToType (ISD::XOR,    SVT, MVT::v4i64);
1144       setOperationAction(ISD::LOAD,   SVT, Promote);
1145       AddPromotedToType (ISD::LOAD,   SVT, MVT::v4i64);
1146       setOperationAction(ISD::SELECT, SVT, Promote);
1147       AddPromotedToType (ISD::SELECT, SVT, MVT::v4i64);
1148     }
1149   }
1150
1151   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1152   // of this type with custom code.
1153   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1154          VT != (unsigned)MVT::LAST_VECTOR_VALUETYPE; VT++) {
1155     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT, Custom);
1156   }
1157
1158   // We want to custom lower some of our intrinsics.
1159   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1160
1161
1162   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1163   // handle type legalization for these operations here.
1164   //
1165   // FIXME: We really should do custom legalization for addition and
1166   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1167   // than generic legalization for 64-bit multiplication-with-overflow, though.
1168   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1169     // Add/Sub/Mul with overflow operations are custom lowered.
1170     MVT VT = IntVTs[i];
1171     setOperationAction(ISD::SADDO, VT, Custom);
1172     setOperationAction(ISD::UADDO, VT, Custom);
1173     setOperationAction(ISD::SSUBO, VT, Custom);
1174     setOperationAction(ISD::USUBO, VT, Custom);
1175     setOperationAction(ISD::SMULO, VT, Custom);
1176     setOperationAction(ISD::UMULO, VT, Custom);
1177   }
1178
1179   // There are no 8-bit 3-address imul/mul instructions
1180   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1181   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1182
1183   if (!Subtarget->is64Bit()) {
1184     // These libcalls are not available in 32-bit.
1185     setLibcallName(RTLIB::SHL_I128, 0);
1186     setLibcallName(RTLIB::SRL_I128, 0);
1187     setLibcallName(RTLIB::SRA_I128, 0);
1188   }
1189
1190   // We have target-specific dag combine patterns for the following nodes:
1191   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1192   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1193   setTargetDAGCombine(ISD::VSELECT);
1194   setTargetDAGCombine(ISD::SELECT);
1195   setTargetDAGCombine(ISD::SHL);
1196   setTargetDAGCombine(ISD::SRA);
1197   setTargetDAGCombine(ISD::SRL);
1198   setTargetDAGCombine(ISD::OR);
1199   setTargetDAGCombine(ISD::AND);
1200   setTargetDAGCombine(ISD::ADD);
1201   setTargetDAGCombine(ISD::FADD);
1202   setTargetDAGCombine(ISD::FSUB);
1203   setTargetDAGCombine(ISD::SUB);
1204   setTargetDAGCombine(ISD::LOAD);
1205   setTargetDAGCombine(ISD::STORE);
1206   setTargetDAGCombine(ISD::ZERO_EXTEND);
1207   setTargetDAGCombine(ISD::SINT_TO_FP);
1208   if (Subtarget->is64Bit())
1209     setTargetDAGCombine(ISD::MUL);
1210   if (Subtarget->hasBMI())
1211     setTargetDAGCombine(ISD::XOR);
1212
1213   computeRegisterProperties();
1214
1215   // On Darwin, -Os means optimize for size without hurting performance,
1216   // do not reduce the limit.
1217   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1218   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1219   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1220   maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1221   maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1222   maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1223   setPrefLoopAlignment(4); // 2^4 bytes.
1224   benefitFromCodePlacementOpt = true;
1225
1226   setPrefFunctionAlignment(4); // 2^4 bytes.
1227 }
1228
1229
1230 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1231   if (!VT.isVector()) return MVT::i8;
1232   return VT.changeVectorElementTypeToInteger();
1233 }
1234
1235
1236 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1237 /// the desired ByVal argument alignment.
1238 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1239   if (MaxAlign == 16)
1240     return;
1241   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1242     if (VTy->getBitWidth() == 128)
1243       MaxAlign = 16;
1244   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1245     unsigned EltAlign = 0;
1246     getMaxByValAlign(ATy->getElementType(), EltAlign);
1247     if (EltAlign > MaxAlign)
1248       MaxAlign = EltAlign;
1249   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1250     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1251       unsigned EltAlign = 0;
1252       getMaxByValAlign(STy->getElementType(i), EltAlign);
1253       if (EltAlign > MaxAlign)
1254         MaxAlign = EltAlign;
1255       if (MaxAlign == 16)
1256         break;
1257     }
1258   }
1259   return;
1260 }
1261
1262 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1263 /// function arguments in the caller parameter area. For X86, aggregates
1264 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1265 /// are at 4-byte boundaries.
1266 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1267   if (Subtarget->is64Bit()) {
1268     // Max of 8 and alignment of type.
1269     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1270     if (TyAlign > 8)
1271       return TyAlign;
1272     return 8;
1273   }
1274
1275   unsigned Align = 4;
1276   if (Subtarget->hasXMM())
1277     getMaxByValAlign(Ty, Align);
1278   return Align;
1279 }
1280
1281 /// getOptimalMemOpType - Returns the target specific optimal type for load
1282 /// and store operations as a result of memset, memcpy, and memmove
1283 /// lowering. If DstAlign is zero that means it's safe to destination
1284 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1285 /// means there isn't a need to check it against alignment requirement,
1286 /// probably because the source does not need to be loaded. If
1287 /// 'IsZeroVal' is true, that means it's safe to return a
1288 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1289 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1290 /// constant so it does not need to be loaded.
1291 /// It returns EVT::Other if the type should be determined using generic
1292 /// target-independent logic.
1293 EVT
1294 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1295                                        unsigned DstAlign, unsigned SrcAlign,
1296                                        bool IsZeroVal,
1297                                        bool MemcpyStrSrc,
1298                                        MachineFunction &MF) const {
1299   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1300   // linux.  This is because the stack realignment code can't handle certain
1301   // cases like PR2962.  This should be removed when PR2962 is fixed.
1302   const Function *F = MF.getFunction();
1303   if (IsZeroVal &&
1304       !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1305     if (Size >= 16 &&
1306         (Subtarget->isUnalignedMemAccessFast() ||
1307          ((DstAlign == 0 || DstAlign >= 16) &&
1308           (SrcAlign == 0 || SrcAlign >= 16))) &&
1309         Subtarget->getStackAlignment() >= 16) {
1310       if (Subtarget->hasAVX() &&
1311           Subtarget->getStackAlignment() >= 32)
1312         return MVT::v8f32;
1313       if (Subtarget->hasXMMInt())
1314         return MVT::v4i32;
1315       if (Subtarget->hasXMM())
1316         return MVT::v4f32;
1317     } else if (!MemcpyStrSrc && Size >= 8 &&
1318                !Subtarget->is64Bit() &&
1319                Subtarget->getStackAlignment() >= 8 &&
1320                Subtarget->hasXMMInt()) {
1321       // Do not use f64 to lower memcpy if source is string constant. It's
1322       // better to use i32 to avoid the loads.
1323       return MVT::f64;
1324     }
1325   }
1326   if (Subtarget->is64Bit() && Size >= 8)
1327     return MVT::i64;
1328   return MVT::i32;
1329 }
1330
1331 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1332 /// current function.  The returned value is a member of the
1333 /// MachineJumpTableInfo::JTEntryKind enum.
1334 unsigned X86TargetLowering::getJumpTableEncoding() const {
1335   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1336   // symbol.
1337   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1338       Subtarget->isPICStyleGOT())
1339     return MachineJumpTableInfo::EK_Custom32;
1340
1341   // Otherwise, use the normal jump table encoding heuristics.
1342   return TargetLowering::getJumpTableEncoding();
1343 }
1344
1345 const MCExpr *
1346 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1347                                              const MachineBasicBlock *MBB,
1348                                              unsigned uid,MCContext &Ctx) const{
1349   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1350          Subtarget->isPICStyleGOT());
1351   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1352   // entries.
1353   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1354                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1355 }
1356
1357 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1358 /// jumptable.
1359 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1360                                                     SelectionDAG &DAG) const {
1361   if (!Subtarget->is64Bit())
1362     // This doesn't have DebugLoc associated with it, but is not really the
1363     // same as a Register.
1364     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1365   return Table;
1366 }
1367
1368 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1369 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1370 /// MCExpr.
1371 const MCExpr *X86TargetLowering::
1372 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1373                              MCContext &Ctx) const {
1374   // X86-64 uses RIP relative addressing based on the jump table label.
1375   if (Subtarget->isPICStyleRIPRel())
1376     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1377
1378   // Otherwise, the reference is relative to the PIC base.
1379   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1380 }
1381
1382 // FIXME: Why this routine is here? Move to RegInfo!
1383 std::pair<const TargetRegisterClass*, uint8_t>
1384 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1385   const TargetRegisterClass *RRC = 0;
1386   uint8_t Cost = 1;
1387   switch (VT.getSimpleVT().SimpleTy) {
1388   default:
1389     return TargetLowering::findRepresentativeClass(VT);
1390   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1391     RRC = (Subtarget->is64Bit()
1392            ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1393     break;
1394   case MVT::x86mmx:
1395     RRC = X86::VR64RegisterClass;
1396     break;
1397   case MVT::f32: case MVT::f64:
1398   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1399   case MVT::v4f32: case MVT::v2f64:
1400   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1401   case MVT::v4f64:
1402     RRC = X86::VR128RegisterClass;
1403     break;
1404   }
1405   return std::make_pair(RRC, Cost);
1406 }
1407
1408 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1409                                                unsigned &Offset) const {
1410   if (!Subtarget->isTargetLinux())
1411     return false;
1412
1413   if (Subtarget->is64Bit()) {
1414     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1415     Offset = 0x28;
1416     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1417       AddressSpace = 256;
1418     else
1419       AddressSpace = 257;
1420   } else {
1421     // %gs:0x14 on i386
1422     Offset = 0x14;
1423     AddressSpace = 256;
1424   }
1425   return true;
1426 }
1427
1428
1429 //===----------------------------------------------------------------------===//
1430 //               Return Value Calling Convention Implementation
1431 //===----------------------------------------------------------------------===//
1432
1433 #include "X86GenCallingConv.inc"
1434
1435 bool
1436 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1437                                   MachineFunction &MF, bool isVarArg,
1438                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1439                         LLVMContext &Context) const {
1440   SmallVector<CCValAssign, 16> RVLocs;
1441   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1442                  RVLocs, Context);
1443   return CCInfo.CheckReturn(Outs, RetCC_X86);
1444 }
1445
1446 SDValue
1447 X86TargetLowering::LowerReturn(SDValue Chain,
1448                                CallingConv::ID CallConv, bool isVarArg,
1449                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1450                                const SmallVectorImpl<SDValue> &OutVals,
1451                                DebugLoc dl, SelectionDAG &DAG) const {
1452   MachineFunction &MF = DAG.getMachineFunction();
1453   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1454
1455   SmallVector<CCValAssign, 16> RVLocs;
1456   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1457                  RVLocs, *DAG.getContext());
1458   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1459
1460   // Add the regs to the liveout set for the function.
1461   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1462   for (unsigned i = 0; i != RVLocs.size(); ++i)
1463     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1464       MRI.addLiveOut(RVLocs[i].getLocReg());
1465
1466   SDValue Flag;
1467
1468   SmallVector<SDValue, 6> RetOps;
1469   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1470   // Operand #1 = Bytes To Pop
1471   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1472                    MVT::i16));
1473
1474   // Copy the result values into the output registers.
1475   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1476     CCValAssign &VA = RVLocs[i];
1477     assert(VA.isRegLoc() && "Can only return in registers!");
1478     SDValue ValToCopy = OutVals[i];
1479     EVT ValVT = ValToCopy.getValueType();
1480
1481     // If this is x86-64, and we disabled SSE, we can't return FP values,
1482     // or SSE or MMX vectors.
1483     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1484          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1485           (Subtarget->is64Bit() && !Subtarget->hasXMM())) {
1486       report_fatal_error("SSE register return with SSE disabled");
1487     }
1488     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1489     // llvm-gcc has never done it right and no one has noticed, so this
1490     // should be OK for now.
1491     if (ValVT == MVT::f64 &&
1492         (Subtarget->is64Bit() && !Subtarget->hasXMMInt()))
1493       report_fatal_error("SSE2 register return with SSE2 disabled");
1494
1495     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1496     // the RET instruction and handled by the FP Stackifier.
1497     if (VA.getLocReg() == X86::ST0 ||
1498         VA.getLocReg() == X86::ST1) {
1499       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1500       // change the value to the FP stack register class.
1501       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1502         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1503       RetOps.push_back(ValToCopy);
1504       // Don't emit a copytoreg.
1505       continue;
1506     }
1507
1508     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1509     // which is returned in RAX / RDX.
1510     if (Subtarget->is64Bit()) {
1511       if (ValVT == MVT::x86mmx) {
1512         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1513           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1514           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1515                                   ValToCopy);
1516           // If we don't have SSE2 available, convert to v4f32 so the generated
1517           // register is legal.
1518           if (!Subtarget->hasXMMInt())
1519             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1520         }
1521       }
1522     }
1523
1524     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1525     Flag = Chain.getValue(1);
1526   }
1527
1528   // The x86-64 ABI for returning structs by value requires that we copy
1529   // the sret argument into %rax for the return. We saved the argument into
1530   // a virtual register in the entry block, so now we copy the value out
1531   // and into %rax.
1532   if (Subtarget->is64Bit() &&
1533       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1534     MachineFunction &MF = DAG.getMachineFunction();
1535     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1536     unsigned Reg = FuncInfo->getSRetReturnReg();
1537     assert(Reg &&
1538            "SRetReturnReg should have been set in LowerFormalArguments().");
1539     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1540
1541     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1542     Flag = Chain.getValue(1);
1543
1544     // RAX now acts like a return value.
1545     MRI.addLiveOut(X86::RAX);
1546   }
1547
1548   RetOps[0] = Chain;  // Update chain.
1549
1550   // Add the flag if we have it.
1551   if (Flag.getNode())
1552     RetOps.push_back(Flag);
1553
1554   return DAG.getNode(X86ISD::RET_FLAG, dl,
1555                      MVT::Other, &RetOps[0], RetOps.size());
1556 }
1557
1558 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1559   if (N->getNumValues() != 1)
1560     return false;
1561   if (!N->hasNUsesOfValue(1, 0))
1562     return false;
1563
1564   SDNode *Copy = *N->use_begin();
1565   if (Copy->getOpcode() != ISD::CopyToReg &&
1566       Copy->getOpcode() != ISD::FP_EXTEND)
1567     return false;
1568
1569   bool HasRet = false;
1570   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1571        UI != UE; ++UI) {
1572     if (UI->getOpcode() != X86ISD::RET_FLAG)
1573       return false;
1574     HasRet = true;
1575   }
1576
1577   return HasRet;
1578 }
1579
1580 EVT
1581 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1582                                             ISD::NodeType ExtendKind) const {
1583   MVT ReturnMVT;
1584   // TODO: Is this also valid on 32-bit?
1585   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1586     ReturnMVT = MVT::i8;
1587   else
1588     ReturnMVT = MVT::i32;
1589
1590   EVT MinVT = getRegisterType(Context, ReturnMVT);
1591   return VT.bitsLT(MinVT) ? MinVT : VT;
1592 }
1593
1594 /// LowerCallResult - Lower the result values of a call into the
1595 /// appropriate copies out of appropriate physical registers.
1596 ///
1597 SDValue
1598 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1599                                    CallingConv::ID CallConv, bool isVarArg,
1600                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1601                                    DebugLoc dl, SelectionDAG &DAG,
1602                                    SmallVectorImpl<SDValue> &InVals) const {
1603
1604   // Assign locations to each value returned by this call.
1605   SmallVector<CCValAssign, 16> RVLocs;
1606   bool Is64Bit = Subtarget->is64Bit();
1607   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1608                  getTargetMachine(), RVLocs, *DAG.getContext());
1609   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1610
1611   // Copy all of the result registers out of their specified physreg.
1612   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1613     CCValAssign &VA = RVLocs[i];
1614     EVT CopyVT = VA.getValVT();
1615
1616     // If this is x86-64, and we disabled SSE, we can't return FP values
1617     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1618         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) {
1619       report_fatal_error("SSE register return with SSE disabled");
1620     }
1621
1622     SDValue Val;
1623
1624     // If this is a call to a function that returns an fp value on the floating
1625     // point stack, we must guarantee the the value is popped from the stack, so
1626     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1627     // if the return value is not used. We use the FpPOP_RETVAL instruction
1628     // instead.
1629     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1630       // If we prefer to use the value in xmm registers, copy it out as f80 and
1631       // use a truncate to move it from fp stack reg to xmm reg.
1632       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1633       SDValue Ops[] = { Chain, InFlag };
1634       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1635                                          MVT::Other, MVT::Glue, Ops, 2), 1);
1636       Val = Chain.getValue(0);
1637
1638       // Round the f80 to the right size, which also moves it to the appropriate
1639       // xmm register.
1640       if (CopyVT != VA.getValVT())
1641         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1642                           // This truncation won't change the value.
1643                           DAG.getIntPtrConstant(1));
1644     } else {
1645       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1646                                  CopyVT, InFlag).getValue(1);
1647       Val = Chain.getValue(0);
1648     }
1649     InFlag = Chain.getValue(2);
1650     InVals.push_back(Val);
1651   }
1652
1653   return Chain;
1654 }
1655
1656
1657 //===----------------------------------------------------------------------===//
1658 //                C & StdCall & Fast Calling Convention implementation
1659 //===----------------------------------------------------------------------===//
1660 //  StdCall calling convention seems to be standard for many Windows' API
1661 //  routines and around. It differs from C calling convention just a little:
1662 //  callee should clean up the stack, not caller. Symbols should be also
1663 //  decorated in some fancy way :) It doesn't support any vector arguments.
1664 //  For info on fast calling convention see Fast Calling Convention (tail call)
1665 //  implementation LowerX86_32FastCCCallTo.
1666
1667 /// CallIsStructReturn - Determines whether a call uses struct return
1668 /// semantics.
1669 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1670   if (Outs.empty())
1671     return false;
1672
1673   return Outs[0].Flags.isSRet();
1674 }
1675
1676 /// ArgsAreStructReturn - Determines whether a function uses struct
1677 /// return semantics.
1678 static bool
1679 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1680   if (Ins.empty())
1681     return false;
1682
1683   return Ins[0].Flags.isSRet();
1684 }
1685
1686 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1687 /// by "Src" to address "Dst" with size and alignment information specified by
1688 /// the specific parameter attribute. The copy will be passed as a byval
1689 /// function parameter.
1690 static SDValue
1691 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1692                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1693                           DebugLoc dl) {
1694   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1695
1696   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1697                        /*isVolatile*/false, /*AlwaysInline=*/true,
1698                        MachinePointerInfo(), MachinePointerInfo());
1699 }
1700
1701 /// IsTailCallConvention - Return true if the calling convention is one that
1702 /// supports tail call optimization.
1703 static bool IsTailCallConvention(CallingConv::ID CC) {
1704   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1705 }
1706
1707 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1708   if (!CI->isTailCall())
1709     return false;
1710
1711   CallSite CS(CI);
1712   CallingConv::ID CalleeCC = CS.getCallingConv();
1713   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1714     return false;
1715
1716   return true;
1717 }
1718
1719 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1720 /// a tailcall target by changing its ABI.
1721 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1722                                    bool GuaranteedTailCallOpt) {
1723   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1724 }
1725
1726 SDValue
1727 X86TargetLowering::LowerMemArgument(SDValue Chain,
1728                                     CallingConv::ID CallConv,
1729                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1730                                     DebugLoc dl, SelectionDAG &DAG,
1731                                     const CCValAssign &VA,
1732                                     MachineFrameInfo *MFI,
1733                                     unsigned i) const {
1734   // Create the nodes corresponding to a load from this parameter slot.
1735   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1736   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1737                               getTargetMachine().Options.GuaranteedTailCallOpt);
1738   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1739   EVT ValVT;
1740
1741   // If value is passed by pointer we have address passed instead of the value
1742   // itself.
1743   if (VA.getLocInfo() == CCValAssign::Indirect)
1744     ValVT = VA.getLocVT();
1745   else
1746     ValVT = VA.getValVT();
1747
1748   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1749   // changed with more analysis.
1750   // In case of tail call optimization mark all arguments mutable. Since they
1751   // could be overwritten by lowering of arguments in case of a tail call.
1752   if (Flags.isByVal()) {
1753     unsigned Bytes = Flags.getByValSize();
1754     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1755     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1756     return DAG.getFrameIndex(FI, getPointerTy());
1757   } else {
1758     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1759                                     VA.getLocMemOffset(), isImmutable);
1760     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1761     return DAG.getLoad(ValVT, dl, Chain, FIN,
1762                        MachinePointerInfo::getFixedStack(FI),
1763                        false, false, false, 0);
1764   }
1765 }
1766
1767 SDValue
1768 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1769                                         CallingConv::ID CallConv,
1770                                         bool isVarArg,
1771                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1772                                         DebugLoc dl,
1773                                         SelectionDAG &DAG,
1774                                         SmallVectorImpl<SDValue> &InVals)
1775                                           const {
1776   MachineFunction &MF = DAG.getMachineFunction();
1777   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1778
1779   const Function* Fn = MF.getFunction();
1780   if (Fn->hasExternalLinkage() &&
1781       Subtarget->isTargetCygMing() &&
1782       Fn->getName() == "main")
1783     FuncInfo->setForceFramePointer(true);
1784
1785   MachineFrameInfo *MFI = MF.getFrameInfo();
1786   bool Is64Bit = Subtarget->is64Bit();
1787   bool IsWin64 = Subtarget->isTargetWin64();
1788
1789   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1790          "Var args not supported with calling convention fastcc or ghc");
1791
1792   // Assign locations to all of the incoming arguments.
1793   SmallVector<CCValAssign, 16> ArgLocs;
1794   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1795                  ArgLocs, *DAG.getContext());
1796
1797   // Allocate shadow area for Win64
1798   if (IsWin64) {
1799     CCInfo.AllocateStack(32, 8);
1800   }
1801
1802   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1803
1804   unsigned LastVal = ~0U;
1805   SDValue ArgValue;
1806   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1807     CCValAssign &VA = ArgLocs[i];
1808     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1809     // places.
1810     assert(VA.getValNo() != LastVal &&
1811            "Don't support value assigned to multiple locs yet");
1812     (void)LastVal;
1813     LastVal = VA.getValNo();
1814
1815     if (VA.isRegLoc()) {
1816       EVT RegVT = VA.getLocVT();
1817       TargetRegisterClass *RC = NULL;
1818       if (RegVT == MVT::i32)
1819         RC = X86::GR32RegisterClass;
1820       else if (Is64Bit && RegVT == MVT::i64)
1821         RC = X86::GR64RegisterClass;
1822       else if (RegVT == MVT::f32)
1823         RC = X86::FR32RegisterClass;
1824       else if (RegVT == MVT::f64)
1825         RC = X86::FR64RegisterClass;
1826       else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1827         RC = X86::VR256RegisterClass;
1828       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1829         RC = X86::VR128RegisterClass;
1830       else if (RegVT == MVT::x86mmx)
1831         RC = X86::VR64RegisterClass;
1832       else
1833         llvm_unreachable("Unknown argument type!");
1834
1835       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1836       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1837
1838       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1839       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1840       // right size.
1841       if (VA.getLocInfo() == CCValAssign::SExt)
1842         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1843                                DAG.getValueType(VA.getValVT()));
1844       else if (VA.getLocInfo() == CCValAssign::ZExt)
1845         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1846                                DAG.getValueType(VA.getValVT()));
1847       else if (VA.getLocInfo() == CCValAssign::BCvt)
1848         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1849
1850       if (VA.isExtInLoc()) {
1851         // Handle MMX values passed in XMM regs.
1852         if (RegVT.isVector()) {
1853           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1854                                  ArgValue);
1855         } else
1856           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1857       }
1858     } else {
1859       assert(VA.isMemLoc());
1860       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1861     }
1862
1863     // If value is passed via pointer - do a load.
1864     if (VA.getLocInfo() == CCValAssign::Indirect)
1865       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1866                              MachinePointerInfo(), false, false, false, 0);
1867
1868     InVals.push_back(ArgValue);
1869   }
1870
1871   // The x86-64 ABI for returning structs by value requires that we copy
1872   // the sret argument into %rax for the return. Save the argument into
1873   // a virtual register so that we can access it from the return points.
1874   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1875     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1876     unsigned Reg = FuncInfo->getSRetReturnReg();
1877     if (!Reg) {
1878       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1879       FuncInfo->setSRetReturnReg(Reg);
1880     }
1881     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1882     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1883   }
1884
1885   unsigned StackSize = CCInfo.getNextStackOffset();
1886   // Align stack specially for tail calls.
1887   if (FuncIsMadeTailCallSafe(CallConv,
1888                              MF.getTarget().Options.GuaranteedTailCallOpt))
1889     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1890
1891   // If the function takes variable number of arguments, make a frame index for
1892   // the start of the first vararg value... for expansion of llvm.va_start.
1893   if (isVarArg) {
1894     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1895                     CallConv != CallingConv::X86_ThisCall)) {
1896       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1897     }
1898     if (Is64Bit) {
1899       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1900
1901       // FIXME: We should really autogenerate these arrays
1902       static const unsigned GPR64ArgRegsWin64[] = {
1903         X86::RCX, X86::RDX, X86::R8,  X86::R9
1904       };
1905       static const unsigned GPR64ArgRegs64Bit[] = {
1906         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1907       };
1908       static const unsigned XMMArgRegs64Bit[] = {
1909         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1910         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1911       };
1912       const unsigned *GPR64ArgRegs;
1913       unsigned NumXMMRegs = 0;
1914
1915       if (IsWin64) {
1916         // The XMM registers which might contain var arg parameters are shadowed
1917         // in their paired GPR.  So we only need to save the GPR to their home
1918         // slots.
1919         TotalNumIntRegs = 4;
1920         GPR64ArgRegs = GPR64ArgRegsWin64;
1921       } else {
1922         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1923         GPR64ArgRegs = GPR64ArgRegs64Bit;
1924
1925         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1926       }
1927       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1928                                                        TotalNumIntRegs);
1929
1930       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1931       assert(!(NumXMMRegs && !Subtarget->hasXMM()) &&
1932              "SSE register cannot be used when SSE is disabled!");
1933       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
1934                NoImplicitFloatOps) &&
1935              "SSE register cannot be used when SSE is disabled!");
1936       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
1937           !Subtarget->hasXMM())
1938         // Kernel mode asks for SSE to be disabled, so don't push them
1939         // on the stack.
1940         TotalNumXMMRegs = 0;
1941
1942       if (IsWin64) {
1943         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1944         // Get to the caller-allocated home save location.  Add 8 to account
1945         // for the return address.
1946         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1947         FuncInfo->setRegSaveFrameIndex(
1948           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1949         // Fixup to set vararg frame on shadow area (4 x i64).
1950         if (NumIntRegs < 4)
1951           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1952       } else {
1953         // For X86-64, if there are vararg parameters that are passed via
1954         // registers, then we must store them to their spots on the stack so they
1955         // may be loaded by deferencing the result of va_next.
1956         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1957         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1958         FuncInfo->setRegSaveFrameIndex(
1959           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1960                                false));
1961       }
1962
1963       // Store the integer parameter registers.
1964       SmallVector<SDValue, 8> MemOps;
1965       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1966                                         getPointerTy());
1967       unsigned Offset = FuncInfo->getVarArgsGPOffset();
1968       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1969         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1970                                   DAG.getIntPtrConstant(Offset));
1971         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1972                                      X86::GR64RegisterClass);
1973         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1974         SDValue Store =
1975           DAG.getStore(Val.getValue(1), dl, Val, FIN,
1976                        MachinePointerInfo::getFixedStack(
1977                          FuncInfo->getRegSaveFrameIndex(), Offset),
1978                        false, false, 0);
1979         MemOps.push_back(Store);
1980         Offset += 8;
1981       }
1982
1983       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1984         // Now store the XMM (fp + vector) parameter registers.
1985         SmallVector<SDValue, 11> SaveXMMOps;
1986         SaveXMMOps.push_back(Chain);
1987
1988         unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1989         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1990         SaveXMMOps.push_back(ALVal);
1991
1992         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1993                                FuncInfo->getRegSaveFrameIndex()));
1994         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1995                                FuncInfo->getVarArgsFPOffset()));
1996
1997         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1998           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
1999                                        X86::VR128RegisterClass);
2000           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2001           SaveXMMOps.push_back(Val);
2002         }
2003         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2004                                      MVT::Other,
2005                                      &SaveXMMOps[0], SaveXMMOps.size()));
2006       }
2007
2008       if (!MemOps.empty())
2009         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2010                             &MemOps[0], MemOps.size());
2011     }
2012   }
2013
2014   // Some CCs need callee pop.
2015   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2016                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2017     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2018   } else {
2019     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2020     // If this is an sret function, the return should pop the hidden pointer.
2021     if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
2022       FuncInfo->setBytesToPopOnReturn(4);
2023   }
2024
2025   if (!Is64Bit) {
2026     // RegSaveFrameIndex is X86-64 only.
2027     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2028     if (CallConv == CallingConv::X86_FastCall ||
2029         CallConv == CallingConv::X86_ThisCall)
2030       // fastcc functions can't have varargs.
2031       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2032   }
2033
2034   FuncInfo->setArgumentStackSize(StackSize);
2035
2036   return Chain;
2037 }
2038
2039 SDValue
2040 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2041                                     SDValue StackPtr, SDValue Arg,
2042                                     DebugLoc dl, SelectionDAG &DAG,
2043                                     const CCValAssign &VA,
2044                                     ISD::ArgFlagsTy Flags) const {
2045   unsigned LocMemOffset = VA.getLocMemOffset();
2046   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2047   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2048   if (Flags.isByVal())
2049     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2050
2051   return DAG.getStore(Chain, dl, Arg, PtrOff,
2052                       MachinePointerInfo::getStack(LocMemOffset),
2053                       false, false, 0);
2054 }
2055
2056 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2057 /// optimization is performed and it is required.
2058 SDValue
2059 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2060                                            SDValue &OutRetAddr, SDValue Chain,
2061                                            bool IsTailCall, bool Is64Bit,
2062                                            int FPDiff, DebugLoc dl) const {
2063   // Adjust the Return address stack slot.
2064   EVT VT = getPointerTy();
2065   OutRetAddr = getReturnAddressFrameIndex(DAG);
2066
2067   // Load the "old" Return address.
2068   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2069                            false, false, false, 0);
2070   return SDValue(OutRetAddr.getNode(), 1);
2071 }
2072
2073 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2074 /// optimization is performed and it is required (FPDiff!=0).
2075 static SDValue
2076 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2077                          SDValue Chain, SDValue RetAddrFrIdx,
2078                          bool Is64Bit, int FPDiff, DebugLoc dl) {
2079   // Store the return address to the appropriate stack slot.
2080   if (!FPDiff) return Chain;
2081   // Calculate the new stack slot for the return address.
2082   int SlotSize = Is64Bit ? 8 : 4;
2083   int NewReturnAddrFI =
2084     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2085   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2086   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
2087   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2088                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2089                        false, false, 0);
2090   return Chain;
2091 }
2092
2093 SDValue
2094 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
2095                              CallingConv::ID CallConv, bool isVarArg,
2096                              bool &isTailCall,
2097                              const SmallVectorImpl<ISD::OutputArg> &Outs,
2098                              const SmallVectorImpl<SDValue> &OutVals,
2099                              const SmallVectorImpl<ISD::InputArg> &Ins,
2100                              DebugLoc dl, SelectionDAG &DAG,
2101                              SmallVectorImpl<SDValue> &InVals) const {
2102   MachineFunction &MF = DAG.getMachineFunction();
2103   bool Is64Bit        = Subtarget->is64Bit();
2104   bool IsWin64        = Subtarget->isTargetWin64();
2105   bool IsStructRet    = CallIsStructReturn(Outs);
2106   bool IsSibcall      = false;
2107
2108   if (isTailCall) {
2109     // Check if it's really possible to do a tail call.
2110     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2111                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
2112                                                    Outs, OutVals, Ins, DAG);
2113
2114     // Sibcalls are automatically detected tailcalls which do not require
2115     // ABI changes.
2116     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2117       IsSibcall = true;
2118
2119     if (isTailCall)
2120       ++NumTailCalls;
2121   }
2122
2123   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2124          "Var args not supported with calling convention fastcc or ghc");
2125
2126   // Analyze operands of the call, assigning locations to each operand.
2127   SmallVector<CCValAssign, 16> ArgLocs;
2128   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2129                  ArgLocs, *DAG.getContext());
2130
2131   // Allocate shadow area for Win64
2132   if (IsWin64) {
2133     CCInfo.AllocateStack(32, 8);
2134   }
2135
2136   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2137
2138   // Get a count of how many bytes are to be pushed on the stack.
2139   unsigned NumBytes = CCInfo.getNextStackOffset();
2140   if (IsSibcall)
2141     // This is a sibcall. The memory operands are available in caller's
2142     // own caller's stack.
2143     NumBytes = 0;
2144   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2145            IsTailCallConvention(CallConv))
2146     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2147
2148   int FPDiff = 0;
2149   if (isTailCall && !IsSibcall) {
2150     // Lower arguments at fp - stackoffset + fpdiff.
2151     unsigned NumBytesCallerPushed =
2152       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2153     FPDiff = NumBytesCallerPushed - NumBytes;
2154
2155     // Set the delta of movement of the returnaddr stackslot.
2156     // But only set if delta is greater than previous delta.
2157     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2158       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2159   }
2160
2161   if (!IsSibcall)
2162     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2163
2164   SDValue RetAddrFrIdx;
2165   // Load return address for tail calls.
2166   if (isTailCall && FPDiff)
2167     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2168                                     Is64Bit, FPDiff, dl);
2169
2170   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2171   SmallVector<SDValue, 8> MemOpChains;
2172   SDValue StackPtr;
2173
2174   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2175   // of tail call optimization arguments are handle later.
2176   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2177     CCValAssign &VA = ArgLocs[i];
2178     EVT RegVT = VA.getLocVT();
2179     SDValue Arg = OutVals[i];
2180     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2181     bool isByVal = Flags.isByVal();
2182
2183     // Promote the value if needed.
2184     switch (VA.getLocInfo()) {
2185     default: llvm_unreachable("Unknown loc info!");
2186     case CCValAssign::Full: break;
2187     case CCValAssign::SExt:
2188       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2189       break;
2190     case CCValAssign::ZExt:
2191       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2192       break;
2193     case CCValAssign::AExt:
2194       if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2195         // Special case: passing MMX values in XMM registers.
2196         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2197         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2198         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2199       } else
2200         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2201       break;
2202     case CCValAssign::BCvt:
2203       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2204       break;
2205     case CCValAssign::Indirect: {
2206       // Store the argument.
2207       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2208       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2209       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2210                            MachinePointerInfo::getFixedStack(FI),
2211                            false, false, 0);
2212       Arg = SpillSlot;
2213       break;
2214     }
2215     }
2216
2217     if (VA.isRegLoc()) {
2218       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2219       if (isVarArg && IsWin64) {
2220         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2221         // shadow reg if callee is a varargs function.
2222         unsigned ShadowReg = 0;
2223         switch (VA.getLocReg()) {
2224         case X86::XMM0: ShadowReg = X86::RCX; break;
2225         case X86::XMM1: ShadowReg = X86::RDX; break;
2226         case X86::XMM2: ShadowReg = X86::R8; break;
2227         case X86::XMM3: ShadowReg = X86::R9; break;
2228         }
2229         if (ShadowReg)
2230           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2231       }
2232     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2233       assert(VA.isMemLoc());
2234       if (StackPtr.getNode() == 0)
2235         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2236       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2237                                              dl, DAG, VA, Flags));
2238     }
2239   }
2240
2241   if (!MemOpChains.empty())
2242     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2243                         &MemOpChains[0], MemOpChains.size());
2244
2245   // Build a sequence of copy-to-reg nodes chained together with token chain
2246   // and flag operands which copy the outgoing args into registers.
2247   SDValue InFlag;
2248   // Tail call byval lowering might overwrite argument registers so in case of
2249   // tail call optimization the copies to registers are lowered later.
2250   if (!isTailCall)
2251     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2252       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2253                                RegsToPass[i].second, InFlag);
2254       InFlag = Chain.getValue(1);
2255     }
2256
2257   if (Subtarget->isPICStyleGOT()) {
2258     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2259     // GOT pointer.
2260     if (!isTailCall) {
2261       Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2262                                DAG.getNode(X86ISD::GlobalBaseReg,
2263                                            DebugLoc(), getPointerTy()),
2264                                InFlag);
2265       InFlag = Chain.getValue(1);
2266     } else {
2267       // If we are tail calling and generating PIC/GOT style code load the
2268       // address of the callee into ECX. The value in ecx is used as target of
2269       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2270       // for tail calls on PIC/GOT architectures. Normally we would just put the
2271       // address of GOT into ebx and then call target@PLT. But for tail calls
2272       // ebx would be restored (since ebx is callee saved) before jumping to the
2273       // target@PLT.
2274
2275       // Note: The actual moving to ECX is done further down.
2276       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2277       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2278           !G->getGlobal()->hasProtectedVisibility())
2279         Callee = LowerGlobalAddress(Callee, DAG);
2280       else if (isa<ExternalSymbolSDNode>(Callee))
2281         Callee = LowerExternalSymbol(Callee, DAG);
2282     }
2283   }
2284
2285   if (Is64Bit && isVarArg && !IsWin64) {
2286     // From AMD64 ABI document:
2287     // For calls that may call functions that use varargs or stdargs
2288     // (prototype-less calls or calls to functions containing ellipsis (...) in
2289     // the declaration) %al is used as hidden argument to specify the number
2290     // of SSE registers used. The contents of %al do not need to match exactly
2291     // the number of registers, but must be an ubound on the number of SSE
2292     // registers used and is in the range 0 - 8 inclusive.
2293
2294     // Count the number of XMM registers allocated.
2295     static const unsigned XMMArgRegs[] = {
2296       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2297       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2298     };
2299     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2300     assert((Subtarget->hasXMM() || !NumXMMRegs)
2301            && "SSE registers cannot be used when SSE is disabled");
2302
2303     Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2304                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2305     InFlag = Chain.getValue(1);
2306   }
2307
2308
2309   // For tail calls lower the arguments to the 'real' stack slot.
2310   if (isTailCall) {
2311     // Force all the incoming stack arguments to be loaded from the stack
2312     // before any new outgoing arguments are stored to the stack, because the
2313     // outgoing stack slots may alias the incoming argument stack slots, and
2314     // the alias isn't otherwise explicit. This is slightly more conservative
2315     // than necessary, because it means that each store effectively depends
2316     // on every argument instead of just those arguments it would clobber.
2317     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2318
2319     SmallVector<SDValue, 8> MemOpChains2;
2320     SDValue FIN;
2321     int FI = 0;
2322     // Do not flag preceding copytoreg stuff together with the following stuff.
2323     InFlag = SDValue();
2324     if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2325       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2326         CCValAssign &VA = ArgLocs[i];
2327         if (VA.isRegLoc())
2328           continue;
2329         assert(VA.isMemLoc());
2330         SDValue Arg = OutVals[i];
2331         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2332         // Create frame index.
2333         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2334         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2335         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2336         FIN = DAG.getFrameIndex(FI, getPointerTy());
2337
2338         if (Flags.isByVal()) {
2339           // Copy relative to framepointer.
2340           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2341           if (StackPtr.getNode() == 0)
2342             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2343                                           getPointerTy());
2344           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2345
2346           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2347                                                            ArgChain,
2348                                                            Flags, DAG, dl));
2349         } else {
2350           // Store relative to framepointer.
2351           MemOpChains2.push_back(
2352             DAG.getStore(ArgChain, dl, Arg, FIN,
2353                          MachinePointerInfo::getFixedStack(FI),
2354                          false, false, 0));
2355         }
2356       }
2357     }
2358
2359     if (!MemOpChains2.empty())
2360       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2361                           &MemOpChains2[0], MemOpChains2.size());
2362
2363     // Copy arguments to their registers.
2364     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2365       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2366                                RegsToPass[i].second, InFlag);
2367       InFlag = Chain.getValue(1);
2368     }
2369     InFlag =SDValue();
2370
2371     // Store the return address to the appropriate stack slot.
2372     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2373                                      FPDiff, dl);
2374   }
2375
2376   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2377     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2378     // In the 64-bit large code model, we have to make all calls
2379     // through a register, since the call instruction's 32-bit
2380     // pc-relative offset may not be large enough to hold the whole
2381     // address.
2382   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2383     // If the callee is a GlobalAddress node (quite common, every direct call
2384     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2385     // it.
2386
2387     // We should use extra load for direct calls to dllimported functions in
2388     // non-JIT mode.
2389     const GlobalValue *GV = G->getGlobal();
2390     if (!GV->hasDLLImportLinkage()) {
2391       unsigned char OpFlags = 0;
2392       bool ExtraLoad = false;
2393       unsigned WrapperKind = ISD::DELETED_NODE;
2394
2395       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2396       // external symbols most go through the PLT in PIC mode.  If the symbol
2397       // has hidden or protected visibility, or if it is static or local, then
2398       // we don't need to use the PLT - we can directly call it.
2399       if (Subtarget->isTargetELF() &&
2400           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2401           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2402         OpFlags = X86II::MO_PLT;
2403       } else if (Subtarget->isPICStyleStubAny() &&
2404                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2405                  (!Subtarget->getTargetTriple().isMacOSX() ||
2406                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2407         // PC-relative references to external symbols should go through $stub,
2408         // unless we're building with the leopard linker or later, which
2409         // automatically synthesizes these stubs.
2410         OpFlags = X86II::MO_DARWIN_STUB;
2411       } else if (Subtarget->isPICStyleRIPRel() &&
2412                  isa<Function>(GV) &&
2413                  cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2414         // If the function is marked as non-lazy, generate an indirect call
2415         // which loads from the GOT directly. This avoids runtime overhead
2416         // at the cost of eager binding (and one extra byte of encoding).
2417         OpFlags = X86II::MO_GOTPCREL;
2418         WrapperKind = X86ISD::WrapperRIP;
2419         ExtraLoad = true;
2420       }
2421
2422       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2423                                           G->getOffset(), OpFlags);
2424
2425       // Add a wrapper if needed.
2426       if (WrapperKind != ISD::DELETED_NODE)
2427         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2428       // Add extra indirection if needed.
2429       if (ExtraLoad)
2430         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2431                              MachinePointerInfo::getGOT(),
2432                              false, false, false, 0);
2433     }
2434   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2435     unsigned char OpFlags = 0;
2436
2437     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2438     // external symbols should go through the PLT.
2439     if (Subtarget->isTargetELF() &&
2440         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2441       OpFlags = X86II::MO_PLT;
2442     } else if (Subtarget->isPICStyleStubAny() &&
2443                (!Subtarget->getTargetTriple().isMacOSX() ||
2444                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2445       // PC-relative references to external symbols should go through $stub,
2446       // unless we're building with the leopard linker or later, which
2447       // automatically synthesizes these stubs.
2448       OpFlags = X86II::MO_DARWIN_STUB;
2449     }
2450
2451     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2452                                          OpFlags);
2453   }
2454
2455   // Returns a chain & a flag for retval copy to use.
2456   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2457   SmallVector<SDValue, 8> Ops;
2458
2459   if (!IsSibcall && isTailCall) {
2460     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2461                            DAG.getIntPtrConstant(0, true), InFlag);
2462     InFlag = Chain.getValue(1);
2463   }
2464
2465   Ops.push_back(Chain);
2466   Ops.push_back(Callee);
2467
2468   if (isTailCall)
2469     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2470
2471   // Add argument registers to the end of the list so that they are known live
2472   // into the call.
2473   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2474     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2475                                   RegsToPass[i].second.getValueType()));
2476
2477   // Add an implicit use GOT pointer in EBX.
2478   if (!isTailCall && Subtarget->isPICStyleGOT())
2479     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2480
2481   // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2482   if (Is64Bit && isVarArg && !IsWin64)
2483     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2484
2485   if (InFlag.getNode())
2486     Ops.push_back(InFlag);
2487
2488   if (isTailCall) {
2489     // We used to do:
2490     //// If this is the first return lowered for this function, add the regs
2491     //// to the liveout set for the function.
2492     // This isn't right, although it's probably harmless on x86; liveouts
2493     // should be computed from returns not tail calls.  Consider a void
2494     // function making a tail call to a function returning int.
2495     return DAG.getNode(X86ISD::TC_RETURN, dl,
2496                        NodeTys, &Ops[0], Ops.size());
2497   }
2498
2499   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2500   InFlag = Chain.getValue(1);
2501
2502   // Create the CALLSEQ_END node.
2503   unsigned NumBytesForCalleeToPush;
2504   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2505                        getTargetMachine().Options.GuaranteedTailCallOpt))
2506     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2507   else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2508     // If this is a call to a struct-return function, the callee
2509     // pops the hidden struct pointer, so we have to push it back.
2510     // This is common for Darwin/X86, Linux & Mingw32 targets.
2511     NumBytesForCalleeToPush = 4;
2512   else
2513     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2514
2515   // Returns a flag for retval copy to use.
2516   if (!IsSibcall) {
2517     Chain = DAG.getCALLSEQ_END(Chain,
2518                                DAG.getIntPtrConstant(NumBytes, true),
2519                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2520                                                      true),
2521                                InFlag);
2522     InFlag = Chain.getValue(1);
2523   }
2524
2525   // Handle result values, copying them out of physregs into vregs that we
2526   // return.
2527   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2528                          Ins, dl, DAG, InVals);
2529 }
2530
2531
2532 //===----------------------------------------------------------------------===//
2533 //                Fast Calling Convention (tail call) implementation
2534 //===----------------------------------------------------------------------===//
2535
2536 //  Like std call, callee cleans arguments, convention except that ECX is
2537 //  reserved for storing the tail called function address. Only 2 registers are
2538 //  free for argument passing (inreg). Tail call optimization is performed
2539 //  provided:
2540 //                * tailcallopt is enabled
2541 //                * caller/callee are fastcc
2542 //  On X86_64 architecture with GOT-style position independent code only local
2543 //  (within module) calls are supported at the moment.
2544 //  To keep the stack aligned according to platform abi the function
2545 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2546 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2547 //  If a tail called function callee has more arguments than the caller the
2548 //  caller needs to make sure that there is room to move the RETADDR to. This is
2549 //  achieved by reserving an area the size of the argument delta right after the
2550 //  original REtADDR, but before the saved framepointer or the spilled registers
2551 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2552 //  stack layout:
2553 //    arg1
2554 //    arg2
2555 //    RETADDR
2556 //    [ new RETADDR
2557 //      move area ]
2558 //    (possible EBP)
2559 //    ESI
2560 //    EDI
2561 //    local1 ..
2562
2563 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2564 /// for a 16 byte align requirement.
2565 unsigned
2566 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2567                                                SelectionDAG& DAG) const {
2568   MachineFunction &MF = DAG.getMachineFunction();
2569   const TargetMachine &TM = MF.getTarget();
2570   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2571   unsigned StackAlignment = TFI.getStackAlignment();
2572   uint64_t AlignMask = StackAlignment - 1;
2573   int64_t Offset = StackSize;
2574   uint64_t SlotSize = TD->getPointerSize();
2575   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2576     // Number smaller than 12 so just add the difference.
2577     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2578   } else {
2579     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2580     Offset = ((~AlignMask) & Offset) + StackAlignment +
2581       (StackAlignment-SlotSize);
2582   }
2583   return Offset;
2584 }
2585
2586 /// MatchingStackOffset - Return true if the given stack call argument is
2587 /// already available in the same position (relatively) of the caller's
2588 /// incoming argument stack.
2589 static
2590 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2591                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2592                          const X86InstrInfo *TII) {
2593   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2594   int FI = INT_MAX;
2595   if (Arg.getOpcode() == ISD::CopyFromReg) {
2596     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2597     if (!TargetRegisterInfo::isVirtualRegister(VR))
2598       return false;
2599     MachineInstr *Def = MRI->getVRegDef(VR);
2600     if (!Def)
2601       return false;
2602     if (!Flags.isByVal()) {
2603       if (!TII->isLoadFromStackSlot(Def, FI))
2604         return false;
2605     } else {
2606       unsigned Opcode = Def->getOpcode();
2607       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2608           Def->getOperand(1).isFI()) {
2609         FI = Def->getOperand(1).getIndex();
2610         Bytes = Flags.getByValSize();
2611       } else
2612         return false;
2613     }
2614   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2615     if (Flags.isByVal())
2616       // ByVal argument is passed in as a pointer but it's now being
2617       // dereferenced. e.g.
2618       // define @foo(%struct.X* %A) {
2619       //   tail call @bar(%struct.X* byval %A)
2620       // }
2621       return false;
2622     SDValue Ptr = Ld->getBasePtr();
2623     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2624     if (!FINode)
2625       return false;
2626     FI = FINode->getIndex();
2627   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2628     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2629     FI = FINode->getIndex();
2630     Bytes = Flags.getByValSize();
2631   } else
2632     return false;
2633
2634   assert(FI != INT_MAX);
2635   if (!MFI->isFixedObjectIndex(FI))
2636     return false;
2637   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2638 }
2639
2640 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2641 /// for tail call optimization. Targets which want to do tail call
2642 /// optimization should implement this function.
2643 bool
2644 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2645                                                      CallingConv::ID CalleeCC,
2646                                                      bool isVarArg,
2647                                                      bool isCalleeStructRet,
2648                                                      bool isCallerStructRet,
2649                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2650                                     const SmallVectorImpl<SDValue> &OutVals,
2651                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2652                                                      SelectionDAG& DAG) const {
2653   if (!IsTailCallConvention(CalleeCC) &&
2654       CalleeCC != CallingConv::C)
2655     return false;
2656
2657   // If -tailcallopt is specified, make fastcc functions tail-callable.
2658   const MachineFunction &MF = DAG.getMachineFunction();
2659   const Function *CallerF = DAG.getMachineFunction().getFunction();
2660   CallingConv::ID CallerCC = CallerF->getCallingConv();
2661   bool CCMatch = CallerCC == CalleeCC;
2662
2663   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2664     if (IsTailCallConvention(CalleeCC) && CCMatch)
2665       return true;
2666     return false;
2667   }
2668
2669   // Look for obvious safe cases to perform tail call optimization that do not
2670   // require ABI changes. This is what gcc calls sibcall.
2671
2672   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2673   // emit a special epilogue.
2674   if (RegInfo->needsStackRealignment(MF))
2675     return false;
2676
2677   // Also avoid sibcall optimization if either caller or callee uses struct
2678   // return semantics.
2679   if (isCalleeStructRet || isCallerStructRet)
2680     return false;
2681
2682   // An stdcall caller is expected to clean up its arguments; the callee
2683   // isn't going to do that.
2684   if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2685     return false;
2686
2687   // Do not sibcall optimize vararg calls unless all arguments are passed via
2688   // registers.
2689   if (isVarArg && !Outs.empty()) {
2690
2691     // Optimizing for varargs on Win64 is unlikely to be safe without
2692     // additional testing.
2693     if (Subtarget->isTargetWin64())
2694       return false;
2695
2696     SmallVector<CCValAssign, 16> ArgLocs;
2697     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2698                    getTargetMachine(), ArgLocs, *DAG.getContext());
2699
2700     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2701     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2702       if (!ArgLocs[i].isRegLoc())
2703         return false;
2704   }
2705
2706   // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2707   // Therefore if it's not used by the call it is not safe to optimize this into
2708   // a sibcall.
2709   bool Unused = false;
2710   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2711     if (!Ins[i].Used) {
2712       Unused = true;
2713       break;
2714     }
2715   }
2716   if (Unused) {
2717     SmallVector<CCValAssign, 16> RVLocs;
2718     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2719                    getTargetMachine(), RVLocs, *DAG.getContext());
2720     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2721     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2722       CCValAssign &VA = RVLocs[i];
2723       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2724         return false;
2725     }
2726   }
2727
2728   // If the calling conventions do not match, then we'd better make sure the
2729   // results are returned in the same way as what the caller expects.
2730   if (!CCMatch) {
2731     SmallVector<CCValAssign, 16> RVLocs1;
2732     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2733                     getTargetMachine(), RVLocs1, *DAG.getContext());
2734     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2735
2736     SmallVector<CCValAssign, 16> RVLocs2;
2737     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2738                     getTargetMachine(), RVLocs2, *DAG.getContext());
2739     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2740
2741     if (RVLocs1.size() != RVLocs2.size())
2742       return false;
2743     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2744       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2745         return false;
2746       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2747         return false;
2748       if (RVLocs1[i].isRegLoc()) {
2749         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2750           return false;
2751       } else {
2752         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2753           return false;
2754       }
2755     }
2756   }
2757
2758   // If the callee takes no arguments then go on to check the results of the
2759   // call.
2760   if (!Outs.empty()) {
2761     // Check if stack adjustment is needed. For now, do not do this if any
2762     // argument is passed on the stack.
2763     SmallVector<CCValAssign, 16> ArgLocs;
2764     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2765                    getTargetMachine(), ArgLocs, *DAG.getContext());
2766
2767     // Allocate shadow area for Win64
2768     if (Subtarget->isTargetWin64()) {
2769       CCInfo.AllocateStack(32, 8);
2770     }
2771
2772     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2773     if (CCInfo.getNextStackOffset()) {
2774       MachineFunction &MF = DAG.getMachineFunction();
2775       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2776         return false;
2777
2778       // Check if the arguments are already laid out in the right way as
2779       // the caller's fixed stack objects.
2780       MachineFrameInfo *MFI = MF.getFrameInfo();
2781       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2782       const X86InstrInfo *TII =
2783         ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2784       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2785         CCValAssign &VA = ArgLocs[i];
2786         SDValue Arg = OutVals[i];
2787         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2788         if (VA.getLocInfo() == CCValAssign::Indirect)
2789           return false;
2790         if (!VA.isRegLoc()) {
2791           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2792                                    MFI, MRI, TII))
2793             return false;
2794         }
2795       }
2796     }
2797
2798     // If the tailcall address may be in a register, then make sure it's
2799     // possible to register allocate for it. In 32-bit, the call address can
2800     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2801     // callee-saved registers are restored. These happen to be the same
2802     // registers used to pass 'inreg' arguments so watch out for those.
2803     if (!Subtarget->is64Bit() &&
2804         !isa<GlobalAddressSDNode>(Callee) &&
2805         !isa<ExternalSymbolSDNode>(Callee)) {
2806       unsigned NumInRegs = 0;
2807       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2808         CCValAssign &VA = ArgLocs[i];
2809         if (!VA.isRegLoc())
2810           continue;
2811         unsigned Reg = VA.getLocReg();
2812         switch (Reg) {
2813         default: break;
2814         case X86::EAX: case X86::EDX: case X86::ECX:
2815           if (++NumInRegs == 3)
2816             return false;
2817           break;
2818         }
2819       }
2820     }
2821   }
2822
2823   return true;
2824 }
2825
2826 FastISel *
2827 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2828   return X86::createFastISel(funcInfo);
2829 }
2830
2831
2832 //===----------------------------------------------------------------------===//
2833 //                           Other Lowering Hooks
2834 //===----------------------------------------------------------------------===//
2835
2836 static bool MayFoldLoad(SDValue Op) {
2837   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2838 }
2839
2840 static bool MayFoldIntoStore(SDValue Op) {
2841   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2842 }
2843
2844 static bool isTargetShuffle(unsigned Opcode) {
2845   switch(Opcode) {
2846   default: return false;
2847   case X86ISD::PSHUFD:
2848   case X86ISD::PSHUFHW:
2849   case X86ISD::PSHUFLW:
2850   case X86ISD::SHUFPD:
2851   case X86ISD::PALIGN:
2852   case X86ISD::SHUFPS:
2853   case X86ISD::MOVLHPS:
2854   case X86ISD::MOVLHPD:
2855   case X86ISD::MOVHLPS:
2856   case X86ISD::MOVLPS:
2857   case X86ISD::MOVLPD:
2858   case X86ISD::MOVSHDUP:
2859   case X86ISD::MOVSLDUP:
2860   case X86ISD::MOVDDUP:
2861   case X86ISD::MOVSS:
2862   case X86ISD::MOVSD:
2863   case X86ISD::UNPCKL:
2864   case X86ISD::UNPCKH:
2865   case X86ISD::VPERMILP:
2866   case X86ISD::VPERM2X128:
2867     return true;
2868   }
2869   return false;
2870 }
2871
2872 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2873                                                SDValue V1, SelectionDAG &DAG) {
2874   switch(Opc) {
2875   default: llvm_unreachable("Unknown x86 shuffle node");
2876   case X86ISD::MOVSHDUP:
2877   case X86ISD::MOVSLDUP:
2878   case X86ISD::MOVDDUP:
2879     return DAG.getNode(Opc, dl, VT, V1);
2880   }
2881
2882   return SDValue();
2883 }
2884
2885 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2886                           SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2887   switch(Opc) {
2888   default: llvm_unreachable("Unknown x86 shuffle node");
2889   case X86ISD::PSHUFD:
2890   case X86ISD::PSHUFHW:
2891   case X86ISD::PSHUFLW:
2892   case X86ISD::VPERMILP:
2893     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2894   }
2895
2896   return SDValue();
2897 }
2898
2899 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2900                SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2901   switch(Opc) {
2902   default: llvm_unreachable("Unknown x86 shuffle node");
2903   case X86ISD::PALIGN:
2904   case X86ISD::SHUFPD:
2905   case X86ISD::SHUFPS:
2906   case X86ISD::VPERM2X128:
2907     return DAG.getNode(Opc, dl, VT, V1, V2,
2908                        DAG.getConstant(TargetMask, MVT::i8));
2909   }
2910   return SDValue();
2911 }
2912
2913 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2914                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
2915   switch(Opc) {
2916   default: llvm_unreachable("Unknown x86 shuffle node");
2917   case X86ISD::MOVLHPS:
2918   case X86ISD::MOVLHPD:
2919   case X86ISD::MOVHLPS:
2920   case X86ISD::MOVLPS:
2921   case X86ISD::MOVLPD:
2922   case X86ISD::MOVSS:
2923   case X86ISD::MOVSD:
2924   case X86ISD::UNPCKL:
2925   case X86ISD::UNPCKH:
2926     return DAG.getNode(Opc, dl, VT, V1, V2);
2927   }
2928   return SDValue();
2929 }
2930
2931 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2932   MachineFunction &MF = DAG.getMachineFunction();
2933   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2934   int ReturnAddrIndex = FuncInfo->getRAIndex();
2935
2936   if (ReturnAddrIndex == 0) {
2937     // Set up a frame object for the return address.
2938     uint64_t SlotSize = TD->getPointerSize();
2939     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2940                                                            false);
2941     FuncInfo->setRAIndex(ReturnAddrIndex);
2942   }
2943
2944   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2945 }
2946
2947
2948 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2949                                        bool hasSymbolicDisplacement) {
2950   // Offset should fit into 32 bit immediate field.
2951   if (!isInt<32>(Offset))
2952     return false;
2953
2954   // If we don't have a symbolic displacement - we don't have any extra
2955   // restrictions.
2956   if (!hasSymbolicDisplacement)
2957     return true;
2958
2959   // FIXME: Some tweaks might be needed for medium code model.
2960   if (M != CodeModel::Small && M != CodeModel::Kernel)
2961     return false;
2962
2963   // For small code model we assume that latest object is 16MB before end of 31
2964   // bits boundary. We may also accept pretty large negative constants knowing
2965   // that all objects are in the positive half of address space.
2966   if (M == CodeModel::Small && Offset < 16*1024*1024)
2967     return true;
2968
2969   // For kernel code model we know that all object resist in the negative half
2970   // of 32bits address space. We may not accept negative offsets, since they may
2971   // be just off and we may accept pretty large positive ones.
2972   if (M == CodeModel::Kernel && Offset > 0)
2973     return true;
2974
2975   return false;
2976 }
2977
2978 /// isCalleePop - Determines whether the callee is required to pop its
2979 /// own arguments. Callee pop is necessary to support tail calls.
2980 bool X86::isCalleePop(CallingConv::ID CallingConv,
2981                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
2982   if (IsVarArg)
2983     return false;
2984
2985   switch (CallingConv) {
2986   default:
2987     return false;
2988   case CallingConv::X86_StdCall:
2989     return !is64Bit;
2990   case CallingConv::X86_FastCall:
2991     return !is64Bit;
2992   case CallingConv::X86_ThisCall:
2993     return !is64Bit;
2994   case CallingConv::Fast:
2995     return TailCallOpt;
2996   case CallingConv::GHC:
2997     return TailCallOpt;
2998   }
2999 }
3000
3001 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3002 /// specific condition code, returning the condition code and the LHS/RHS of the
3003 /// comparison to make.
3004 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3005                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3006   if (!isFP) {
3007     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3008       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3009         // X > -1   -> X == 0, jump !sign.
3010         RHS = DAG.getConstant(0, RHS.getValueType());
3011         return X86::COND_NS;
3012       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3013         // X < 0   -> X == 0, jump on sign.
3014         return X86::COND_S;
3015       } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3016         // X < 1   -> X <= 0
3017         RHS = DAG.getConstant(0, RHS.getValueType());
3018         return X86::COND_LE;
3019       }
3020     }
3021
3022     switch (SetCCOpcode) {
3023     default: llvm_unreachable("Invalid integer condition!");
3024     case ISD::SETEQ:  return X86::COND_E;
3025     case ISD::SETGT:  return X86::COND_G;
3026     case ISD::SETGE:  return X86::COND_GE;
3027     case ISD::SETLT:  return X86::COND_L;
3028     case ISD::SETLE:  return X86::COND_LE;
3029     case ISD::SETNE:  return X86::COND_NE;
3030     case ISD::SETULT: return X86::COND_B;
3031     case ISD::SETUGT: return X86::COND_A;
3032     case ISD::SETULE: return X86::COND_BE;
3033     case ISD::SETUGE: return X86::COND_AE;
3034     }
3035   }
3036
3037   // First determine if it is required or is profitable to flip the operands.
3038
3039   // If LHS is a foldable load, but RHS is not, flip the condition.
3040   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3041       !ISD::isNON_EXTLoad(RHS.getNode())) {
3042     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3043     std::swap(LHS, RHS);
3044   }
3045
3046   switch (SetCCOpcode) {
3047   default: break;
3048   case ISD::SETOLT:
3049   case ISD::SETOLE:
3050   case ISD::SETUGT:
3051   case ISD::SETUGE:
3052     std::swap(LHS, RHS);
3053     break;
3054   }
3055
3056   // On a floating point condition, the flags are set as follows:
3057   // ZF  PF  CF   op
3058   //  0 | 0 | 0 | X > Y
3059   //  0 | 0 | 1 | X < Y
3060   //  1 | 0 | 0 | X == Y
3061   //  1 | 1 | 1 | unordered
3062   switch (SetCCOpcode) {
3063   default: llvm_unreachable("Condcode should be pre-legalized away");
3064   case ISD::SETUEQ:
3065   case ISD::SETEQ:   return X86::COND_E;
3066   case ISD::SETOLT:              // flipped
3067   case ISD::SETOGT:
3068   case ISD::SETGT:   return X86::COND_A;
3069   case ISD::SETOLE:              // flipped
3070   case ISD::SETOGE:
3071   case ISD::SETGE:   return X86::COND_AE;
3072   case ISD::SETUGT:              // flipped
3073   case ISD::SETULT:
3074   case ISD::SETLT:   return X86::COND_B;
3075   case ISD::SETUGE:              // flipped
3076   case ISD::SETULE:
3077   case ISD::SETLE:   return X86::COND_BE;
3078   case ISD::SETONE:
3079   case ISD::SETNE:   return X86::COND_NE;
3080   case ISD::SETUO:   return X86::COND_P;
3081   case ISD::SETO:    return X86::COND_NP;
3082   case ISD::SETOEQ:
3083   case ISD::SETUNE:  return X86::COND_INVALID;
3084   }
3085 }
3086
3087 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3088 /// code. Current x86 isa includes the following FP cmov instructions:
3089 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3090 static bool hasFPCMov(unsigned X86CC) {
3091   switch (X86CC) {
3092   default:
3093     return false;
3094   case X86::COND_B:
3095   case X86::COND_BE:
3096   case X86::COND_E:
3097   case X86::COND_P:
3098   case X86::COND_A:
3099   case X86::COND_AE:
3100   case X86::COND_NE:
3101   case X86::COND_NP:
3102     return true;
3103   }
3104 }
3105
3106 /// isFPImmLegal - Returns true if the target can instruction select the
3107 /// specified FP immediate natively. If false, the legalizer will
3108 /// materialize the FP immediate as a load from a constant pool.
3109 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3110   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3111     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3112       return true;
3113   }
3114   return false;
3115 }
3116
3117 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3118 /// the specified range (L, H].
3119 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3120   return (Val < 0) || (Val >= Low && Val < Hi);
3121 }
3122
3123 /// isUndefOrInRange - Return true if every element in Mask, begining
3124 /// from position Pos and ending in Pos+Size, falls within the specified
3125 /// range (L, L+Pos]. or is undef.
3126 static bool isUndefOrInRange(const SmallVectorImpl<int> &Mask,
3127                              int Pos, int Size, int Low, int Hi) {
3128   for (int i = Pos, e = Pos+Size; i != e; ++i)
3129     if (!isUndefOrInRange(Mask[i], Low, Hi))
3130       return false;
3131   return true;
3132 }
3133
3134 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3135 /// specified value.
3136 static bool isUndefOrEqual(int Val, int CmpVal) {
3137   if (Val < 0 || Val == CmpVal)
3138     return true;
3139   return false;
3140 }
3141
3142 /// isSequentialOrUndefInRange - Return true if every element in Mask, begining
3143 /// from position Pos and ending in Pos+Size, falls within the specified
3144 /// sequential range (L, L+Pos]. or is undef.
3145 static bool isSequentialOrUndefInRange(const SmallVectorImpl<int> &Mask,
3146                                        int Pos, int Size, int Low) {
3147   for (int i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3148     if (!isUndefOrEqual(Mask[i], Low))
3149       return false;
3150   return true;
3151 }
3152
3153 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3154 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3155 /// the second operand.
3156 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3157   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3158     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3159   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3160     return (Mask[0] < 2 && Mask[1] < 2);
3161   return false;
3162 }
3163
3164 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
3165   SmallVector<int, 8> M;
3166   N->getMask(M);
3167   return ::isPSHUFDMask(M, N->getValueType(0));
3168 }
3169
3170 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3171 /// is suitable for input to PSHUFHW.
3172 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3173   if (VT != MVT::v8i16)
3174     return false;
3175
3176   // Lower quadword copied in order or undef.
3177   for (int i = 0; i != 4; ++i)
3178     if (Mask[i] >= 0 && Mask[i] != i)
3179       return false;
3180
3181   // Upper quadword shuffled.
3182   for (int i = 4; i != 8; ++i)
3183     if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
3184       return false;
3185
3186   return true;
3187 }
3188
3189 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
3190   SmallVector<int, 8> M;
3191   N->getMask(M);
3192   return ::isPSHUFHWMask(M, N->getValueType(0));
3193 }
3194
3195 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3196 /// is suitable for input to PSHUFLW.
3197 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3198   if (VT != MVT::v8i16)
3199     return false;
3200
3201   // Upper quadword copied in order.
3202   for (int i = 4; i != 8; ++i)
3203     if (Mask[i] >= 0 && Mask[i] != i)
3204       return false;
3205
3206   // Lower quadword shuffled.
3207   for (int i = 0; i != 4; ++i)
3208     if (Mask[i] >= 4)
3209       return false;
3210
3211   return true;
3212 }
3213
3214 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
3215   SmallVector<int, 8> M;
3216   N->getMask(M);
3217   return ::isPSHUFLWMask(M, N->getValueType(0));
3218 }
3219
3220 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3221 /// is suitable for input to PALIGNR.
3222 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
3223                           bool hasSSSE3OrAVX) {
3224   int i, e = VT.getVectorNumElements();
3225   if (VT.getSizeInBits() != 128)
3226     return false;
3227
3228   // Do not handle v2i64 / v2f64 shuffles with palignr.
3229   if (e < 4 || !hasSSSE3OrAVX)
3230     return false;
3231
3232   for (i = 0; i != e; ++i)
3233     if (Mask[i] >= 0)
3234       break;
3235
3236   // All undef, not a palignr.
3237   if (i == e)
3238     return false;
3239
3240   // Make sure we're shifting in the right direction.
3241   if (Mask[i] <= i)
3242     return false;
3243
3244   int s = Mask[i] - i;
3245
3246   // Check the rest of the elements to see if they are consecutive.
3247   for (++i; i != e; ++i) {
3248     int m = Mask[i];
3249     if (m >= 0 && m != s+i)
3250       return false;
3251   }
3252   return true;
3253 }
3254
3255 /// isVSHUFPYMask - Return true if the specified VECTOR_SHUFFLE operand
3256 /// specifies a shuffle of elements that is suitable for input to 256-bit
3257 /// VSHUFPSY.
3258 static bool isVSHUFPYMask(const SmallVectorImpl<int> &Mask, EVT VT,
3259                           bool HasAVX, bool Commuted = false) {
3260   int NumElems = VT.getVectorNumElements();
3261
3262   if (!HasAVX || VT.getSizeInBits() != 256)
3263     return false;
3264
3265   if (NumElems != 4 && NumElems != 8)
3266     return false;
3267
3268   // VSHUFPSY divides the resulting vector into 4 chunks.
3269   // The sources are also splitted into 4 chunks, and each destination
3270   // chunk must come from a different source chunk.
3271   //
3272   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3273   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3274   //
3275   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3276   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3277   //
3278   // VSHUFPDY divides the resulting vector into 4 chunks.
3279   // The sources are also splitted into 4 chunks, and each destination
3280   // chunk must come from a different source chunk.
3281   //
3282   //  SRC1 =>      X3       X2       X1       X0
3283   //  SRC2 =>      Y3       Y2       Y1       Y0
3284   //
3285   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3286   //
3287   unsigned QuarterSize = NumElems/4;
3288   unsigned HalfSize = QuarterSize*2;
3289   for (unsigned l = 0; l != 2; ++l) {
3290     unsigned LaneStart = l*HalfSize;
3291     for (unsigned s = 0; s != 2; ++s) {
3292       unsigned QuarterStart = s*QuarterSize;
3293       unsigned Src = (Commuted) ? (1-s) : s;
3294       unsigned SrcStart = Src*NumElems + LaneStart;
3295       for (unsigned i = 0; i != QuarterSize; ++i) {
3296         int Idx = Mask[i+QuarterStart+LaneStart];
3297         if (!isUndefOrInRange(Idx, SrcStart, SrcStart+HalfSize))
3298           return false;
3299         // For VSHUFPSY, the mask of the second half must be the same as the first
3300         // but with the appropriate offsets. This works in the same way as
3301         // VPERMILPS works with masks.
3302         if (NumElems == 4 || l == 0 || Mask[i+QuarterStart] < 0)
3303           continue;
3304         if (!isUndefOrEqual(Idx, Mask[i+QuarterStart]+HalfSize))
3305           return false;
3306       }
3307     }
3308   }
3309
3310   return true;
3311 }
3312
3313 /// getShuffleVSHUFPYImmediate - Return the appropriate immediate to shuffle
3314 /// the specified VECTOR_MASK mask with VSHUFPSY/VSHUFPDY instructions.
3315 static unsigned getShuffleVSHUFPYImmediate(SDNode *N) {
3316   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3317   EVT VT = SVOp->getValueType(0);
3318   int NumElems = VT.getVectorNumElements();
3319
3320   assert(VT.getSizeInBits() == 256 && "Only supports 256-bit types");
3321   assert((NumElems == 4 || NumElems == 8) && "Only supports v4 and v8 types");
3322
3323   int HalfSize = NumElems/2;
3324   unsigned Mul = (NumElems == 8) ? 2 : 1;
3325   unsigned Mask = 0;
3326   for (int i = 0; i != NumElems; ++i) {
3327     int Elt = SVOp->getMaskElt(i);
3328     if (Elt < 0)
3329       continue;
3330     Elt %= HalfSize;
3331     unsigned Shamt = i;
3332     // For VSHUFPSY, the mask of the first half must be equal to the second one.
3333     if (NumElems == 8) Shamt %= HalfSize;
3334     Mask |= Elt << (Shamt*Mul);
3335   }
3336
3337   return Mask;
3338 }
3339
3340 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3341 /// the two vector operands have swapped position.
3342 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3343                                      unsigned NumElems) {
3344   for (unsigned i = 0; i != NumElems; ++i) {
3345     int idx = Mask[i];
3346     if (idx < 0)
3347       continue;
3348     else if (idx < (int)NumElems)
3349       Mask[i] = idx + NumElems;
3350     else
3351       Mask[i] = idx - NumElems;
3352   }
3353 }
3354
3355 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3356 /// specifies a shuffle of elements that is suitable for input to 128-bit
3357 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3358 /// reverse of what x86 shuffles want.
3359 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT,
3360                         bool Commuted = false) {
3361   unsigned NumElems = VT.getVectorNumElements();
3362
3363   if (VT.getSizeInBits() != 128)
3364     return false;
3365
3366   if (NumElems != 2 && NumElems != 4)
3367     return false;
3368
3369   unsigned Half = NumElems / 2;
3370   unsigned SrcStart = Commuted ? NumElems : 0;
3371   for (unsigned i = 0; i != Half; ++i)
3372     if (!isUndefOrInRange(Mask[i], SrcStart, SrcStart+NumElems))
3373       return false;
3374   SrcStart = Commuted ? 0 : NumElems;
3375   for (unsigned i = Half; i != NumElems; ++i)
3376     if (!isUndefOrInRange(Mask[i], SrcStart, SrcStart+NumElems))
3377       return false;
3378
3379   return true;
3380 }
3381
3382 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
3383   SmallVector<int, 8> M;
3384   N->getMask(M);
3385   return ::isSHUFPMask(M, N->getValueType(0));
3386 }
3387
3388 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3389 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3390 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3391   EVT VT = N->getValueType(0);
3392   unsigned NumElems = VT.getVectorNumElements();
3393
3394   if (VT.getSizeInBits() != 128)
3395     return false;
3396
3397   if (NumElems != 4)
3398     return false;
3399
3400   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3401   return isUndefOrEqual(N->getMaskElt(0), 6) &&
3402          isUndefOrEqual(N->getMaskElt(1), 7) &&
3403          isUndefOrEqual(N->getMaskElt(2), 2) &&
3404          isUndefOrEqual(N->getMaskElt(3), 3);
3405 }
3406
3407 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3408 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3409 /// <2, 3, 2, 3>
3410 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3411   EVT VT = N->getValueType(0);
3412   unsigned NumElems = VT.getVectorNumElements();
3413
3414   if (VT.getSizeInBits() != 128)
3415     return false;
3416
3417   if (NumElems != 4)
3418     return false;
3419
3420   return isUndefOrEqual(N->getMaskElt(0), 2) &&
3421          isUndefOrEqual(N->getMaskElt(1), 3) &&
3422          isUndefOrEqual(N->getMaskElt(2), 2) &&
3423          isUndefOrEqual(N->getMaskElt(3), 3);
3424 }
3425
3426 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3427 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3428 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3429   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3430
3431   if (NumElems != 2 && NumElems != 4)
3432     return false;
3433
3434   for (unsigned i = 0; i < NumElems/2; ++i)
3435     if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3436       return false;
3437
3438   for (unsigned i = NumElems/2; i < NumElems; ++i)
3439     if (!isUndefOrEqual(N->getMaskElt(i), i))
3440       return false;
3441
3442   return true;
3443 }
3444
3445 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3446 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3447 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3448   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3449
3450   if ((NumElems != 2 && NumElems != 4)
3451       || N->getValueType(0).getSizeInBits() > 128)
3452     return false;
3453
3454   for (unsigned i = 0; i < NumElems/2; ++i)
3455     if (!isUndefOrEqual(N->getMaskElt(i), i))
3456       return false;
3457
3458   for (unsigned i = 0; i < NumElems/2; ++i)
3459     if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3460       return false;
3461
3462   return true;
3463 }
3464
3465 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3466 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3467 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3468                          bool HasAVX2, bool V2IsSplat = false) {
3469   unsigned NumElts = VT.getVectorNumElements();
3470
3471   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3472          "Unsupported vector type for unpckh");
3473
3474   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3475       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3476     return false;
3477
3478   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3479   // independently on 128-bit lanes.
3480   unsigned NumLanes = VT.getSizeInBits()/128;
3481   unsigned NumLaneElts = NumElts/NumLanes;
3482
3483   for (unsigned l = 0; l != NumLanes; ++l) {
3484     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3485          i != (l+1)*NumLaneElts;
3486          i += 2, ++j) {
3487       int BitI  = Mask[i];
3488       int BitI1 = Mask[i+1];
3489       if (!isUndefOrEqual(BitI, j))
3490         return false;
3491       if (V2IsSplat) {
3492         if (!isUndefOrEqual(BitI1, NumElts))
3493           return false;
3494       } else {
3495         if (!isUndefOrEqual(BitI1, j + NumElts))
3496           return false;
3497       }
3498     }
3499   }
3500
3501   return true;
3502 }
3503
3504 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool HasAVX2, bool V2IsSplat) {
3505   SmallVector<int, 8> M;
3506   N->getMask(M);
3507   return ::isUNPCKLMask(M, N->getValueType(0), HasAVX2, V2IsSplat);
3508 }
3509
3510 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3511 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3512 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3513                          bool HasAVX2, bool V2IsSplat = false) {
3514   unsigned NumElts = VT.getVectorNumElements();
3515
3516   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3517          "Unsupported vector type for unpckh");
3518
3519   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3520       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3521     return false;
3522
3523   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3524   // independently on 128-bit lanes.
3525   unsigned NumLanes = VT.getSizeInBits()/128;
3526   unsigned NumLaneElts = NumElts/NumLanes;
3527
3528   for (unsigned l = 0; l != NumLanes; ++l) {
3529     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3530          i != (l+1)*NumLaneElts; i += 2, ++j) {
3531       int BitI  = Mask[i];
3532       int BitI1 = Mask[i+1];
3533       if (!isUndefOrEqual(BitI, j))
3534         return false;
3535       if (V2IsSplat) {
3536         if (isUndefOrEqual(BitI1, NumElts))
3537           return false;
3538       } else {
3539         if (!isUndefOrEqual(BitI1, j+NumElts))
3540           return false;
3541       }
3542     }
3543   }
3544   return true;
3545 }
3546
3547 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool HasAVX2, bool V2IsSplat) {
3548   SmallVector<int, 8> M;
3549   N->getMask(M);
3550   return ::isUNPCKHMask(M, N->getValueType(0), HasAVX2, V2IsSplat);
3551 }
3552
3553 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3554 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3555 /// <0, 0, 1, 1>
3556 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT,
3557                                   bool HasAVX2) {
3558   unsigned NumElts = VT.getVectorNumElements();
3559
3560   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3561          "Unsupported vector type for unpckh");
3562
3563   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3564       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3565     return false;
3566
3567   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3568   // FIXME: Need a better way to get rid of this, there's no latency difference
3569   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3570   // the former later. We should also remove the "_undef" special mask.
3571   if (NumElts == 4 && VT.getSizeInBits() == 256)
3572     return false;
3573
3574   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3575   // independently on 128-bit lanes.
3576   unsigned NumLanes = VT.getSizeInBits()/128;
3577   unsigned NumLaneElts = NumElts/NumLanes;
3578
3579   for (unsigned l = 0; l != NumLanes; ++l) {
3580     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3581          i != (l+1)*NumLaneElts;
3582          i += 2, ++j) {
3583       int BitI  = Mask[i];
3584       int BitI1 = Mask[i+1];
3585
3586       if (!isUndefOrEqual(BitI, j))
3587         return false;
3588       if (!isUndefOrEqual(BitI1, j))
3589         return false;
3590     }
3591   }
3592
3593   return true;
3594 }
3595
3596 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N, bool HasAVX2) {
3597   SmallVector<int, 8> M;
3598   N->getMask(M);
3599   return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0), HasAVX2);
3600 }
3601
3602 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3603 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3604 /// <2, 2, 3, 3>
3605 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT,
3606                                   bool HasAVX2) {
3607   unsigned NumElts = VT.getVectorNumElements();
3608
3609   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3610          "Unsupported vector type for unpckh");
3611
3612   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3613       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3614     return false;
3615
3616   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3617   // independently on 128-bit lanes.
3618   unsigned NumLanes = VT.getSizeInBits()/128;
3619   unsigned NumLaneElts = NumElts/NumLanes;
3620
3621   for (unsigned l = 0; l != NumLanes; ++l) {
3622     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3623          i != (l+1)*NumLaneElts; i += 2, ++j) {
3624       int BitI  = Mask[i];
3625       int BitI1 = Mask[i+1];
3626       if (!isUndefOrEqual(BitI, j))
3627         return false;
3628       if (!isUndefOrEqual(BitI1, j))
3629         return false;
3630     }
3631   }
3632   return true;
3633 }
3634
3635 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N, bool HasAVX2) {
3636   SmallVector<int, 8> M;
3637   N->getMask(M);
3638   return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0), HasAVX2);
3639 }
3640
3641 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3642 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3643 /// MOVSD, and MOVD, i.e. setting the lowest element.
3644 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3645   if (VT.getVectorElementType().getSizeInBits() < 32)
3646     return false;
3647
3648   int NumElts = VT.getVectorNumElements();
3649
3650   if (!isUndefOrEqual(Mask[0], NumElts))
3651     return false;
3652
3653   for (int i = 1; i < NumElts; ++i)
3654     if (!isUndefOrEqual(Mask[i], i))
3655       return false;
3656
3657   return true;
3658 }
3659
3660 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3661   SmallVector<int, 8> M;
3662   N->getMask(M);
3663   return ::isMOVLMask(M, N->getValueType(0));
3664 }
3665
3666 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3667 /// as permutations between 128-bit chunks or halves. As an example: this
3668 /// shuffle bellow:
3669 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3670 /// The first half comes from the second half of V1 and the second half from the
3671 /// the second half of V2.
3672 static bool isVPERM2X128Mask(const SmallVectorImpl<int> &Mask, EVT VT,
3673                              bool HasAVX) {
3674   if (!HasAVX || VT.getSizeInBits() != 256)
3675     return false;
3676
3677   // The shuffle result is divided into half A and half B. In total the two
3678   // sources have 4 halves, namely: C, D, E, F. The final values of A and
3679   // B must come from C, D, E or F.
3680   int HalfSize = VT.getVectorNumElements()/2;
3681   bool MatchA = false, MatchB = false;
3682
3683   // Check if A comes from one of C, D, E, F.
3684   for (int Half = 0; Half < 4; ++Half) {
3685     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3686       MatchA = true;
3687       break;
3688     }
3689   }
3690
3691   // Check if B comes from one of C, D, E, F.
3692   for (int Half = 0; Half < 4; ++Half) {
3693     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3694       MatchB = true;
3695       break;
3696     }
3697   }
3698
3699   return MatchA && MatchB;
3700 }
3701
3702 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3703 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3704 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3705   EVT VT = SVOp->getValueType(0);
3706
3707   int HalfSize = VT.getVectorNumElements()/2;
3708
3709   int FstHalf = 0, SndHalf = 0;
3710   for (int i = 0; i < HalfSize; ++i) {
3711     if (SVOp->getMaskElt(i) > 0) {
3712       FstHalf = SVOp->getMaskElt(i)/HalfSize;
3713       break;
3714     }
3715   }
3716   for (int i = HalfSize; i < HalfSize*2; ++i) {
3717     if (SVOp->getMaskElt(i) > 0) {
3718       SndHalf = SVOp->getMaskElt(i)/HalfSize;
3719       break;
3720     }
3721   }
3722
3723   return (FstHalf | (SndHalf << 4));
3724 }
3725
3726 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3727 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3728 /// Note that VPERMIL mask matching is different depending whether theunderlying
3729 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3730 /// to the same elements of the low, but to the higher half of the source.
3731 /// In VPERMILPD the two lanes could be shuffled independently of each other
3732 /// with the same restriction that lanes can't be crossed.
3733 static bool isVPERMILPMask(const SmallVectorImpl<int> &Mask, EVT VT,
3734                            bool HasAVX) {
3735   int NumElts = VT.getVectorNumElements();
3736   int NumLanes = VT.getSizeInBits()/128;
3737
3738   if (!HasAVX)
3739     return false;
3740
3741   // Only match 256-bit with 32/64-bit types
3742   if (VT.getSizeInBits() != 256 || (NumElts != 4 && NumElts != 8))
3743     return false;
3744
3745   int LaneSize = NumElts/NumLanes;
3746   for (int l = 0; l != NumLanes; ++l) {
3747     int LaneStart = l*LaneSize;
3748     for (int i = 0; i != LaneSize; ++i) {
3749       if (!isUndefOrInRange(Mask[i+LaneStart], LaneStart, LaneStart+LaneSize))
3750         return false;
3751       if (NumElts == 4 || l == 0)
3752         continue;
3753       // VPERMILPS handling
3754       if (Mask[i] < 0)
3755         continue;
3756       if (!isUndefOrEqual(Mask[i+LaneStart], Mask[i]+LaneSize))
3757         return false;
3758     }
3759   }
3760
3761   return true;
3762 }
3763
3764 /// getShuffleVPERMILPImmediate - Return the appropriate immediate to shuffle
3765 /// the specified VECTOR_MASK mask with VPERMILPS/D* instructions.
3766 static unsigned getShuffleVPERMILPImmediate(ShuffleVectorSDNode *SVOp) {
3767   EVT VT = SVOp->getValueType(0);
3768
3769   int NumElts = VT.getVectorNumElements();
3770   int NumLanes = VT.getSizeInBits()/128;
3771   int LaneSize = NumElts/NumLanes;
3772
3773   // Although the mask is equal for both lanes do it twice to get the cases
3774   // where a mask will match because the same mask element is undef on the
3775   // first half but valid on the second. This would get pathological cases
3776   // such as: shuffle <u, 0, 1, 2, 4, 4, 5, 6>, which is completely valid.
3777   unsigned Shift = (LaneSize == 4) ? 2 : 1;
3778   unsigned Mask = 0;
3779   for (int i = 0; i != NumElts; ++i) {
3780     int MaskElt = SVOp->getMaskElt(i);
3781     if (MaskElt < 0)
3782       continue;
3783     MaskElt %= LaneSize;
3784     unsigned Shamt = i;
3785     // VPERMILPSY, the mask of the first half must be equal to the second one
3786     if (NumElts == 8) Shamt %= LaneSize;
3787     Mask |= MaskElt << (Shamt*Shift);
3788   }
3789
3790   return Mask;
3791 }
3792
3793 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3794 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3795 /// element of vector 2 and the other elements to come from vector 1 in order.
3796 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3797                                bool V2IsSplat = false, bool V2IsUndef = false) {
3798   int NumOps = VT.getVectorNumElements();
3799   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3800     return false;
3801
3802   if (!isUndefOrEqual(Mask[0], 0))
3803     return false;
3804
3805   for (int i = 1; i < NumOps; ++i)
3806     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3807           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3808           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3809       return false;
3810
3811   return true;
3812 }
3813
3814 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3815                            bool V2IsUndef = false) {
3816   SmallVector<int, 8> M;
3817   N->getMask(M);
3818   return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3819 }
3820
3821 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3822 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3823 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3824 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N,
3825                          const X86Subtarget *Subtarget) {
3826   if (!Subtarget->hasSSE3orAVX())
3827     return false;
3828
3829   // The second vector must be undef
3830   if (N->getOperand(1).getOpcode() != ISD::UNDEF)
3831     return false;
3832
3833   EVT VT = N->getValueType(0);
3834   unsigned NumElems = VT.getVectorNumElements();
3835
3836   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3837       (VT.getSizeInBits() == 256 && NumElems != 8))
3838     return false;
3839
3840   // "i+1" is the value the indexed mask element must have
3841   for (unsigned i = 0; i < NumElems; i += 2)
3842     if (!isUndefOrEqual(N->getMaskElt(i), i+1) ||
3843         !isUndefOrEqual(N->getMaskElt(i+1), i+1))
3844       return false;
3845
3846   return true;
3847 }
3848
3849 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3850 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3851 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3852 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N,
3853                          const X86Subtarget *Subtarget) {
3854   if (!Subtarget->hasSSE3orAVX())
3855     return false;
3856
3857   // The second vector must be undef
3858   if (N->getOperand(1).getOpcode() != ISD::UNDEF)
3859     return false;
3860
3861   EVT VT = N->getValueType(0);
3862   unsigned NumElems = VT.getVectorNumElements();
3863
3864   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3865       (VT.getSizeInBits() == 256 && NumElems != 8))
3866     return false;
3867
3868   // "i" is the value the indexed mask element must have
3869   for (unsigned i = 0; i < NumElems; i += 2)
3870     if (!isUndefOrEqual(N->getMaskElt(i), i) ||
3871         !isUndefOrEqual(N->getMaskElt(i+1), i))
3872       return false;
3873
3874   return true;
3875 }
3876
3877 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3878 /// specifies a shuffle of elements that is suitable for input to 256-bit
3879 /// version of MOVDDUP.
3880 static bool isMOVDDUPYMask(const SmallVectorImpl<int> &Mask, EVT VT,
3881                            bool HasAVX) {
3882   int NumElts = VT.getVectorNumElements();
3883
3884   if (!HasAVX || VT.getSizeInBits() != 256 || NumElts != 4)
3885     return false;
3886
3887   for (int i = 0; i != NumElts/2; ++i)
3888     if (!isUndefOrEqual(Mask[i], 0))
3889       return false;
3890   for (int i = NumElts/2; i != NumElts; ++i)
3891     if (!isUndefOrEqual(Mask[i], NumElts/2))
3892       return false;
3893   return true;
3894 }
3895
3896 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3897 /// specifies a shuffle of elements that is suitable for input to 128-bit
3898 /// version of MOVDDUP.
3899 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3900   EVT VT = N->getValueType(0);
3901
3902   if (VT.getSizeInBits() != 128)
3903     return false;
3904
3905   int e = VT.getVectorNumElements() / 2;
3906   for (int i = 0; i < e; ++i)
3907     if (!isUndefOrEqual(N->getMaskElt(i), i))
3908       return false;
3909   for (int i = 0; i < e; ++i)
3910     if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3911       return false;
3912   return true;
3913 }
3914
3915 /// isVEXTRACTF128Index - Return true if the specified
3916 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3917 /// suitable for input to VEXTRACTF128.
3918 bool X86::isVEXTRACTF128Index(SDNode *N) {
3919   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3920     return false;
3921
3922   // The index should be aligned on a 128-bit boundary.
3923   uint64_t Index =
3924     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3925
3926   unsigned VL = N->getValueType(0).getVectorNumElements();
3927   unsigned VBits = N->getValueType(0).getSizeInBits();
3928   unsigned ElSize = VBits / VL;
3929   bool Result = (Index * ElSize) % 128 == 0;
3930
3931   return Result;
3932 }
3933
3934 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3935 /// operand specifies a subvector insert that is suitable for input to
3936 /// VINSERTF128.
3937 bool X86::isVINSERTF128Index(SDNode *N) {
3938   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3939     return false;
3940
3941   // The index should be aligned on a 128-bit boundary.
3942   uint64_t Index =
3943     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3944
3945   unsigned VL = N->getValueType(0).getVectorNumElements();
3946   unsigned VBits = N->getValueType(0).getSizeInBits();
3947   unsigned ElSize = VBits / VL;
3948   bool Result = (Index * ElSize) % 128 == 0;
3949
3950   return Result;
3951 }
3952
3953 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3954 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3955 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3956   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3957   int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3958
3959   unsigned Shift = (NumOperands == 4) ? 2 : 1;
3960   unsigned Mask = 0;
3961   for (int i = 0; i < NumOperands; ++i) {
3962     int Val = SVOp->getMaskElt(NumOperands-i-1);
3963     if (Val < 0) Val = 0;
3964     if (Val >= NumOperands) Val -= NumOperands;
3965     Mask |= Val;
3966     if (i != NumOperands - 1)
3967       Mask <<= Shift;
3968   }
3969   return Mask;
3970 }
3971
3972 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3973 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3974 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3975   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3976   unsigned Mask = 0;
3977   // 8 nodes, but we only care about the last 4.
3978   for (unsigned i = 7; i >= 4; --i) {
3979     int Val = SVOp->getMaskElt(i);
3980     if (Val >= 0)
3981       Mask |= (Val - 4);
3982     if (i != 4)
3983       Mask <<= 2;
3984   }
3985   return Mask;
3986 }
3987
3988 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3989 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3990 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3991   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3992   unsigned Mask = 0;
3993   // 8 nodes, but we only care about the first 4.
3994   for (int i = 3; i >= 0; --i) {
3995     int Val = SVOp->getMaskElt(i);
3996     if (Val >= 0)
3997       Mask |= Val;
3998     if (i != 0)
3999       Mask <<= 2;
4000   }
4001   return Mask;
4002 }
4003
4004 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4005 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4006 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4007   EVT VT = SVOp->getValueType(0);
4008   unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4009   int Val = 0;
4010
4011   unsigned i, e;
4012   for (i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
4013     Val = SVOp->getMaskElt(i);
4014     if (Val >= 0)
4015       break;
4016   }
4017   assert(Val - i > 0 && "PALIGNR imm should be positive");
4018   return (Val - i) * EltSize;
4019 }
4020
4021 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4022 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4023 /// instructions.
4024 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4025   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4026     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4027
4028   uint64_t Index =
4029     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4030
4031   EVT VecVT = N->getOperand(0).getValueType();
4032   EVT ElVT = VecVT.getVectorElementType();
4033
4034   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4035   return Index / NumElemsPerChunk;
4036 }
4037
4038 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4039 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4040 /// instructions.
4041 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4042   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4043     llvm_unreachable("Illegal insert subvector for VINSERTF128");
4044
4045   uint64_t Index =
4046     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4047
4048   EVT VecVT = N->getValueType(0);
4049   EVT ElVT = VecVT.getVectorElementType();
4050
4051   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4052   return Index / NumElemsPerChunk;
4053 }
4054
4055 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4056 /// constant +0.0.
4057 bool X86::isZeroNode(SDValue Elt) {
4058   return ((isa<ConstantSDNode>(Elt) &&
4059            cast<ConstantSDNode>(Elt)->isNullValue()) ||
4060           (isa<ConstantFPSDNode>(Elt) &&
4061            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4062 }
4063
4064 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4065 /// their permute mask.
4066 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4067                                     SelectionDAG &DAG) {
4068   EVT VT = SVOp->getValueType(0);
4069   unsigned NumElems = VT.getVectorNumElements();
4070   SmallVector<int, 8> MaskVec;
4071
4072   for (unsigned i = 0; i != NumElems; ++i) {
4073     int idx = SVOp->getMaskElt(i);
4074     if (idx < 0)
4075       MaskVec.push_back(idx);
4076     else if (idx < (int)NumElems)
4077       MaskVec.push_back(idx + NumElems);
4078     else
4079       MaskVec.push_back(idx - NumElems);
4080   }
4081   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4082                               SVOp->getOperand(0), &MaskVec[0]);
4083 }
4084
4085 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4086 /// match movhlps. The lower half elements should come from upper half of
4087 /// V1 (and in order), and the upper half elements should come from the upper
4088 /// half of V2 (and in order).
4089 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
4090   EVT VT = Op->getValueType(0);
4091   if (VT.getSizeInBits() != 128)
4092     return false;
4093   if (VT.getVectorNumElements() != 4)
4094     return false;
4095   for (unsigned i = 0, e = 2; i != e; ++i)
4096     if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
4097       return false;
4098   for (unsigned i = 2; i != 4; ++i)
4099     if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
4100       return false;
4101   return true;
4102 }
4103
4104 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4105 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4106 /// required.
4107 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4108   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4109     return false;
4110   N = N->getOperand(0).getNode();
4111   if (!ISD::isNON_EXTLoad(N))
4112     return false;
4113   if (LD)
4114     *LD = cast<LoadSDNode>(N);
4115   return true;
4116 }
4117
4118 // Test whether the given value is a vector value which will be legalized
4119 // into a load.
4120 static bool WillBeConstantPoolLoad(SDNode *N) {
4121   if (N->getOpcode() != ISD::BUILD_VECTOR)
4122     return false;
4123
4124   // Check for any non-constant elements.
4125   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4126     switch (N->getOperand(i).getNode()->getOpcode()) {
4127     case ISD::UNDEF:
4128     case ISD::ConstantFP:
4129     case ISD::Constant:
4130       break;
4131     default:
4132       return false;
4133     }
4134
4135   // Vectors of all-zeros and all-ones are materialized with special
4136   // instructions rather than being loaded.
4137   return !ISD::isBuildVectorAllZeros(N) &&
4138          !ISD::isBuildVectorAllOnes(N);
4139 }
4140
4141 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4142 /// match movlp{s|d}. The lower half elements should come from lower half of
4143 /// V1 (and in order), and the upper half elements should come from the upper
4144 /// half of V2 (and in order). And since V1 will become the source of the
4145 /// MOVLP, it must be either a vector load or a scalar load to vector.
4146 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4147                                ShuffleVectorSDNode *Op) {
4148   EVT VT = Op->getValueType(0);
4149   if (VT.getSizeInBits() != 128)
4150     return false;
4151
4152   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4153     return false;
4154   // Is V2 is a vector load, don't do this transformation. We will try to use
4155   // load folding shufps op.
4156   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4157     return false;
4158
4159   unsigned NumElems = VT.getVectorNumElements();
4160
4161   if (NumElems != 2 && NumElems != 4)
4162     return false;
4163   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4164     if (!isUndefOrEqual(Op->getMaskElt(i), i))
4165       return false;
4166   for (unsigned i = NumElems/2; i != NumElems; ++i)
4167     if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
4168       return false;
4169   return true;
4170 }
4171
4172 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4173 /// all the same.
4174 static bool isSplatVector(SDNode *N) {
4175   if (N->getOpcode() != ISD::BUILD_VECTOR)
4176     return false;
4177
4178   SDValue SplatValue = N->getOperand(0);
4179   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4180     if (N->getOperand(i) != SplatValue)
4181       return false;
4182   return true;
4183 }
4184
4185 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4186 /// to an zero vector.
4187 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4188 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4189   SDValue V1 = N->getOperand(0);
4190   SDValue V2 = N->getOperand(1);
4191   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4192   for (unsigned i = 0; i != NumElems; ++i) {
4193     int Idx = N->getMaskElt(i);
4194     if (Idx >= (int)NumElems) {
4195       unsigned Opc = V2.getOpcode();
4196       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4197         continue;
4198       if (Opc != ISD::BUILD_VECTOR ||
4199           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4200         return false;
4201     } else if (Idx >= 0) {
4202       unsigned Opc = V1.getOpcode();
4203       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4204         continue;
4205       if (Opc != ISD::BUILD_VECTOR ||
4206           !X86::isZeroNode(V1.getOperand(Idx)))
4207         return false;
4208     }
4209   }
4210   return true;
4211 }
4212
4213 /// getZeroVector - Returns a vector of specified type with all zero elements.
4214 ///
4215 static SDValue getZeroVector(EVT VT, bool HasXMMInt, SelectionDAG &DAG,
4216                              DebugLoc dl) {
4217   assert(VT.isVector() && "Expected a vector type");
4218
4219   // Always build SSE zero vectors as <4 x i32> bitcasted
4220   // to their dest type. This ensures they get CSE'd.
4221   SDValue Vec;
4222   if (VT.getSizeInBits() == 128) {  // SSE
4223     if (HasXMMInt) {  // SSE2
4224       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4225       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4226     } else { // SSE1
4227       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4228       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4229     }
4230   } else if (VT.getSizeInBits() == 256) { // AVX
4231     // 256-bit logic and arithmetic instructions in AVX are
4232     // all floating-point, no support for integer ops. Default
4233     // to emitting fp zeroed vectors then.
4234     SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4235     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4236     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4237   }
4238   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4239 }
4240
4241 /// getOnesVector - Returns a vector of specified type with all bits set.
4242 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4243 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4244 /// Then bitcast to their original type, ensuring they get CSE'd.
4245 static SDValue getOnesVector(EVT VT, bool HasAVX2, SelectionDAG &DAG,
4246                              DebugLoc dl) {
4247   assert(VT.isVector() && "Expected a vector type");
4248   assert((VT.is128BitVector() || VT.is256BitVector())
4249          && "Expected a 128-bit or 256-bit vector type");
4250
4251   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4252   SDValue Vec;
4253   if (VT.getSizeInBits() == 256) {
4254     if (HasAVX2) { // AVX2
4255       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4256       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4257     } else { // AVX
4258       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4259       SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, MVT::v8i32),
4260                                 Vec, DAG.getConstant(0, MVT::i32), DAG, dl);
4261       Vec = Insert128BitVector(InsV, Vec,
4262                     DAG.getConstant(4 /* NumElems/2 */, MVT::i32), DAG, dl);
4263     }
4264   } else {
4265     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4266   }
4267
4268   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4269 }
4270
4271 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4272 /// that point to V2 points to its first element.
4273 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4274   EVT VT = SVOp->getValueType(0);
4275   unsigned NumElems = VT.getVectorNumElements();
4276
4277   bool Changed = false;
4278   SmallVector<int, 8> MaskVec;
4279   SVOp->getMask(MaskVec);
4280
4281   for (unsigned i = 0; i != NumElems; ++i) {
4282     if (MaskVec[i] > (int)NumElems) {
4283       MaskVec[i] = NumElems;
4284       Changed = true;
4285     }
4286   }
4287   if (Changed)
4288     return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
4289                                 SVOp->getOperand(1), &MaskVec[0]);
4290   return SDValue(SVOp, 0);
4291 }
4292
4293 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4294 /// operation of specified width.
4295 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4296                        SDValue V2) {
4297   unsigned NumElems = VT.getVectorNumElements();
4298   SmallVector<int, 8> Mask;
4299   Mask.push_back(NumElems);
4300   for (unsigned i = 1; i != NumElems; ++i)
4301     Mask.push_back(i);
4302   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4303 }
4304
4305 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4306 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4307                           SDValue V2) {
4308   unsigned NumElems = VT.getVectorNumElements();
4309   SmallVector<int, 8> Mask;
4310   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4311     Mask.push_back(i);
4312     Mask.push_back(i + NumElems);
4313   }
4314   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4315 }
4316
4317 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4318 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4319                           SDValue V2) {
4320   unsigned NumElems = VT.getVectorNumElements();
4321   unsigned Half = NumElems/2;
4322   SmallVector<int, 8> Mask;
4323   for (unsigned i = 0; i != Half; ++i) {
4324     Mask.push_back(i + Half);
4325     Mask.push_back(i + NumElems + Half);
4326   }
4327   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4328 }
4329
4330 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4331 // a generic shuffle instruction because the target has no such instructions.
4332 // Generate shuffles which repeat i16 and i8 several times until they can be
4333 // represented by v4f32 and then be manipulated by target suported shuffles.
4334 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4335   EVT VT = V.getValueType();
4336   int NumElems = VT.getVectorNumElements();
4337   DebugLoc dl = V.getDebugLoc();
4338
4339   while (NumElems > 4) {
4340     if (EltNo < NumElems/2) {
4341       V = getUnpackl(DAG, dl, VT, V, V);
4342     } else {
4343       V = getUnpackh(DAG, dl, VT, V, V);
4344       EltNo -= NumElems/2;
4345     }
4346     NumElems >>= 1;
4347   }
4348   return V;
4349 }
4350
4351 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4352 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4353   EVT VT = V.getValueType();
4354   DebugLoc dl = V.getDebugLoc();
4355   assert((VT.getSizeInBits() == 128 || VT.getSizeInBits() == 256)
4356          && "Vector size not supported");
4357
4358   if (VT.getSizeInBits() == 128) {
4359     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4360     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4361     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4362                              &SplatMask[0]);
4363   } else {
4364     // To use VPERMILPS to splat scalars, the second half of indicies must
4365     // refer to the higher part, which is a duplication of the lower one,
4366     // because VPERMILPS can only handle in-lane permutations.
4367     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4368                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4369
4370     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4371     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4372                              &SplatMask[0]);
4373   }
4374
4375   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4376 }
4377
4378 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4379 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4380   EVT SrcVT = SV->getValueType(0);
4381   SDValue V1 = SV->getOperand(0);
4382   DebugLoc dl = SV->getDebugLoc();
4383
4384   int EltNo = SV->getSplatIndex();
4385   int NumElems = SrcVT.getVectorNumElements();
4386   unsigned Size = SrcVT.getSizeInBits();
4387
4388   assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4389           "Unknown how to promote splat for type");
4390
4391   // Extract the 128-bit part containing the splat element and update
4392   // the splat element index when it refers to the higher register.
4393   if (Size == 256) {
4394     unsigned Idx = (EltNo > NumElems/2) ? NumElems/2 : 0;
4395     V1 = Extract128BitVector(V1, DAG.getConstant(Idx, MVT::i32), DAG, dl);
4396     if (Idx > 0)
4397       EltNo -= NumElems/2;
4398   }
4399
4400   // All i16 and i8 vector types can't be used directly by a generic shuffle
4401   // instruction because the target has no such instruction. Generate shuffles
4402   // which repeat i16 and i8 several times until they fit in i32, and then can
4403   // be manipulated by target suported shuffles.
4404   EVT EltVT = SrcVT.getVectorElementType();
4405   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4406     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4407
4408   // Recreate the 256-bit vector and place the same 128-bit vector
4409   // into the low and high part. This is necessary because we want
4410   // to use VPERM* to shuffle the vectors
4411   if (Size == 256) {
4412     SDValue InsV = Insert128BitVector(DAG.getUNDEF(SrcVT), V1,
4413                          DAG.getConstant(0, MVT::i32), DAG, dl);
4414     V1 = Insert128BitVector(InsV, V1,
4415                DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
4416   }
4417
4418   return getLegalSplat(DAG, V1, EltNo);
4419 }
4420
4421 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4422 /// vector of zero or undef vector.  This produces a shuffle where the low
4423 /// element of V2 is swizzled into the zero/undef vector, landing at element
4424 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4425 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4426                                            bool isZero, bool HasXMMInt,
4427                                            SelectionDAG &DAG) {
4428   EVT VT = V2.getValueType();
4429   SDValue V1 = isZero
4430     ? getZeroVector(VT, HasXMMInt, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4431   unsigned NumElems = VT.getVectorNumElements();
4432   SmallVector<int, 16> MaskVec;
4433   for (unsigned i = 0; i != NumElems; ++i)
4434     // If this is the insertion idx, put the low elt of V2 here.
4435     MaskVec.push_back(i == Idx ? NumElems : i);
4436   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4437 }
4438
4439 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4440 /// element of the result of the vector shuffle.
4441 static SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
4442                                    unsigned Depth) {
4443   if (Depth == 6)
4444     return SDValue();  // Limit search depth.
4445
4446   SDValue V = SDValue(N, 0);
4447   EVT VT = V.getValueType();
4448   unsigned Opcode = V.getOpcode();
4449
4450   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4451   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4452     Index = SV->getMaskElt(Index);
4453
4454     if (Index < 0)
4455       return DAG.getUNDEF(VT.getVectorElementType());
4456
4457     int NumElems = VT.getVectorNumElements();
4458     SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
4459     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
4460   }
4461
4462   // Recurse into target specific vector shuffles to find scalars.
4463   if (isTargetShuffle(Opcode)) {
4464     int NumElems = VT.getVectorNumElements();
4465     SmallVector<unsigned, 16> ShuffleMask;
4466     SDValue ImmN;
4467
4468     switch(Opcode) {
4469     case X86ISD::SHUFPS:
4470     case X86ISD::SHUFPD:
4471       ImmN = N->getOperand(N->getNumOperands()-1);
4472       DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4473                       ShuffleMask);
4474       break;
4475     case X86ISD::UNPCKH:
4476       DecodeUNPCKHMask(VT, ShuffleMask);
4477       break;
4478     case X86ISD::UNPCKL:
4479       DecodeUNPCKLMask(VT, ShuffleMask);
4480       break;
4481     case X86ISD::MOVHLPS:
4482       DecodeMOVHLPSMask(NumElems, ShuffleMask);
4483       break;
4484     case X86ISD::MOVLHPS:
4485       DecodeMOVLHPSMask(NumElems, ShuffleMask);
4486       break;
4487     case X86ISD::PSHUFD:
4488       ImmN = N->getOperand(N->getNumOperands()-1);
4489       DecodePSHUFMask(NumElems,
4490                       cast<ConstantSDNode>(ImmN)->getZExtValue(),
4491                       ShuffleMask);
4492       break;
4493     case X86ISD::PSHUFHW:
4494       ImmN = N->getOperand(N->getNumOperands()-1);
4495       DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4496                         ShuffleMask);
4497       break;
4498     case X86ISD::PSHUFLW:
4499       ImmN = N->getOperand(N->getNumOperands()-1);
4500       DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4501                         ShuffleMask);
4502       break;
4503     case X86ISD::MOVSS:
4504     case X86ISD::MOVSD: {
4505       // The index 0 always comes from the first element of the second source,
4506       // this is why MOVSS and MOVSD are used in the first place. The other
4507       // elements come from the other positions of the first source vector.
4508       unsigned OpNum = (Index == 0) ? 1 : 0;
4509       return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
4510                                  Depth+1);
4511     }
4512     case X86ISD::VPERMILP:
4513       ImmN = N->getOperand(N->getNumOperands()-1);
4514       DecodeVPERMILPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4515                         ShuffleMask);
4516       break;
4517     case X86ISD::VPERM2X128:
4518       ImmN = N->getOperand(N->getNumOperands()-1);
4519       DecodeVPERM2F128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4520                            ShuffleMask);
4521       break;
4522     case X86ISD::MOVDDUP:
4523     case X86ISD::MOVLHPD:
4524     case X86ISD::MOVLPD:
4525     case X86ISD::MOVLPS:
4526     case X86ISD::MOVSHDUP:
4527     case X86ISD::MOVSLDUP:
4528     case X86ISD::PALIGN:
4529       return SDValue(); // Not yet implemented.
4530     default:
4531       assert(0 && "unknown target shuffle node");
4532       return SDValue();
4533     }
4534
4535     Index = ShuffleMask[Index];
4536     if (Index < 0)
4537       return DAG.getUNDEF(VT.getVectorElementType());
4538
4539     SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
4540     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
4541                                Depth+1);
4542   }
4543
4544   // Actual nodes that may contain scalar elements
4545   if (Opcode == ISD::BITCAST) {
4546     V = V.getOperand(0);
4547     EVT SrcVT = V.getValueType();
4548     unsigned NumElems = VT.getVectorNumElements();
4549
4550     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4551       return SDValue();
4552   }
4553
4554   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4555     return (Index == 0) ? V.getOperand(0)
4556                           : DAG.getUNDEF(VT.getVectorElementType());
4557
4558   if (V.getOpcode() == ISD::BUILD_VECTOR)
4559     return V.getOperand(Index);
4560
4561   return SDValue();
4562 }
4563
4564 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4565 /// shuffle operation which come from a consecutively from a zero. The
4566 /// search can start in two different directions, from left or right.
4567 static
4568 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
4569                                   bool ZerosFromLeft, SelectionDAG &DAG) {
4570   int i = 0;
4571
4572   while (i < NumElems) {
4573     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4574     SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
4575     if (!(Elt.getNode() &&
4576          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4577       break;
4578     ++i;
4579   }
4580
4581   return i;
4582 }
4583
4584 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
4585 /// MaskE correspond consecutively to elements from one of the vector operands,
4586 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4587 static
4588 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
4589                               int OpIdx, int NumElems, unsigned &OpNum) {
4590   bool SeenV1 = false;
4591   bool SeenV2 = false;
4592
4593   for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
4594     int Idx = SVOp->getMaskElt(i);
4595     // Ignore undef indicies
4596     if (Idx < 0)
4597       continue;
4598
4599     if (Idx < NumElems)
4600       SeenV1 = true;
4601     else
4602       SeenV2 = true;
4603
4604     // Only accept consecutive elements from the same vector
4605     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4606       return false;
4607   }
4608
4609   OpNum = SeenV1 ? 0 : 1;
4610   return true;
4611 }
4612
4613 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4614 /// logical left shift of a vector.
4615 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4616                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4617   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4618   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4619               false /* check zeros from right */, DAG);
4620   unsigned OpSrc;
4621
4622   if (!NumZeros)
4623     return false;
4624
4625   // Considering the elements in the mask that are not consecutive zeros,
4626   // check if they consecutively come from only one of the source vectors.
4627   //
4628   //               V1 = {X, A, B, C}     0
4629   //                         \  \  \    /
4630   //   vector_shuffle V1, V2 <1, 2, 3, X>
4631   //
4632   if (!isShuffleMaskConsecutive(SVOp,
4633             0,                   // Mask Start Index
4634             NumElems-NumZeros-1, // Mask End Index
4635             NumZeros,            // Where to start looking in the src vector
4636             NumElems,            // Number of elements in vector
4637             OpSrc))              // Which source operand ?
4638     return false;
4639
4640   isLeft = false;
4641   ShAmt = NumZeros;
4642   ShVal = SVOp->getOperand(OpSrc);
4643   return true;
4644 }
4645
4646 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4647 /// logical left shift of a vector.
4648 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4649                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4650   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4651   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4652               true /* check zeros from left */, DAG);
4653   unsigned OpSrc;
4654
4655   if (!NumZeros)
4656     return false;
4657
4658   // Considering the elements in the mask that are not consecutive zeros,
4659   // check if they consecutively come from only one of the source vectors.
4660   //
4661   //                           0    { A, B, X, X } = V2
4662   //                          / \    /  /
4663   //   vector_shuffle V1, V2 <X, X, 4, 5>
4664   //
4665   if (!isShuffleMaskConsecutive(SVOp,
4666             NumZeros,     // Mask Start Index
4667             NumElems-1,   // Mask End Index
4668             0,            // Where to start looking in the src vector
4669             NumElems,     // Number of elements in vector
4670             OpSrc))       // Which source operand ?
4671     return false;
4672
4673   isLeft = true;
4674   ShAmt = NumZeros;
4675   ShVal = SVOp->getOperand(OpSrc);
4676   return true;
4677 }
4678
4679 /// isVectorShift - Returns true if the shuffle can be implemented as a
4680 /// logical left or right shift of a vector.
4681 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4682                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4683   // Although the logic below support any bitwidth size, there are no
4684   // shift instructions which handle more than 128-bit vectors.
4685   if (SVOp->getValueType(0).getSizeInBits() > 128)
4686     return false;
4687
4688   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4689       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4690     return true;
4691
4692   return false;
4693 }
4694
4695 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4696 ///
4697 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4698                                        unsigned NumNonZero, unsigned NumZero,
4699                                        SelectionDAG &DAG,
4700                                        const TargetLowering &TLI) {
4701   if (NumNonZero > 8)
4702     return SDValue();
4703
4704   DebugLoc dl = Op.getDebugLoc();
4705   SDValue V(0, 0);
4706   bool First = true;
4707   for (unsigned i = 0; i < 16; ++i) {
4708     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4709     if (ThisIsNonZero && First) {
4710       if (NumZero)
4711         V = getZeroVector(MVT::v8i16, true, DAG, dl);
4712       else
4713         V = DAG.getUNDEF(MVT::v8i16);
4714       First = false;
4715     }
4716
4717     if ((i & 1) != 0) {
4718       SDValue ThisElt(0, 0), LastElt(0, 0);
4719       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4720       if (LastIsNonZero) {
4721         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4722                               MVT::i16, Op.getOperand(i-1));
4723       }
4724       if (ThisIsNonZero) {
4725         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4726         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4727                               ThisElt, DAG.getConstant(8, MVT::i8));
4728         if (LastIsNonZero)
4729           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4730       } else
4731         ThisElt = LastElt;
4732
4733       if (ThisElt.getNode())
4734         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4735                         DAG.getIntPtrConstant(i/2));
4736     }
4737   }
4738
4739   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4740 }
4741
4742 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4743 ///
4744 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4745                                      unsigned NumNonZero, unsigned NumZero,
4746                                      SelectionDAG &DAG,
4747                                      const TargetLowering &TLI) {
4748   if (NumNonZero > 4)
4749     return SDValue();
4750
4751   DebugLoc dl = Op.getDebugLoc();
4752   SDValue V(0, 0);
4753   bool First = true;
4754   for (unsigned i = 0; i < 8; ++i) {
4755     bool isNonZero = (NonZeros & (1 << i)) != 0;
4756     if (isNonZero) {
4757       if (First) {
4758         if (NumZero)
4759           V = getZeroVector(MVT::v8i16, true, DAG, dl);
4760         else
4761           V = DAG.getUNDEF(MVT::v8i16);
4762         First = false;
4763       }
4764       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4765                       MVT::v8i16, V, Op.getOperand(i),
4766                       DAG.getIntPtrConstant(i));
4767     }
4768   }
4769
4770   return V;
4771 }
4772
4773 /// getVShift - Return a vector logical shift node.
4774 ///
4775 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4776                          unsigned NumBits, SelectionDAG &DAG,
4777                          const TargetLowering &TLI, DebugLoc dl) {
4778   assert(VT.getSizeInBits() == 128 && "Unknown type for VShift");
4779   EVT ShVT = MVT::v2i64;
4780   unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
4781   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4782   return DAG.getNode(ISD::BITCAST, dl, VT,
4783                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4784                              DAG.getConstant(NumBits,
4785                                   TLI.getShiftAmountTy(SrcOp.getValueType()))));
4786 }
4787
4788 SDValue
4789 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4790                                           SelectionDAG &DAG) const {
4791
4792   // Check if the scalar load can be widened into a vector load. And if
4793   // the address is "base + cst" see if the cst can be "absorbed" into
4794   // the shuffle mask.
4795   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4796     SDValue Ptr = LD->getBasePtr();
4797     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4798       return SDValue();
4799     EVT PVT = LD->getValueType(0);
4800     if (PVT != MVT::i32 && PVT != MVT::f32)
4801       return SDValue();
4802
4803     int FI = -1;
4804     int64_t Offset = 0;
4805     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4806       FI = FINode->getIndex();
4807       Offset = 0;
4808     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4809                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4810       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4811       Offset = Ptr.getConstantOperandVal(1);
4812       Ptr = Ptr.getOperand(0);
4813     } else {
4814       return SDValue();
4815     }
4816
4817     // FIXME: 256-bit vector instructions don't require a strict alignment,
4818     // improve this code to support it better.
4819     unsigned RequiredAlign = VT.getSizeInBits()/8;
4820     SDValue Chain = LD->getChain();
4821     // Make sure the stack object alignment is at least 16 or 32.
4822     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4823     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4824       if (MFI->isFixedObjectIndex(FI)) {
4825         // Can't change the alignment. FIXME: It's possible to compute
4826         // the exact stack offset and reference FI + adjust offset instead.
4827         // If someone *really* cares about this. That's the way to implement it.
4828         return SDValue();
4829       } else {
4830         MFI->setObjectAlignment(FI, RequiredAlign);
4831       }
4832     }
4833
4834     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4835     // Ptr + (Offset & ~15).
4836     if (Offset < 0)
4837       return SDValue();
4838     if ((Offset % RequiredAlign) & 3)
4839       return SDValue();
4840     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4841     if (StartOffset)
4842       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4843                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4844
4845     int EltNo = (Offset - StartOffset) >> 2;
4846     int NumElems = VT.getVectorNumElements();
4847
4848     EVT CanonVT = VT.getSizeInBits() == 128 ? MVT::v4i32 : MVT::v8i32;
4849     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4850     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4851                              LD->getPointerInfo().getWithOffset(StartOffset),
4852                              false, false, false, 0);
4853
4854     // Canonicalize it to a v4i32 or v8i32 shuffle.
4855     SmallVector<int, 8> Mask;
4856     for (int i = 0; i < NumElems; ++i)
4857       Mask.push_back(EltNo);
4858
4859     V1 = DAG.getNode(ISD::BITCAST, dl, CanonVT, V1);
4860     return DAG.getNode(ISD::BITCAST, dl, NVT,
4861                        DAG.getVectorShuffle(CanonVT, dl, V1,
4862                                             DAG.getUNDEF(CanonVT),&Mask[0]));
4863   }
4864
4865   return SDValue();
4866 }
4867
4868 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4869 /// vector of type 'VT', see if the elements can be replaced by a single large
4870 /// load which has the same value as a build_vector whose operands are 'elts'.
4871 ///
4872 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4873 ///
4874 /// FIXME: we'd also like to handle the case where the last elements are zero
4875 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4876 /// There's even a handy isZeroNode for that purpose.
4877 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4878                                         DebugLoc &DL, SelectionDAG &DAG) {
4879   EVT EltVT = VT.getVectorElementType();
4880   unsigned NumElems = Elts.size();
4881
4882   LoadSDNode *LDBase = NULL;
4883   unsigned LastLoadedElt = -1U;
4884
4885   // For each element in the initializer, see if we've found a load or an undef.
4886   // If we don't find an initial load element, or later load elements are
4887   // non-consecutive, bail out.
4888   for (unsigned i = 0; i < NumElems; ++i) {
4889     SDValue Elt = Elts[i];
4890
4891     if (!Elt.getNode() ||
4892         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4893       return SDValue();
4894     if (!LDBase) {
4895       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4896         return SDValue();
4897       LDBase = cast<LoadSDNode>(Elt.getNode());
4898       LastLoadedElt = i;
4899       continue;
4900     }
4901     if (Elt.getOpcode() == ISD::UNDEF)
4902       continue;
4903
4904     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4905     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4906       return SDValue();
4907     LastLoadedElt = i;
4908   }
4909
4910   // If we have found an entire vector of loads and undefs, then return a large
4911   // load of the entire vector width starting at the base pointer.  If we found
4912   // consecutive loads for the low half, generate a vzext_load node.
4913   if (LastLoadedElt == NumElems - 1) {
4914     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4915       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4916                          LDBase->getPointerInfo(),
4917                          LDBase->isVolatile(), LDBase->isNonTemporal(),
4918                          LDBase->isInvariant(), 0);
4919     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4920                        LDBase->getPointerInfo(),
4921                        LDBase->isVolatile(), LDBase->isNonTemporal(),
4922                        LDBase->isInvariant(), LDBase->getAlignment());
4923   } else if (NumElems == 4 && LastLoadedElt == 1 &&
4924              DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4925     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4926     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4927     SDValue ResNode =
4928         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
4929                                 LDBase->getPointerInfo(),
4930                                 LDBase->getAlignment(),
4931                                 false/*isVolatile*/, true/*ReadMem*/,
4932                                 false/*WriteMem*/);
4933     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4934   }
4935   return SDValue();
4936 }
4937
4938 /// isVectorBroadcast - Check if the node chain is suitable to be xformed to
4939 /// a vbroadcast node. We support two patterns:
4940 /// 1. A splat BUILD_VECTOR which uses a single scalar load.
4941 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
4942 /// a scalar load.
4943 /// The scalar load node is returned when a pattern is found,
4944 /// or SDValue() otherwise.
4945 static SDValue isVectorBroadcast(SDValue &Op, bool hasAVX2) {
4946   EVT VT = Op.getValueType();
4947   SDValue V = Op;
4948
4949   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
4950     V = V.getOperand(0);
4951
4952   //A suspected load to be broadcasted.
4953   SDValue Ld;
4954
4955   switch (V.getOpcode()) {
4956     default:
4957       // Unknown pattern found.
4958       return SDValue();
4959
4960     case ISD::BUILD_VECTOR: {
4961       // The BUILD_VECTOR node must be a splat.
4962       if (!isSplatVector(V.getNode()))
4963         return SDValue();
4964
4965       Ld = V.getOperand(0);
4966
4967       // The suspected load node has several users. Make sure that all
4968       // of its users are from the BUILD_VECTOR node.
4969       if (!Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
4970         return SDValue();
4971       break;
4972     }
4973
4974     case ISD::VECTOR_SHUFFLE: {
4975       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4976
4977       // Shuffles must have a splat mask where the first element is
4978       // broadcasted.
4979       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
4980         return SDValue();
4981
4982       SDValue Sc = Op.getOperand(0);
4983       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR)
4984         return SDValue();
4985
4986       Ld = Sc.getOperand(0);
4987
4988       // The scalar_to_vector node and the suspected
4989       // load node must have exactly one user.
4990       if (!Sc.hasOneUse() || !Ld.hasOneUse())
4991         return SDValue();
4992       break;
4993     }
4994   }
4995
4996   // The scalar source must be a normal load.
4997   if (!ISD::isNormalLoad(Ld.getNode()))
4998     return SDValue();
4999
5000   bool Is256 = VT.getSizeInBits() == 256;
5001   bool Is128 = VT.getSizeInBits() == 128;
5002   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5003
5004   if (hasAVX2) {
5005     // VBroadcast to YMM
5006     if (Is256 && (ScalarSize == 8  || ScalarSize == 16 ||
5007                   ScalarSize == 32 || ScalarSize == 64 ))
5008       return Ld;
5009
5010     // VBroadcast to XMM
5011     if (Is128 && (ScalarSize ==  8 || ScalarSize == 32 ||
5012                   ScalarSize == 16 || ScalarSize == 64 ))
5013       return Ld;
5014   }
5015
5016   // VBroadcast to YMM
5017   if (Is256 && (ScalarSize == 32 || ScalarSize == 64))
5018     return Ld;
5019
5020   // VBroadcast to XMM
5021   if (Is128 && (ScalarSize == 32))
5022     return Ld;
5023
5024
5025   // Unsupported broadcast.
5026   return SDValue();
5027 }
5028
5029 SDValue
5030 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5031   DebugLoc dl = Op.getDebugLoc();
5032
5033   EVT VT = Op.getValueType();
5034   EVT ExtVT = VT.getVectorElementType();
5035   unsigned NumElems = Op.getNumOperands();
5036
5037   // Vectors containing all zeros can be matched by pxor and xorps later
5038   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5039     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5040     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5041     if (Op.getValueType() == MVT::v4i32 ||
5042         Op.getValueType() == MVT::v8i32)
5043       return Op;
5044
5045     return getZeroVector(Op.getValueType(), Subtarget->hasXMMInt(), DAG, dl);
5046   }
5047
5048   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5049   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5050   // vpcmpeqd on 256-bit vectors.
5051   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5052     if (Op.getValueType() == MVT::v4i32 ||
5053         (Op.getValueType() == MVT::v8i32 && Subtarget->hasAVX2()))
5054       return Op;
5055
5056     return getOnesVector(Op.getValueType(), Subtarget->hasAVX2(), DAG, dl);
5057   }
5058
5059   SDValue LD = isVectorBroadcast(Op, Subtarget->hasAVX2());
5060   if (Subtarget->hasAVX() && LD.getNode())
5061       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, LD);
5062
5063   unsigned EVTBits = ExtVT.getSizeInBits();
5064
5065   unsigned NumZero  = 0;
5066   unsigned NumNonZero = 0;
5067   unsigned NonZeros = 0;
5068   bool IsAllConstants = true;
5069   SmallSet<SDValue, 8> Values;
5070   for (unsigned i = 0; i < NumElems; ++i) {
5071     SDValue Elt = Op.getOperand(i);
5072     if (Elt.getOpcode() == ISD::UNDEF)
5073       continue;
5074     Values.insert(Elt);
5075     if (Elt.getOpcode() != ISD::Constant &&
5076         Elt.getOpcode() != ISD::ConstantFP)
5077       IsAllConstants = false;
5078     if (X86::isZeroNode(Elt))
5079       NumZero++;
5080     else {
5081       NonZeros |= (1 << i);
5082       NumNonZero++;
5083     }
5084   }
5085
5086   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5087   if (NumNonZero == 0)
5088     return DAG.getUNDEF(VT);
5089
5090   // Special case for single non-zero, non-undef, element.
5091   if (NumNonZero == 1) {
5092     unsigned Idx = CountTrailingZeros_32(NonZeros);
5093     SDValue Item = Op.getOperand(Idx);
5094
5095     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5096     // the value are obviously zero, truncate the value to i32 and do the
5097     // insertion that way.  Only do this if the value is non-constant or if the
5098     // value is a constant being inserted into element 0.  It is cheaper to do
5099     // a constant pool load than it is to do a movd + shuffle.
5100     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5101         (!IsAllConstants || Idx == 0)) {
5102       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5103         // Handle SSE only.
5104         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5105         EVT VecVT = MVT::v4i32;
5106         unsigned VecElts = 4;
5107
5108         // Truncate the value (which may itself be a constant) to i32, and
5109         // convert it to a vector with movd (S2V+shuffle to zero extend).
5110         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5111         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5112         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
5113                                            Subtarget->hasXMMInt(), DAG);
5114
5115         // Now we have our 32-bit value zero extended in the low element of
5116         // a vector.  If Idx != 0, swizzle it into place.
5117         if (Idx != 0) {
5118           SmallVector<int, 4> Mask;
5119           Mask.push_back(Idx);
5120           for (unsigned i = 1; i != VecElts; ++i)
5121             Mask.push_back(i);
5122           Item = DAG.getVectorShuffle(VecVT, dl, Item,
5123                                       DAG.getUNDEF(Item.getValueType()),
5124                                       &Mask[0]);
5125         }
5126         return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
5127       }
5128     }
5129
5130     // If we have a constant or non-constant insertion into the low element of
5131     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5132     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5133     // depending on what the source datatype is.
5134     if (Idx == 0) {
5135       if (NumZero == 0) {
5136         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5137       } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5138           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5139         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5140         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5141         return getShuffleVectorZeroOrUndef(Item, 0, true,Subtarget->hasXMMInt(),
5142                                            DAG);
5143       } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5144         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5145         unsigned NumBits = VT.getSizeInBits();
5146         assert((NumBits == 128 || NumBits == 256) && 
5147                "Expected an SSE or AVX value type!");
5148         EVT MiddleVT = NumBits == 128 ? MVT::v4i32 : MVT::v8i32;
5149         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
5150         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
5151                                            Subtarget->hasXMMInt(), DAG);
5152         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5153       }
5154     }
5155
5156     // Is it a vector logical left shift?
5157     if (NumElems == 2 && Idx == 1 &&
5158         X86::isZeroNode(Op.getOperand(0)) &&
5159         !X86::isZeroNode(Op.getOperand(1))) {
5160       unsigned NumBits = VT.getSizeInBits();
5161       return getVShift(true, VT,
5162                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5163                                    VT, Op.getOperand(1)),
5164                        NumBits/2, DAG, *this, dl);
5165     }
5166
5167     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5168       return SDValue();
5169
5170     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5171     // is a non-constant being inserted into an element other than the low one,
5172     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5173     // movd/movss) to move this into the low element, then shuffle it into
5174     // place.
5175     if (EVTBits == 32) {
5176       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5177
5178       // Turn it into a shuffle of zero and zero-extended scalar to vector.
5179       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
5180                                          Subtarget->hasXMMInt(), DAG);
5181       SmallVector<int, 8> MaskVec;
5182       for (unsigned i = 0; i < NumElems; i++)
5183         MaskVec.push_back(i == Idx ? 0 : 1);
5184       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5185     }
5186   }
5187
5188   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5189   if (Values.size() == 1) {
5190     if (EVTBits == 32) {
5191       // Instead of a shuffle like this:
5192       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5193       // Check if it's possible to issue this instead.
5194       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5195       unsigned Idx = CountTrailingZeros_32(NonZeros);
5196       SDValue Item = Op.getOperand(Idx);
5197       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5198         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5199     }
5200     return SDValue();
5201   }
5202
5203   // A vector full of immediates; various special cases are already
5204   // handled, so this is best done with a single constant-pool load.
5205   if (IsAllConstants)
5206     return SDValue();
5207
5208   // For AVX-length vectors, build the individual 128-bit pieces and use
5209   // shuffles to put them in place.
5210   if (VT.getSizeInBits() == 256 && !ISD::isBuildVectorAllZeros(Op.getNode())) {
5211     SmallVector<SDValue, 32> V;
5212     for (unsigned i = 0; i < NumElems; ++i)
5213       V.push_back(Op.getOperand(i));
5214
5215     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5216
5217     // Build both the lower and upper subvector.
5218     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5219     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5220                                 NumElems/2);
5221
5222     // Recreate the wider vector with the lower and upper part.
5223     SDValue Vec = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), Lower,
5224                                 DAG.getConstant(0, MVT::i32), DAG, dl);
5225     return Insert128BitVector(Vec, Upper, DAG.getConstant(NumElems/2, MVT::i32),
5226                               DAG, dl);
5227   }
5228
5229   // Let legalizer expand 2-wide build_vectors.
5230   if (EVTBits == 64) {
5231     if (NumNonZero == 1) {
5232       // One half is zero or undef.
5233       unsigned Idx = CountTrailingZeros_32(NonZeros);
5234       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5235                                  Op.getOperand(Idx));
5236       return getShuffleVectorZeroOrUndef(V2, Idx, true,
5237                                          Subtarget->hasXMMInt(), DAG);
5238     }
5239     return SDValue();
5240   }
5241
5242   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5243   if (EVTBits == 8 && NumElems == 16) {
5244     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5245                                         *this);
5246     if (V.getNode()) return V;
5247   }
5248
5249   if (EVTBits == 16 && NumElems == 8) {
5250     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5251                                       *this);
5252     if (V.getNode()) return V;
5253   }
5254
5255   // If element VT is == 32 bits, turn it into a number of shuffles.
5256   SmallVector<SDValue, 8> V;
5257   V.resize(NumElems);
5258   if (NumElems == 4 && NumZero > 0) {
5259     for (unsigned i = 0; i < 4; ++i) {
5260       bool isZero = !(NonZeros & (1 << i));
5261       if (isZero)
5262         V[i] = getZeroVector(VT, Subtarget->hasXMMInt(), DAG, dl);
5263       else
5264         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5265     }
5266
5267     for (unsigned i = 0; i < 2; ++i) {
5268       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5269         default: break;
5270         case 0:
5271           V[i] = V[i*2];  // Must be a zero vector.
5272           break;
5273         case 1:
5274           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5275           break;
5276         case 2:
5277           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5278           break;
5279         case 3:
5280           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5281           break;
5282       }
5283     }
5284
5285     SmallVector<int, 8> MaskVec;
5286     bool Reverse = (NonZeros & 0x3) == 2;
5287     for (unsigned i = 0; i < 2; ++i)
5288       MaskVec.push_back(Reverse ? 1-i : i);
5289     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5290     for (unsigned i = 0; i < 2; ++i)
5291       MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
5292     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5293   }
5294
5295   if (Values.size() > 1 && VT.getSizeInBits() == 128) {
5296     // Check for a build vector of consecutive loads.
5297     for (unsigned i = 0; i < NumElems; ++i)
5298       V[i] = Op.getOperand(i);
5299
5300     // Check for elements which are consecutive loads.
5301     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5302     if (LD.getNode())
5303       return LD;
5304
5305     // For SSE 4.1, use insertps to put the high elements into the low element.
5306     if (getSubtarget()->hasSSE41orAVX()) {
5307       SDValue Result;
5308       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5309         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5310       else
5311         Result = DAG.getUNDEF(VT);
5312
5313       for (unsigned i = 1; i < NumElems; ++i) {
5314         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5315         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5316                              Op.getOperand(i), DAG.getIntPtrConstant(i));
5317       }
5318       return Result;
5319     }
5320
5321     // Otherwise, expand into a number of unpckl*, start by extending each of
5322     // our (non-undef) elements to the full vector width with the element in the
5323     // bottom slot of the vector (which generates no code for SSE).
5324     for (unsigned i = 0; i < NumElems; ++i) {
5325       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5326         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5327       else
5328         V[i] = DAG.getUNDEF(VT);
5329     }
5330
5331     // Next, we iteratively mix elements, e.g. for v4f32:
5332     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5333     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5334     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5335     unsigned EltStride = NumElems >> 1;
5336     while (EltStride != 0) {
5337       for (unsigned i = 0; i < EltStride; ++i) {
5338         // If V[i+EltStride] is undef and this is the first round of mixing,
5339         // then it is safe to just drop this shuffle: V[i] is already in the
5340         // right place, the one element (since it's the first round) being
5341         // inserted as undef can be dropped.  This isn't safe for successive
5342         // rounds because they will permute elements within both vectors.
5343         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5344             EltStride == NumElems/2)
5345           continue;
5346
5347         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5348       }
5349       EltStride >>= 1;
5350     }
5351     return V[0];
5352   }
5353   return SDValue();
5354 }
5355
5356 // LowerMMXCONCAT_VECTORS - We support concatenate two MMX registers and place
5357 // them in a MMX register.  This is better than doing a stack convert.
5358 static SDValue LowerMMXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5359   DebugLoc dl = Op.getDebugLoc();
5360   EVT ResVT = Op.getValueType();
5361
5362   assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
5363          ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
5364   int Mask[2];
5365   SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
5366   SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5367   InVec = Op.getOperand(1);
5368   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5369     unsigned NumElts = ResVT.getVectorNumElements();
5370     VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5371     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
5372                        InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
5373   } else {
5374     InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
5375     SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5376     Mask[0] = 0; Mask[1] = 2;
5377     VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
5378   }
5379   return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5380 }
5381
5382 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5383 // to create 256-bit vectors from two other 128-bit ones.
5384 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5385   DebugLoc dl = Op.getDebugLoc();
5386   EVT ResVT = Op.getValueType();
5387
5388   assert(ResVT.getSizeInBits() == 256 && "Value type must be 256-bit wide");
5389
5390   SDValue V1 = Op.getOperand(0);
5391   SDValue V2 = Op.getOperand(1);
5392   unsigned NumElems = ResVT.getVectorNumElements();
5393
5394   SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, ResVT), V1,
5395                                  DAG.getConstant(0, MVT::i32), DAG, dl);
5396   return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32),
5397                             DAG, dl);
5398 }
5399
5400 SDValue
5401 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
5402   EVT ResVT = Op.getValueType();
5403
5404   assert(Op.getNumOperands() == 2);
5405   assert((ResVT.getSizeInBits() == 128 || ResVT.getSizeInBits() == 256) &&
5406          "Unsupported CONCAT_VECTORS for value type");
5407
5408   // We support concatenate two MMX registers and place them in a MMX register.
5409   // This is better than doing a stack convert.
5410   if (ResVT.is128BitVector())
5411     return LowerMMXCONCAT_VECTORS(Op, DAG);
5412
5413   // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5414   // from two other 128-bit ones.
5415   return LowerAVXCONCAT_VECTORS(Op, DAG);
5416 }
5417
5418 // v8i16 shuffles - Prefer shuffles in the following order:
5419 // 1. [all]   pshuflw, pshufhw, optional move
5420 // 2. [ssse3] 1 x pshufb
5421 // 3. [ssse3] 2 x pshufb + 1 x por
5422 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5423 SDValue
5424 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
5425                                             SelectionDAG &DAG) const {
5426   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5427   SDValue V1 = SVOp->getOperand(0);
5428   SDValue V2 = SVOp->getOperand(1);
5429   DebugLoc dl = SVOp->getDebugLoc();
5430   SmallVector<int, 8> MaskVals;
5431
5432   // Determine if more than 1 of the words in each of the low and high quadwords
5433   // of the result come from the same quadword of one of the two inputs.  Undef
5434   // mask values count as coming from any quadword, for better codegen.
5435   unsigned LoQuad[] = { 0, 0, 0, 0 };
5436   unsigned HiQuad[] = { 0, 0, 0, 0 };
5437   BitVector InputQuads(4);
5438   for (unsigned i = 0; i < 8; ++i) {
5439     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5440     int EltIdx = SVOp->getMaskElt(i);
5441     MaskVals.push_back(EltIdx);
5442     if (EltIdx < 0) {
5443       ++Quad[0];
5444       ++Quad[1];
5445       ++Quad[2];
5446       ++Quad[3];
5447       continue;
5448     }
5449     ++Quad[EltIdx / 4];
5450     InputQuads.set(EltIdx / 4);
5451   }
5452
5453   int BestLoQuad = -1;
5454   unsigned MaxQuad = 1;
5455   for (unsigned i = 0; i < 4; ++i) {
5456     if (LoQuad[i] > MaxQuad) {
5457       BestLoQuad = i;
5458       MaxQuad = LoQuad[i];
5459     }
5460   }
5461
5462   int BestHiQuad = -1;
5463   MaxQuad = 1;
5464   for (unsigned i = 0; i < 4; ++i) {
5465     if (HiQuad[i] > MaxQuad) {
5466       BestHiQuad = i;
5467       MaxQuad = HiQuad[i];
5468     }
5469   }
5470
5471   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5472   // of the two input vectors, shuffle them into one input vector so only a
5473   // single pshufb instruction is necessary. If There are more than 2 input
5474   // quads, disable the next transformation since it does not help SSSE3.
5475   bool V1Used = InputQuads[0] || InputQuads[1];
5476   bool V2Used = InputQuads[2] || InputQuads[3];
5477   if (Subtarget->hasSSSE3orAVX()) {
5478     if (InputQuads.count() == 2 && V1Used && V2Used) {
5479       BestLoQuad = InputQuads.find_first();
5480       BestHiQuad = InputQuads.find_next(BestLoQuad);
5481     }
5482     if (InputQuads.count() > 2) {
5483       BestLoQuad = -1;
5484       BestHiQuad = -1;
5485     }
5486   }
5487
5488   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5489   // the shuffle mask.  If a quad is scored as -1, that means that it contains
5490   // words from all 4 input quadwords.
5491   SDValue NewV;
5492   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5493     SmallVector<int, 8> MaskV;
5494     MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
5495     MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
5496     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5497                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5498                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5499     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5500
5501     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5502     // source words for the shuffle, to aid later transformations.
5503     bool AllWordsInNewV = true;
5504     bool InOrder[2] = { true, true };
5505     for (unsigned i = 0; i != 8; ++i) {
5506       int idx = MaskVals[i];
5507       if (idx != (int)i)
5508         InOrder[i/4] = false;
5509       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5510         continue;
5511       AllWordsInNewV = false;
5512       break;
5513     }
5514
5515     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5516     if (AllWordsInNewV) {
5517       for (int i = 0; i != 8; ++i) {
5518         int idx = MaskVals[i];
5519         if (idx < 0)
5520           continue;
5521         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5522         if ((idx != i) && idx < 4)
5523           pshufhw = false;
5524         if ((idx != i) && idx > 3)
5525           pshuflw = false;
5526       }
5527       V1 = NewV;
5528       V2Used = false;
5529       BestLoQuad = 0;
5530       BestHiQuad = 1;
5531     }
5532
5533     // If we've eliminated the use of V2, and the new mask is a pshuflw or
5534     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
5535     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5536       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5537       unsigned TargetMask = 0;
5538       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5539                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5540       TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
5541                              X86::getShufflePSHUFLWImmediate(NewV.getNode());
5542       V1 = NewV.getOperand(0);
5543       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5544     }
5545   }
5546
5547   // If we have SSSE3, and all words of the result are from 1 input vector,
5548   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5549   // is present, fall back to case 4.
5550   if (Subtarget->hasSSSE3orAVX()) {
5551     SmallVector<SDValue,16> pshufbMask;
5552
5553     // If we have elements from both input vectors, set the high bit of the
5554     // shuffle mask element to zero out elements that come from V2 in the V1
5555     // mask, and elements that come from V1 in the V2 mask, so that the two
5556     // results can be OR'd together.
5557     bool TwoInputs = V1Used && V2Used;
5558     for (unsigned i = 0; i != 8; ++i) {
5559       int EltIdx = MaskVals[i] * 2;
5560       if (TwoInputs && (EltIdx >= 16)) {
5561         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5562         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5563         continue;
5564       }
5565       pshufbMask.push_back(DAG.getConstant(EltIdx,   MVT::i8));
5566       pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
5567     }
5568     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5569     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5570                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5571                                  MVT::v16i8, &pshufbMask[0], 16));
5572     if (!TwoInputs)
5573       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5574
5575     // Calculate the shuffle mask for the second input, shuffle it, and
5576     // OR it with the first shuffled input.
5577     pshufbMask.clear();
5578     for (unsigned i = 0; i != 8; ++i) {
5579       int EltIdx = MaskVals[i] * 2;
5580       if (EltIdx < 16) {
5581         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5582         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5583         continue;
5584       }
5585       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5586       pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
5587     }
5588     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5589     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5590                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5591                                  MVT::v16i8, &pshufbMask[0], 16));
5592     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5593     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5594   }
5595
5596   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5597   // and update MaskVals with new element order.
5598   BitVector InOrder(8);
5599   if (BestLoQuad >= 0) {
5600     SmallVector<int, 8> MaskV;
5601     for (int i = 0; i != 4; ++i) {
5602       int idx = MaskVals[i];
5603       if (idx < 0) {
5604         MaskV.push_back(-1);
5605         InOrder.set(i);
5606       } else if ((idx / 4) == BestLoQuad) {
5607         MaskV.push_back(idx & 3);
5608         InOrder.set(i);
5609       } else {
5610         MaskV.push_back(-1);
5611       }
5612     }
5613     for (unsigned i = 4; i != 8; ++i)
5614       MaskV.push_back(i);
5615     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5616                                 &MaskV[0]);
5617
5618     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3orAVX())
5619       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5620                                NewV.getOperand(0),
5621                                X86::getShufflePSHUFLWImmediate(NewV.getNode()),
5622                                DAG);
5623   }
5624
5625   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5626   // and update MaskVals with the new element order.
5627   if (BestHiQuad >= 0) {
5628     SmallVector<int, 8> MaskV;
5629     for (unsigned i = 0; i != 4; ++i)
5630       MaskV.push_back(i);
5631     for (unsigned i = 4; i != 8; ++i) {
5632       int idx = MaskVals[i];
5633       if (idx < 0) {
5634         MaskV.push_back(-1);
5635         InOrder.set(i);
5636       } else if ((idx / 4) == BestHiQuad) {
5637         MaskV.push_back((idx & 3) + 4);
5638         InOrder.set(i);
5639       } else {
5640         MaskV.push_back(-1);
5641       }
5642     }
5643     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5644                                 &MaskV[0]);
5645
5646     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3orAVX())
5647       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5648                               NewV.getOperand(0),
5649                               X86::getShufflePSHUFHWImmediate(NewV.getNode()),
5650                               DAG);
5651   }
5652
5653   // In case BestHi & BestLo were both -1, which means each quadword has a word
5654   // from each of the four input quadwords, calculate the InOrder bitvector now
5655   // before falling through to the insert/extract cleanup.
5656   if (BestLoQuad == -1 && BestHiQuad == -1) {
5657     NewV = V1;
5658     for (int i = 0; i != 8; ++i)
5659       if (MaskVals[i] < 0 || MaskVals[i] == i)
5660         InOrder.set(i);
5661   }
5662
5663   // The other elements are put in the right place using pextrw and pinsrw.
5664   for (unsigned i = 0; i != 8; ++i) {
5665     if (InOrder[i])
5666       continue;
5667     int EltIdx = MaskVals[i];
5668     if (EltIdx < 0)
5669       continue;
5670     SDValue ExtOp = (EltIdx < 8)
5671     ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5672                   DAG.getIntPtrConstant(EltIdx))
5673     : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5674                   DAG.getIntPtrConstant(EltIdx - 8));
5675     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5676                        DAG.getIntPtrConstant(i));
5677   }
5678   return NewV;
5679 }
5680
5681 // v16i8 shuffles - Prefer shuffles in the following order:
5682 // 1. [ssse3] 1 x pshufb
5683 // 2. [ssse3] 2 x pshufb + 1 x por
5684 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
5685 static
5686 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5687                                  SelectionDAG &DAG,
5688                                  const X86TargetLowering &TLI) {
5689   SDValue V1 = SVOp->getOperand(0);
5690   SDValue V2 = SVOp->getOperand(1);
5691   DebugLoc dl = SVOp->getDebugLoc();
5692   SmallVector<int, 16> MaskVals;
5693   SVOp->getMask(MaskVals);
5694
5695   // If we have SSSE3, case 1 is generated when all result bytes come from
5696   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
5697   // present, fall back to case 3.
5698   // FIXME: kill V2Only once shuffles are canonizalized by getNode.
5699   bool V1Only = true;
5700   bool V2Only = true;
5701   for (unsigned i = 0; i < 16; ++i) {
5702     int EltIdx = MaskVals[i];
5703     if (EltIdx < 0)
5704       continue;
5705     if (EltIdx < 16)
5706       V2Only = false;
5707     else
5708       V1Only = false;
5709   }
5710
5711   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5712   if (TLI.getSubtarget()->hasSSSE3orAVX()) {
5713     SmallVector<SDValue,16> pshufbMask;
5714
5715     // If all result elements are from one input vector, then only translate
5716     // undef mask values to 0x80 (zero out result) in the pshufb mask.
5717     //
5718     // Otherwise, we have elements from both input vectors, and must zero out
5719     // elements that come from V2 in the first mask, and V1 in the second mask
5720     // so that we can OR them together.
5721     bool TwoInputs = !(V1Only || V2Only);
5722     for (unsigned i = 0; i != 16; ++i) {
5723       int EltIdx = MaskVals[i];
5724       if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
5725         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5726         continue;
5727       }
5728       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5729     }
5730     // If all the elements are from V2, assign it to V1 and return after
5731     // building the first pshufb.
5732     if (V2Only)
5733       V1 = V2;
5734     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5735                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5736                                  MVT::v16i8, &pshufbMask[0], 16));
5737     if (!TwoInputs)
5738       return V1;
5739
5740     // Calculate the shuffle mask for the second input, shuffle it, and
5741     // OR it with the first shuffled input.
5742     pshufbMask.clear();
5743     for (unsigned i = 0; i != 16; ++i) {
5744       int EltIdx = MaskVals[i];
5745       if (EltIdx < 16) {
5746         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5747         continue;
5748       }
5749       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5750     }
5751     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5752                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5753                                  MVT::v16i8, &pshufbMask[0], 16));
5754     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5755   }
5756
5757   // No SSSE3 - Calculate in place words and then fix all out of place words
5758   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
5759   // the 16 different words that comprise the two doublequadword input vectors.
5760   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5761   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5762   SDValue NewV = V2Only ? V2 : V1;
5763   for (int i = 0; i != 8; ++i) {
5764     int Elt0 = MaskVals[i*2];
5765     int Elt1 = MaskVals[i*2+1];
5766
5767     // This word of the result is all undef, skip it.
5768     if (Elt0 < 0 && Elt1 < 0)
5769       continue;
5770
5771     // This word of the result is already in the correct place, skip it.
5772     if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
5773       continue;
5774     if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
5775       continue;
5776
5777     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5778     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5779     SDValue InsElt;
5780
5781     // If Elt0 and Elt1 are defined, are consecutive, and can be load
5782     // using a single extract together, load it and store it.
5783     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5784       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5785                            DAG.getIntPtrConstant(Elt1 / 2));
5786       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5787                         DAG.getIntPtrConstant(i));
5788       continue;
5789     }
5790
5791     // If Elt1 is defined, extract it from the appropriate source.  If the
5792     // source byte is not also odd, shift the extracted word left 8 bits
5793     // otherwise clear the bottom 8 bits if we need to do an or.
5794     if (Elt1 >= 0) {
5795       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5796                            DAG.getIntPtrConstant(Elt1 / 2));
5797       if ((Elt1 & 1) == 0)
5798         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5799                              DAG.getConstant(8,
5800                                   TLI.getShiftAmountTy(InsElt.getValueType())));
5801       else if (Elt0 >= 0)
5802         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5803                              DAG.getConstant(0xFF00, MVT::i16));
5804     }
5805     // If Elt0 is defined, extract it from the appropriate source.  If the
5806     // source byte is not also even, shift the extracted word right 8 bits. If
5807     // Elt1 was also defined, OR the extracted values together before
5808     // inserting them in the result.
5809     if (Elt0 >= 0) {
5810       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5811                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5812       if ((Elt0 & 1) != 0)
5813         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5814                               DAG.getConstant(8,
5815                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
5816       else if (Elt1 >= 0)
5817         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5818                              DAG.getConstant(0x00FF, MVT::i16));
5819       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5820                          : InsElt0;
5821     }
5822     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5823                        DAG.getIntPtrConstant(i));
5824   }
5825   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5826 }
5827
5828 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5829 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5830 /// done when every pair / quad of shuffle mask elements point to elements in
5831 /// the right sequence. e.g.
5832 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5833 static
5834 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5835                                  SelectionDAG &DAG, DebugLoc dl) {
5836   EVT VT = SVOp->getValueType(0);
5837   SDValue V1 = SVOp->getOperand(0);
5838   SDValue V2 = SVOp->getOperand(1);
5839   unsigned NumElems = VT.getVectorNumElements();
5840   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
5841   EVT NewVT;
5842   switch (VT.getSimpleVT().SimpleTy) {
5843   default: assert(false && "Unexpected!");
5844   case MVT::v4f32: NewVT = MVT::v2f64; break;
5845   case MVT::v4i32: NewVT = MVT::v2i64; break;
5846   case MVT::v8i16: NewVT = MVT::v4i32; break;
5847   case MVT::v16i8: NewVT = MVT::v4i32; break;
5848   }
5849
5850   int Scale = NumElems / NewWidth;
5851   SmallVector<int, 8> MaskVec;
5852   for (unsigned i = 0; i < NumElems; i += Scale) {
5853     int StartIdx = -1;
5854     for (int j = 0; j < Scale; ++j) {
5855       int EltIdx = SVOp->getMaskElt(i+j);
5856       if (EltIdx < 0)
5857         continue;
5858       if (StartIdx == -1)
5859         StartIdx = EltIdx - (EltIdx % Scale);
5860       if (EltIdx != StartIdx + j)
5861         return SDValue();
5862     }
5863     if (StartIdx == -1)
5864       MaskVec.push_back(-1);
5865     else
5866       MaskVec.push_back(StartIdx / Scale);
5867   }
5868
5869   V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
5870   V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
5871   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5872 }
5873
5874 /// getVZextMovL - Return a zero-extending vector move low node.
5875 ///
5876 static SDValue getVZextMovL(EVT VT, EVT OpVT,
5877                             SDValue SrcOp, SelectionDAG &DAG,
5878                             const X86Subtarget *Subtarget, DebugLoc dl) {
5879   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
5880     LoadSDNode *LD = NULL;
5881     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
5882       LD = dyn_cast<LoadSDNode>(SrcOp);
5883     if (!LD) {
5884       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
5885       // instead.
5886       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
5887       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
5888           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5889           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
5890           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
5891         // PR2108
5892         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
5893         return DAG.getNode(ISD::BITCAST, dl, VT,
5894                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5895                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5896                                                    OpVT,
5897                                                    SrcOp.getOperand(0)
5898                                                           .getOperand(0))));
5899       }
5900     }
5901   }
5902
5903   return DAG.getNode(ISD::BITCAST, dl, VT,
5904                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5905                                  DAG.getNode(ISD::BITCAST, dl,
5906                                              OpVT, SrcOp)));
5907 }
5908
5909 /// areShuffleHalvesWithinDisjointLanes - Check whether each half of a vector
5910 /// shuffle node referes to only one lane in the sources.
5911 static bool areShuffleHalvesWithinDisjointLanes(ShuffleVectorSDNode *SVOp) {
5912   EVT VT = SVOp->getValueType(0);
5913   int NumElems = VT.getVectorNumElements();
5914   int HalfSize = NumElems/2;
5915   SmallVector<int, 16> M;
5916   SVOp->getMask(M);
5917   bool MatchA = false, MatchB = false;
5918
5919   for (int l = 0; l < NumElems*2; l += HalfSize) {
5920     if (isUndefOrInRange(M, 0, HalfSize, l, l+HalfSize)) {
5921       MatchA = true;
5922       break;
5923     }
5924   }
5925
5926   for (int l = 0; l < NumElems*2; l += HalfSize) {
5927     if (isUndefOrInRange(M, HalfSize, HalfSize, l, l+HalfSize)) {
5928       MatchB = true;
5929       break;
5930     }
5931   }
5932
5933   return MatchA && MatchB;
5934 }
5935
5936 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
5937 /// which could not be matched by any known target speficic shuffle
5938 static SDValue
5939 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5940   if (areShuffleHalvesWithinDisjointLanes(SVOp)) {
5941     // If each half of a vector shuffle node referes to only one lane in the
5942     // source vectors, extract each used 128-bit lane and shuffle them using
5943     // 128-bit shuffles. Then, concatenate the results. Otherwise leave
5944     // the work to the legalizer.
5945     DebugLoc dl = SVOp->getDebugLoc();
5946     EVT VT = SVOp->getValueType(0);
5947     int NumElems = VT.getVectorNumElements();
5948     int HalfSize = NumElems/2;
5949
5950     // Extract the reference for each half
5951     int FstVecExtractIdx = 0, SndVecExtractIdx = 0;
5952     int FstVecOpNum = 0, SndVecOpNum = 0;
5953     for (int i = 0; i < HalfSize; ++i) {
5954       int Elt = SVOp->getMaskElt(i);
5955       if (SVOp->getMaskElt(i) < 0)
5956         continue;
5957       FstVecOpNum = Elt/NumElems;
5958       FstVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize;
5959       break;
5960     }
5961     for (int i = HalfSize; i < NumElems; ++i) {
5962       int Elt = SVOp->getMaskElt(i);
5963       if (SVOp->getMaskElt(i) < 0)
5964         continue;
5965       SndVecOpNum = Elt/NumElems;
5966       SndVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize;
5967       break;
5968     }
5969
5970     // Extract the subvectors
5971     SDValue V1 = Extract128BitVector(SVOp->getOperand(FstVecOpNum),
5972                       DAG.getConstant(FstVecExtractIdx, MVT::i32), DAG, dl);
5973     SDValue V2 = Extract128BitVector(SVOp->getOperand(SndVecOpNum),
5974                       DAG.getConstant(SndVecExtractIdx, MVT::i32), DAG, dl);
5975
5976     // Generate 128-bit shuffles
5977     SmallVector<int, 16> MaskV1, MaskV2;
5978     for (int i = 0; i < HalfSize; ++i) {
5979       int Elt = SVOp->getMaskElt(i);
5980       MaskV1.push_back(Elt < 0 ? Elt : Elt % HalfSize);
5981     }
5982     for (int i = HalfSize; i < NumElems; ++i) {
5983       int Elt = SVOp->getMaskElt(i);
5984       MaskV2.push_back(Elt < 0 ? Elt : Elt % HalfSize);
5985     }
5986
5987     EVT NVT = V1.getValueType();
5988     V1 = DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &MaskV1[0]);
5989     V2 = DAG.getVectorShuffle(NVT, dl, V2, DAG.getUNDEF(NVT), &MaskV2[0]);
5990
5991     // Concatenate the result back
5992     SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), V1,
5993                                    DAG.getConstant(0, MVT::i32), DAG, dl);
5994     return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32),
5995                               DAG, dl);
5996   }
5997
5998   return SDValue();
5999 }
6000
6001 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6002 /// 4 elements, and match them with several different shuffle types.
6003 static SDValue
6004 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6005   SDValue V1 = SVOp->getOperand(0);
6006   SDValue V2 = SVOp->getOperand(1);
6007   DebugLoc dl = SVOp->getDebugLoc();
6008   EVT VT = SVOp->getValueType(0);
6009
6010   assert(VT.getSizeInBits() == 128 && "Unsupported vector size");
6011
6012   SmallVector<std::pair<int, int>, 8> Locs;
6013   Locs.resize(4);
6014   SmallVector<int, 8> Mask1(4U, -1);
6015   SmallVector<int, 8> PermMask;
6016   SVOp->getMask(PermMask);
6017
6018   unsigned NumHi = 0;
6019   unsigned NumLo = 0;
6020   for (unsigned i = 0; i != 4; ++i) {
6021     int Idx = PermMask[i];
6022     if (Idx < 0) {
6023       Locs[i] = std::make_pair(-1, -1);
6024     } else {
6025       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6026       if (Idx < 4) {
6027         Locs[i] = std::make_pair(0, NumLo);
6028         Mask1[NumLo] = Idx;
6029         NumLo++;
6030       } else {
6031         Locs[i] = std::make_pair(1, NumHi);
6032         if (2+NumHi < 4)
6033           Mask1[2+NumHi] = Idx;
6034         NumHi++;
6035       }
6036     }
6037   }
6038
6039   if (NumLo <= 2 && NumHi <= 2) {
6040     // If no more than two elements come from either vector. This can be
6041     // implemented with two shuffles. First shuffle gather the elements.
6042     // The second shuffle, which takes the first shuffle as both of its
6043     // vector operands, put the elements into the right order.
6044     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6045
6046     SmallVector<int, 8> Mask2(4U, -1);
6047
6048     for (unsigned i = 0; i != 4; ++i) {
6049       if (Locs[i].first == -1)
6050         continue;
6051       else {
6052         unsigned Idx = (i < 2) ? 0 : 4;
6053         Idx += Locs[i].first * 2 + Locs[i].second;
6054         Mask2[i] = Idx;
6055       }
6056     }
6057
6058     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6059   } else if (NumLo == 3 || NumHi == 3) {
6060     // Otherwise, we must have three elements from one vector, call it X, and
6061     // one element from the other, call it Y.  First, use a shufps to build an
6062     // intermediate vector with the one element from Y and the element from X
6063     // that will be in the same half in the final destination (the indexes don't
6064     // matter). Then, use a shufps to build the final vector, taking the half
6065     // containing the element from Y from the intermediate, and the other half
6066     // from X.
6067     if (NumHi == 3) {
6068       // Normalize it so the 3 elements come from V1.
6069       CommuteVectorShuffleMask(PermMask, 4);
6070       std::swap(V1, V2);
6071     }
6072
6073     // Find the element from V2.
6074     unsigned HiIndex;
6075     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6076       int Val = PermMask[HiIndex];
6077       if (Val < 0)
6078         continue;
6079       if (Val >= 4)
6080         break;
6081     }
6082
6083     Mask1[0] = PermMask[HiIndex];
6084     Mask1[1] = -1;
6085     Mask1[2] = PermMask[HiIndex^1];
6086     Mask1[3] = -1;
6087     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6088
6089     if (HiIndex >= 2) {
6090       Mask1[0] = PermMask[0];
6091       Mask1[1] = PermMask[1];
6092       Mask1[2] = HiIndex & 1 ? 6 : 4;
6093       Mask1[3] = HiIndex & 1 ? 4 : 6;
6094       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6095     } else {
6096       Mask1[0] = HiIndex & 1 ? 2 : 0;
6097       Mask1[1] = HiIndex & 1 ? 0 : 2;
6098       Mask1[2] = PermMask[2];
6099       Mask1[3] = PermMask[3];
6100       if (Mask1[2] >= 0)
6101         Mask1[2] += 4;
6102       if (Mask1[3] >= 0)
6103         Mask1[3] += 4;
6104       return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6105     }
6106   }
6107
6108   // Break it into (shuffle shuffle_hi, shuffle_lo).
6109   Locs.clear();
6110   Locs.resize(4);
6111   SmallVector<int,8> LoMask(4U, -1);
6112   SmallVector<int,8> HiMask(4U, -1);
6113
6114   SmallVector<int,8> *MaskPtr = &LoMask;
6115   unsigned MaskIdx = 0;
6116   unsigned LoIdx = 0;
6117   unsigned HiIdx = 2;
6118   for (unsigned i = 0; i != 4; ++i) {
6119     if (i == 2) {
6120       MaskPtr = &HiMask;
6121       MaskIdx = 1;
6122       LoIdx = 0;
6123       HiIdx = 2;
6124     }
6125     int Idx = PermMask[i];
6126     if (Idx < 0) {
6127       Locs[i] = std::make_pair(-1, -1);
6128     } else if (Idx < 4) {
6129       Locs[i] = std::make_pair(MaskIdx, LoIdx);
6130       (*MaskPtr)[LoIdx] = Idx;
6131       LoIdx++;
6132     } else {
6133       Locs[i] = std::make_pair(MaskIdx, HiIdx);
6134       (*MaskPtr)[HiIdx] = Idx;
6135       HiIdx++;
6136     }
6137   }
6138
6139   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6140   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6141   SmallVector<int, 8> MaskOps;
6142   for (unsigned i = 0; i != 4; ++i) {
6143     if (Locs[i].first == -1) {
6144       MaskOps.push_back(-1);
6145     } else {
6146       unsigned Idx = Locs[i].first * 4 + Locs[i].second;
6147       MaskOps.push_back(Idx);
6148     }
6149   }
6150   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6151 }
6152
6153 static bool MayFoldVectorLoad(SDValue V) {
6154   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6155     V = V.getOperand(0);
6156   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6157     V = V.getOperand(0);
6158   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6159       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6160     // BUILD_VECTOR (load), undef
6161     V = V.getOperand(0);
6162   if (MayFoldLoad(V))
6163     return true;
6164   return false;
6165 }
6166
6167 // FIXME: the version above should always be used. Since there's
6168 // a bug where several vector shuffles can't be folded because the
6169 // DAG is not updated during lowering and a node claims to have two
6170 // uses while it only has one, use this version, and let isel match
6171 // another instruction if the load really happens to have more than
6172 // one use. Remove this version after this bug get fixed.
6173 // rdar://8434668, PR8156
6174 static bool RelaxedMayFoldVectorLoad(SDValue V) {
6175   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6176     V = V.getOperand(0);
6177   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6178     V = V.getOperand(0);
6179   if (ISD::isNormalLoad(V.getNode()))
6180     return true;
6181   return false;
6182 }
6183
6184 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
6185 /// a vector extract, and if both can be later optimized into a single load.
6186 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
6187 /// here because otherwise a target specific shuffle node is going to be
6188 /// emitted for this shuffle, and the optimization not done.
6189 /// FIXME: This is probably not the best approach, but fix the problem
6190 /// until the right path is decided.
6191 static
6192 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
6193                                          const TargetLowering &TLI) {
6194   EVT VT = V.getValueType();
6195   ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
6196
6197   // Be sure that the vector shuffle is present in a pattern like this:
6198   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
6199   if (!V.hasOneUse())
6200     return false;
6201
6202   SDNode *N = *V.getNode()->use_begin();
6203   if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
6204     return false;
6205
6206   SDValue EltNo = N->getOperand(1);
6207   if (!isa<ConstantSDNode>(EltNo))
6208     return false;
6209
6210   // If the bit convert changed the number of elements, it is unsafe
6211   // to examine the mask.
6212   bool HasShuffleIntoBitcast = false;
6213   if (V.getOpcode() == ISD::BITCAST) {
6214     EVT SrcVT = V.getOperand(0).getValueType();
6215     if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
6216       return false;
6217     V = V.getOperand(0);
6218     HasShuffleIntoBitcast = true;
6219   }
6220
6221   // Select the input vector, guarding against out of range extract vector.
6222   unsigned NumElems = VT.getVectorNumElements();
6223   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6224   int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
6225   V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
6226
6227   // Skip one more bit_convert if necessary
6228   if (V.getOpcode() == ISD::BITCAST)
6229     V = V.getOperand(0);
6230
6231   if (ISD::isNormalLoad(V.getNode())) {
6232     // Is the original load suitable?
6233     LoadSDNode *LN0 = cast<LoadSDNode>(V);
6234
6235     // FIXME: avoid the multi-use bug that is preventing lots of
6236     // of foldings to be detected, this is still wrong of course, but
6237     // give the temporary desired behavior, and if it happens that
6238     // the load has real more uses, during isel it will not fold, and
6239     // will generate poor code.
6240     if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
6241       return false;
6242
6243     if (!HasShuffleIntoBitcast)
6244       return true;
6245
6246     // If there's a bitcast before the shuffle, check if the load type and
6247     // alignment is valid.
6248     unsigned Align = LN0->getAlignment();
6249     unsigned NewAlign =
6250       TLI.getTargetData()->getABITypeAlignment(
6251                                     VT.getTypeForEVT(*DAG.getContext()));
6252
6253     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
6254       return false;
6255   }
6256
6257   return true;
6258 }
6259
6260 static
6261 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6262   EVT VT = Op.getValueType();
6263
6264   // Canonizalize to v2f64.
6265   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6266   return DAG.getNode(ISD::BITCAST, dl, VT,
6267                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6268                                           V1, DAG));
6269 }
6270
6271 static
6272 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6273                         bool HasXMMInt) {
6274   SDValue V1 = Op.getOperand(0);
6275   SDValue V2 = Op.getOperand(1);
6276   EVT VT = Op.getValueType();
6277
6278   assert(VT != MVT::v2i64 && "unsupported shuffle type");
6279
6280   if (HasXMMInt && VT == MVT::v2f64)
6281     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6282
6283   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6284   return DAG.getNode(ISD::BITCAST, dl, VT,
6285                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6286                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6287                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6288 }
6289
6290 static
6291 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6292   SDValue V1 = Op.getOperand(0);
6293   SDValue V2 = Op.getOperand(1);
6294   EVT VT = Op.getValueType();
6295
6296   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6297          "unsupported shuffle type");
6298
6299   if (V2.getOpcode() == ISD::UNDEF)
6300     V2 = V1;
6301
6302   // v4i32 or v4f32
6303   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6304 }
6305
6306 static inline unsigned getSHUFPOpcode(EVT VT) {
6307   switch(VT.getSimpleVT().SimpleTy) {
6308   case MVT::v8i32: // Use fp unit for int unpack.
6309   case MVT::v8f32:
6310   case MVT::v4i32: // Use fp unit for int unpack.
6311   case MVT::v4f32: return X86ISD::SHUFPS;
6312   case MVT::v4i64: // Use fp unit for int unpack.
6313   case MVT::v4f64:
6314   case MVT::v2i64: // Use fp unit for int unpack.
6315   case MVT::v2f64: return X86ISD::SHUFPD;
6316   default:
6317     llvm_unreachable("Unknown type for shufp*");
6318   }
6319   return 0;
6320 }
6321
6322 static
6323 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasXMMInt) {
6324   SDValue V1 = Op.getOperand(0);
6325   SDValue V2 = Op.getOperand(1);
6326   EVT VT = Op.getValueType();
6327   unsigned NumElems = VT.getVectorNumElements();
6328
6329   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6330   // operand of these instructions is only memory, so check if there's a
6331   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6332   // same masks.
6333   bool CanFoldLoad = false;
6334
6335   // Trivial case, when V2 comes from a load.
6336   if (MayFoldVectorLoad(V2))
6337     CanFoldLoad = true;
6338
6339   // When V1 is a load, it can be folded later into a store in isel, example:
6340   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6341   //    turns into:
6342   //  (MOVLPSmr addr:$src1, VR128:$src2)
6343   // So, recognize this potential and also use MOVLPS or MOVLPD
6344   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6345     CanFoldLoad = true;
6346
6347   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6348   if (CanFoldLoad) {
6349     if (HasXMMInt && NumElems == 2)
6350       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6351
6352     if (NumElems == 4)
6353       // If we don't care about the second element, procede to use movss.
6354       if (SVOp->getMaskElt(1) != -1)
6355         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6356   }
6357
6358   // movl and movlp will both match v2i64, but v2i64 is never matched by
6359   // movl earlier because we make it strict to avoid messing with the movlp load
6360   // folding logic (see the code above getMOVLP call). Match it here then,
6361   // this is horrible, but will stay like this until we move all shuffle
6362   // matching to x86 specific nodes. Note that for the 1st condition all
6363   // types are matched with movsd.
6364   if (HasXMMInt) {
6365     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6366     // as to remove this logic from here, as much as possible
6367     if (NumElems == 2 || !X86::isMOVLMask(SVOp))
6368       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6369     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6370   }
6371
6372   assert(VT != MVT::v4i32 && "unsupported shuffle type");
6373
6374   // Invert the operand order and use SHUFPS to match it.
6375   return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V2, V1,
6376                               X86::getShuffleSHUFImmediate(SVOp), DAG);
6377 }
6378
6379 static
6380 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
6381                                const TargetLowering &TLI,
6382                                const X86Subtarget *Subtarget) {
6383   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6384   EVT VT = Op.getValueType();
6385   DebugLoc dl = Op.getDebugLoc();
6386   SDValue V1 = Op.getOperand(0);
6387   SDValue V2 = Op.getOperand(1);
6388
6389   if (isZeroShuffle(SVOp))
6390     return getZeroVector(VT, Subtarget->hasXMMInt(), DAG, dl);
6391
6392   // Handle splat operations
6393   if (SVOp->isSplat()) {
6394     unsigned NumElem = VT.getVectorNumElements();
6395     int Size = VT.getSizeInBits();
6396     // Special case, this is the only place now where it's allowed to return
6397     // a vector_shuffle operation without using a target specific node, because
6398     // *hopefully* it will be optimized away by the dag combiner. FIXME: should
6399     // this be moved to DAGCombine instead?
6400     if (NumElem <= 4 && CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
6401       return Op;
6402
6403     // Use vbroadcast whenever the splat comes from a foldable load
6404     SDValue LD = isVectorBroadcast(Op, Subtarget->hasAVX2());
6405     if (Subtarget->hasAVX() && LD.getNode())
6406       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, LD);
6407
6408     // Handle splats by matching through known shuffle masks
6409     if ((Size == 128 && NumElem <= 4) ||
6410         (Size == 256 && NumElem < 8))
6411       return SDValue();
6412
6413     // All remaning splats are promoted to target supported vector shuffles.
6414     return PromoteSplat(SVOp, DAG);
6415   }
6416
6417   // If the shuffle can be profitably rewritten as a narrower shuffle, then
6418   // do it!
6419   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
6420     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6421     if (NewOp.getNode())
6422       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6423   } else if ((VT == MVT::v4i32 ||
6424              (VT == MVT::v4f32 && Subtarget->hasXMMInt()))) {
6425     // FIXME: Figure out a cleaner way to do this.
6426     // Try to make use of movq to zero out the top part.
6427     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6428       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6429       if (NewOp.getNode()) {
6430         if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
6431           return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
6432                               DAG, Subtarget, dl);
6433       }
6434     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6435       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6436       if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
6437         return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
6438                             DAG, Subtarget, dl);
6439     }
6440   }
6441   return SDValue();
6442 }
6443
6444 SDValue
6445 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6446   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6447   SDValue V1 = Op.getOperand(0);
6448   SDValue V2 = Op.getOperand(1);
6449   EVT VT = Op.getValueType();
6450   DebugLoc dl = Op.getDebugLoc();
6451   unsigned NumElems = VT.getVectorNumElements();
6452   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6453   bool V1IsSplat = false;
6454   bool V2IsSplat = false;
6455   bool HasXMMInt = Subtarget->hasXMMInt();
6456   bool HasAVX    = Subtarget->hasAVX();
6457   bool HasAVX2   = Subtarget->hasAVX2();
6458   MachineFunction &MF = DAG.getMachineFunction();
6459   bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
6460
6461   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6462
6463   assert(V1.getOpcode() != ISD::UNDEF && "Op 1 of shuffle should not be undef");
6464
6465   // Vector shuffle lowering takes 3 steps:
6466   //
6467   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6468   //    narrowing and commutation of operands should be handled.
6469   // 2) Matching of shuffles with known shuffle masks to x86 target specific
6470   //    shuffle nodes.
6471   // 3) Rewriting of unmatched masks into new generic shuffle operations,
6472   //    so the shuffle can be broken into other shuffles and the legalizer can
6473   //    try the lowering again.
6474   //
6475   // The general idea is that no vector_shuffle operation should be left to
6476   // be matched during isel, all of them must be converted to a target specific
6477   // node here.
6478
6479   // Normalize the input vectors. Here splats, zeroed vectors, profitable
6480   // narrowing and commutation of operands should be handled. The actual code
6481   // doesn't include all of those, work in progress...
6482   SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
6483   if (NewOp.getNode())
6484     return NewOp;
6485
6486   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6487   // unpckh_undef). Only use pshufd if speed is more important than size.
6488   if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp, HasAVX2))
6489     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6490   if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp, HasAVX2))
6491     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6492
6493   if (X86::isMOVDDUPMask(SVOp) && Subtarget->hasSSE3orAVX() &&
6494       V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6495     return getMOVDDup(Op, dl, V1, DAG);
6496
6497   if (X86::isMOVHLPS_v_undef_Mask(SVOp))
6498     return getMOVHighToLow(Op, dl, DAG);
6499
6500   // Use to match splats
6501   if (HasXMMInt && X86::isUNPCKHMask(SVOp, HasAVX2) && V2IsUndef &&
6502       (VT == MVT::v2f64 || VT == MVT::v2i64))
6503     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6504
6505   if (X86::isPSHUFDMask(SVOp)) {
6506     // The actual implementation will match the mask in the if above and then
6507     // during isel it can match several different instructions, not only pshufd
6508     // as its name says, sad but true, emulate the behavior for now...
6509     if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6510         return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6511
6512     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
6513
6514     if (HasXMMInt && (VT == MVT::v4f32 || VT == MVT::v4i32))
6515       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6516
6517     return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V1,
6518                                 TargetMask, DAG);
6519   }
6520
6521   // Check if this can be converted into a logical shift.
6522   bool isLeft = false;
6523   unsigned ShAmt = 0;
6524   SDValue ShVal;
6525   bool isShift = HasXMMInt && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6526   if (isShift && ShVal.hasOneUse()) {
6527     // If the shifted value has multiple uses, it may be cheaper to use
6528     // v_set0 + movlhps or movhlps, etc.
6529     EVT EltVT = VT.getVectorElementType();
6530     ShAmt *= EltVT.getSizeInBits();
6531     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6532   }
6533
6534   if (X86::isMOVLMask(SVOp)) {
6535     if (ISD::isBuildVectorAllZeros(V1.getNode()))
6536       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6537     if (!X86::isMOVLPMask(SVOp)) {
6538       if (HasXMMInt && (VT == MVT::v2i64 || VT == MVT::v2f64))
6539         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6540
6541       if (VT == MVT::v4i32 || VT == MVT::v4f32)
6542         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6543     }
6544   }
6545
6546   // FIXME: fold these into legal mask.
6547   if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp, HasAVX2))
6548     return getMOVLowToHigh(Op, dl, DAG, HasXMMInt);
6549
6550   if (X86::isMOVHLPSMask(SVOp))
6551     return getMOVHighToLow(Op, dl, DAG);
6552
6553   if (X86::isMOVSHDUPMask(SVOp, Subtarget))
6554     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6555
6556   if (X86::isMOVSLDUPMask(SVOp, Subtarget))
6557     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6558
6559   if (X86::isMOVLPMask(SVOp))
6560     return getMOVLP(Op, dl, DAG, HasXMMInt);
6561
6562   if (ShouldXformToMOVHLPS(SVOp) ||
6563       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
6564     return CommuteVectorShuffle(SVOp, DAG);
6565
6566   if (isShift) {
6567     // No better options. Use a vshl / vsrl.
6568     EVT EltVT = VT.getVectorElementType();
6569     ShAmt *= EltVT.getSizeInBits();
6570     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6571   }
6572
6573   bool Commuted = false;
6574   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
6575   // 1,1,1,1 -> v8i16 though.
6576   V1IsSplat = isSplatVector(V1.getNode());
6577   V2IsSplat = isSplatVector(V2.getNode());
6578
6579   // Canonicalize the splat or undef, if present, to be on the RHS.
6580   if (V1IsSplat && !V2IsSplat) {
6581     Op = CommuteVectorShuffle(SVOp, DAG);
6582     SVOp = cast<ShuffleVectorSDNode>(Op);
6583     V1 = SVOp->getOperand(0);
6584     V2 = SVOp->getOperand(1);
6585     std::swap(V1IsSplat, V2IsSplat);
6586     Commuted = true;
6587   }
6588
6589   SmallVector<int, 32> M;
6590   SVOp->getMask(M);
6591
6592   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6593     // Shuffling low element of v1 into undef, just return v1.
6594     if (V2IsUndef)
6595       return V1;
6596     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6597     // the instruction selector will not match, so get a canonical MOVL with
6598     // swapped operands to undo the commute.
6599     return getMOVL(DAG, dl, VT, V2, V1);
6600   }
6601
6602   if (isUNPCKLMask(M, VT, HasAVX2))
6603     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6604
6605   if (isUNPCKHMask(M, VT, HasAVX2))
6606     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6607
6608   if (V2IsSplat) {
6609     // Normalize mask so all entries that point to V2 points to its first
6610     // element then try to match unpck{h|l} again. If match, return a
6611     // new vector_shuffle with the corrected mask.
6612     SDValue NewMask = NormalizeMask(SVOp, DAG);
6613     ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
6614     if (NSVOp != SVOp) {
6615       if (X86::isUNPCKLMask(NSVOp, HasAVX2, true)) {
6616         return NewMask;
6617       } else if (X86::isUNPCKHMask(NSVOp, HasAVX2, true)) {
6618         return NewMask;
6619       }
6620     }
6621   }
6622
6623   if (Commuted) {
6624     // Commute is back and try unpck* again.
6625     // FIXME: this seems wrong.
6626     SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
6627     ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
6628
6629     if (X86::isUNPCKLMask(NewSVOp, HasAVX2))
6630       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V2, V1, DAG);
6631
6632     if (X86::isUNPCKHMask(NewSVOp, HasAVX2))
6633       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V2, V1, DAG);
6634   }
6635
6636   // Normalize the node to match x86 shuffle ops if needed
6637   if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true) ||
6638                      isVSHUFPYMask(M, VT, HasAVX, /* Commuted */ true)))
6639     return CommuteVectorShuffle(SVOp, DAG);
6640
6641   // The checks below are all present in isShuffleMaskLegal, but they are
6642   // inlined here right now to enable us to directly emit target specific
6643   // nodes, and remove one by one until they don't return Op anymore.
6644
6645   if (isPALIGNRMask(M, VT, Subtarget->hasSSSE3orAVX()))
6646     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6647                                 getShufflePALIGNRImmediate(SVOp),
6648                                 DAG);
6649
6650   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6651       SVOp->getSplatIndex() == 0 && V2IsUndef) {
6652     if (VT == MVT::v2f64 || VT == MVT::v2i64)
6653       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6654   }
6655
6656   if (isPSHUFHWMask(M, VT))
6657     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6658                                 X86::getShufflePSHUFHWImmediate(SVOp),
6659                                 DAG);
6660
6661   if (isPSHUFLWMask(M, VT))
6662     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6663                                 X86::getShufflePSHUFLWImmediate(SVOp),
6664                                 DAG);
6665
6666   if (isSHUFPMask(M, VT))
6667     return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6668                                 X86::getShuffleSHUFImmediate(SVOp), DAG);
6669
6670   if (isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6671     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6672   if (isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6673     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6674
6675   //===--------------------------------------------------------------------===//
6676   // Generate target specific nodes for 128 or 256-bit shuffles only
6677   // supported in the AVX instruction set.
6678   //
6679
6680   // Handle VMOVDDUPY permutations
6681   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasAVX))
6682     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6683
6684   // Handle VPERMILPS/D* permutations
6685   if (isVPERMILPMask(M, VT, HasAVX))
6686     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
6687                                 getShuffleVPERMILPImmediate(SVOp), DAG);
6688
6689   // Handle VPERM2F128/VPERM2I128 permutations
6690   if (isVPERM2X128Mask(M, VT, HasAVX))
6691     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
6692                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
6693
6694   // Handle VSHUFPS/DY permutations
6695   if (isVSHUFPYMask(M, VT, HasAVX))
6696     return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6697                                 getShuffleVSHUFPYImmediate(SVOp), DAG);
6698
6699   //===--------------------------------------------------------------------===//
6700   // Since no target specific shuffle was selected for this generic one,
6701   // lower it into other known shuffles. FIXME: this isn't true yet, but
6702   // this is the plan.
6703   //
6704
6705   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6706   if (VT == MVT::v8i16) {
6707     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
6708     if (NewOp.getNode())
6709       return NewOp;
6710   }
6711
6712   if (VT == MVT::v16i8) {
6713     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6714     if (NewOp.getNode())
6715       return NewOp;
6716   }
6717
6718   // Handle all 128-bit wide vectors with 4 elements, and match them with
6719   // several different shuffle types.
6720   if (NumElems == 4 && VT.getSizeInBits() == 128)
6721     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6722
6723   // Handle general 256-bit shuffles
6724   if (VT.is256BitVector())
6725     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6726
6727   return SDValue();
6728 }
6729
6730 SDValue
6731 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6732                                                 SelectionDAG &DAG) const {
6733   EVT VT = Op.getValueType();
6734   DebugLoc dl = Op.getDebugLoc();
6735
6736   if (Op.getOperand(0).getValueType().getSizeInBits() != 128)
6737     return SDValue();
6738
6739   if (VT.getSizeInBits() == 8) {
6740     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6741                                     Op.getOperand(0), Op.getOperand(1));
6742     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6743                                     DAG.getValueType(VT));
6744     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6745   } else if (VT.getSizeInBits() == 16) {
6746     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6747     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6748     if (Idx == 0)
6749       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6750                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6751                                      DAG.getNode(ISD::BITCAST, dl,
6752                                                  MVT::v4i32,
6753                                                  Op.getOperand(0)),
6754                                      Op.getOperand(1)));
6755     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6756                                     Op.getOperand(0), Op.getOperand(1));
6757     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6758                                     DAG.getValueType(VT));
6759     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6760   } else if (VT == MVT::f32) {
6761     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6762     // the result back to FR32 register. It's only worth matching if the
6763     // result has a single use which is a store or a bitcast to i32.  And in
6764     // the case of a store, it's not worth it if the index is a constant 0,
6765     // because a MOVSSmr can be used instead, which is smaller and faster.
6766     if (!Op.hasOneUse())
6767       return SDValue();
6768     SDNode *User = *Op.getNode()->use_begin();
6769     if ((User->getOpcode() != ISD::STORE ||
6770          (isa<ConstantSDNode>(Op.getOperand(1)) &&
6771           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6772         (User->getOpcode() != ISD::BITCAST ||
6773          User->getValueType(0) != MVT::i32))
6774       return SDValue();
6775     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6776                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6777                                               Op.getOperand(0)),
6778                                               Op.getOperand(1));
6779     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6780   } else if (VT == MVT::i32 || VT == MVT::i64) {
6781     // ExtractPS/pextrq works with constant index.
6782     if (isa<ConstantSDNode>(Op.getOperand(1)))
6783       return Op;
6784   }
6785   return SDValue();
6786 }
6787
6788
6789 SDValue
6790 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6791                                            SelectionDAG &DAG) const {
6792   if (!isa<ConstantSDNode>(Op.getOperand(1)))
6793     return SDValue();
6794
6795   SDValue Vec = Op.getOperand(0);
6796   EVT VecVT = Vec.getValueType();
6797
6798   // If this is a 256-bit vector result, first extract the 128-bit vector and
6799   // then extract the element from the 128-bit vector.
6800   if (VecVT.getSizeInBits() == 256) {
6801     DebugLoc dl = Op.getNode()->getDebugLoc();
6802     unsigned NumElems = VecVT.getVectorNumElements();
6803     SDValue Idx = Op.getOperand(1);
6804     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6805
6806     // Get the 128-bit vector.
6807     bool Upper = IdxVal >= NumElems/2;
6808     Vec = Extract128BitVector(Vec,
6809                     DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32), DAG, dl);
6810
6811     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6812                     Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : Idx);
6813   }
6814
6815   assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
6816
6817   if (Subtarget->hasSSE41orAVX()) {
6818     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6819     if (Res.getNode())
6820       return Res;
6821   }
6822
6823   EVT VT = Op.getValueType();
6824   DebugLoc dl = Op.getDebugLoc();
6825   // TODO: handle v16i8.
6826   if (VT.getSizeInBits() == 16) {
6827     SDValue Vec = Op.getOperand(0);
6828     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6829     if (Idx == 0)
6830       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6831                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6832                                      DAG.getNode(ISD::BITCAST, dl,
6833                                                  MVT::v4i32, Vec),
6834                                      Op.getOperand(1)));
6835     // Transform it so it match pextrw which produces a 32-bit result.
6836     EVT EltVT = MVT::i32;
6837     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6838                                     Op.getOperand(0), Op.getOperand(1));
6839     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6840                                     DAG.getValueType(VT));
6841     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6842   } else if (VT.getSizeInBits() == 32) {
6843     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6844     if (Idx == 0)
6845       return Op;
6846
6847     // SHUFPS the element to the lowest double word, then movss.
6848     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
6849     EVT VVT = Op.getOperand(0).getValueType();
6850     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6851                                        DAG.getUNDEF(VVT), Mask);
6852     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6853                        DAG.getIntPtrConstant(0));
6854   } else if (VT.getSizeInBits() == 64) {
6855     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6856     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6857     //        to match extract_elt for f64.
6858     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6859     if (Idx == 0)
6860       return Op;
6861
6862     // UNPCKHPD the element to the lowest double word, then movsd.
6863     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
6864     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
6865     int Mask[2] = { 1, -1 };
6866     EVT VVT = Op.getOperand(0).getValueType();
6867     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6868                                        DAG.getUNDEF(VVT), Mask);
6869     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6870                        DAG.getIntPtrConstant(0));
6871   }
6872
6873   return SDValue();
6874 }
6875
6876 SDValue
6877 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
6878                                                SelectionDAG &DAG) const {
6879   EVT VT = Op.getValueType();
6880   EVT EltVT = VT.getVectorElementType();
6881   DebugLoc dl = Op.getDebugLoc();
6882
6883   SDValue N0 = Op.getOperand(0);
6884   SDValue N1 = Op.getOperand(1);
6885   SDValue N2 = Op.getOperand(2);
6886
6887   if (VT.getSizeInBits() == 256)
6888     return SDValue();
6889
6890   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
6891       isa<ConstantSDNode>(N2)) {
6892     unsigned Opc;
6893     if (VT == MVT::v8i16)
6894       Opc = X86ISD::PINSRW;
6895     else if (VT == MVT::v16i8)
6896       Opc = X86ISD::PINSRB;
6897     else
6898       Opc = X86ISD::PINSRB;
6899
6900     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
6901     // argument.
6902     if (N1.getValueType() != MVT::i32)
6903       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6904     if (N2.getValueType() != MVT::i32)
6905       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6906     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
6907   } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
6908     // Bits [7:6] of the constant are the source select.  This will always be
6909     //  zero here.  The DAG Combiner may combine an extract_elt index into these
6910     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
6911     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
6912     // Bits [5:4] of the constant are the destination select.  This is the
6913     //  value of the incoming immediate.
6914     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
6915     //   combine either bitwise AND or insert of float 0.0 to set these bits.
6916     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
6917     // Create this as a scalar to vector..
6918     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
6919     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
6920   } else if ((EltVT == MVT::i32 || EltVT == MVT::i64) && 
6921              isa<ConstantSDNode>(N2)) {
6922     // PINSR* works with constant index.
6923     return Op;
6924   }
6925   return SDValue();
6926 }
6927
6928 SDValue
6929 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
6930   EVT VT = Op.getValueType();
6931   EVT EltVT = VT.getVectorElementType();
6932
6933   DebugLoc dl = Op.getDebugLoc();
6934   SDValue N0 = Op.getOperand(0);
6935   SDValue N1 = Op.getOperand(1);
6936   SDValue N2 = Op.getOperand(2);
6937
6938   // If this is a 256-bit vector result, first extract the 128-bit vector,
6939   // insert the element into the extracted half and then place it back.
6940   if (VT.getSizeInBits() == 256) {
6941     if (!isa<ConstantSDNode>(N2))
6942       return SDValue();
6943
6944     // Get the desired 128-bit vector half.
6945     unsigned NumElems = VT.getVectorNumElements();
6946     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
6947     bool Upper = IdxVal >= NumElems/2;
6948     SDValue Ins128Idx = DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32);
6949     SDValue V = Extract128BitVector(N0, Ins128Idx, DAG, dl);
6950
6951     // Insert the element into the desired half.
6952     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V,
6953                  N1, Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : N2);
6954
6955     // Insert the changed part back to the 256-bit vector
6956     return Insert128BitVector(N0, V, Ins128Idx, DAG, dl);
6957   }
6958
6959   if (Subtarget->hasSSE41orAVX())
6960     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
6961
6962   if (EltVT == MVT::i8)
6963     return SDValue();
6964
6965   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
6966     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
6967     // as its second argument.
6968     if (N1.getValueType() != MVT::i32)
6969       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6970     if (N2.getValueType() != MVT::i32)
6971       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6972     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
6973   }
6974   return SDValue();
6975 }
6976
6977 SDValue
6978 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6979   LLVMContext *Context = DAG.getContext();
6980   DebugLoc dl = Op.getDebugLoc();
6981   EVT OpVT = Op.getValueType();
6982
6983   // If this is a 256-bit vector result, first insert into a 128-bit
6984   // vector and then insert into the 256-bit vector.
6985   if (OpVT.getSizeInBits() > 128) {
6986     // Insert into a 128-bit vector.
6987     EVT VT128 = EVT::getVectorVT(*Context,
6988                                  OpVT.getVectorElementType(),
6989                                  OpVT.getVectorNumElements() / 2);
6990
6991     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
6992
6993     // Insert the 128-bit vector.
6994     return Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, OpVT), Op,
6995                               DAG.getConstant(0, MVT::i32),
6996                               DAG, dl);
6997   }
6998
6999   if (Op.getValueType() == MVT::v1i64 &&
7000       Op.getOperand(0).getValueType() == MVT::i64)
7001     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7002
7003   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7004   assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
7005          "Expected an SSE type!");
7006   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
7007                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7008 }
7009
7010 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7011 // a simple subregister reference or explicit instructions to grab
7012 // upper bits of a vector.
7013 SDValue
7014 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7015   if (Subtarget->hasAVX()) {
7016     DebugLoc dl = Op.getNode()->getDebugLoc();
7017     SDValue Vec = Op.getNode()->getOperand(0);
7018     SDValue Idx = Op.getNode()->getOperand(1);
7019
7020     if (Op.getNode()->getValueType(0).getSizeInBits() == 128
7021         && Vec.getNode()->getValueType(0).getSizeInBits() == 256) {
7022         return Extract128BitVector(Vec, Idx, DAG, dl);
7023     }
7024   }
7025   return SDValue();
7026 }
7027
7028 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7029 // simple superregister reference or explicit instructions to insert
7030 // the upper bits of a vector.
7031 SDValue
7032 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7033   if (Subtarget->hasAVX()) {
7034     DebugLoc dl = Op.getNode()->getDebugLoc();
7035     SDValue Vec = Op.getNode()->getOperand(0);
7036     SDValue SubVec = Op.getNode()->getOperand(1);
7037     SDValue Idx = Op.getNode()->getOperand(2);
7038
7039     if (Op.getNode()->getValueType(0).getSizeInBits() == 256
7040         && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) {
7041       return Insert128BitVector(Vec, SubVec, Idx, DAG, dl);
7042     }
7043   }
7044   return SDValue();
7045 }
7046
7047 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7048 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7049 // one of the above mentioned nodes. It has to be wrapped because otherwise
7050 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7051 // be used to form addressing mode. These wrapped nodes will be selected
7052 // into MOV32ri.
7053 SDValue
7054 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7055   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7056
7057   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7058   // global base reg.
7059   unsigned char OpFlag = 0;
7060   unsigned WrapperKind = X86ISD::Wrapper;
7061   CodeModel::Model M = getTargetMachine().getCodeModel();
7062
7063   if (Subtarget->isPICStyleRIPRel() &&
7064       (M == CodeModel::Small || M == CodeModel::Kernel))
7065     WrapperKind = X86ISD::WrapperRIP;
7066   else if (Subtarget->isPICStyleGOT())
7067     OpFlag = X86II::MO_GOTOFF;
7068   else if (Subtarget->isPICStyleStubPIC())
7069     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7070
7071   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7072                                              CP->getAlignment(),
7073                                              CP->getOffset(), OpFlag);
7074   DebugLoc DL = CP->getDebugLoc();
7075   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7076   // With PIC, the address is actually $g + Offset.
7077   if (OpFlag) {
7078     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7079                          DAG.getNode(X86ISD::GlobalBaseReg,
7080                                      DebugLoc(), getPointerTy()),
7081                          Result);
7082   }
7083
7084   return Result;
7085 }
7086
7087 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7088   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7089
7090   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7091   // global base reg.
7092   unsigned char OpFlag = 0;
7093   unsigned WrapperKind = X86ISD::Wrapper;
7094   CodeModel::Model M = getTargetMachine().getCodeModel();
7095
7096   if (Subtarget->isPICStyleRIPRel() &&
7097       (M == CodeModel::Small || M == CodeModel::Kernel))
7098     WrapperKind = X86ISD::WrapperRIP;
7099   else if (Subtarget->isPICStyleGOT())
7100     OpFlag = X86II::MO_GOTOFF;
7101   else if (Subtarget->isPICStyleStubPIC())
7102     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7103
7104   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7105                                           OpFlag);
7106   DebugLoc DL = JT->getDebugLoc();
7107   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7108
7109   // With PIC, the address is actually $g + Offset.
7110   if (OpFlag)
7111     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7112                          DAG.getNode(X86ISD::GlobalBaseReg,
7113                                      DebugLoc(), getPointerTy()),
7114                          Result);
7115
7116   return Result;
7117 }
7118
7119 SDValue
7120 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7121   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7122
7123   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7124   // global base reg.
7125   unsigned char OpFlag = 0;
7126   unsigned WrapperKind = X86ISD::Wrapper;
7127   CodeModel::Model M = getTargetMachine().getCodeModel();
7128
7129   if (Subtarget->isPICStyleRIPRel() &&
7130       (M == CodeModel::Small || M == CodeModel::Kernel)) {
7131     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7132       OpFlag = X86II::MO_GOTPCREL;
7133     WrapperKind = X86ISD::WrapperRIP;
7134   } else if (Subtarget->isPICStyleGOT()) {
7135     OpFlag = X86II::MO_GOT;
7136   } else if (Subtarget->isPICStyleStubPIC()) {
7137     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7138   } else if (Subtarget->isPICStyleStubNoDynamic()) {
7139     OpFlag = X86II::MO_DARWIN_NONLAZY;
7140   }
7141
7142   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7143
7144   DebugLoc DL = Op.getDebugLoc();
7145   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7146
7147
7148   // With PIC, the address is actually $g + Offset.
7149   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7150       !Subtarget->is64Bit()) {
7151     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7152                          DAG.getNode(X86ISD::GlobalBaseReg,
7153                                      DebugLoc(), getPointerTy()),
7154                          Result);
7155   }
7156
7157   // For symbols that require a load from a stub to get the address, emit the
7158   // load.
7159   if (isGlobalStubReference(OpFlag))
7160     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7161                          MachinePointerInfo::getGOT(), false, false, false, 0);
7162
7163   return Result;
7164 }
7165
7166 SDValue
7167 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7168   // Create the TargetBlockAddressAddress node.
7169   unsigned char OpFlags =
7170     Subtarget->ClassifyBlockAddressReference();
7171   CodeModel::Model M = getTargetMachine().getCodeModel();
7172   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7173   DebugLoc dl = Op.getDebugLoc();
7174   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
7175                                        /*isTarget=*/true, OpFlags);
7176
7177   if (Subtarget->isPICStyleRIPRel() &&
7178       (M == CodeModel::Small || M == CodeModel::Kernel))
7179     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7180   else
7181     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7182
7183   // With PIC, the address is actually $g + Offset.
7184   if (isGlobalRelativeToPICBase(OpFlags)) {
7185     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7186                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7187                          Result);
7188   }
7189
7190   return Result;
7191 }
7192
7193 SDValue
7194 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7195                                       int64_t Offset,
7196                                       SelectionDAG &DAG) const {
7197   // Create the TargetGlobalAddress node, folding in the constant
7198   // offset if it is legal.
7199   unsigned char OpFlags =
7200     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7201   CodeModel::Model M = getTargetMachine().getCodeModel();
7202   SDValue Result;
7203   if (OpFlags == X86II::MO_NO_FLAG &&
7204       X86::isOffsetSuitableForCodeModel(Offset, M)) {
7205     // A direct static reference to a global.
7206     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7207     Offset = 0;
7208   } else {
7209     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7210   }
7211
7212   if (Subtarget->isPICStyleRIPRel() &&
7213       (M == CodeModel::Small || M == CodeModel::Kernel))
7214     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7215   else
7216     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7217
7218   // With PIC, the address is actually $g + Offset.
7219   if (isGlobalRelativeToPICBase(OpFlags)) {
7220     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7221                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7222                          Result);
7223   }
7224
7225   // For globals that require a load from a stub to get the address, emit the
7226   // load.
7227   if (isGlobalStubReference(OpFlags))
7228     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7229                          MachinePointerInfo::getGOT(), false, false, false, 0);
7230
7231   // If there was a non-zero offset that we didn't fold, create an explicit
7232   // addition for it.
7233   if (Offset != 0)
7234     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7235                          DAG.getConstant(Offset, getPointerTy()));
7236
7237   return Result;
7238 }
7239
7240 SDValue
7241 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7242   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7243   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7244   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7245 }
7246
7247 static SDValue
7248 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7249            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7250            unsigned char OperandFlags) {
7251   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7252   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7253   DebugLoc dl = GA->getDebugLoc();
7254   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7255                                            GA->getValueType(0),
7256                                            GA->getOffset(),
7257                                            OperandFlags);
7258   if (InFlag) {
7259     SDValue Ops[] = { Chain,  TGA, *InFlag };
7260     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
7261   } else {
7262     SDValue Ops[]  = { Chain, TGA };
7263     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
7264   }
7265
7266   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7267   MFI->setAdjustsStack(true);
7268
7269   SDValue Flag = Chain.getValue(1);
7270   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7271 }
7272
7273 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7274 static SDValue
7275 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7276                                 const EVT PtrVT) {
7277   SDValue InFlag;
7278   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
7279   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7280                                      DAG.getNode(X86ISD::GlobalBaseReg,
7281                                                  DebugLoc(), PtrVT), InFlag);
7282   InFlag = Chain.getValue(1);
7283
7284   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7285 }
7286
7287 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7288 static SDValue
7289 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7290                                 const EVT PtrVT) {
7291   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7292                     X86::RAX, X86II::MO_TLSGD);
7293 }
7294
7295 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
7296 // "local exec" model.
7297 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7298                                    const EVT PtrVT, TLSModel::Model model,
7299                                    bool is64Bit) {
7300   DebugLoc dl = GA->getDebugLoc();
7301
7302   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7303   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7304                                                          is64Bit ? 257 : 256));
7305
7306   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7307                                       DAG.getIntPtrConstant(0),
7308                                       MachinePointerInfo(Ptr),
7309                                       false, false, false, 0);
7310
7311   unsigned char OperandFlags = 0;
7312   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
7313   // initialexec.
7314   unsigned WrapperKind = X86ISD::Wrapper;
7315   if (model == TLSModel::LocalExec) {
7316     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7317   } else if (is64Bit) {
7318     assert(model == TLSModel::InitialExec);
7319     OperandFlags = X86II::MO_GOTTPOFF;
7320     WrapperKind = X86ISD::WrapperRIP;
7321   } else {
7322     assert(model == TLSModel::InitialExec);
7323     OperandFlags = X86II::MO_INDNTPOFF;
7324   }
7325
7326   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
7327   // exec)
7328   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7329                                            GA->getValueType(0),
7330                                            GA->getOffset(), OperandFlags);
7331   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7332
7333   if (model == TLSModel::InitialExec)
7334     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7335                          MachinePointerInfo::getGOT(), false, false, false, 0);
7336
7337   // The address of the thread local variable is the add of the thread
7338   // pointer with the offset of the variable.
7339   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7340 }
7341
7342 SDValue
7343 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7344
7345   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7346   const GlobalValue *GV = GA->getGlobal();
7347
7348   if (Subtarget->isTargetELF()) {
7349     // TODO: implement the "local dynamic" model
7350     // TODO: implement the "initial exec"model for pic executables
7351
7352     // If GV is an alias then use the aliasee for determining
7353     // thread-localness.
7354     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7355       GV = GA->resolveAliasedGlobal(false);
7356
7357     TLSModel::Model model
7358       = getTLSModel(GV, getTargetMachine().getRelocationModel());
7359
7360     switch (model) {
7361       case TLSModel::GeneralDynamic:
7362       case TLSModel::LocalDynamic: // not implemented
7363         if (Subtarget->is64Bit())
7364           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7365         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7366
7367       case TLSModel::InitialExec:
7368       case TLSModel::LocalExec:
7369         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7370                                    Subtarget->is64Bit());
7371     }
7372   } else if (Subtarget->isTargetDarwin()) {
7373     // Darwin only has one model of TLS.  Lower to that.
7374     unsigned char OpFlag = 0;
7375     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7376                            X86ISD::WrapperRIP : X86ISD::Wrapper;
7377
7378     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7379     // global base reg.
7380     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7381                   !Subtarget->is64Bit();
7382     if (PIC32)
7383       OpFlag = X86II::MO_TLVP_PIC_BASE;
7384     else
7385       OpFlag = X86II::MO_TLVP;
7386     DebugLoc DL = Op.getDebugLoc();
7387     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7388                                                 GA->getValueType(0),
7389                                                 GA->getOffset(), OpFlag);
7390     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7391
7392     // With PIC32, the address is actually $g + Offset.
7393     if (PIC32)
7394       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7395                            DAG.getNode(X86ISD::GlobalBaseReg,
7396                                        DebugLoc(), getPointerTy()),
7397                            Offset);
7398
7399     // Lowering the machine isd will make sure everything is in the right
7400     // location.
7401     SDValue Chain = DAG.getEntryNode();
7402     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7403     SDValue Args[] = { Chain, Offset };
7404     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7405
7406     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7407     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7408     MFI->setAdjustsStack(true);
7409
7410     // And our return value (tls address) is in the standard call return value
7411     // location.
7412     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7413     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7414                               Chain.getValue(1));
7415   }
7416
7417   assert(false &&
7418          "TLS not implemented for this target.");
7419
7420   llvm_unreachable("Unreachable");
7421   return SDValue();
7422 }
7423
7424
7425 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values and
7426 /// take a 2 x i32 value to shift plus a shift amount.
7427 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const {
7428   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7429   EVT VT = Op.getValueType();
7430   unsigned VTBits = VT.getSizeInBits();
7431   DebugLoc dl = Op.getDebugLoc();
7432   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7433   SDValue ShOpLo = Op.getOperand(0);
7434   SDValue ShOpHi = Op.getOperand(1);
7435   SDValue ShAmt  = Op.getOperand(2);
7436   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7437                                      DAG.getConstant(VTBits - 1, MVT::i8))
7438                        : DAG.getConstant(0, VT);
7439
7440   SDValue Tmp2, Tmp3;
7441   if (Op.getOpcode() == ISD::SHL_PARTS) {
7442     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7443     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7444   } else {
7445     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7446     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7447   }
7448
7449   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7450                                 DAG.getConstant(VTBits, MVT::i8));
7451   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7452                              AndNode, DAG.getConstant(0, MVT::i8));
7453
7454   SDValue Hi, Lo;
7455   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7456   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7457   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7458
7459   if (Op.getOpcode() == ISD::SHL_PARTS) {
7460     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7461     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7462   } else {
7463     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7464     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7465   }
7466
7467   SDValue Ops[2] = { Lo, Hi };
7468   return DAG.getMergeValues(Ops, 2, dl);
7469 }
7470
7471 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7472                                            SelectionDAG &DAG) const {
7473   EVT SrcVT = Op.getOperand(0).getValueType();
7474
7475   if (SrcVT.isVector())
7476     return SDValue();
7477
7478   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7479          "Unknown SINT_TO_FP to lower!");
7480
7481   // These are really Legal; return the operand so the caller accepts it as
7482   // Legal.
7483   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7484     return Op;
7485   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7486       Subtarget->is64Bit()) {
7487     return Op;
7488   }
7489
7490   DebugLoc dl = Op.getDebugLoc();
7491   unsigned Size = SrcVT.getSizeInBits()/8;
7492   MachineFunction &MF = DAG.getMachineFunction();
7493   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7494   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7495   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7496                                StackSlot,
7497                                MachinePointerInfo::getFixedStack(SSFI),
7498                                false, false, 0);
7499   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7500 }
7501
7502 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7503                                      SDValue StackSlot,
7504                                      SelectionDAG &DAG) const {
7505   // Build the FILD
7506   DebugLoc DL = Op.getDebugLoc();
7507   SDVTList Tys;
7508   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7509   if (useSSE)
7510     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7511   else
7512     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7513
7514   unsigned ByteSize = SrcVT.getSizeInBits()/8;
7515
7516   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7517   MachineMemOperand *MMO;
7518   if (FI) {
7519     int SSFI = FI->getIndex();
7520     MMO =
7521       DAG.getMachineFunction()
7522       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7523                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
7524   } else {
7525     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7526     StackSlot = StackSlot.getOperand(1);
7527   }
7528   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7529   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7530                                            X86ISD::FILD, DL,
7531                                            Tys, Ops, array_lengthof(Ops),
7532                                            SrcVT, MMO);
7533
7534   if (useSSE) {
7535     Chain = Result.getValue(1);
7536     SDValue InFlag = Result.getValue(2);
7537
7538     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7539     // shouldn't be necessary except that RFP cannot be live across
7540     // multiple blocks. When stackifier is fixed, they can be uncoupled.
7541     MachineFunction &MF = DAG.getMachineFunction();
7542     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7543     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7544     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7545     Tys = DAG.getVTList(MVT::Other);
7546     SDValue Ops[] = {
7547       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7548     };
7549     MachineMemOperand *MMO =
7550       DAG.getMachineFunction()
7551       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7552                             MachineMemOperand::MOStore, SSFISize, SSFISize);
7553
7554     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7555                                     Ops, array_lengthof(Ops),
7556                                     Op.getValueType(), MMO);
7557     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7558                          MachinePointerInfo::getFixedStack(SSFI),
7559                          false, false, false, 0);
7560   }
7561
7562   return Result;
7563 }
7564
7565 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7566 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7567                                                SelectionDAG &DAG) const {
7568   // This algorithm is not obvious. Here it is in C code, more or less:
7569   /*
7570     double uint64_to_double( uint32_t hi, uint32_t lo ) {
7571       static const __m128i exp = { 0x4330000045300000ULL, 0 };
7572       static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
7573
7574       // Copy ints to xmm registers.
7575       __m128i xh = _mm_cvtsi32_si128( hi );
7576       __m128i xl = _mm_cvtsi32_si128( lo );
7577
7578       // Combine into low half of a single xmm register.
7579       __m128i x = _mm_unpacklo_epi32( xh, xl );
7580       __m128d d;
7581       double sd;
7582
7583       // Merge in appropriate exponents to give the integer bits the right
7584       // magnitude.
7585       x = _mm_unpacklo_epi32( x, exp );
7586
7587       // Subtract away the biases to deal with the IEEE-754 double precision
7588       // implicit 1.
7589       d = _mm_sub_pd( (__m128d) x, bias );
7590
7591       // All conversions up to here are exact. The correctly rounded result is
7592       // calculated using the current rounding mode using the following
7593       // horizontal add.
7594       d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
7595       _mm_store_sd( &sd, d );   // Because we are returning doubles in XMM, this
7596                                 // store doesn't really need to be here (except
7597                                 // maybe to zero the other double)
7598       return sd;
7599     }
7600   */
7601
7602   DebugLoc dl = Op.getDebugLoc();
7603   LLVMContext *Context = DAG.getContext();
7604
7605   // Build some magic constants.
7606   SmallVector<Constant*,4> CV0;
7607   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
7608   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
7609   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7610   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7611   Constant *C0 = ConstantVector::get(CV0);
7612   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7613
7614   SmallVector<Constant*,2> CV1;
7615   CV1.push_back(
7616     ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7617   CV1.push_back(
7618     ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7619   Constant *C1 = ConstantVector::get(CV1);
7620   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7621
7622   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7623                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7624                                         Op.getOperand(0),
7625                                         DAG.getIntPtrConstant(1)));
7626   SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7627                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7628                                         Op.getOperand(0),
7629                                         DAG.getIntPtrConstant(0)));
7630   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
7631   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7632                               MachinePointerInfo::getConstantPool(),
7633                               false, false, false, 16);
7634   SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
7635   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
7636   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7637                               MachinePointerInfo::getConstantPool(),
7638                               false, false, false, 16);
7639   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7640
7641   // Add the halves; easiest way is to swap them into another reg first.
7642   int ShufMask[2] = { 1, -1 };
7643   SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
7644                                       DAG.getUNDEF(MVT::v2f64), ShufMask);
7645   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
7646   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
7647                      DAG.getIntPtrConstant(0));
7648 }
7649
7650 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7651 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7652                                                SelectionDAG &DAG) const {
7653   DebugLoc dl = Op.getDebugLoc();
7654   // FP constant to bias correct the final result.
7655   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7656                                    MVT::f64);
7657
7658   // Load the 32-bit value into an XMM register.
7659   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7660                              Op.getOperand(0));
7661
7662   // Zero out the upper parts of the register.
7663   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget->hasXMMInt(),
7664                                      DAG);
7665
7666   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7667                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7668                      DAG.getIntPtrConstant(0));
7669
7670   // Or the load with the bias.
7671   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7672                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7673                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7674                                                    MVT::v2f64, Load)),
7675                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7676                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7677                                                    MVT::v2f64, Bias)));
7678   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7679                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7680                    DAG.getIntPtrConstant(0));
7681
7682   // Subtract the bias.
7683   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7684
7685   // Handle final rounding.
7686   EVT DestVT = Op.getValueType();
7687
7688   if (DestVT.bitsLT(MVT::f64)) {
7689     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7690                        DAG.getIntPtrConstant(0));
7691   } else if (DestVT.bitsGT(MVT::f64)) {
7692     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7693   }
7694
7695   // Handle final rounding.
7696   return Sub;
7697 }
7698
7699 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7700                                            SelectionDAG &DAG) const {
7701   SDValue N0 = Op.getOperand(0);
7702   DebugLoc dl = Op.getDebugLoc();
7703
7704   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
7705   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
7706   // the optimization here.
7707   if (DAG.SignBitIsZero(N0))
7708     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
7709
7710   EVT SrcVT = N0.getValueType();
7711   EVT DstVT = Op.getValueType();
7712   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
7713     return LowerUINT_TO_FP_i64(Op, DAG);
7714   else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
7715     return LowerUINT_TO_FP_i32(Op, DAG);
7716
7717   // Make a 64-bit buffer, and use it to build an FILD.
7718   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
7719   if (SrcVT == MVT::i32) {
7720     SDValue WordOff = DAG.getConstant(4, getPointerTy());
7721     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
7722                                      getPointerTy(), StackSlot, WordOff);
7723     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7724                                   StackSlot, MachinePointerInfo(),
7725                                   false, false, 0);
7726     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
7727                                   OffsetSlot, MachinePointerInfo(),
7728                                   false, false, 0);
7729     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
7730     return Fild;
7731   }
7732
7733   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
7734   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7735                                 StackSlot, MachinePointerInfo(),
7736                                false, false, 0);
7737   // For i64 source, we need to add the appropriate power of 2 if the input
7738   // was negative.  This is the same as the optimization in
7739   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
7740   // we must be careful to do the computation in x87 extended precision, not
7741   // in SSE. (The generic code can't know it's OK to do this, or how to.)
7742   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
7743   MachineMemOperand *MMO =
7744     DAG.getMachineFunction()
7745     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7746                           MachineMemOperand::MOLoad, 8, 8);
7747
7748   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
7749   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
7750   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
7751                                          MVT::i64, MMO);
7752
7753   APInt FF(32, 0x5F800000ULL);
7754
7755   // Check whether the sign bit is set.
7756   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
7757                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
7758                                  ISD::SETLT);
7759
7760   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
7761   SDValue FudgePtr = DAG.getConstantPool(
7762                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
7763                                          getPointerTy());
7764
7765   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
7766   SDValue Zero = DAG.getIntPtrConstant(0);
7767   SDValue Four = DAG.getIntPtrConstant(4);
7768   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
7769                                Zero, Four);
7770   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
7771
7772   // Load the value out, extending it from f32 to f80.
7773   // FIXME: Avoid the extend by constructing the right constant pool?
7774   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
7775                                  FudgePtr, MachinePointerInfo::getConstantPool(),
7776                                  MVT::f32, false, false, 4);
7777   // Extend everything to 80 bits to force it to be done on x87.
7778   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
7779   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
7780 }
7781
7782 std::pair<SDValue,SDValue> X86TargetLowering::
7783 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
7784   DebugLoc DL = Op.getDebugLoc();
7785
7786   EVT DstTy = Op.getValueType();
7787
7788   if (!IsSigned) {
7789     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
7790     DstTy = MVT::i64;
7791   }
7792
7793   assert(DstTy.getSimpleVT() <= MVT::i64 &&
7794          DstTy.getSimpleVT() >= MVT::i16 &&
7795          "Unknown FP_TO_SINT to lower!");
7796
7797   // These are really Legal.
7798   if (DstTy == MVT::i32 &&
7799       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7800     return std::make_pair(SDValue(), SDValue());
7801   if (Subtarget->is64Bit() &&
7802       DstTy == MVT::i64 &&
7803       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7804     return std::make_pair(SDValue(), SDValue());
7805
7806   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
7807   // stack slot.
7808   MachineFunction &MF = DAG.getMachineFunction();
7809   unsigned MemSize = DstTy.getSizeInBits()/8;
7810   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7811   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7812
7813
7814
7815   unsigned Opc;
7816   switch (DstTy.getSimpleVT().SimpleTy) {
7817   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
7818   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
7819   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
7820   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
7821   }
7822
7823   SDValue Chain = DAG.getEntryNode();
7824   SDValue Value = Op.getOperand(0);
7825   EVT TheVT = Op.getOperand(0).getValueType();
7826   if (isScalarFPTypeInSSEReg(TheVT)) {
7827     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
7828     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
7829                          MachinePointerInfo::getFixedStack(SSFI),
7830                          false, false, 0);
7831     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
7832     SDValue Ops[] = {
7833       Chain, StackSlot, DAG.getValueType(TheVT)
7834     };
7835
7836     MachineMemOperand *MMO =
7837       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7838                               MachineMemOperand::MOLoad, MemSize, MemSize);
7839     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
7840                                     DstTy, MMO);
7841     Chain = Value.getValue(1);
7842     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7843     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7844   }
7845
7846   MachineMemOperand *MMO =
7847     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7848                             MachineMemOperand::MOStore, MemSize, MemSize);
7849
7850   // Build the FP_TO_INT*_IN_MEM
7851   SDValue Ops[] = { Chain, Value, StackSlot };
7852   SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
7853                                          Ops, 3, DstTy, MMO);
7854
7855   return std::make_pair(FIST, StackSlot);
7856 }
7857
7858 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
7859                                            SelectionDAG &DAG) const {
7860   if (Op.getValueType().isVector())
7861     return SDValue();
7862
7863   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
7864   SDValue FIST = Vals.first, StackSlot = Vals.second;
7865   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
7866   if (FIST.getNode() == 0) return Op;
7867
7868   // Load the result.
7869   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7870                      FIST, StackSlot, MachinePointerInfo(),
7871                      false, false, false, 0);
7872 }
7873
7874 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
7875                                            SelectionDAG &DAG) const {
7876   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
7877   SDValue FIST = Vals.first, StackSlot = Vals.second;
7878   assert(FIST.getNode() && "Unexpected failure");
7879
7880   // Load the result.
7881   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7882                      FIST, StackSlot, MachinePointerInfo(),
7883                      false, false, false, 0);
7884 }
7885
7886 SDValue X86TargetLowering::LowerFABS(SDValue Op,
7887                                      SelectionDAG &DAG) const {
7888   LLVMContext *Context = DAG.getContext();
7889   DebugLoc dl = Op.getDebugLoc();
7890   EVT VT = Op.getValueType();
7891   EVT EltVT = VT;
7892   if (VT.isVector())
7893     EltVT = VT.getVectorElementType();
7894   SmallVector<Constant*,4> CV;
7895   if (EltVT == MVT::f64) {
7896     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
7897     CV.assign(2, C);
7898   } else {
7899     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
7900     CV.assign(4, C);
7901   }
7902   Constant *C = ConstantVector::get(CV);
7903   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7904   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7905                              MachinePointerInfo::getConstantPool(),
7906                              false, false, false, 16);
7907   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
7908 }
7909
7910 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
7911   LLVMContext *Context = DAG.getContext();
7912   DebugLoc dl = Op.getDebugLoc();
7913   EVT VT = Op.getValueType();
7914   EVT EltVT = VT;
7915   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
7916   if (VT.isVector()) {
7917     EltVT = VT.getVectorElementType();
7918     NumElts = VT.getVectorNumElements();
7919   }
7920   SmallVector<Constant*,8> CV;
7921   if (EltVT == MVT::f64) {
7922     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
7923     CV.assign(NumElts, C);
7924   } else {
7925     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
7926     CV.assign(NumElts, C);
7927   }
7928   Constant *C = ConstantVector::get(CV);
7929   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7930   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7931                              MachinePointerInfo::getConstantPool(),
7932                              false, false, false, 16);
7933   if (VT.isVector()) {
7934     MVT XORVT = VT.getSizeInBits() == 128 ? MVT::v2i64 : MVT::v4i64;
7935     return DAG.getNode(ISD::BITCAST, dl, VT,
7936                        DAG.getNode(ISD::XOR, dl, XORVT,
7937                     DAG.getNode(ISD::BITCAST, dl, XORVT,
7938                                 Op.getOperand(0)),
7939                     DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
7940   } else {
7941     return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
7942   }
7943 }
7944
7945 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
7946   LLVMContext *Context = DAG.getContext();
7947   SDValue Op0 = Op.getOperand(0);
7948   SDValue Op1 = Op.getOperand(1);
7949   DebugLoc dl = Op.getDebugLoc();
7950   EVT VT = Op.getValueType();
7951   EVT SrcVT = Op1.getValueType();
7952
7953   // If second operand is smaller, extend it first.
7954   if (SrcVT.bitsLT(VT)) {
7955     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
7956     SrcVT = VT;
7957   }
7958   // And if it is bigger, shrink it first.
7959   if (SrcVT.bitsGT(VT)) {
7960     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
7961     SrcVT = VT;
7962   }
7963
7964   // At this point the operands and the result should have the same
7965   // type, and that won't be f80 since that is not custom lowered.
7966
7967   // First get the sign bit of second operand.
7968   SmallVector<Constant*,4> CV;
7969   if (SrcVT == MVT::f64) {
7970     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
7971     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7972   } else {
7973     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
7974     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7975     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7976     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7977   }
7978   Constant *C = ConstantVector::get(CV);
7979   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7980   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
7981                               MachinePointerInfo::getConstantPool(),
7982                               false, false, false, 16);
7983   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
7984
7985   // Shift sign bit right or left if the two operands have different types.
7986   if (SrcVT.bitsGT(VT)) {
7987     // Op0 is MVT::f32, Op1 is MVT::f64.
7988     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
7989     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
7990                           DAG.getConstant(32, MVT::i32));
7991     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
7992     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
7993                           DAG.getIntPtrConstant(0));
7994   }
7995
7996   // Clear first operand sign bit.
7997   CV.clear();
7998   if (VT == MVT::f64) {
7999     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8000     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8001   } else {
8002     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8003     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8004     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8005     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8006   }
8007   C = ConstantVector::get(CV);
8008   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8009   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8010                               MachinePointerInfo::getConstantPool(),
8011                               false, false, false, 16);
8012   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8013
8014   // Or the value with the sign bit.
8015   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8016 }
8017
8018 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
8019   SDValue N0 = Op.getOperand(0);
8020   DebugLoc dl = Op.getDebugLoc();
8021   EVT VT = Op.getValueType();
8022
8023   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8024   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8025                                   DAG.getConstant(1, VT));
8026   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8027 }
8028
8029 /// Emit nodes that will be selected as "test Op0,Op0", or something
8030 /// equivalent.
8031 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8032                                     SelectionDAG &DAG) const {
8033   DebugLoc dl = Op.getDebugLoc();
8034
8035   // CF and OF aren't always set the way we want. Determine which
8036   // of these we need.
8037   bool NeedCF = false;
8038   bool NeedOF = false;
8039   switch (X86CC) {
8040   default: break;
8041   case X86::COND_A: case X86::COND_AE:
8042   case X86::COND_B: case X86::COND_BE:
8043     NeedCF = true;
8044     break;
8045   case X86::COND_G: case X86::COND_GE:
8046   case X86::COND_L: case X86::COND_LE:
8047   case X86::COND_O: case X86::COND_NO:
8048     NeedOF = true;
8049     break;
8050   }
8051
8052   // See if we can use the EFLAGS value from the operand instead of
8053   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8054   // we prove that the arithmetic won't overflow, we can't use OF or CF.
8055   if (Op.getResNo() != 0 || NeedOF || NeedCF)
8056     // Emit a CMP with 0, which is the TEST pattern.
8057     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8058                        DAG.getConstant(0, Op.getValueType()));
8059
8060   unsigned Opcode = 0;
8061   unsigned NumOperands = 0;
8062   switch (Op.getNode()->getOpcode()) {
8063   case ISD::ADD:
8064     // Due to an isel shortcoming, be conservative if this add is likely to be
8065     // selected as part of a load-modify-store instruction. When the root node
8066     // in a match is a store, isel doesn't know how to remap non-chain non-flag
8067     // uses of other nodes in the match, such as the ADD in this case. This
8068     // leads to the ADD being left around and reselected, with the result being
8069     // two adds in the output.  Alas, even if none our users are stores, that
8070     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
8071     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
8072     // climbing the DAG back to the root, and it doesn't seem to be worth the
8073     // effort.
8074     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8075          UE = Op.getNode()->use_end(); UI != UE; ++UI)
8076       if (UI->getOpcode() != ISD::CopyToReg &&
8077           UI->getOpcode() != ISD::SETCC &&
8078           UI->getOpcode() != ISD::STORE)
8079         goto default_case;
8080
8081     if (ConstantSDNode *C =
8082         dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
8083       // An add of one will be selected as an INC.
8084       if (C->getAPIntValue() == 1) {
8085         Opcode = X86ISD::INC;
8086         NumOperands = 1;
8087         break;
8088       }
8089
8090       // An add of negative one (subtract of one) will be selected as a DEC.
8091       if (C->getAPIntValue().isAllOnesValue()) {
8092         Opcode = X86ISD::DEC;
8093         NumOperands = 1;
8094         break;
8095       }
8096     }
8097
8098     // Otherwise use a regular EFLAGS-setting add.
8099     Opcode = X86ISD::ADD;
8100     NumOperands = 2;
8101     break;
8102   case ISD::AND: {
8103     // If the primary and result isn't used, don't bother using X86ISD::AND,
8104     // because a TEST instruction will be better.
8105     bool NonFlagUse = false;
8106     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8107            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8108       SDNode *User = *UI;
8109       unsigned UOpNo = UI.getOperandNo();
8110       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8111         // Look pass truncate.
8112         UOpNo = User->use_begin().getOperandNo();
8113         User = *User->use_begin();
8114       }
8115
8116       if (User->getOpcode() != ISD::BRCOND &&
8117           User->getOpcode() != ISD::SETCC &&
8118           (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
8119         NonFlagUse = true;
8120         break;
8121       }
8122     }
8123
8124     if (!NonFlagUse)
8125       break;
8126   }
8127     // FALL THROUGH
8128   case ISD::SUB:
8129   case ISD::OR:
8130   case ISD::XOR:
8131     // Due to the ISEL shortcoming noted above, be conservative if this op is
8132     // likely to be selected as part of a load-modify-store instruction.
8133     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8134            UE = Op.getNode()->use_end(); UI != UE; ++UI)
8135       if (UI->getOpcode() == ISD::STORE)
8136         goto default_case;
8137
8138     // Otherwise use a regular EFLAGS-setting instruction.
8139     switch (Op.getNode()->getOpcode()) {
8140     default: llvm_unreachable("unexpected operator!");
8141     case ISD::SUB: Opcode = X86ISD::SUB; break;
8142     case ISD::OR:  Opcode = X86ISD::OR;  break;
8143     case ISD::XOR: Opcode = X86ISD::XOR; break;
8144     case ISD::AND: Opcode = X86ISD::AND; break;
8145     }
8146
8147     NumOperands = 2;
8148     break;
8149   case X86ISD::ADD:
8150   case X86ISD::SUB:
8151   case X86ISD::INC:
8152   case X86ISD::DEC:
8153   case X86ISD::OR:
8154   case X86ISD::XOR:
8155   case X86ISD::AND:
8156     return SDValue(Op.getNode(), 1);
8157   default:
8158   default_case:
8159     break;
8160   }
8161
8162   if (Opcode == 0)
8163     // Emit a CMP with 0, which is the TEST pattern.
8164     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8165                        DAG.getConstant(0, Op.getValueType()));
8166
8167   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8168   SmallVector<SDValue, 4> Ops;
8169   for (unsigned i = 0; i != NumOperands; ++i)
8170     Ops.push_back(Op.getOperand(i));
8171
8172   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8173   DAG.ReplaceAllUsesWith(Op, New);
8174   return SDValue(New.getNode(), 1);
8175 }
8176
8177 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8178 /// equivalent.
8179 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8180                                    SelectionDAG &DAG) const {
8181   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8182     if (C->getAPIntValue() == 0)
8183       return EmitTest(Op0, X86CC, DAG);
8184
8185   DebugLoc dl = Op0.getDebugLoc();
8186   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8187 }
8188
8189 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8190 /// if it's possible.
8191 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8192                                      DebugLoc dl, SelectionDAG &DAG) const {
8193   SDValue Op0 = And.getOperand(0);
8194   SDValue Op1 = And.getOperand(1);
8195   if (Op0.getOpcode() == ISD::TRUNCATE)
8196     Op0 = Op0.getOperand(0);
8197   if (Op1.getOpcode() == ISD::TRUNCATE)
8198     Op1 = Op1.getOperand(0);
8199
8200   SDValue LHS, RHS;
8201   if (Op1.getOpcode() == ISD::SHL)
8202     std::swap(Op0, Op1);
8203   if (Op0.getOpcode() == ISD::SHL) {
8204     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8205       if (And00C->getZExtValue() == 1) {
8206         // If we looked past a truncate, check that it's only truncating away
8207         // known zeros.
8208         unsigned BitWidth = Op0.getValueSizeInBits();
8209         unsigned AndBitWidth = And.getValueSizeInBits();
8210         if (BitWidth > AndBitWidth) {
8211           APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
8212           DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
8213           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8214             return SDValue();
8215         }
8216         LHS = Op1;
8217         RHS = Op0.getOperand(1);
8218       }
8219   } else if (Op1.getOpcode() == ISD::Constant) {
8220     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8221     uint64_t AndRHSVal = AndRHS->getZExtValue();
8222     SDValue AndLHS = Op0;
8223
8224     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
8225       LHS = AndLHS.getOperand(0);
8226       RHS = AndLHS.getOperand(1);
8227     }
8228
8229     // Use BT if the immediate can't be encoded in a TEST instruction.
8230     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
8231       LHS = AndLHS;
8232       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
8233     }
8234   }
8235
8236   if (LHS.getNode()) {
8237     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
8238     // instruction.  Since the shift amount is in-range-or-undefined, we know
8239     // that doing a bittest on the i32 value is ok.  We extend to i32 because
8240     // the encoding for the i16 version is larger than the i32 version.
8241     // Also promote i16 to i32 for performance / code size reason.
8242     if (LHS.getValueType() == MVT::i8 ||
8243         LHS.getValueType() == MVT::i16)
8244       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8245
8246     // If the operand types disagree, extend the shift amount to match.  Since
8247     // BT ignores high bits (like shifts) we can use anyextend.
8248     if (LHS.getValueType() != RHS.getValueType())
8249       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8250
8251     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8252     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8253     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8254                        DAG.getConstant(Cond, MVT::i8), BT);
8255   }
8256
8257   return SDValue();
8258 }
8259
8260 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8261
8262   if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8263
8264   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8265   SDValue Op0 = Op.getOperand(0);
8266   SDValue Op1 = Op.getOperand(1);
8267   DebugLoc dl = Op.getDebugLoc();
8268   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8269
8270   // Optimize to BT if possible.
8271   // Lower (X & (1 << N)) == 0 to BT(X, N).
8272   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8273   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8274   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8275       Op1.getOpcode() == ISD::Constant &&
8276       cast<ConstantSDNode>(Op1)->isNullValue() &&
8277       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8278     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8279     if (NewSetCC.getNode())
8280       return NewSetCC;
8281   }
8282
8283   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
8284   // these.
8285   if (Op1.getOpcode() == ISD::Constant &&
8286       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8287        cast<ConstantSDNode>(Op1)->isNullValue()) &&
8288       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8289
8290     // If the input is a setcc, then reuse the input setcc or use a new one with
8291     // the inverted condition.
8292     if (Op0.getOpcode() == X86ISD::SETCC) {
8293       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8294       bool Invert = (CC == ISD::SETNE) ^
8295         cast<ConstantSDNode>(Op1)->isNullValue();
8296       if (!Invert) return Op0;
8297
8298       CCode = X86::GetOppositeBranchCondition(CCode);
8299       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8300                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8301     }
8302   }
8303
8304   bool isFP = Op1.getValueType().isFloatingPoint();
8305   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8306   if (X86CC == X86::COND_INVALID)
8307     return SDValue();
8308
8309   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8310   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8311                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8312 }
8313
8314 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8315 // ones, and then concatenate the result back.
8316 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
8317   EVT VT = Op.getValueType();
8318
8319   assert(VT.getSizeInBits() == 256 && Op.getOpcode() == ISD::SETCC &&
8320          "Unsupported value type for operation");
8321
8322   int NumElems = VT.getVectorNumElements();
8323   DebugLoc dl = Op.getDebugLoc();
8324   SDValue CC = Op.getOperand(2);
8325   SDValue Idx0 = DAG.getConstant(0, MVT::i32);
8326   SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
8327
8328   // Extract the LHS vectors
8329   SDValue LHS = Op.getOperand(0);
8330   SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
8331   SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
8332
8333   // Extract the RHS vectors
8334   SDValue RHS = Op.getOperand(1);
8335   SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl);
8336   SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl);
8337
8338   // Issue the operation on the smaller types and concatenate the result back
8339   MVT EltVT = VT.getVectorElementType().getSimpleVT();
8340   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8341   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8342                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8343                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8344 }
8345
8346
8347 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8348   SDValue Cond;
8349   SDValue Op0 = Op.getOperand(0);
8350   SDValue Op1 = Op.getOperand(1);
8351   SDValue CC = Op.getOperand(2);
8352   EVT VT = Op.getValueType();
8353   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8354   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8355   DebugLoc dl = Op.getDebugLoc();
8356
8357   if (isFP) {
8358     unsigned SSECC = 8;
8359     EVT EltVT = Op0.getValueType().getVectorElementType();
8360     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
8361
8362     unsigned Opc = EltVT == MVT::f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
8363     bool Swap = false;
8364
8365     // SSE Condition code mapping:
8366     //  0 - EQ
8367     //  1 - LT
8368     //  2 - LE
8369     //  3 - UNORD
8370     //  4 - NEQ
8371     //  5 - NLT
8372     //  6 - NLE
8373     //  7 - ORD
8374     switch (SetCCOpcode) {
8375     default: break;
8376     case ISD::SETOEQ:
8377     case ISD::SETEQ:  SSECC = 0; break;
8378     case ISD::SETOGT:
8379     case ISD::SETGT: Swap = true; // Fallthrough
8380     case ISD::SETLT:
8381     case ISD::SETOLT: SSECC = 1; break;
8382     case ISD::SETOGE:
8383     case ISD::SETGE: Swap = true; // Fallthrough
8384     case ISD::SETLE:
8385     case ISD::SETOLE: SSECC = 2; break;
8386     case ISD::SETUO:  SSECC = 3; break;
8387     case ISD::SETUNE:
8388     case ISD::SETNE:  SSECC = 4; break;
8389     case ISD::SETULE: Swap = true;
8390     case ISD::SETUGE: SSECC = 5; break;
8391     case ISD::SETULT: Swap = true;
8392     case ISD::SETUGT: SSECC = 6; break;
8393     case ISD::SETO:   SSECC = 7; break;
8394     }
8395     if (Swap)
8396       std::swap(Op0, Op1);
8397
8398     // In the two special cases we can't handle, emit two comparisons.
8399     if (SSECC == 8) {
8400       if (SetCCOpcode == ISD::SETUEQ) {
8401         SDValue UNORD, EQ;
8402         UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
8403         EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
8404         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
8405       } else if (SetCCOpcode == ISD::SETONE) {
8406         SDValue ORD, NEQ;
8407         ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
8408         NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
8409         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
8410       }
8411       llvm_unreachable("Illegal FP comparison");
8412     }
8413     // Handle all other FP comparisons here.
8414     return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
8415   }
8416
8417   // Break 256-bit integer vector compare into smaller ones.
8418   if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2())
8419     return Lower256IntVSETCC(Op, DAG);
8420
8421   // We are handling one of the integer comparisons here.  Since SSE only has
8422   // GT and EQ comparisons for integer, swapping operands and multiple
8423   // operations may be required for some comparisons.
8424   unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
8425   bool Swap = false, Invert = false, FlipSigns = false;
8426
8427   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
8428   default: break;
8429   case MVT::i8:   EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
8430   case MVT::i16:  EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
8431   case MVT::i32:  EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
8432   case MVT::i64:  EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
8433   }
8434
8435   switch (SetCCOpcode) {
8436   default: break;
8437   case ISD::SETNE:  Invert = true;
8438   case ISD::SETEQ:  Opc = EQOpc; break;
8439   case ISD::SETLT:  Swap = true;
8440   case ISD::SETGT:  Opc = GTOpc; break;
8441   case ISD::SETGE:  Swap = true;
8442   case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
8443   case ISD::SETULT: Swap = true;
8444   case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
8445   case ISD::SETUGE: Swap = true;
8446   case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
8447   }
8448   if (Swap)
8449     std::swap(Op0, Op1);
8450
8451   // Check that the operation in question is available (most are plain SSE2,
8452   // but PCMPGTQ and PCMPEQQ have different requirements).
8453   if (Opc == X86ISD::PCMPGTQ && !Subtarget->hasSSE42orAVX())
8454     return SDValue();
8455   if (Opc == X86ISD::PCMPEQQ && !Subtarget->hasSSE41orAVX())
8456     return SDValue();
8457
8458   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
8459   // bits of the inputs before performing those operations.
8460   if (FlipSigns) {
8461     EVT EltVT = VT.getVectorElementType();
8462     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
8463                                       EltVT);
8464     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
8465     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
8466                                     SignBits.size());
8467     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
8468     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
8469   }
8470
8471   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
8472
8473   // If the logical-not of the result is required, perform that now.
8474   if (Invert)
8475     Result = DAG.getNOT(dl, Result, VT);
8476
8477   return Result;
8478 }
8479
8480 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
8481 static bool isX86LogicalCmp(SDValue Op) {
8482   unsigned Opc = Op.getNode()->getOpcode();
8483   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
8484     return true;
8485   if (Op.getResNo() == 1 &&
8486       (Opc == X86ISD::ADD ||
8487        Opc == X86ISD::SUB ||
8488        Opc == X86ISD::ADC ||
8489        Opc == X86ISD::SBB ||
8490        Opc == X86ISD::SMUL ||
8491        Opc == X86ISD::UMUL ||
8492        Opc == X86ISD::INC ||
8493        Opc == X86ISD::DEC ||
8494        Opc == X86ISD::OR ||
8495        Opc == X86ISD::XOR ||
8496        Opc == X86ISD::AND))
8497     return true;
8498
8499   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
8500     return true;
8501
8502   return false;
8503 }
8504
8505 static bool isZero(SDValue V) {
8506   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8507   return C && C->isNullValue();
8508 }
8509
8510 static bool isAllOnes(SDValue V) {
8511   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8512   return C && C->isAllOnesValue();
8513 }
8514
8515 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8516   bool addTest = true;
8517   SDValue Cond  = Op.getOperand(0);
8518   SDValue Op1 = Op.getOperand(1);
8519   SDValue Op2 = Op.getOperand(2);
8520   DebugLoc DL = Op.getDebugLoc();
8521   SDValue CC;
8522
8523   if (Cond.getOpcode() == ISD::SETCC) {
8524     SDValue NewCond = LowerSETCC(Cond, DAG);
8525     if (NewCond.getNode())
8526       Cond = NewCond;
8527   }
8528
8529   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
8530   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
8531   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
8532   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
8533   if (Cond.getOpcode() == X86ISD::SETCC &&
8534       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
8535       isZero(Cond.getOperand(1).getOperand(1))) {
8536     SDValue Cmp = Cond.getOperand(1);
8537
8538     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
8539
8540     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
8541         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
8542       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
8543
8544       SDValue CmpOp0 = Cmp.getOperand(0);
8545       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
8546                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
8547
8548       SDValue Res =   // Res = 0 or -1.
8549         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8550                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
8551
8552       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
8553         Res = DAG.getNOT(DL, Res, Res.getValueType());
8554
8555       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
8556       if (N2C == 0 || !N2C->isNullValue())
8557         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
8558       return Res;
8559     }
8560   }
8561
8562   // Look past (and (setcc_carry (cmp ...)), 1).
8563   if (Cond.getOpcode() == ISD::AND &&
8564       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8565     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8566     if (C && C->getAPIntValue() == 1)
8567       Cond = Cond.getOperand(0);
8568   }
8569
8570   // If condition flag is set by a X86ISD::CMP, then use it as the condition
8571   // setting operand in place of the X86ISD::SETCC.
8572   unsigned CondOpcode = Cond.getOpcode();
8573   if (CondOpcode == X86ISD::SETCC ||
8574       CondOpcode == X86ISD::SETCC_CARRY) {
8575     CC = Cond.getOperand(0);
8576
8577     SDValue Cmp = Cond.getOperand(1);
8578     unsigned Opc = Cmp.getOpcode();
8579     EVT VT = Op.getValueType();
8580
8581     bool IllegalFPCMov = false;
8582     if (VT.isFloatingPoint() && !VT.isVector() &&
8583         !isScalarFPTypeInSSEReg(VT))  // FPStack?
8584       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
8585
8586     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
8587         Opc == X86ISD::BT) { // FIXME
8588       Cond = Cmp;
8589       addTest = false;
8590     }
8591   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
8592              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
8593              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
8594               Cond.getOperand(0).getValueType() != MVT::i8)) {
8595     SDValue LHS = Cond.getOperand(0);
8596     SDValue RHS = Cond.getOperand(1);
8597     unsigned X86Opcode;
8598     unsigned X86Cond;
8599     SDVTList VTs;
8600     switch (CondOpcode) {
8601     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
8602     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
8603     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
8604     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
8605     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
8606     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
8607     default: llvm_unreachable("unexpected overflowing operator");
8608     }
8609     if (CondOpcode == ISD::UMULO)
8610       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
8611                           MVT::i32);
8612     else
8613       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
8614
8615     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
8616
8617     if (CondOpcode == ISD::UMULO)
8618       Cond = X86Op.getValue(2);
8619     else
8620       Cond = X86Op.getValue(1);
8621
8622     CC = DAG.getConstant(X86Cond, MVT::i8);
8623     addTest = false;
8624   }
8625
8626   if (addTest) {
8627     // Look pass the truncate.
8628     if (Cond.getOpcode() == ISD::TRUNCATE)
8629       Cond = Cond.getOperand(0);
8630
8631     // We know the result of AND is compared against zero. Try to match
8632     // it to BT.
8633     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8634       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
8635       if (NewSetCC.getNode()) {
8636         CC = NewSetCC.getOperand(0);
8637         Cond = NewSetCC.getOperand(1);
8638         addTest = false;
8639       }
8640     }
8641   }
8642
8643   if (addTest) {
8644     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8645     Cond = EmitTest(Cond, X86::COND_NE, DAG);
8646   }
8647
8648   // a <  b ? -1 :  0 -> RES = ~setcc_carry
8649   // a <  b ?  0 : -1 -> RES = setcc_carry
8650   // a >= b ? -1 :  0 -> RES = setcc_carry
8651   // a >= b ?  0 : -1 -> RES = ~setcc_carry
8652   if (Cond.getOpcode() == X86ISD::CMP) {
8653     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
8654
8655     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
8656         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
8657       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8658                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
8659       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
8660         return DAG.getNOT(DL, Res, Res.getValueType());
8661       return Res;
8662     }
8663   }
8664
8665   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
8666   // condition is true.
8667   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
8668   SDValue Ops[] = { Op2, Op1, CC, Cond };
8669   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
8670 }
8671
8672 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
8673 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
8674 // from the AND / OR.
8675 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
8676   Opc = Op.getOpcode();
8677   if (Opc != ISD::OR && Opc != ISD::AND)
8678     return false;
8679   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8680           Op.getOperand(0).hasOneUse() &&
8681           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
8682           Op.getOperand(1).hasOneUse());
8683 }
8684
8685 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
8686 // 1 and that the SETCC node has a single use.
8687 static bool isXor1OfSetCC(SDValue Op) {
8688   if (Op.getOpcode() != ISD::XOR)
8689     return false;
8690   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8691   if (N1C && N1C->getAPIntValue() == 1) {
8692     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8693       Op.getOperand(0).hasOneUse();
8694   }
8695   return false;
8696 }
8697
8698 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
8699   bool addTest = true;
8700   SDValue Chain = Op.getOperand(0);
8701   SDValue Cond  = Op.getOperand(1);
8702   SDValue Dest  = Op.getOperand(2);
8703   DebugLoc dl = Op.getDebugLoc();
8704   SDValue CC;
8705   bool Inverted = false;
8706
8707   if (Cond.getOpcode() == ISD::SETCC) {
8708     // Check for setcc([su]{add,sub,mul}o == 0).
8709     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
8710         isa<ConstantSDNode>(Cond.getOperand(1)) &&
8711         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
8712         Cond.getOperand(0).getResNo() == 1 &&
8713         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
8714          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
8715          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
8716          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
8717          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
8718          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
8719       Inverted = true;
8720       Cond = Cond.getOperand(0);
8721     } else {
8722       SDValue NewCond = LowerSETCC(Cond, DAG);
8723       if (NewCond.getNode())
8724         Cond = NewCond;
8725     }
8726   }
8727 #if 0
8728   // FIXME: LowerXALUO doesn't handle these!!
8729   else if (Cond.getOpcode() == X86ISD::ADD  ||
8730            Cond.getOpcode() == X86ISD::SUB  ||
8731            Cond.getOpcode() == X86ISD::SMUL ||
8732            Cond.getOpcode() == X86ISD::UMUL)
8733     Cond = LowerXALUO(Cond, DAG);
8734 #endif
8735
8736   // Look pass (and (setcc_carry (cmp ...)), 1).
8737   if (Cond.getOpcode() == ISD::AND &&
8738       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8739     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8740     if (C && C->getAPIntValue() == 1)
8741       Cond = Cond.getOperand(0);
8742   }
8743
8744   // If condition flag is set by a X86ISD::CMP, then use it as the condition
8745   // setting operand in place of the X86ISD::SETCC.
8746   unsigned CondOpcode = Cond.getOpcode();
8747   if (CondOpcode == X86ISD::SETCC ||
8748       CondOpcode == X86ISD::SETCC_CARRY) {
8749     CC = Cond.getOperand(0);
8750
8751     SDValue Cmp = Cond.getOperand(1);
8752     unsigned Opc = Cmp.getOpcode();
8753     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
8754     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
8755       Cond = Cmp;
8756       addTest = false;
8757     } else {
8758       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
8759       default: break;
8760       case X86::COND_O:
8761       case X86::COND_B:
8762         // These can only come from an arithmetic instruction with overflow,
8763         // e.g. SADDO, UADDO.
8764         Cond = Cond.getNode()->getOperand(1);
8765         addTest = false;
8766         break;
8767       }
8768     }
8769   }
8770   CondOpcode = Cond.getOpcode();
8771   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
8772       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
8773       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
8774        Cond.getOperand(0).getValueType() != MVT::i8)) {
8775     SDValue LHS = Cond.getOperand(0);
8776     SDValue RHS = Cond.getOperand(1);
8777     unsigned X86Opcode;
8778     unsigned X86Cond;
8779     SDVTList VTs;
8780     switch (CondOpcode) {
8781     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
8782     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
8783     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
8784     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
8785     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
8786     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
8787     default: llvm_unreachable("unexpected overflowing operator");
8788     }
8789     if (Inverted)
8790       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
8791     if (CondOpcode == ISD::UMULO)
8792       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
8793                           MVT::i32);
8794     else
8795       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
8796
8797     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
8798
8799     if (CondOpcode == ISD::UMULO)
8800       Cond = X86Op.getValue(2);
8801     else
8802       Cond = X86Op.getValue(1);
8803
8804     CC = DAG.getConstant(X86Cond, MVT::i8);
8805     addTest = false;
8806   } else {
8807     unsigned CondOpc;
8808     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
8809       SDValue Cmp = Cond.getOperand(0).getOperand(1);
8810       if (CondOpc == ISD::OR) {
8811         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
8812         // two branches instead of an explicit OR instruction with a
8813         // separate test.
8814         if (Cmp == Cond.getOperand(1).getOperand(1) &&
8815             isX86LogicalCmp(Cmp)) {
8816           CC = Cond.getOperand(0).getOperand(0);
8817           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8818                               Chain, Dest, CC, Cmp);
8819           CC = Cond.getOperand(1).getOperand(0);
8820           Cond = Cmp;
8821           addTest = false;
8822         }
8823       } else { // ISD::AND
8824         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
8825         // two branches instead of an explicit AND instruction with a
8826         // separate test. However, we only do this if this block doesn't
8827         // have a fall-through edge, because this requires an explicit
8828         // jmp when the condition is false.
8829         if (Cmp == Cond.getOperand(1).getOperand(1) &&
8830             isX86LogicalCmp(Cmp) &&
8831             Op.getNode()->hasOneUse()) {
8832           X86::CondCode CCode =
8833             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
8834           CCode = X86::GetOppositeBranchCondition(CCode);
8835           CC = DAG.getConstant(CCode, MVT::i8);
8836           SDNode *User = *Op.getNode()->use_begin();
8837           // Look for an unconditional branch following this conditional branch.
8838           // We need this because we need to reverse the successors in order
8839           // to implement FCMP_OEQ.
8840           if (User->getOpcode() == ISD::BR) {
8841             SDValue FalseBB = User->getOperand(1);
8842             SDNode *NewBR =
8843               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
8844             assert(NewBR == User);
8845             (void)NewBR;
8846             Dest = FalseBB;
8847
8848             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8849                                 Chain, Dest, CC, Cmp);
8850             X86::CondCode CCode =
8851               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
8852             CCode = X86::GetOppositeBranchCondition(CCode);
8853             CC = DAG.getConstant(CCode, MVT::i8);
8854             Cond = Cmp;
8855             addTest = false;
8856           }
8857         }
8858       }
8859     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
8860       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
8861       // It should be transformed during dag combiner except when the condition
8862       // is set by a arithmetics with overflow node.
8863       X86::CondCode CCode =
8864         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
8865       CCode = X86::GetOppositeBranchCondition(CCode);
8866       CC = DAG.getConstant(CCode, MVT::i8);
8867       Cond = Cond.getOperand(0).getOperand(1);
8868       addTest = false;
8869     } else if (Cond.getOpcode() == ISD::SETCC &&
8870                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
8871       // For FCMP_OEQ, we can emit
8872       // two branches instead of an explicit AND instruction with a
8873       // separate test. However, we only do this if this block doesn't
8874       // have a fall-through edge, because this requires an explicit
8875       // jmp when the condition is false.
8876       if (Op.getNode()->hasOneUse()) {
8877         SDNode *User = *Op.getNode()->use_begin();
8878         // Look for an unconditional branch following this conditional branch.
8879         // We need this because we need to reverse the successors in order
8880         // to implement FCMP_OEQ.
8881         if (User->getOpcode() == ISD::BR) {
8882           SDValue FalseBB = User->getOperand(1);
8883           SDNode *NewBR =
8884             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
8885           assert(NewBR == User);
8886           (void)NewBR;
8887           Dest = FalseBB;
8888
8889           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8890                                     Cond.getOperand(0), Cond.getOperand(1));
8891           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8892           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8893                               Chain, Dest, CC, Cmp);
8894           CC = DAG.getConstant(X86::COND_P, MVT::i8);
8895           Cond = Cmp;
8896           addTest = false;
8897         }
8898       }
8899     } else if (Cond.getOpcode() == ISD::SETCC &&
8900                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
8901       // For FCMP_UNE, we can emit
8902       // two branches instead of an explicit AND instruction with a
8903       // separate test. However, we only do this if this block doesn't
8904       // have a fall-through edge, because this requires an explicit
8905       // jmp when the condition is false.
8906       if (Op.getNode()->hasOneUse()) {
8907         SDNode *User = *Op.getNode()->use_begin();
8908         // Look for an unconditional branch following this conditional branch.
8909         // We need this because we need to reverse the successors in order
8910         // to implement FCMP_UNE.
8911         if (User->getOpcode() == ISD::BR) {
8912           SDValue FalseBB = User->getOperand(1);
8913           SDNode *NewBR =
8914             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
8915           assert(NewBR == User);
8916           (void)NewBR;
8917
8918           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8919                                     Cond.getOperand(0), Cond.getOperand(1));
8920           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8921           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8922                               Chain, Dest, CC, Cmp);
8923           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
8924           Cond = Cmp;
8925           addTest = false;
8926           Dest = FalseBB;
8927         }
8928       }
8929     }
8930   }
8931
8932   if (addTest) {
8933     // Look pass the truncate.
8934     if (Cond.getOpcode() == ISD::TRUNCATE)
8935       Cond = Cond.getOperand(0);
8936
8937     // We know the result of AND is compared against zero. Try to match
8938     // it to BT.
8939     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8940       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
8941       if (NewSetCC.getNode()) {
8942         CC = NewSetCC.getOperand(0);
8943         Cond = NewSetCC.getOperand(1);
8944         addTest = false;
8945       }
8946     }
8947   }
8948
8949   if (addTest) {
8950     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8951     Cond = EmitTest(Cond, X86::COND_NE, DAG);
8952   }
8953   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8954                      Chain, Dest, CC, Cond);
8955 }
8956
8957
8958 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
8959 // Calls to _alloca is needed to probe the stack when allocating more than 4k
8960 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
8961 // that the guard pages used by the OS virtual memory manager are allocated in
8962 // correct sequence.
8963 SDValue
8964 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
8965                                            SelectionDAG &DAG) const {
8966   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
8967           getTargetMachine().Options.EnableSegmentedStacks) &&
8968          "This should be used only on Windows targets or when segmented stacks "
8969          "are being used");
8970   assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
8971   DebugLoc dl = Op.getDebugLoc();
8972
8973   // Get the inputs.
8974   SDValue Chain = Op.getOperand(0);
8975   SDValue Size  = Op.getOperand(1);
8976   // FIXME: Ensure alignment here
8977
8978   bool Is64Bit = Subtarget->is64Bit();
8979   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
8980
8981   if (getTargetMachine().Options.EnableSegmentedStacks) {
8982     MachineFunction &MF = DAG.getMachineFunction();
8983     MachineRegisterInfo &MRI = MF.getRegInfo();
8984
8985     if (Is64Bit) {
8986       // The 64 bit implementation of segmented stacks needs to clobber both r10
8987       // r11. This makes it impossible to use it along with nested parameters.
8988       const Function *F = MF.getFunction();
8989
8990       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
8991            I != E; I++)
8992         if (I->hasNestAttr())
8993           report_fatal_error("Cannot use segmented stacks with functions that "
8994                              "have nested arguments.");
8995     }
8996
8997     const TargetRegisterClass *AddrRegClass =
8998       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
8999     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9000     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9001     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9002                                 DAG.getRegister(Vreg, SPTy));
9003     SDValue Ops1[2] = { Value, Chain };
9004     return DAG.getMergeValues(Ops1, 2, dl);
9005   } else {
9006     SDValue Flag;
9007     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9008
9009     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9010     Flag = Chain.getValue(1);
9011     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9012
9013     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
9014     Flag = Chain.getValue(1);
9015
9016     Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
9017
9018     SDValue Ops1[2] = { Chain.getValue(0), Chain };
9019     return DAG.getMergeValues(Ops1, 2, dl);
9020   }
9021 }
9022
9023 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9024   MachineFunction &MF = DAG.getMachineFunction();
9025   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9026
9027   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9028   DebugLoc DL = Op.getDebugLoc();
9029
9030   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9031     // vastart just stores the address of the VarArgsFrameIndex slot into the
9032     // memory location argument.
9033     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9034                                    getPointerTy());
9035     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9036                         MachinePointerInfo(SV), false, false, 0);
9037   }
9038
9039   // __va_list_tag:
9040   //   gp_offset         (0 - 6 * 8)
9041   //   fp_offset         (48 - 48 + 8 * 16)
9042   //   overflow_arg_area (point to parameters coming in memory).
9043   //   reg_save_area
9044   SmallVector<SDValue, 8> MemOps;
9045   SDValue FIN = Op.getOperand(1);
9046   // Store gp_offset
9047   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9048                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9049                                                MVT::i32),
9050                                FIN, MachinePointerInfo(SV), false, false, 0);
9051   MemOps.push_back(Store);
9052
9053   // Store fp_offset
9054   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9055                     FIN, DAG.getIntPtrConstant(4));
9056   Store = DAG.getStore(Op.getOperand(0), DL,
9057                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9058                                        MVT::i32),
9059                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
9060   MemOps.push_back(Store);
9061
9062   // Store ptr to overflow_arg_area
9063   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9064                     FIN, DAG.getIntPtrConstant(4));
9065   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9066                                     getPointerTy());
9067   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9068                        MachinePointerInfo(SV, 8),
9069                        false, false, 0);
9070   MemOps.push_back(Store);
9071
9072   // Store ptr to reg_save_area.
9073   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9074                     FIN, DAG.getIntPtrConstant(8));
9075   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9076                                     getPointerTy());
9077   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9078                        MachinePointerInfo(SV, 16), false, false, 0);
9079   MemOps.push_back(Store);
9080   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9081                      &MemOps[0], MemOps.size());
9082 }
9083
9084 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9085   assert(Subtarget->is64Bit() &&
9086          "LowerVAARG only handles 64-bit va_arg!");
9087   assert((Subtarget->isTargetLinux() ||
9088           Subtarget->isTargetDarwin()) &&
9089           "Unhandled target in LowerVAARG");
9090   assert(Op.getNode()->getNumOperands() == 4);
9091   SDValue Chain = Op.getOperand(0);
9092   SDValue SrcPtr = Op.getOperand(1);
9093   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9094   unsigned Align = Op.getConstantOperandVal(3);
9095   DebugLoc dl = Op.getDebugLoc();
9096
9097   EVT ArgVT = Op.getNode()->getValueType(0);
9098   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9099   uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
9100   uint8_t ArgMode;
9101
9102   // Decide which area this value should be read from.
9103   // TODO: Implement the AMD64 ABI in its entirety. This simple
9104   // selection mechanism works only for the basic types.
9105   if (ArgVT == MVT::f80) {
9106     llvm_unreachable("va_arg for f80 not yet implemented");
9107   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9108     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
9109   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9110     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
9111   } else {
9112     llvm_unreachable("Unhandled argument type in LowerVAARG");
9113   }
9114
9115   if (ArgMode == 2) {
9116     // Sanity Check: Make sure using fp_offset makes sense.
9117     assert(!getTargetMachine().Options.UseSoftFloat &&
9118            !(DAG.getMachineFunction()
9119                 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
9120            Subtarget->hasXMM());
9121   }
9122
9123   // Insert VAARG_64 node into the DAG
9124   // VAARG_64 returns two values: Variable Argument Address, Chain
9125   SmallVector<SDValue, 11> InstOps;
9126   InstOps.push_back(Chain);
9127   InstOps.push_back(SrcPtr);
9128   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9129   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9130   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9131   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9132   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9133                                           VTs, &InstOps[0], InstOps.size(),
9134                                           MVT::i64,
9135                                           MachinePointerInfo(SV),
9136                                           /*Align=*/0,
9137                                           /*Volatile=*/false,
9138                                           /*ReadMem=*/true,
9139                                           /*WriteMem=*/true);
9140   Chain = VAARG.getValue(1);
9141
9142   // Load the next argument and return it
9143   return DAG.getLoad(ArgVT, dl,
9144                      Chain,
9145                      VAARG,
9146                      MachinePointerInfo(),
9147                      false, false, false, 0);
9148 }
9149
9150 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
9151   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9152   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9153   SDValue Chain = Op.getOperand(0);
9154   SDValue DstPtr = Op.getOperand(1);
9155   SDValue SrcPtr = Op.getOperand(2);
9156   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9157   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9158   DebugLoc DL = Op.getDebugLoc();
9159
9160   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9161                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9162                        false,
9163                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9164 }
9165
9166 SDValue
9167 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
9168   DebugLoc dl = Op.getDebugLoc();
9169   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9170   switch (IntNo) {
9171   default: return SDValue();    // Don't custom lower most intrinsics.
9172   // Comparison intrinsics.
9173   case Intrinsic::x86_sse_comieq_ss:
9174   case Intrinsic::x86_sse_comilt_ss:
9175   case Intrinsic::x86_sse_comile_ss:
9176   case Intrinsic::x86_sse_comigt_ss:
9177   case Intrinsic::x86_sse_comige_ss:
9178   case Intrinsic::x86_sse_comineq_ss:
9179   case Intrinsic::x86_sse_ucomieq_ss:
9180   case Intrinsic::x86_sse_ucomilt_ss:
9181   case Intrinsic::x86_sse_ucomile_ss:
9182   case Intrinsic::x86_sse_ucomigt_ss:
9183   case Intrinsic::x86_sse_ucomige_ss:
9184   case Intrinsic::x86_sse_ucomineq_ss:
9185   case Intrinsic::x86_sse2_comieq_sd:
9186   case Intrinsic::x86_sse2_comilt_sd:
9187   case Intrinsic::x86_sse2_comile_sd:
9188   case Intrinsic::x86_sse2_comigt_sd:
9189   case Intrinsic::x86_sse2_comige_sd:
9190   case Intrinsic::x86_sse2_comineq_sd:
9191   case Intrinsic::x86_sse2_ucomieq_sd:
9192   case Intrinsic::x86_sse2_ucomilt_sd:
9193   case Intrinsic::x86_sse2_ucomile_sd:
9194   case Intrinsic::x86_sse2_ucomigt_sd:
9195   case Intrinsic::x86_sse2_ucomige_sd:
9196   case Intrinsic::x86_sse2_ucomineq_sd: {
9197     unsigned Opc = 0;
9198     ISD::CondCode CC = ISD::SETCC_INVALID;
9199     switch (IntNo) {
9200     default: break;
9201     case Intrinsic::x86_sse_comieq_ss:
9202     case Intrinsic::x86_sse2_comieq_sd:
9203       Opc = X86ISD::COMI;
9204       CC = ISD::SETEQ;
9205       break;
9206     case Intrinsic::x86_sse_comilt_ss:
9207     case Intrinsic::x86_sse2_comilt_sd:
9208       Opc = X86ISD::COMI;
9209       CC = ISD::SETLT;
9210       break;
9211     case Intrinsic::x86_sse_comile_ss:
9212     case Intrinsic::x86_sse2_comile_sd:
9213       Opc = X86ISD::COMI;
9214       CC = ISD::SETLE;
9215       break;
9216     case Intrinsic::x86_sse_comigt_ss:
9217     case Intrinsic::x86_sse2_comigt_sd:
9218       Opc = X86ISD::COMI;
9219       CC = ISD::SETGT;
9220       break;
9221     case Intrinsic::x86_sse_comige_ss:
9222     case Intrinsic::x86_sse2_comige_sd:
9223       Opc = X86ISD::COMI;
9224       CC = ISD::SETGE;
9225       break;
9226     case Intrinsic::x86_sse_comineq_ss:
9227     case Intrinsic::x86_sse2_comineq_sd:
9228       Opc = X86ISD::COMI;
9229       CC = ISD::SETNE;
9230       break;
9231     case Intrinsic::x86_sse_ucomieq_ss:
9232     case Intrinsic::x86_sse2_ucomieq_sd:
9233       Opc = X86ISD::UCOMI;
9234       CC = ISD::SETEQ;
9235       break;
9236     case Intrinsic::x86_sse_ucomilt_ss:
9237     case Intrinsic::x86_sse2_ucomilt_sd:
9238       Opc = X86ISD::UCOMI;
9239       CC = ISD::SETLT;
9240       break;
9241     case Intrinsic::x86_sse_ucomile_ss:
9242     case Intrinsic::x86_sse2_ucomile_sd:
9243       Opc = X86ISD::UCOMI;
9244       CC = ISD::SETLE;
9245       break;
9246     case Intrinsic::x86_sse_ucomigt_ss:
9247     case Intrinsic::x86_sse2_ucomigt_sd:
9248       Opc = X86ISD::UCOMI;
9249       CC = ISD::SETGT;
9250       break;
9251     case Intrinsic::x86_sse_ucomige_ss:
9252     case Intrinsic::x86_sse2_ucomige_sd:
9253       Opc = X86ISD::UCOMI;
9254       CC = ISD::SETGE;
9255       break;
9256     case Intrinsic::x86_sse_ucomineq_ss:
9257     case Intrinsic::x86_sse2_ucomineq_sd:
9258       Opc = X86ISD::UCOMI;
9259       CC = ISD::SETNE;
9260       break;
9261     }
9262
9263     SDValue LHS = Op.getOperand(1);
9264     SDValue RHS = Op.getOperand(2);
9265     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
9266     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
9267     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
9268     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9269                                 DAG.getConstant(X86CC, MVT::i8), Cond);
9270     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9271   }
9272   // Arithmetic intrinsics.
9273   case Intrinsic::x86_sse3_hadd_ps:
9274   case Intrinsic::x86_sse3_hadd_pd:
9275   case Intrinsic::x86_avx_hadd_ps_256:
9276   case Intrinsic::x86_avx_hadd_pd_256:
9277     return DAG.getNode(X86ISD::FHADD, dl, Op.getValueType(),
9278                        Op.getOperand(1), Op.getOperand(2));
9279   case Intrinsic::x86_sse3_hsub_ps:
9280   case Intrinsic::x86_sse3_hsub_pd:
9281   case Intrinsic::x86_avx_hsub_ps_256:
9282   case Intrinsic::x86_avx_hsub_pd_256:
9283     return DAG.getNode(X86ISD::FHSUB, dl, Op.getValueType(),
9284                        Op.getOperand(1), Op.getOperand(2));
9285   case Intrinsic::x86_avx2_psllv_d:
9286   case Intrinsic::x86_avx2_psllv_q:
9287   case Intrinsic::x86_avx2_psllv_d_256:
9288   case Intrinsic::x86_avx2_psllv_q_256:
9289     return DAG.getNode(ISD::SHL, dl, Op.getValueType(),
9290                       Op.getOperand(1), Op.getOperand(2));
9291   case Intrinsic::x86_avx2_psrlv_d:
9292   case Intrinsic::x86_avx2_psrlv_q:
9293   case Intrinsic::x86_avx2_psrlv_d_256:
9294   case Intrinsic::x86_avx2_psrlv_q_256:
9295     return DAG.getNode(ISD::SRL, dl, Op.getValueType(),
9296                       Op.getOperand(1), Op.getOperand(2));
9297   case Intrinsic::x86_avx2_psrav_d:
9298   case Intrinsic::x86_avx2_psrav_d_256:
9299     return DAG.getNode(ISD::SRA, dl, Op.getValueType(),
9300                       Op.getOperand(1), Op.getOperand(2));
9301
9302   // ptest and testp intrinsics. The intrinsic these come from are designed to
9303   // return an integer value, not just an instruction so lower it to the ptest
9304   // or testp pattern and a setcc for the result.
9305   case Intrinsic::x86_sse41_ptestz:
9306   case Intrinsic::x86_sse41_ptestc:
9307   case Intrinsic::x86_sse41_ptestnzc:
9308   case Intrinsic::x86_avx_ptestz_256:
9309   case Intrinsic::x86_avx_ptestc_256:
9310   case Intrinsic::x86_avx_ptestnzc_256:
9311   case Intrinsic::x86_avx_vtestz_ps:
9312   case Intrinsic::x86_avx_vtestc_ps:
9313   case Intrinsic::x86_avx_vtestnzc_ps:
9314   case Intrinsic::x86_avx_vtestz_pd:
9315   case Intrinsic::x86_avx_vtestc_pd:
9316   case Intrinsic::x86_avx_vtestnzc_pd:
9317   case Intrinsic::x86_avx_vtestz_ps_256:
9318   case Intrinsic::x86_avx_vtestc_ps_256:
9319   case Intrinsic::x86_avx_vtestnzc_ps_256:
9320   case Intrinsic::x86_avx_vtestz_pd_256:
9321   case Intrinsic::x86_avx_vtestc_pd_256:
9322   case Intrinsic::x86_avx_vtestnzc_pd_256: {
9323     bool IsTestPacked = false;
9324     unsigned X86CC = 0;
9325     switch (IntNo) {
9326     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
9327     case Intrinsic::x86_avx_vtestz_ps:
9328     case Intrinsic::x86_avx_vtestz_pd:
9329     case Intrinsic::x86_avx_vtestz_ps_256:
9330     case Intrinsic::x86_avx_vtestz_pd_256:
9331       IsTestPacked = true; // Fallthrough
9332     case Intrinsic::x86_sse41_ptestz:
9333     case Intrinsic::x86_avx_ptestz_256:
9334       // ZF = 1
9335       X86CC = X86::COND_E;
9336       break;
9337     case Intrinsic::x86_avx_vtestc_ps:
9338     case Intrinsic::x86_avx_vtestc_pd:
9339     case Intrinsic::x86_avx_vtestc_ps_256:
9340     case Intrinsic::x86_avx_vtestc_pd_256:
9341       IsTestPacked = true; // Fallthrough
9342     case Intrinsic::x86_sse41_ptestc:
9343     case Intrinsic::x86_avx_ptestc_256:
9344       // CF = 1
9345       X86CC = X86::COND_B;
9346       break;
9347     case Intrinsic::x86_avx_vtestnzc_ps:
9348     case Intrinsic::x86_avx_vtestnzc_pd:
9349     case Intrinsic::x86_avx_vtestnzc_ps_256:
9350     case Intrinsic::x86_avx_vtestnzc_pd_256:
9351       IsTestPacked = true; // Fallthrough
9352     case Intrinsic::x86_sse41_ptestnzc:
9353     case Intrinsic::x86_avx_ptestnzc_256:
9354       // ZF and CF = 0
9355       X86CC = X86::COND_A;
9356       break;
9357     }
9358
9359     SDValue LHS = Op.getOperand(1);
9360     SDValue RHS = Op.getOperand(2);
9361     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
9362     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
9363     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
9364     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
9365     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9366   }
9367
9368   // Fix vector shift instructions where the last operand is a non-immediate
9369   // i32 value.
9370   case Intrinsic::x86_avx2_pslli_w:
9371   case Intrinsic::x86_avx2_pslli_d:
9372   case Intrinsic::x86_avx2_pslli_q:
9373   case Intrinsic::x86_avx2_psrli_w:
9374   case Intrinsic::x86_avx2_psrli_d:
9375   case Intrinsic::x86_avx2_psrli_q:
9376   case Intrinsic::x86_avx2_psrai_w:
9377   case Intrinsic::x86_avx2_psrai_d:
9378   case Intrinsic::x86_sse2_pslli_w:
9379   case Intrinsic::x86_sse2_pslli_d:
9380   case Intrinsic::x86_sse2_pslli_q:
9381   case Intrinsic::x86_sse2_psrli_w:
9382   case Intrinsic::x86_sse2_psrli_d:
9383   case Intrinsic::x86_sse2_psrli_q:
9384   case Intrinsic::x86_sse2_psrai_w:
9385   case Intrinsic::x86_sse2_psrai_d:
9386   case Intrinsic::x86_mmx_pslli_w:
9387   case Intrinsic::x86_mmx_pslli_d:
9388   case Intrinsic::x86_mmx_pslli_q:
9389   case Intrinsic::x86_mmx_psrli_w:
9390   case Intrinsic::x86_mmx_psrli_d:
9391   case Intrinsic::x86_mmx_psrli_q:
9392   case Intrinsic::x86_mmx_psrai_w:
9393   case Intrinsic::x86_mmx_psrai_d: {
9394     SDValue ShAmt = Op.getOperand(2);
9395     if (isa<ConstantSDNode>(ShAmt))
9396       return SDValue();
9397
9398     unsigned NewIntNo = 0;
9399     EVT ShAmtVT = MVT::v4i32;
9400     switch (IntNo) {
9401     case Intrinsic::x86_sse2_pslli_w:
9402       NewIntNo = Intrinsic::x86_sse2_psll_w;
9403       break;
9404     case Intrinsic::x86_sse2_pslli_d:
9405       NewIntNo = Intrinsic::x86_sse2_psll_d;
9406       break;
9407     case Intrinsic::x86_sse2_pslli_q:
9408       NewIntNo = Intrinsic::x86_sse2_psll_q;
9409       break;
9410     case Intrinsic::x86_sse2_psrli_w:
9411       NewIntNo = Intrinsic::x86_sse2_psrl_w;
9412       break;
9413     case Intrinsic::x86_sse2_psrli_d:
9414       NewIntNo = Intrinsic::x86_sse2_psrl_d;
9415       break;
9416     case Intrinsic::x86_sse2_psrli_q:
9417       NewIntNo = Intrinsic::x86_sse2_psrl_q;
9418       break;
9419     case Intrinsic::x86_sse2_psrai_w:
9420       NewIntNo = Intrinsic::x86_sse2_psra_w;
9421       break;
9422     case Intrinsic::x86_sse2_psrai_d:
9423       NewIntNo = Intrinsic::x86_sse2_psra_d;
9424       break;
9425     case Intrinsic::x86_avx2_pslli_w:
9426       NewIntNo = Intrinsic::x86_avx2_psll_w;
9427       break;
9428     case Intrinsic::x86_avx2_pslli_d:
9429       NewIntNo = Intrinsic::x86_avx2_psll_d;
9430       break;
9431     case Intrinsic::x86_avx2_pslli_q:
9432       NewIntNo = Intrinsic::x86_avx2_psll_q;
9433       break;
9434     case Intrinsic::x86_avx2_psrli_w:
9435       NewIntNo = Intrinsic::x86_avx2_psrl_w;
9436       break;
9437     case Intrinsic::x86_avx2_psrli_d:
9438       NewIntNo = Intrinsic::x86_avx2_psrl_d;
9439       break;
9440     case Intrinsic::x86_avx2_psrli_q:
9441       NewIntNo = Intrinsic::x86_avx2_psrl_q;
9442       break;
9443     case Intrinsic::x86_avx2_psrai_w:
9444       NewIntNo = Intrinsic::x86_avx2_psra_w;
9445       break;
9446     case Intrinsic::x86_avx2_psrai_d:
9447       NewIntNo = Intrinsic::x86_avx2_psra_d;
9448       break;
9449     default: {
9450       ShAmtVT = MVT::v2i32;
9451       switch (IntNo) {
9452       case Intrinsic::x86_mmx_pslli_w:
9453         NewIntNo = Intrinsic::x86_mmx_psll_w;
9454         break;
9455       case Intrinsic::x86_mmx_pslli_d:
9456         NewIntNo = Intrinsic::x86_mmx_psll_d;
9457         break;
9458       case Intrinsic::x86_mmx_pslli_q:
9459         NewIntNo = Intrinsic::x86_mmx_psll_q;
9460         break;
9461       case Intrinsic::x86_mmx_psrli_w:
9462         NewIntNo = Intrinsic::x86_mmx_psrl_w;
9463         break;
9464       case Intrinsic::x86_mmx_psrli_d:
9465         NewIntNo = Intrinsic::x86_mmx_psrl_d;
9466         break;
9467       case Intrinsic::x86_mmx_psrli_q:
9468         NewIntNo = Intrinsic::x86_mmx_psrl_q;
9469         break;
9470       case Intrinsic::x86_mmx_psrai_w:
9471         NewIntNo = Intrinsic::x86_mmx_psra_w;
9472         break;
9473       case Intrinsic::x86_mmx_psrai_d:
9474         NewIntNo = Intrinsic::x86_mmx_psra_d;
9475         break;
9476       default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9477       }
9478       break;
9479     }
9480     }
9481
9482     // The vector shift intrinsics with scalars uses 32b shift amounts but
9483     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
9484     // to be zero.
9485     SDValue ShOps[4];
9486     ShOps[0] = ShAmt;
9487     ShOps[1] = DAG.getConstant(0, MVT::i32);
9488     if (ShAmtVT == MVT::v4i32) {
9489       ShOps[2] = DAG.getUNDEF(MVT::i32);
9490       ShOps[3] = DAG.getUNDEF(MVT::i32);
9491       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
9492     } else {
9493       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
9494 // FIXME this must be lowered to get rid of the invalid type.
9495     }
9496
9497     EVT VT = Op.getValueType();
9498     ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
9499     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9500                        DAG.getConstant(NewIntNo, MVT::i32),
9501                        Op.getOperand(1), ShAmt);
9502   }
9503   }
9504 }
9505
9506 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
9507                                            SelectionDAG &DAG) const {
9508   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9509   MFI->setReturnAddressIsTaken(true);
9510
9511   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9512   DebugLoc dl = Op.getDebugLoc();
9513
9514   if (Depth > 0) {
9515     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
9516     SDValue Offset =
9517       DAG.getConstant(TD->getPointerSize(),
9518                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
9519     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9520                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
9521                                    FrameAddr, Offset),
9522                        MachinePointerInfo(), false, false, false, 0);
9523   }
9524
9525   // Just load the return address.
9526   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
9527   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9528                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
9529 }
9530
9531 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
9532   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9533   MFI->setFrameAddressIsTaken(true);
9534
9535   EVT VT = Op.getValueType();
9536   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
9537   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9538   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
9539   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
9540   while (Depth--)
9541     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
9542                             MachinePointerInfo(),
9543                             false, false, false, 0);
9544   return FrameAddr;
9545 }
9546
9547 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
9548                                                      SelectionDAG &DAG) const {
9549   return DAG.getIntPtrConstant(2*TD->getPointerSize());
9550 }
9551
9552 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
9553   MachineFunction &MF = DAG.getMachineFunction();
9554   SDValue Chain     = Op.getOperand(0);
9555   SDValue Offset    = Op.getOperand(1);
9556   SDValue Handler   = Op.getOperand(2);
9557   DebugLoc dl       = Op.getDebugLoc();
9558
9559   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
9560                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
9561                                      getPointerTy());
9562   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
9563
9564   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
9565                                   DAG.getIntPtrConstant(TD->getPointerSize()));
9566   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
9567   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
9568                        false, false, 0);
9569   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
9570   MF.getRegInfo().addLiveOut(StoreAddrReg);
9571
9572   return DAG.getNode(X86ISD::EH_RETURN, dl,
9573                      MVT::Other,
9574                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
9575 }
9576
9577 SDValue X86TargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
9578                                                   SelectionDAG &DAG) const {
9579   return Op.getOperand(0);
9580 }
9581
9582 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
9583                                                 SelectionDAG &DAG) const {
9584   SDValue Root = Op.getOperand(0);
9585   SDValue Trmp = Op.getOperand(1); // trampoline
9586   SDValue FPtr = Op.getOperand(2); // nested function
9587   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
9588   DebugLoc dl  = Op.getDebugLoc();
9589
9590   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9591
9592   if (Subtarget->is64Bit()) {
9593     SDValue OutChains[6];
9594
9595     // Large code-model.
9596     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
9597     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
9598
9599     const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10);
9600     const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11);
9601
9602     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
9603
9604     // Load the pointer to the nested function into R11.
9605     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
9606     SDValue Addr = Trmp;
9607     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9608                                 Addr, MachinePointerInfo(TrmpAddr),
9609                                 false, false, 0);
9610
9611     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9612                        DAG.getConstant(2, MVT::i64));
9613     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
9614                                 MachinePointerInfo(TrmpAddr, 2),
9615                                 false, false, 2);
9616
9617     // Load the 'nest' parameter value into R10.
9618     // R10 is specified in X86CallingConv.td
9619     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
9620     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9621                        DAG.getConstant(10, MVT::i64));
9622     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9623                                 Addr, MachinePointerInfo(TrmpAddr, 10),
9624                                 false, false, 0);
9625
9626     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9627                        DAG.getConstant(12, MVT::i64));
9628     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
9629                                 MachinePointerInfo(TrmpAddr, 12),
9630                                 false, false, 2);
9631
9632     // Jump to the nested function.
9633     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
9634     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9635                        DAG.getConstant(20, MVT::i64));
9636     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9637                                 Addr, MachinePointerInfo(TrmpAddr, 20),
9638                                 false, false, 0);
9639
9640     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
9641     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9642                        DAG.getConstant(22, MVT::i64));
9643     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
9644                                 MachinePointerInfo(TrmpAddr, 22),
9645                                 false, false, 0);
9646
9647     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
9648   } else {
9649     const Function *Func =
9650       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
9651     CallingConv::ID CC = Func->getCallingConv();
9652     unsigned NestReg;
9653
9654     switch (CC) {
9655     default:
9656       llvm_unreachable("Unsupported calling convention");
9657     case CallingConv::C:
9658     case CallingConv::X86_StdCall: {
9659       // Pass 'nest' parameter in ECX.
9660       // Must be kept in sync with X86CallingConv.td
9661       NestReg = X86::ECX;
9662
9663       // Check that ECX wasn't needed by an 'inreg' parameter.
9664       FunctionType *FTy = Func->getFunctionType();
9665       const AttrListPtr &Attrs = Func->getAttributes();
9666
9667       if (!Attrs.isEmpty() && !Func->isVarArg()) {
9668         unsigned InRegCount = 0;
9669         unsigned Idx = 1;
9670
9671         for (FunctionType::param_iterator I = FTy->param_begin(),
9672              E = FTy->param_end(); I != E; ++I, ++Idx)
9673           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
9674             // FIXME: should only count parameters that are lowered to integers.
9675             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
9676
9677         if (InRegCount > 2) {
9678           report_fatal_error("Nest register in use - reduce number of inreg"
9679                              " parameters!");
9680         }
9681       }
9682       break;
9683     }
9684     case CallingConv::X86_FastCall:
9685     case CallingConv::X86_ThisCall:
9686     case CallingConv::Fast:
9687       // Pass 'nest' parameter in EAX.
9688       // Must be kept in sync with X86CallingConv.td
9689       NestReg = X86::EAX;
9690       break;
9691     }
9692
9693     SDValue OutChains[4];
9694     SDValue Addr, Disp;
9695
9696     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9697                        DAG.getConstant(10, MVT::i32));
9698     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
9699
9700     // This is storing the opcode for MOV32ri.
9701     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
9702     const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg);
9703     OutChains[0] = DAG.getStore(Root, dl,
9704                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
9705                                 Trmp, MachinePointerInfo(TrmpAddr),
9706                                 false, false, 0);
9707
9708     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9709                        DAG.getConstant(1, MVT::i32));
9710     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
9711                                 MachinePointerInfo(TrmpAddr, 1),
9712                                 false, false, 1);
9713
9714     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
9715     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9716                        DAG.getConstant(5, MVT::i32));
9717     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
9718                                 MachinePointerInfo(TrmpAddr, 5),
9719                                 false, false, 1);
9720
9721     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9722                        DAG.getConstant(6, MVT::i32));
9723     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
9724                                 MachinePointerInfo(TrmpAddr, 6),
9725                                 false, false, 1);
9726
9727     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
9728   }
9729 }
9730
9731 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
9732                                             SelectionDAG &DAG) const {
9733   /*
9734    The rounding mode is in bits 11:10 of FPSR, and has the following
9735    settings:
9736      00 Round to nearest
9737      01 Round to -inf
9738      10 Round to +inf
9739      11 Round to 0
9740
9741   FLT_ROUNDS, on the other hand, expects the following:
9742     -1 Undefined
9743      0 Round to 0
9744      1 Round to nearest
9745      2 Round to +inf
9746      3 Round to -inf
9747
9748   To perform the conversion, we do:
9749     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
9750   */
9751
9752   MachineFunction &MF = DAG.getMachineFunction();
9753   const TargetMachine &TM = MF.getTarget();
9754   const TargetFrameLowering &TFI = *TM.getFrameLowering();
9755   unsigned StackAlignment = TFI.getStackAlignment();
9756   EVT VT = Op.getValueType();
9757   DebugLoc DL = Op.getDebugLoc();
9758
9759   // Save FP Control Word to stack slot
9760   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
9761   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9762
9763
9764   MachineMemOperand *MMO =
9765    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9766                            MachineMemOperand::MOStore, 2, 2);
9767
9768   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
9769   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
9770                                           DAG.getVTList(MVT::Other),
9771                                           Ops, 2, MVT::i16, MMO);
9772
9773   // Load FP Control Word from stack slot
9774   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
9775                             MachinePointerInfo(), false, false, false, 0);
9776
9777   // Transform as necessary
9778   SDValue CWD1 =
9779     DAG.getNode(ISD::SRL, DL, MVT::i16,
9780                 DAG.getNode(ISD::AND, DL, MVT::i16,
9781                             CWD, DAG.getConstant(0x800, MVT::i16)),
9782                 DAG.getConstant(11, MVT::i8));
9783   SDValue CWD2 =
9784     DAG.getNode(ISD::SRL, DL, MVT::i16,
9785                 DAG.getNode(ISD::AND, DL, MVT::i16,
9786                             CWD, DAG.getConstant(0x400, MVT::i16)),
9787                 DAG.getConstant(9, MVT::i8));
9788
9789   SDValue RetVal =
9790     DAG.getNode(ISD::AND, DL, MVT::i16,
9791                 DAG.getNode(ISD::ADD, DL, MVT::i16,
9792                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
9793                             DAG.getConstant(1, MVT::i16)),
9794                 DAG.getConstant(3, MVT::i16));
9795
9796
9797   return DAG.getNode((VT.getSizeInBits() < 16 ?
9798                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
9799 }
9800
9801 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
9802   EVT VT = Op.getValueType();
9803   EVT OpVT = VT;
9804   unsigned NumBits = VT.getSizeInBits();
9805   DebugLoc dl = Op.getDebugLoc();
9806
9807   Op = Op.getOperand(0);
9808   if (VT == MVT::i8) {
9809     // Zero extend to i32 since there is not an i8 bsr.
9810     OpVT = MVT::i32;
9811     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
9812   }
9813
9814   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
9815   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
9816   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
9817
9818   // If src is zero (i.e. bsr sets ZF), returns NumBits.
9819   SDValue Ops[] = {
9820     Op,
9821     DAG.getConstant(NumBits+NumBits-1, OpVT),
9822     DAG.getConstant(X86::COND_E, MVT::i8),
9823     Op.getValue(1)
9824   };
9825   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
9826
9827   // Finally xor with NumBits-1.
9828   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
9829
9830   if (VT == MVT::i8)
9831     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
9832   return Op;
9833 }
9834
9835 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
9836   EVT VT = Op.getValueType();
9837   EVT OpVT = VT;
9838   unsigned NumBits = VT.getSizeInBits();
9839   DebugLoc dl = Op.getDebugLoc();
9840
9841   Op = Op.getOperand(0);
9842   if (VT == MVT::i8) {
9843     OpVT = MVT::i32;
9844     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
9845   }
9846
9847   // Issue a bsf (scan bits forward) which also sets EFLAGS.
9848   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
9849   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
9850
9851   // If src is zero (i.e. bsf sets ZF), returns NumBits.
9852   SDValue Ops[] = {
9853     Op,
9854     DAG.getConstant(NumBits, OpVT),
9855     DAG.getConstant(X86::COND_E, MVT::i8),
9856     Op.getValue(1)
9857   };
9858   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
9859
9860   if (VT == MVT::i8)
9861     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
9862   return Op;
9863 }
9864
9865 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
9866 // ones, and then concatenate the result back.
9867 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
9868   EVT VT = Op.getValueType();
9869
9870   assert(VT.getSizeInBits() == 256 && VT.isInteger() &&
9871          "Unsupported value type for operation");
9872
9873   int NumElems = VT.getVectorNumElements();
9874   DebugLoc dl = Op.getDebugLoc();
9875   SDValue Idx0 = DAG.getConstant(0, MVT::i32);
9876   SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
9877
9878   // Extract the LHS vectors
9879   SDValue LHS = Op.getOperand(0);
9880   SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
9881   SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
9882
9883   // Extract the RHS vectors
9884   SDValue RHS = Op.getOperand(1);
9885   SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl);
9886   SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl);
9887
9888   MVT EltVT = VT.getVectorElementType().getSimpleVT();
9889   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9890
9891   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9892                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
9893                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
9894 }
9895
9896 SDValue X86TargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const {
9897   assert(Op.getValueType().getSizeInBits() == 256 &&
9898          Op.getValueType().isInteger() &&
9899          "Only handle AVX 256-bit vector integer operation");
9900   return Lower256IntArith(Op, DAG);
9901 }
9902
9903 SDValue X86TargetLowering::LowerSUB(SDValue Op, SelectionDAG &DAG) const {
9904   assert(Op.getValueType().getSizeInBits() == 256 &&
9905          Op.getValueType().isInteger() &&
9906          "Only handle AVX 256-bit vector integer operation");
9907   return Lower256IntArith(Op, DAG);
9908 }
9909
9910 SDValue X86TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
9911   EVT VT = Op.getValueType();
9912
9913   // Decompose 256-bit ops into smaller 128-bit ops.
9914   if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2())
9915     return Lower256IntArith(Op, DAG);
9916
9917   DebugLoc dl = Op.getDebugLoc();
9918
9919   SDValue A = Op.getOperand(0);
9920   SDValue B = Op.getOperand(1);
9921
9922   if (VT == MVT::v4i64) {
9923     assert(Subtarget->hasAVX2() && "Lowering v4i64 multiply requires AVX2");
9924
9925     //  ulong2 Ahi = __builtin_ia32_psrlqi256( a, 32);
9926     //  ulong2 Bhi = __builtin_ia32_psrlqi256( b, 32);
9927     //  ulong2 AloBlo = __builtin_ia32_pmuludq256( a, b );
9928     //  ulong2 AloBhi = __builtin_ia32_pmuludq256( a, Bhi );
9929     //  ulong2 AhiBlo = __builtin_ia32_pmuludq256( Ahi, b );
9930     //
9931     //  AloBhi = __builtin_ia32_psllqi256( AloBhi, 32 );
9932     //  AhiBlo = __builtin_ia32_psllqi256( AhiBlo, 32 );
9933     //  return AloBlo + AloBhi + AhiBlo;
9934
9935     SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9936                          DAG.getConstant(Intrinsic::x86_avx2_psrli_q, MVT::i32),
9937                          A, DAG.getConstant(32, MVT::i32));
9938     SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9939                          DAG.getConstant(Intrinsic::x86_avx2_psrli_q, MVT::i32),
9940                          B, DAG.getConstant(32, MVT::i32));
9941     SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9942                          DAG.getConstant(Intrinsic::x86_avx2_pmulu_dq, MVT::i32),
9943                          A, B);
9944     SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9945                          DAG.getConstant(Intrinsic::x86_avx2_pmulu_dq, MVT::i32),
9946                          A, Bhi);
9947     SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9948                          DAG.getConstant(Intrinsic::x86_avx2_pmulu_dq, MVT::i32),
9949                          Ahi, B);
9950     AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9951                          DAG.getConstant(Intrinsic::x86_avx2_pslli_q, MVT::i32),
9952                          AloBhi, DAG.getConstant(32, MVT::i32));
9953     AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9954                          DAG.getConstant(Intrinsic::x86_avx2_pslli_q, MVT::i32),
9955                          AhiBlo, DAG.getConstant(32, MVT::i32));
9956     SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
9957     Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
9958     return Res;
9959   }
9960
9961   assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
9962
9963   //  ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
9964   //  ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
9965   //  ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
9966   //  ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
9967   //  ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
9968   //
9969   //  AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
9970   //  AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
9971   //  return AloBlo + AloBhi + AhiBlo;
9972
9973   SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9974                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9975                        A, DAG.getConstant(32, MVT::i32));
9976   SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9977                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9978                        B, DAG.getConstant(32, MVT::i32));
9979   SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9980                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
9981                        A, B);
9982   SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9983                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
9984                        A, Bhi);
9985   SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9986                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
9987                        Ahi, B);
9988   AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9989                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9990                        AloBhi, DAG.getConstant(32, MVT::i32));
9991   AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9992                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9993                        AhiBlo, DAG.getConstant(32, MVT::i32));
9994   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
9995   Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
9996   return Res;
9997 }
9998
9999 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
10000
10001   EVT VT = Op.getValueType();
10002   DebugLoc dl = Op.getDebugLoc();
10003   SDValue R = Op.getOperand(0);
10004   SDValue Amt = Op.getOperand(1);
10005   LLVMContext *Context = DAG.getContext();
10006
10007   if (!Subtarget->hasXMMInt())
10008     return SDValue();
10009
10010   // Optimize shl/srl/sra with constant shift amount.
10011   if (isSplatVector(Amt.getNode())) {
10012     SDValue SclrAmt = Amt->getOperand(0);
10013     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
10014       uint64_t ShiftAmt = C->getZExtValue();
10015
10016       if (VT == MVT::v16i8 && Op.getOpcode() == ISD::SHL) {
10017         // Make a large shift.
10018         SDValue SHL =
10019           DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10020                       DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10021                       R, DAG.getConstant(ShiftAmt, MVT::i32));
10022         // Zero out the rightmost bits.
10023         SmallVector<SDValue, 16> V(16, DAG.getConstant(uint8_t(-1U << ShiftAmt),
10024                                                        MVT::i8));
10025         return DAG.getNode(ISD::AND, dl, VT, SHL,
10026                            DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10027       }
10028
10029       if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SHL)
10030        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10031                      DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
10032                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10033
10034       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SHL)
10035        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10036                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
10037                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10038
10039       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SHL)
10040        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10041                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10042                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10043
10044       if (VT == MVT::v16i8 && Op.getOpcode() == ISD::SRL) {
10045         // Make a large shift.
10046         SDValue SRL =
10047           DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10048                       DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
10049                       R, DAG.getConstant(ShiftAmt, MVT::i32));
10050         // Zero out the leftmost bits.
10051         SmallVector<SDValue, 16> V(16, DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10052                                                        MVT::i8));
10053         return DAG.getNode(ISD::AND, dl, VT, SRL,
10054                            DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10055       }
10056
10057       if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SRL)
10058        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10059                      DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
10060                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10061
10062       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRL)
10063        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10064                      DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
10065                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10066
10067       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRL)
10068        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10069                      DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
10070                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10071
10072       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRA)
10073        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10074                      DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
10075                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10076
10077       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRA)
10078        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10079                      DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
10080                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10081
10082       if (VT == MVT::v16i8 && Op.getOpcode() == ISD::SRA) {
10083         if (ShiftAmt == 7) {
10084           // R s>> 7  ===  R s< 0
10085           SDValue Zeros = getZeroVector(VT, true /* HasXMMInt */, DAG, dl);
10086           return DAG.getNode(X86ISD::PCMPGTB, dl, VT, Zeros, R);
10087         }
10088
10089         // R s>> a === ((R u>> a) ^ m) - m
10090         SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10091         SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
10092                                                        MVT::i8));
10093         SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
10094         Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10095         Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10096         return Res;
10097       }
10098
10099       if (Subtarget->hasAVX2() && VT == MVT::v32i8) {
10100         if (Op.getOpcode() == ISD::SHL) {
10101           // Make a large shift.
10102           SDValue SHL =
10103             DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10104                         DAG.getConstant(Intrinsic::x86_avx2_pslli_w, MVT::i32),
10105                         R, DAG.getConstant(ShiftAmt, MVT::i32));
10106           // Zero out the rightmost bits.
10107           SmallVector<SDValue, 32> V(32, DAG.getConstant(uint8_t(-1U << ShiftAmt),
10108                                                          MVT::i8));
10109           return DAG.getNode(ISD::AND, dl, VT, SHL,
10110                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10111         }
10112         if (Op.getOpcode() == ISD::SRL) {
10113           // Make a large shift.
10114           SDValue SRL =
10115             DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10116                         DAG.getConstant(Intrinsic::x86_avx2_psrli_w, MVT::i32),
10117                         R, DAG.getConstant(ShiftAmt, MVT::i32));
10118           // Zero out the leftmost bits.
10119           SmallVector<SDValue, 32> V(32, DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10120                                                          MVT::i8));
10121           return DAG.getNode(ISD::AND, dl, VT, SRL,
10122                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10123         }
10124         if (Op.getOpcode() == ISD::SRA) {
10125           if (ShiftAmt == 7) {
10126             // R s>> 7  ===  R s< 0
10127             SDValue Zeros = getZeroVector(VT, true /* HasXMMInt */, DAG, dl);
10128             return DAG.getNode(X86ISD::PCMPGTB, dl, VT, Zeros, R);
10129           }
10130
10131           // R s>> a === ((R u>> a) ^ m) - m
10132           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10133           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
10134                                                          MVT::i8));
10135           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
10136           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10137           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10138           return Res;
10139         }
10140       }
10141     }
10142   }
10143
10144   // Lower SHL with variable shift amount.
10145   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
10146     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10147                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
10148                      Op.getOperand(1), DAG.getConstant(23, MVT::i32));
10149
10150     ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
10151
10152     std::vector<Constant*> CV(4, CI);
10153     Constant *C = ConstantVector::get(CV);
10154     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10155     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10156                                  MachinePointerInfo::getConstantPool(),
10157                                  false, false, false, 16);
10158
10159     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
10160     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
10161     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
10162     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
10163   }
10164   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
10165     assert((Subtarget->hasSSE2() || Subtarget->hasAVX()) &&
10166             "Need SSE2 for pslli/pcmpeq.");
10167
10168     // a = a << 5;
10169     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10170                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10171                      Op.getOperand(1), DAG.getConstant(5, MVT::i32));
10172
10173     // Turn 'a' into a mask suitable for VSELECT
10174     SDValue VSelM = DAG.getConstant(0x80, VT);
10175     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10176     OpVSel = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10177                         DAG.getConstant(Intrinsic::x86_sse2_pcmpeq_b, MVT::i32),
10178                         OpVSel, VSelM);
10179
10180     SDValue CM1 = DAG.getConstant(0x0f, VT);
10181     SDValue CM2 = DAG.getConstant(0x3f, VT);
10182
10183     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
10184     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
10185     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10186                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
10187                     DAG.getConstant(4, MVT::i32));
10188     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10189
10190     // a += a
10191     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10192     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10193     OpVSel = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10194                         DAG.getConstant(Intrinsic::x86_sse2_pcmpeq_b, MVT::i32),
10195                         OpVSel, VSelM);
10196
10197     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
10198     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
10199     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10200                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
10201                     DAG.getConstant(2, MVT::i32));
10202     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10203
10204     // a += a
10205     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10206     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10207     OpVSel = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10208                         DAG.getConstant(Intrinsic::x86_sse2_pcmpeq_b, MVT::i32),
10209                         OpVSel, VSelM);
10210
10211     // return VSELECT(r, r+r, a);
10212     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
10213                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
10214     return R;
10215   }
10216
10217   // Decompose 256-bit shifts into smaller 128-bit shifts.
10218   if (VT.getSizeInBits() == 256) {
10219     int NumElems = VT.getVectorNumElements();
10220     MVT EltVT = VT.getVectorElementType().getSimpleVT();
10221     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10222
10223     // Extract the two vectors
10224     SDValue V1 = Extract128BitVector(R, DAG.getConstant(0, MVT::i32), DAG, dl);
10225     SDValue V2 = Extract128BitVector(R, DAG.getConstant(NumElems/2, MVT::i32),
10226                                      DAG, dl);
10227
10228     // Recreate the shift amount vectors
10229     SDValue Amt1, Amt2;
10230     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
10231       // Constant shift amount
10232       SmallVector<SDValue, 4> Amt1Csts;
10233       SmallVector<SDValue, 4> Amt2Csts;
10234       for (int i = 0; i < NumElems/2; ++i)
10235         Amt1Csts.push_back(Amt->getOperand(i));
10236       for (int i = NumElems/2; i < NumElems; ++i)
10237         Amt2Csts.push_back(Amt->getOperand(i));
10238
10239       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10240                                  &Amt1Csts[0], NumElems/2);
10241       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10242                                  &Amt2Csts[0], NumElems/2);
10243     } else {
10244       // Variable shift amount
10245       Amt1 = Extract128BitVector(Amt, DAG.getConstant(0, MVT::i32), DAG, dl);
10246       Amt2 = Extract128BitVector(Amt, DAG.getConstant(NumElems/2, MVT::i32),
10247                                  DAG, dl);
10248     }
10249
10250     // Issue new vector shifts for the smaller types
10251     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
10252     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
10253
10254     // Concatenate the result back
10255     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
10256   }
10257
10258   return SDValue();
10259 }
10260
10261 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
10262   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
10263   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
10264   // looks for this combo and may remove the "setcc" instruction if the "setcc"
10265   // has only one use.
10266   SDNode *N = Op.getNode();
10267   SDValue LHS = N->getOperand(0);
10268   SDValue RHS = N->getOperand(1);
10269   unsigned BaseOp = 0;
10270   unsigned Cond = 0;
10271   DebugLoc DL = Op.getDebugLoc();
10272   switch (Op.getOpcode()) {
10273   default: llvm_unreachable("Unknown ovf instruction!");
10274   case ISD::SADDO:
10275     // A subtract of one will be selected as a INC. Note that INC doesn't
10276     // set CF, so we can't do this for UADDO.
10277     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10278       if (C->isOne()) {
10279         BaseOp = X86ISD::INC;
10280         Cond = X86::COND_O;
10281         break;
10282       }
10283     BaseOp = X86ISD::ADD;
10284     Cond = X86::COND_O;
10285     break;
10286   case ISD::UADDO:
10287     BaseOp = X86ISD::ADD;
10288     Cond = X86::COND_B;
10289     break;
10290   case ISD::SSUBO:
10291     // A subtract of one will be selected as a DEC. Note that DEC doesn't
10292     // set CF, so we can't do this for USUBO.
10293     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10294       if (C->isOne()) {
10295         BaseOp = X86ISD::DEC;
10296         Cond = X86::COND_O;
10297         break;
10298       }
10299     BaseOp = X86ISD::SUB;
10300     Cond = X86::COND_O;
10301     break;
10302   case ISD::USUBO:
10303     BaseOp = X86ISD::SUB;
10304     Cond = X86::COND_B;
10305     break;
10306   case ISD::SMULO:
10307     BaseOp = X86ISD::SMUL;
10308     Cond = X86::COND_O;
10309     break;
10310   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
10311     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
10312                                  MVT::i32);
10313     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
10314
10315     SDValue SetCC =
10316       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10317                   DAG.getConstant(X86::COND_O, MVT::i32),
10318                   SDValue(Sum.getNode(), 2));
10319
10320     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10321   }
10322   }
10323
10324   // Also sets EFLAGS.
10325   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
10326   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
10327
10328   SDValue SetCC =
10329     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
10330                 DAG.getConstant(Cond, MVT::i32),
10331                 SDValue(Sum.getNode(), 1));
10332
10333   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10334 }
10335
10336 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op, SelectionDAG &DAG) const{
10337   DebugLoc dl = Op.getDebugLoc();
10338   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
10339   EVT VT = Op.getValueType();
10340
10341   if (Subtarget->hasXMMInt() && VT.isVector()) {
10342     unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
10343                         ExtraVT.getScalarType().getSizeInBits();
10344     SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
10345
10346     unsigned SHLIntrinsicsID = 0;
10347     unsigned SRAIntrinsicsID = 0;
10348     switch (VT.getSimpleVT().SimpleTy) {
10349       default:
10350         return SDValue();
10351       case MVT::v4i32:
10352         SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_d;
10353         SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_d;
10354         break;
10355       case MVT::v8i16:
10356         SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_w;
10357         SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_w;
10358         break;
10359       case MVT::v8i32:
10360       case MVT::v16i16:
10361         if (!Subtarget->hasAVX())
10362           return SDValue();
10363         if (!Subtarget->hasAVX2()) {
10364           // needs to be split
10365           int NumElems = VT.getVectorNumElements();
10366           SDValue Idx0 = DAG.getConstant(0, MVT::i32);
10367           SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
10368
10369           // Extract the LHS vectors
10370           SDValue LHS = Op.getOperand(0);
10371           SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
10372           SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
10373
10374           MVT EltVT = VT.getVectorElementType().getSimpleVT();
10375           EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10376
10377           EVT ExtraEltVT = ExtraVT.getVectorElementType();
10378           int ExtraNumElems = ExtraVT.getVectorNumElements();
10379           ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
10380                                      ExtraNumElems/2);
10381           SDValue Extra = DAG.getValueType(ExtraVT);
10382
10383           LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
10384           LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
10385
10386           return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);;
10387         }
10388         if (VT == MVT::v8i32) {
10389           SHLIntrinsicsID = Intrinsic::x86_avx2_pslli_d;
10390           SRAIntrinsicsID = Intrinsic::x86_avx2_psrai_d;
10391         } else {
10392           SHLIntrinsicsID = Intrinsic::x86_avx2_pslli_w;
10393           SRAIntrinsicsID = Intrinsic::x86_avx2_psrai_w;
10394         }
10395     }
10396
10397     SDValue Tmp1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10398                          DAG.getConstant(SHLIntrinsicsID, MVT::i32),
10399                          Op.getOperand(0), ShAmt);
10400
10401     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10402                        DAG.getConstant(SRAIntrinsicsID, MVT::i32),
10403                        Tmp1, ShAmt);
10404   }
10405
10406   return SDValue();
10407 }
10408
10409
10410 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
10411   DebugLoc dl = Op.getDebugLoc();
10412
10413   // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
10414   // There isn't any reason to disable it if the target processor supports it.
10415   if (!Subtarget->hasXMMInt() && !Subtarget->is64Bit()) {
10416     SDValue Chain = Op.getOperand(0);
10417     SDValue Zero = DAG.getConstant(0, MVT::i32);
10418     SDValue Ops[] = {
10419       DAG.getRegister(X86::ESP, MVT::i32), // Base
10420       DAG.getTargetConstant(1, MVT::i8),   // Scale
10421       DAG.getRegister(0, MVT::i32),        // Index
10422       DAG.getTargetConstant(0, MVT::i32),  // Disp
10423       DAG.getRegister(0, MVT::i32),        // Segment.
10424       Zero,
10425       Chain
10426     };
10427     SDNode *Res =
10428       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10429                           array_lengthof(Ops));
10430     return SDValue(Res, 0);
10431   }
10432
10433   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
10434   if (!isDev)
10435     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10436
10437   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10438   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
10439   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
10440   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
10441
10442   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
10443   if (!Op1 && !Op2 && !Op3 && Op4)
10444     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
10445
10446   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
10447   if (Op1 && !Op2 && !Op3 && !Op4)
10448     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
10449
10450   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
10451   //           (MFENCE)>;
10452   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10453 }
10454
10455 SDValue X86TargetLowering::LowerATOMIC_FENCE(SDValue Op,
10456                                              SelectionDAG &DAG) const {
10457   DebugLoc dl = Op.getDebugLoc();
10458   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
10459     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
10460   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
10461     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
10462
10463   // The only fence that needs an instruction is a sequentially-consistent
10464   // cross-thread fence.
10465   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
10466     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
10467     // no-sse2). There isn't any reason to disable it if the target processor
10468     // supports it.
10469     if (Subtarget->hasXMMInt() || Subtarget->is64Bit())
10470       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10471
10472     SDValue Chain = Op.getOperand(0);
10473     SDValue Zero = DAG.getConstant(0, MVT::i32);
10474     SDValue Ops[] = {
10475       DAG.getRegister(X86::ESP, MVT::i32), // Base
10476       DAG.getTargetConstant(1, MVT::i8),   // Scale
10477       DAG.getRegister(0, MVT::i32),        // Index
10478       DAG.getTargetConstant(0, MVT::i32),  // Disp
10479       DAG.getRegister(0, MVT::i32),        // Segment.
10480       Zero,
10481       Chain
10482     };
10483     SDNode *Res =
10484       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10485                          array_lengthof(Ops));
10486     return SDValue(Res, 0);
10487   }
10488
10489   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
10490   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10491 }
10492
10493
10494 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
10495   EVT T = Op.getValueType();
10496   DebugLoc DL = Op.getDebugLoc();
10497   unsigned Reg = 0;
10498   unsigned size = 0;
10499   switch(T.getSimpleVT().SimpleTy) {
10500   default:
10501     assert(false && "Invalid value type!");
10502   case MVT::i8:  Reg = X86::AL;  size = 1; break;
10503   case MVT::i16: Reg = X86::AX;  size = 2; break;
10504   case MVT::i32: Reg = X86::EAX; size = 4; break;
10505   case MVT::i64:
10506     assert(Subtarget->is64Bit() && "Node not type legal!");
10507     Reg = X86::RAX; size = 8;
10508     break;
10509   }
10510   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
10511                                     Op.getOperand(2), SDValue());
10512   SDValue Ops[] = { cpIn.getValue(0),
10513                     Op.getOperand(1),
10514                     Op.getOperand(3),
10515                     DAG.getTargetConstant(size, MVT::i8),
10516                     cpIn.getValue(1) };
10517   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10518   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
10519   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
10520                                            Ops, 5, T, MMO);
10521   SDValue cpOut =
10522     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
10523   return cpOut;
10524 }
10525
10526 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
10527                                                  SelectionDAG &DAG) const {
10528   assert(Subtarget->is64Bit() && "Result not type legalized?");
10529   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10530   SDValue TheChain = Op.getOperand(0);
10531   DebugLoc dl = Op.getDebugLoc();
10532   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10533   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
10534   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
10535                                    rax.getValue(2));
10536   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
10537                             DAG.getConstant(32, MVT::i8));
10538   SDValue Ops[] = {
10539     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
10540     rdx.getValue(1)
10541   };
10542   return DAG.getMergeValues(Ops, 2, dl);
10543 }
10544
10545 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
10546                                             SelectionDAG &DAG) const {
10547   EVT SrcVT = Op.getOperand(0).getValueType();
10548   EVT DstVT = Op.getValueType();
10549   assert(Subtarget->is64Bit() && !Subtarget->hasXMMInt() &&
10550          Subtarget->hasMMX() && "Unexpected custom BITCAST");
10551   assert((DstVT == MVT::i64 ||
10552           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
10553          "Unexpected custom BITCAST");
10554   // i64 <=> MMX conversions are Legal.
10555   if (SrcVT==MVT::i64 && DstVT.isVector())
10556     return Op;
10557   if (DstVT==MVT::i64 && SrcVT.isVector())
10558     return Op;
10559   // MMX <=> MMX conversions are Legal.
10560   if (SrcVT.isVector() && DstVT.isVector())
10561     return Op;
10562   // All other conversions need to be expanded.
10563   return SDValue();
10564 }
10565
10566 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
10567   SDNode *Node = Op.getNode();
10568   DebugLoc dl = Node->getDebugLoc();
10569   EVT T = Node->getValueType(0);
10570   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
10571                               DAG.getConstant(0, T), Node->getOperand(2));
10572   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
10573                        cast<AtomicSDNode>(Node)->getMemoryVT(),
10574                        Node->getOperand(0),
10575                        Node->getOperand(1), negOp,
10576                        cast<AtomicSDNode>(Node)->getSrcValue(),
10577                        cast<AtomicSDNode>(Node)->getAlignment(),
10578                        cast<AtomicSDNode>(Node)->getOrdering(),
10579                        cast<AtomicSDNode>(Node)->getSynchScope());
10580 }
10581
10582 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
10583   SDNode *Node = Op.getNode();
10584   DebugLoc dl = Node->getDebugLoc();
10585   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10586
10587   // Convert seq_cst store -> xchg
10588   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
10589   // FIXME: On 32-bit, store -> fist or movq would be more efficient
10590   //        (The only way to get a 16-byte store is cmpxchg16b)
10591   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
10592   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
10593       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
10594     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
10595                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
10596                                  Node->getOperand(0),
10597                                  Node->getOperand(1), Node->getOperand(2),
10598                                  cast<AtomicSDNode>(Node)->getMemOperand(),
10599                                  cast<AtomicSDNode>(Node)->getOrdering(),
10600                                  cast<AtomicSDNode>(Node)->getSynchScope());
10601     return Swap.getValue(1);
10602   }
10603   // Other atomic stores have a simple pattern.
10604   return Op;
10605 }
10606
10607 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
10608   EVT VT = Op.getNode()->getValueType(0);
10609
10610   // Let legalize expand this if it isn't a legal type yet.
10611   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10612     return SDValue();
10613
10614   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10615
10616   unsigned Opc;
10617   bool ExtraOp = false;
10618   switch (Op.getOpcode()) {
10619   default: assert(0 && "Invalid code");
10620   case ISD::ADDC: Opc = X86ISD::ADD; break;
10621   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
10622   case ISD::SUBC: Opc = X86ISD::SUB; break;
10623   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
10624   }
10625
10626   if (!ExtraOp)
10627     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10628                        Op.getOperand(1));
10629   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10630                      Op.getOperand(1), Op.getOperand(2));
10631 }
10632
10633 /// LowerOperation - Provide custom lowering hooks for some operations.
10634 ///
10635 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10636   switch (Op.getOpcode()) {
10637   default: llvm_unreachable("Should not custom lower this!");
10638   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
10639   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op,DAG);
10640   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op,DAG);
10641   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
10642   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
10643   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
10644   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
10645   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
10646   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
10647   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
10648   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
10649   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op, DAG);
10650   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, DAG);
10651   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
10652   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
10653   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
10654   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
10655   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
10656   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
10657   case ISD::SHL_PARTS:
10658   case ISD::SRA_PARTS:
10659   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
10660   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
10661   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
10662   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
10663   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
10664   case ISD::FABS:               return LowerFABS(Op, DAG);
10665   case ISD::FNEG:               return LowerFNEG(Op, DAG);
10666   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
10667   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
10668   case ISD::SETCC:              return LowerSETCC(Op, DAG);
10669   case ISD::SELECT:             return LowerSELECT(Op, DAG);
10670   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
10671   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
10672   case ISD::VASTART:            return LowerVASTART(Op, DAG);
10673   case ISD::VAARG:              return LowerVAARG(Op, DAG);
10674   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
10675   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10676   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
10677   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
10678   case ISD::FRAME_TO_ARGS_OFFSET:
10679                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
10680   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10681   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
10682   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
10683   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
10684   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
10685   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
10686   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
10687   case ISD::MUL:                return LowerMUL(Op, DAG);
10688   case ISD::SRA:
10689   case ISD::SRL:
10690   case ISD::SHL:                return LowerShift(Op, DAG);
10691   case ISD::SADDO:
10692   case ISD::UADDO:
10693   case ISD::SSUBO:
10694   case ISD::USUBO:
10695   case ISD::SMULO:
10696   case ISD::UMULO:              return LowerXALUO(Op, DAG);
10697   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
10698   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
10699   case ISD::ADDC:
10700   case ISD::ADDE:
10701   case ISD::SUBC:
10702   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
10703   case ISD::ADD:                return LowerADD(Op, DAG);
10704   case ISD::SUB:                return LowerSUB(Op, DAG);
10705   }
10706 }
10707
10708 static void ReplaceATOMIC_LOAD(SDNode *Node,
10709                                   SmallVectorImpl<SDValue> &Results,
10710                                   SelectionDAG &DAG) {
10711   DebugLoc dl = Node->getDebugLoc();
10712   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10713
10714   // Convert wide load -> cmpxchg8b/cmpxchg16b
10715   // FIXME: On 32-bit, load -> fild or movq would be more efficient
10716   //        (The only way to get a 16-byte load is cmpxchg16b)
10717   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
10718   SDValue Zero = DAG.getConstant(0, VT);
10719   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
10720                                Node->getOperand(0),
10721                                Node->getOperand(1), Zero, Zero,
10722                                cast<AtomicSDNode>(Node)->getMemOperand(),
10723                                cast<AtomicSDNode>(Node)->getOrdering(),
10724                                cast<AtomicSDNode>(Node)->getSynchScope());
10725   Results.push_back(Swap.getValue(0));
10726   Results.push_back(Swap.getValue(1));
10727 }
10728
10729 void X86TargetLowering::
10730 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
10731                         SelectionDAG &DAG, unsigned NewOp) const {
10732   DebugLoc dl = Node->getDebugLoc();
10733   assert (Node->getValueType(0) == MVT::i64 &&
10734           "Only know how to expand i64 atomics");
10735
10736   SDValue Chain = Node->getOperand(0);
10737   SDValue In1 = Node->getOperand(1);
10738   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10739                              Node->getOperand(2), DAG.getIntPtrConstant(0));
10740   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10741                              Node->getOperand(2), DAG.getIntPtrConstant(1));
10742   SDValue Ops[] = { Chain, In1, In2L, In2H };
10743   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
10744   SDValue Result =
10745     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
10746                             cast<MemSDNode>(Node)->getMemOperand());
10747   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
10748   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
10749   Results.push_back(Result.getValue(2));
10750 }
10751
10752 /// ReplaceNodeResults - Replace a node with an illegal result type
10753 /// with a new node built out of custom code.
10754 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
10755                                            SmallVectorImpl<SDValue>&Results,
10756                                            SelectionDAG &DAG) const {
10757   DebugLoc dl = N->getDebugLoc();
10758   switch (N->getOpcode()) {
10759   default:
10760     assert(false && "Do not know how to custom type legalize this operation!");
10761     return;
10762   case ISD::SIGN_EXTEND_INREG:
10763   case ISD::ADDC:
10764   case ISD::ADDE:
10765   case ISD::SUBC:
10766   case ISD::SUBE:
10767     // We don't want to expand or promote these.
10768     return;
10769   case ISD::FP_TO_SINT: {
10770     std::pair<SDValue,SDValue> Vals =
10771         FP_TO_INTHelper(SDValue(N, 0), DAG, true);
10772     SDValue FIST = Vals.first, StackSlot = Vals.second;
10773     if (FIST.getNode() != 0) {
10774       EVT VT = N->getValueType(0);
10775       // Return a load from the stack slot.
10776       Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
10777                                     MachinePointerInfo(), 
10778                                     false, false, false, 0));
10779     }
10780     return;
10781   }
10782   case ISD::READCYCLECOUNTER: {
10783     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10784     SDValue TheChain = N->getOperand(0);
10785     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10786     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
10787                                      rd.getValue(1));
10788     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
10789                                      eax.getValue(2));
10790     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
10791     SDValue Ops[] = { eax, edx };
10792     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
10793     Results.push_back(edx.getValue(1));
10794     return;
10795   }
10796   case ISD::ATOMIC_CMP_SWAP: {
10797     EVT T = N->getValueType(0);
10798     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
10799     bool Regs64bit = T == MVT::i128;
10800     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
10801     SDValue cpInL, cpInH;
10802     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
10803                         DAG.getConstant(0, HalfT));
10804     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
10805                         DAG.getConstant(1, HalfT));
10806     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
10807                              Regs64bit ? X86::RAX : X86::EAX,
10808                              cpInL, SDValue());
10809     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
10810                              Regs64bit ? X86::RDX : X86::EDX,
10811                              cpInH, cpInL.getValue(1));
10812     SDValue swapInL, swapInH;
10813     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
10814                           DAG.getConstant(0, HalfT));
10815     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
10816                           DAG.getConstant(1, HalfT));
10817     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
10818                                Regs64bit ? X86::RBX : X86::EBX,
10819                                swapInL, cpInH.getValue(1));
10820     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
10821                                Regs64bit ? X86::RCX : X86::ECX, 
10822                                swapInH, swapInL.getValue(1));
10823     SDValue Ops[] = { swapInH.getValue(0),
10824                       N->getOperand(1),
10825                       swapInH.getValue(1) };
10826     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10827     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
10828     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
10829                                   X86ISD::LCMPXCHG8_DAG;
10830     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
10831                                              Ops, 3, T, MMO);
10832     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
10833                                         Regs64bit ? X86::RAX : X86::EAX,
10834                                         HalfT, Result.getValue(1));
10835     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
10836                                         Regs64bit ? X86::RDX : X86::EDX,
10837                                         HalfT, cpOutL.getValue(2));
10838     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
10839     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
10840     Results.push_back(cpOutH.getValue(1));
10841     return;
10842   }
10843   case ISD::ATOMIC_LOAD_ADD:
10844     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
10845     return;
10846   case ISD::ATOMIC_LOAD_AND:
10847     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
10848     return;
10849   case ISD::ATOMIC_LOAD_NAND:
10850     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
10851     return;
10852   case ISD::ATOMIC_LOAD_OR:
10853     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
10854     return;
10855   case ISD::ATOMIC_LOAD_SUB:
10856     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
10857     return;
10858   case ISD::ATOMIC_LOAD_XOR:
10859     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
10860     return;
10861   case ISD::ATOMIC_SWAP:
10862     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
10863     return;
10864   case ISD::ATOMIC_LOAD:
10865     ReplaceATOMIC_LOAD(N, Results, DAG);
10866   }
10867 }
10868
10869 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
10870   switch (Opcode) {
10871   default: return NULL;
10872   case X86ISD::BSF:                return "X86ISD::BSF";
10873   case X86ISD::BSR:                return "X86ISD::BSR";
10874   case X86ISD::SHLD:               return "X86ISD::SHLD";
10875   case X86ISD::SHRD:               return "X86ISD::SHRD";
10876   case X86ISD::FAND:               return "X86ISD::FAND";
10877   case X86ISD::FOR:                return "X86ISD::FOR";
10878   case X86ISD::FXOR:               return "X86ISD::FXOR";
10879   case X86ISD::FSRL:               return "X86ISD::FSRL";
10880   case X86ISD::FILD:               return "X86ISD::FILD";
10881   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
10882   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
10883   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
10884   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
10885   case X86ISD::FLD:                return "X86ISD::FLD";
10886   case X86ISD::FST:                return "X86ISD::FST";
10887   case X86ISD::CALL:               return "X86ISD::CALL";
10888   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
10889   case X86ISD::BT:                 return "X86ISD::BT";
10890   case X86ISD::CMP:                return "X86ISD::CMP";
10891   case X86ISD::COMI:               return "X86ISD::COMI";
10892   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
10893   case X86ISD::SETCC:              return "X86ISD::SETCC";
10894   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
10895   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
10896   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
10897   case X86ISD::CMOV:               return "X86ISD::CMOV";
10898   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
10899   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
10900   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
10901   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
10902   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
10903   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
10904   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
10905   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
10906   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
10907   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
10908   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
10909   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
10910   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
10911   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
10912   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
10913   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
10914   case X86ISD::HADD:               return "X86ISD::HADD";
10915   case X86ISD::HSUB:               return "X86ISD::HSUB";
10916   case X86ISD::FHADD:              return "X86ISD::FHADD";
10917   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
10918   case X86ISD::FMAX:               return "X86ISD::FMAX";
10919   case X86ISD::FMIN:               return "X86ISD::FMIN";
10920   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
10921   case X86ISD::FRCP:               return "X86ISD::FRCP";
10922   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
10923   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
10924   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
10925   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
10926   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
10927   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
10928   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
10929   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
10930   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
10931   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
10932   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
10933   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
10934   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
10935   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
10936   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
10937   case X86ISD::VSHL:               return "X86ISD::VSHL";
10938   case X86ISD::VSRL:               return "X86ISD::VSRL";
10939   case X86ISD::CMPPD:              return "X86ISD::CMPPD";
10940   case X86ISD::CMPPS:              return "X86ISD::CMPPS";
10941   case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
10942   case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
10943   case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
10944   case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
10945   case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
10946   case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
10947   case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
10948   case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
10949   case X86ISD::ADD:                return "X86ISD::ADD";
10950   case X86ISD::SUB:                return "X86ISD::SUB";
10951   case X86ISD::ADC:                return "X86ISD::ADC";
10952   case X86ISD::SBB:                return "X86ISD::SBB";
10953   case X86ISD::SMUL:               return "X86ISD::SMUL";
10954   case X86ISD::UMUL:               return "X86ISD::UMUL";
10955   case X86ISD::INC:                return "X86ISD::INC";
10956   case X86ISD::DEC:                return "X86ISD::DEC";
10957   case X86ISD::OR:                 return "X86ISD::OR";
10958   case X86ISD::XOR:                return "X86ISD::XOR";
10959   case X86ISD::AND:                return "X86ISD::AND";
10960   case X86ISD::ANDN:               return "X86ISD::ANDN";
10961   case X86ISD::BLSI:               return "X86ISD::BLSI";
10962   case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
10963   case X86ISD::BLSR:               return "X86ISD::BLSR";
10964   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
10965   case X86ISD::PTEST:              return "X86ISD::PTEST";
10966   case X86ISD::TESTP:              return "X86ISD::TESTP";
10967   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
10968   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
10969   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
10970   case X86ISD::PSHUFHW_LD:         return "X86ISD::PSHUFHW_LD";
10971   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
10972   case X86ISD::PSHUFLW_LD:         return "X86ISD::PSHUFLW_LD";
10973   case X86ISD::SHUFPS:             return "X86ISD::SHUFPS";
10974   case X86ISD::SHUFPD:             return "X86ISD::SHUFPD";
10975   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
10976   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
10977   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
10978   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
10979   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
10980   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
10981   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
10982   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
10983   case X86ISD::MOVSHDUP_LD:        return "X86ISD::MOVSHDUP_LD";
10984   case X86ISD::MOVSLDUP_LD:        return "X86ISD::MOVSLDUP_LD";
10985   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
10986   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
10987   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
10988   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
10989   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
10990   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
10991   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
10992   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
10993   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
10994   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
10995   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
10996   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
10997   }
10998 }
10999
11000 // isLegalAddressingMode - Return true if the addressing mode represented
11001 // by AM is legal for this target, for a load/store of the specified type.
11002 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
11003                                               Type *Ty) const {
11004   // X86 supports extremely general addressing modes.
11005   CodeModel::Model M = getTargetMachine().getCodeModel();
11006   Reloc::Model R = getTargetMachine().getRelocationModel();
11007
11008   // X86 allows a sign-extended 32-bit immediate field as a displacement.
11009   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
11010     return false;
11011
11012   if (AM.BaseGV) {
11013     unsigned GVFlags =
11014       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
11015
11016     // If a reference to this global requires an extra load, we can't fold it.
11017     if (isGlobalStubReference(GVFlags))
11018       return false;
11019
11020     // If BaseGV requires a register for the PIC base, we cannot also have a
11021     // BaseReg specified.
11022     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
11023       return false;
11024
11025     // If lower 4G is not available, then we must use rip-relative addressing.
11026     if ((M != CodeModel::Small || R != Reloc::Static) &&
11027         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
11028       return false;
11029   }
11030
11031   switch (AM.Scale) {
11032   case 0:
11033   case 1:
11034   case 2:
11035   case 4:
11036   case 8:
11037     // These scales always work.
11038     break;
11039   case 3:
11040   case 5:
11041   case 9:
11042     // These scales are formed with basereg+scalereg.  Only accept if there is
11043     // no basereg yet.
11044     if (AM.HasBaseReg)
11045       return false;
11046     break;
11047   default:  // Other stuff never works.
11048     return false;
11049   }
11050
11051   return true;
11052 }
11053
11054
11055 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11056   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11057     return false;
11058   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11059   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11060   if (NumBits1 <= NumBits2)
11061     return false;
11062   return true;
11063 }
11064
11065 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11066   if (!VT1.isInteger() || !VT2.isInteger())
11067     return false;
11068   unsigned NumBits1 = VT1.getSizeInBits();
11069   unsigned NumBits2 = VT2.getSizeInBits();
11070   if (NumBits1 <= NumBits2)
11071     return false;
11072   return true;
11073 }
11074
11075 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
11076   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11077   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
11078 }
11079
11080 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
11081   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11082   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
11083 }
11084
11085 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
11086   // i16 instructions are longer (0x66 prefix) and potentially slower.
11087   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
11088 }
11089
11090 /// isShuffleMaskLegal - Targets can use this to indicate that they only
11091 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
11092 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
11093 /// are assumed to be legal.
11094 bool
11095 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
11096                                       EVT VT) const {
11097   // Very little shuffling can be done for 64-bit vectors right now.
11098   if (VT.getSizeInBits() == 64)
11099     return false;
11100
11101   // FIXME: pshufb, blends, shifts.
11102   return (VT.getVectorNumElements() == 2 ||
11103           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
11104           isMOVLMask(M, VT) ||
11105           isSHUFPMask(M, VT) ||
11106           isPSHUFDMask(M, VT) ||
11107           isPSHUFHWMask(M, VT) ||
11108           isPSHUFLWMask(M, VT) ||
11109           isPALIGNRMask(M, VT, Subtarget->hasSSSE3orAVX()) ||
11110           isUNPCKLMask(M, VT, Subtarget->hasAVX2()) ||
11111           isUNPCKHMask(M, VT, Subtarget->hasAVX2()) ||
11112           isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasAVX2()) ||
11113           isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasAVX2()));
11114 }
11115
11116 bool
11117 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
11118                                           EVT VT) const {
11119   unsigned NumElts = VT.getVectorNumElements();
11120   // FIXME: This collection of masks seems suspect.
11121   if (NumElts == 2)
11122     return true;
11123   if (NumElts == 4 && VT.getSizeInBits() == 128) {
11124     return (isMOVLMask(Mask, VT)  ||
11125             isCommutedMOVLMask(Mask, VT, true) ||
11126             isSHUFPMask(Mask, VT) ||
11127             isSHUFPMask(Mask, VT, /* Commuted */ true));
11128   }
11129   return false;
11130 }
11131
11132 //===----------------------------------------------------------------------===//
11133 //                           X86 Scheduler Hooks
11134 //===----------------------------------------------------------------------===//
11135
11136 // private utility function
11137 MachineBasicBlock *
11138 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
11139                                                        MachineBasicBlock *MBB,
11140                                                        unsigned regOpc,
11141                                                        unsigned immOpc,
11142                                                        unsigned LoadOpc,
11143                                                        unsigned CXchgOpc,
11144                                                        unsigned notOpc,
11145                                                        unsigned EAXreg,
11146                                                        TargetRegisterClass *RC,
11147                                                        bool invSrc) const {
11148   // For the atomic bitwise operator, we generate
11149   //   thisMBB:
11150   //   newMBB:
11151   //     ld  t1 = [bitinstr.addr]
11152   //     op  t2 = t1, [bitinstr.val]
11153   //     mov EAX = t1
11154   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
11155   //     bz  newMBB
11156   //     fallthrough -->nextMBB
11157   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11158   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11159   MachineFunction::iterator MBBIter = MBB;
11160   ++MBBIter;
11161
11162   /// First build the CFG
11163   MachineFunction *F = MBB->getParent();
11164   MachineBasicBlock *thisMBB = MBB;
11165   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11166   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11167   F->insert(MBBIter, newMBB);
11168   F->insert(MBBIter, nextMBB);
11169
11170   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11171   nextMBB->splice(nextMBB->begin(), thisMBB,
11172                   llvm::next(MachineBasicBlock::iterator(bInstr)),
11173                   thisMBB->end());
11174   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11175
11176   // Update thisMBB to fall through to newMBB
11177   thisMBB->addSuccessor(newMBB);
11178
11179   // newMBB jumps to itself and fall through to nextMBB
11180   newMBB->addSuccessor(nextMBB);
11181   newMBB->addSuccessor(newMBB);
11182
11183   // Insert instructions into newMBB based on incoming instruction
11184   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11185          "unexpected number of operands");
11186   DebugLoc dl = bInstr->getDebugLoc();
11187   MachineOperand& destOper = bInstr->getOperand(0);
11188   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11189   int numArgs = bInstr->getNumOperands() - 1;
11190   for (int i=0; i < numArgs; ++i)
11191     argOpers[i] = &bInstr->getOperand(i+1);
11192
11193   // x86 address has 4 operands: base, index, scale, and displacement
11194   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11195   int valArgIndx = lastAddrIndx + 1;
11196
11197   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11198   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
11199   for (int i=0; i <= lastAddrIndx; ++i)
11200     (*MIB).addOperand(*argOpers[i]);
11201
11202   unsigned tt = F->getRegInfo().createVirtualRegister(RC);
11203   if (invSrc) {
11204     MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
11205   }
11206   else
11207     tt = t1;
11208
11209   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11210   assert((argOpers[valArgIndx]->isReg() ||
11211           argOpers[valArgIndx]->isImm()) &&
11212          "invalid operand");
11213   if (argOpers[valArgIndx]->isReg())
11214     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
11215   else
11216     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
11217   MIB.addReg(tt);
11218   (*MIB).addOperand(*argOpers[valArgIndx]);
11219
11220   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
11221   MIB.addReg(t1);
11222
11223   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
11224   for (int i=0; i <= lastAddrIndx; ++i)
11225     (*MIB).addOperand(*argOpers[i]);
11226   MIB.addReg(t2);
11227   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11228   (*MIB).setMemRefs(bInstr->memoperands_begin(),
11229                     bInstr->memoperands_end());
11230
11231   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11232   MIB.addReg(EAXreg);
11233
11234   // insert branch
11235   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11236
11237   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
11238   return nextMBB;
11239 }
11240
11241 // private utility function:  64 bit atomics on 32 bit host.
11242 MachineBasicBlock *
11243 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
11244                                                        MachineBasicBlock *MBB,
11245                                                        unsigned regOpcL,
11246                                                        unsigned regOpcH,
11247                                                        unsigned immOpcL,
11248                                                        unsigned immOpcH,
11249                                                        bool invSrc) const {
11250   // For the atomic bitwise operator, we generate
11251   //   thisMBB (instructions are in pairs, except cmpxchg8b)
11252   //     ld t1,t2 = [bitinstr.addr]
11253   //   newMBB:
11254   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
11255   //     op  t5, t6 <- out1, out2, [bitinstr.val]
11256   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
11257   //     mov ECX, EBX <- t5, t6
11258   //     mov EAX, EDX <- t1, t2
11259   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
11260   //     mov t3, t4 <- EAX, EDX
11261   //     bz  newMBB
11262   //     result in out1, out2
11263   //     fallthrough -->nextMBB
11264
11265   const TargetRegisterClass *RC = X86::GR32RegisterClass;
11266   const unsigned LoadOpc = X86::MOV32rm;
11267   const unsigned NotOpc = X86::NOT32r;
11268   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11269   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11270   MachineFunction::iterator MBBIter = MBB;
11271   ++MBBIter;
11272
11273   /// First build the CFG
11274   MachineFunction *F = MBB->getParent();
11275   MachineBasicBlock *thisMBB = MBB;
11276   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11277   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11278   F->insert(MBBIter, newMBB);
11279   F->insert(MBBIter, nextMBB);
11280
11281   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11282   nextMBB->splice(nextMBB->begin(), thisMBB,
11283                   llvm::next(MachineBasicBlock::iterator(bInstr)),
11284                   thisMBB->end());
11285   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11286
11287   // Update thisMBB to fall through to newMBB
11288   thisMBB->addSuccessor(newMBB);
11289
11290   // newMBB jumps to itself and fall through to nextMBB
11291   newMBB->addSuccessor(nextMBB);
11292   newMBB->addSuccessor(newMBB);
11293
11294   DebugLoc dl = bInstr->getDebugLoc();
11295   // Insert instructions into newMBB based on incoming instruction
11296   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
11297   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
11298          "unexpected number of operands");
11299   MachineOperand& dest1Oper = bInstr->getOperand(0);
11300   MachineOperand& dest2Oper = bInstr->getOperand(1);
11301   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11302   for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
11303     argOpers[i] = &bInstr->getOperand(i+2);
11304
11305     // We use some of the operands multiple times, so conservatively just
11306     // clear any kill flags that might be present.
11307     if (argOpers[i]->isReg() && argOpers[i]->isUse())
11308       argOpers[i]->setIsKill(false);
11309   }
11310
11311   // x86 address has 5 operands: base, index, scale, displacement, and segment.
11312   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11313
11314   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11315   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
11316   for (int i=0; i <= lastAddrIndx; ++i)
11317     (*MIB).addOperand(*argOpers[i]);
11318   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11319   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
11320   // add 4 to displacement.
11321   for (int i=0; i <= lastAddrIndx-2; ++i)
11322     (*MIB).addOperand(*argOpers[i]);
11323   MachineOperand newOp3 = *(argOpers[3]);
11324   if (newOp3.isImm())
11325     newOp3.setImm(newOp3.getImm()+4);
11326   else
11327     newOp3.setOffset(newOp3.getOffset()+4);
11328   (*MIB).addOperand(newOp3);
11329   (*MIB).addOperand(*argOpers[lastAddrIndx]);
11330
11331   // t3/4 are defined later, at the bottom of the loop
11332   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11333   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
11334   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
11335     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
11336   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
11337     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
11338
11339   // The subsequent operations should be using the destination registers of
11340   //the PHI instructions.
11341   if (invSrc) {
11342     t1 = F->getRegInfo().createVirtualRegister(RC);
11343     t2 = F->getRegInfo().createVirtualRegister(RC);
11344     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
11345     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
11346   } else {
11347     t1 = dest1Oper.getReg();
11348     t2 = dest2Oper.getReg();
11349   }
11350
11351   int valArgIndx = lastAddrIndx + 1;
11352   assert((argOpers[valArgIndx]->isReg() ||
11353           argOpers[valArgIndx]->isImm()) &&
11354          "invalid operand");
11355   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
11356   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
11357   if (argOpers[valArgIndx]->isReg())
11358     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
11359   else
11360     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
11361   if (regOpcL != X86::MOV32rr)
11362     MIB.addReg(t1);
11363   (*MIB).addOperand(*argOpers[valArgIndx]);
11364   assert(argOpers[valArgIndx + 1]->isReg() ==
11365          argOpers[valArgIndx]->isReg());
11366   assert(argOpers[valArgIndx + 1]->isImm() ==
11367          argOpers[valArgIndx]->isImm());
11368   if (argOpers[valArgIndx + 1]->isReg())
11369     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
11370   else
11371     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
11372   if (regOpcH != X86::MOV32rr)
11373     MIB.addReg(t2);
11374   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
11375
11376   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11377   MIB.addReg(t1);
11378   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
11379   MIB.addReg(t2);
11380
11381   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
11382   MIB.addReg(t5);
11383   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
11384   MIB.addReg(t6);
11385
11386   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
11387   for (int i=0; i <= lastAddrIndx; ++i)
11388     (*MIB).addOperand(*argOpers[i]);
11389
11390   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11391   (*MIB).setMemRefs(bInstr->memoperands_begin(),
11392                     bInstr->memoperands_end());
11393
11394   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
11395   MIB.addReg(X86::EAX);
11396   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
11397   MIB.addReg(X86::EDX);
11398
11399   // insert branch
11400   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11401
11402   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
11403   return nextMBB;
11404 }
11405
11406 // private utility function
11407 MachineBasicBlock *
11408 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
11409                                                       MachineBasicBlock *MBB,
11410                                                       unsigned cmovOpc) const {
11411   // For the atomic min/max operator, we generate
11412   //   thisMBB:
11413   //   newMBB:
11414   //     ld t1 = [min/max.addr]
11415   //     mov t2 = [min/max.val]
11416   //     cmp  t1, t2
11417   //     cmov[cond] t2 = t1
11418   //     mov EAX = t1
11419   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
11420   //     bz   newMBB
11421   //     fallthrough -->nextMBB
11422   //
11423   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11424   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11425   MachineFunction::iterator MBBIter = MBB;
11426   ++MBBIter;
11427
11428   /// First build the CFG
11429   MachineFunction *F = MBB->getParent();
11430   MachineBasicBlock *thisMBB = MBB;
11431   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11432   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11433   F->insert(MBBIter, newMBB);
11434   F->insert(MBBIter, nextMBB);
11435
11436   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11437   nextMBB->splice(nextMBB->begin(), thisMBB,
11438                   llvm::next(MachineBasicBlock::iterator(mInstr)),
11439                   thisMBB->end());
11440   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11441
11442   // Update thisMBB to fall through to newMBB
11443   thisMBB->addSuccessor(newMBB);
11444
11445   // newMBB jumps to newMBB and fall through to nextMBB
11446   newMBB->addSuccessor(nextMBB);
11447   newMBB->addSuccessor(newMBB);
11448
11449   DebugLoc dl = mInstr->getDebugLoc();
11450   // Insert instructions into newMBB based on incoming instruction
11451   assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11452          "unexpected number of operands");
11453   MachineOperand& destOper = mInstr->getOperand(0);
11454   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11455   int numArgs = mInstr->getNumOperands() - 1;
11456   for (int i=0; i < numArgs; ++i)
11457     argOpers[i] = &mInstr->getOperand(i+1);
11458
11459   // x86 address has 4 operands: base, index, scale, and displacement
11460   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11461   int valArgIndx = lastAddrIndx + 1;
11462
11463   unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11464   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
11465   for (int i=0; i <= lastAddrIndx; ++i)
11466     (*MIB).addOperand(*argOpers[i]);
11467
11468   // We only support register and immediate values
11469   assert((argOpers[valArgIndx]->isReg() ||
11470           argOpers[valArgIndx]->isImm()) &&
11471          "invalid operand");
11472
11473   unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11474   if (argOpers[valArgIndx]->isReg())
11475     MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
11476   else
11477     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
11478   (*MIB).addOperand(*argOpers[valArgIndx]);
11479
11480   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11481   MIB.addReg(t1);
11482
11483   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
11484   MIB.addReg(t1);
11485   MIB.addReg(t2);
11486
11487   // Generate movc
11488   unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11489   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
11490   MIB.addReg(t2);
11491   MIB.addReg(t1);
11492
11493   // Cmp and exchange if none has modified the memory location
11494   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
11495   for (int i=0; i <= lastAddrIndx; ++i)
11496     (*MIB).addOperand(*argOpers[i]);
11497   MIB.addReg(t3);
11498   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11499   (*MIB).setMemRefs(mInstr->memoperands_begin(),
11500                     mInstr->memoperands_end());
11501
11502   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11503   MIB.addReg(X86::EAX);
11504
11505   // insert branch
11506   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11507
11508   mInstr->eraseFromParent();   // The pseudo instruction is gone now.
11509   return nextMBB;
11510 }
11511
11512 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
11513 // or XMM0_V32I8 in AVX all of this code can be replaced with that
11514 // in the .td file.
11515 MachineBasicBlock *
11516 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
11517                             unsigned numArgs, bool memArg) const {
11518   assert(Subtarget->hasSSE42orAVX() &&
11519          "Target must have SSE4.2 or AVX features enabled");
11520
11521   DebugLoc dl = MI->getDebugLoc();
11522   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11523   unsigned Opc;
11524   if (!Subtarget->hasAVX()) {
11525     if (memArg)
11526       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
11527     else
11528       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
11529   } else {
11530     if (memArg)
11531       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
11532     else
11533       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
11534   }
11535
11536   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
11537   for (unsigned i = 0; i < numArgs; ++i) {
11538     MachineOperand &Op = MI->getOperand(i+1);
11539     if (!(Op.isReg() && Op.isImplicit()))
11540       MIB.addOperand(Op);
11541   }
11542   BuildMI(*BB, MI, dl,
11543     TII->get(Subtarget->hasAVX() ? X86::VMOVAPSrr : X86::MOVAPSrr),
11544              MI->getOperand(0).getReg())
11545     .addReg(X86::XMM0);
11546
11547   MI->eraseFromParent();
11548   return BB;
11549 }
11550
11551 MachineBasicBlock *
11552 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
11553   DebugLoc dl = MI->getDebugLoc();
11554   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11555
11556   // Address into RAX/EAX, other two args into ECX, EDX.
11557   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
11558   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11559   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
11560   for (int i = 0; i < X86::AddrNumOperands; ++i)
11561     MIB.addOperand(MI->getOperand(i));
11562
11563   unsigned ValOps = X86::AddrNumOperands;
11564   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11565     .addReg(MI->getOperand(ValOps).getReg());
11566   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
11567     .addReg(MI->getOperand(ValOps+1).getReg());
11568
11569   // The instruction doesn't actually take any operands though.
11570   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
11571
11572   MI->eraseFromParent(); // The pseudo is gone now.
11573   return BB;
11574 }
11575
11576 MachineBasicBlock *
11577 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
11578   DebugLoc dl = MI->getDebugLoc();
11579   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11580
11581   // First arg in ECX, the second in EAX.
11582   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11583     .addReg(MI->getOperand(0).getReg());
11584   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
11585     .addReg(MI->getOperand(1).getReg());
11586
11587   // The instruction doesn't actually take any operands though.
11588   BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
11589
11590   MI->eraseFromParent(); // The pseudo is gone now.
11591   return BB;
11592 }
11593
11594 MachineBasicBlock *
11595 X86TargetLowering::EmitVAARG64WithCustomInserter(
11596                    MachineInstr *MI,
11597                    MachineBasicBlock *MBB) const {
11598   // Emit va_arg instruction on X86-64.
11599
11600   // Operands to this pseudo-instruction:
11601   // 0  ) Output        : destination address (reg)
11602   // 1-5) Input         : va_list address (addr, i64mem)
11603   // 6  ) ArgSize       : Size (in bytes) of vararg type
11604   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
11605   // 8  ) Align         : Alignment of type
11606   // 9  ) EFLAGS (implicit-def)
11607
11608   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
11609   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
11610
11611   unsigned DestReg = MI->getOperand(0).getReg();
11612   MachineOperand &Base = MI->getOperand(1);
11613   MachineOperand &Scale = MI->getOperand(2);
11614   MachineOperand &Index = MI->getOperand(3);
11615   MachineOperand &Disp = MI->getOperand(4);
11616   MachineOperand &Segment = MI->getOperand(5);
11617   unsigned ArgSize = MI->getOperand(6).getImm();
11618   unsigned ArgMode = MI->getOperand(7).getImm();
11619   unsigned Align = MI->getOperand(8).getImm();
11620
11621   // Memory Reference
11622   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
11623   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
11624   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
11625
11626   // Machine Information
11627   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11628   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
11629   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
11630   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
11631   DebugLoc DL = MI->getDebugLoc();
11632
11633   // struct va_list {
11634   //   i32   gp_offset
11635   //   i32   fp_offset
11636   //   i64   overflow_area (address)
11637   //   i64   reg_save_area (address)
11638   // }
11639   // sizeof(va_list) = 24
11640   // alignment(va_list) = 8
11641
11642   unsigned TotalNumIntRegs = 6;
11643   unsigned TotalNumXMMRegs = 8;
11644   bool UseGPOffset = (ArgMode == 1);
11645   bool UseFPOffset = (ArgMode == 2);
11646   unsigned MaxOffset = TotalNumIntRegs * 8 +
11647                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
11648
11649   /* Align ArgSize to a multiple of 8 */
11650   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
11651   bool NeedsAlign = (Align > 8);
11652
11653   MachineBasicBlock *thisMBB = MBB;
11654   MachineBasicBlock *overflowMBB;
11655   MachineBasicBlock *offsetMBB;
11656   MachineBasicBlock *endMBB;
11657
11658   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
11659   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
11660   unsigned OffsetReg = 0;
11661
11662   if (!UseGPOffset && !UseFPOffset) {
11663     // If we only pull from the overflow region, we don't create a branch.
11664     // We don't need to alter control flow.
11665     OffsetDestReg = 0; // unused
11666     OverflowDestReg = DestReg;
11667
11668     offsetMBB = NULL;
11669     overflowMBB = thisMBB;
11670     endMBB = thisMBB;
11671   } else {
11672     // First emit code to check if gp_offset (or fp_offset) is below the bound.
11673     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
11674     // If not, pull from overflow_area. (branch to overflowMBB)
11675     //
11676     //       thisMBB
11677     //         |     .
11678     //         |        .
11679     //     offsetMBB   overflowMBB
11680     //         |        .
11681     //         |     .
11682     //        endMBB
11683
11684     // Registers for the PHI in endMBB
11685     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
11686     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
11687
11688     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11689     MachineFunction *MF = MBB->getParent();
11690     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11691     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11692     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11693
11694     MachineFunction::iterator MBBIter = MBB;
11695     ++MBBIter;
11696
11697     // Insert the new basic blocks
11698     MF->insert(MBBIter, offsetMBB);
11699     MF->insert(MBBIter, overflowMBB);
11700     MF->insert(MBBIter, endMBB);
11701
11702     // Transfer the remainder of MBB and its successor edges to endMBB.
11703     endMBB->splice(endMBB->begin(), thisMBB,
11704                     llvm::next(MachineBasicBlock::iterator(MI)),
11705                     thisMBB->end());
11706     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11707
11708     // Make offsetMBB and overflowMBB successors of thisMBB
11709     thisMBB->addSuccessor(offsetMBB);
11710     thisMBB->addSuccessor(overflowMBB);
11711
11712     // endMBB is a successor of both offsetMBB and overflowMBB
11713     offsetMBB->addSuccessor(endMBB);
11714     overflowMBB->addSuccessor(endMBB);
11715
11716     // Load the offset value into a register
11717     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
11718     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
11719       .addOperand(Base)
11720       .addOperand(Scale)
11721       .addOperand(Index)
11722       .addDisp(Disp, UseFPOffset ? 4 : 0)
11723       .addOperand(Segment)
11724       .setMemRefs(MMOBegin, MMOEnd);
11725
11726     // Check if there is enough room left to pull this argument.
11727     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
11728       .addReg(OffsetReg)
11729       .addImm(MaxOffset + 8 - ArgSizeA8);
11730
11731     // Branch to "overflowMBB" if offset >= max
11732     // Fall through to "offsetMBB" otherwise
11733     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
11734       .addMBB(overflowMBB);
11735   }
11736
11737   // In offsetMBB, emit code to use the reg_save_area.
11738   if (offsetMBB) {
11739     assert(OffsetReg != 0);
11740
11741     // Read the reg_save_area address.
11742     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
11743     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
11744       .addOperand(Base)
11745       .addOperand(Scale)
11746       .addOperand(Index)
11747       .addDisp(Disp, 16)
11748       .addOperand(Segment)
11749       .setMemRefs(MMOBegin, MMOEnd);
11750
11751     // Zero-extend the offset
11752     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
11753       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
11754         .addImm(0)
11755         .addReg(OffsetReg)
11756         .addImm(X86::sub_32bit);
11757
11758     // Add the offset to the reg_save_area to get the final address.
11759     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
11760       .addReg(OffsetReg64)
11761       .addReg(RegSaveReg);
11762
11763     // Compute the offset for the next argument
11764     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
11765     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
11766       .addReg(OffsetReg)
11767       .addImm(UseFPOffset ? 16 : 8);
11768
11769     // Store it back into the va_list.
11770     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
11771       .addOperand(Base)
11772       .addOperand(Scale)
11773       .addOperand(Index)
11774       .addDisp(Disp, UseFPOffset ? 4 : 0)
11775       .addOperand(Segment)
11776       .addReg(NextOffsetReg)
11777       .setMemRefs(MMOBegin, MMOEnd);
11778
11779     // Jump to endMBB
11780     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
11781       .addMBB(endMBB);
11782   }
11783
11784   //
11785   // Emit code to use overflow area
11786   //
11787
11788   // Load the overflow_area address into a register.
11789   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
11790   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
11791     .addOperand(Base)
11792     .addOperand(Scale)
11793     .addOperand(Index)
11794     .addDisp(Disp, 8)
11795     .addOperand(Segment)
11796     .setMemRefs(MMOBegin, MMOEnd);
11797
11798   // If we need to align it, do so. Otherwise, just copy the address
11799   // to OverflowDestReg.
11800   if (NeedsAlign) {
11801     // Align the overflow address
11802     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
11803     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
11804
11805     // aligned_addr = (addr + (align-1)) & ~(align-1)
11806     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
11807       .addReg(OverflowAddrReg)
11808       .addImm(Align-1);
11809
11810     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
11811       .addReg(TmpReg)
11812       .addImm(~(uint64_t)(Align-1));
11813   } else {
11814     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
11815       .addReg(OverflowAddrReg);
11816   }
11817
11818   // Compute the next overflow address after this argument.
11819   // (the overflow address should be kept 8-byte aligned)
11820   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
11821   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
11822     .addReg(OverflowDestReg)
11823     .addImm(ArgSizeA8);
11824
11825   // Store the new overflow address.
11826   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
11827     .addOperand(Base)
11828     .addOperand(Scale)
11829     .addOperand(Index)
11830     .addDisp(Disp, 8)
11831     .addOperand(Segment)
11832     .addReg(NextAddrReg)
11833     .setMemRefs(MMOBegin, MMOEnd);
11834
11835   // If we branched, emit the PHI to the front of endMBB.
11836   if (offsetMBB) {
11837     BuildMI(*endMBB, endMBB->begin(), DL,
11838             TII->get(X86::PHI), DestReg)
11839       .addReg(OffsetDestReg).addMBB(offsetMBB)
11840       .addReg(OverflowDestReg).addMBB(overflowMBB);
11841   }
11842
11843   // Erase the pseudo instruction
11844   MI->eraseFromParent();
11845
11846   return endMBB;
11847 }
11848
11849 MachineBasicBlock *
11850 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
11851                                                  MachineInstr *MI,
11852                                                  MachineBasicBlock *MBB) const {
11853   // Emit code to save XMM registers to the stack. The ABI says that the
11854   // number of registers to save is given in %al, so it's theoretically
11855   // possible to do an indirect jump trick to avoid saving all of them,
11856   // however this code takes a simpler approach and just executes all
11857   // of the stores if %al is non-zero. It's less code, and it's probably
11858   // easier on the hardware branch predictor, and stores aren't all that
11859   // expensive anyway.
11860
11861   // Create the new basic blocks. One block contains all the XMM stores,
11862   // and one block is the final destination regardless of whether any
11863   // stores were performed.
11864   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11865   MachineFunction *F = MBB->getParent();
11866   MachineFunction::iterator MBBIter = MBB;
11867   ++MBBIter;
11868   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
11869   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
11870   F->insert(MBBIter, XMMSaveMBB);
11871   F->insert(MBBIter, EndMBB);
11872
11873   // Transfer the remainder of MBB and its successor edges to EndMBB.
11874   EndMBB->splice(EndMBB->begin(), MBB,
11875                  llvm::next(MachineBasicBlock::iterator(MI)),
11876                  MBB->end());
11877   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
11878
11879   // The original block will now fall through to the XMM save block.
11880   MBB->addSuccessor(XMMSaveMBB);
11881   // The XMMSaveMBB will fall through to the end block.
11882   XMMSaveMBB->addSuccessor(EndMBB);
11883
11884   // Now add the instructions.
11885   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11886   DebugLoc DL = MI->getDebugLoc();
11887
11888   unsigned CountReg = MI->getOperand(0).getReg();
11889   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
11890   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
11891
11892   if (!Subtarget->isTargetWin64()) {
11893     // If %al is 0, branch around the XMM save block.
11894     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
11895     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
11896     MBB->addSuccessor(EndMBB);
11897   }
11898
11899   unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
11900   // In the XMM save block, save all the XMM argument registers.
11901   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
11902     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
11903     MachineMemOperand *MMO =
11904       F->getMachineMemOperand(
11905           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
11906         MachineMemOperand::MOStore,
11907         /*Size=*/16, /*Align=*/16);
11908     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
11909       .addFrameIndex(RegSaveFrameIndex)
11910       .addImm(/*Scale=*/1)
11911       .addReg(/*IndexReg=*/0)
11912       .addImm(/*Disp=*/Offset)
11913       .addReg(/*Segment=*/0)
11914       .addReg(MI->getOperand(i).getReg())
11915       .addMemOperand(MMO);
11916   }
11917
11918   MI->eraseFromParent();   // The pseudo instruction is gone now.
11919
11920   return EndMBB;
11921 }
11922
11923 MachineBasicBlock *
11924 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
11925                                      MachineBasicBlock *BB) const {
11926   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11927   DebugLoc DL = MI->getDebugLoc();
11928
11929   // To "insert" a SELECT_CC instruction, we actually have to insert the
11930   // diamond control-flow pattern.  The incoming instruction knows the
11931   // destination vreg to set, the condition code register to branch on, the
11932   // true/false values to select between, and a branch opcode to use.
11933   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11934   MachineFunction::iterator It = BB;
11935   ++It;
11936
11937   //  thisMBB:
11938   //  ...
11939   //   TrueVal = ...
11940   //   cmpTY ccX, r1, r2
11941   //   bCC copy1MBB
11942   //   fallthrough --> copy0MBB
11943   MachineBasicBlock *thisMBB = BB;
11944   MachineFunction *F = BB->getParent();
11945   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
11946   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11947   F->insert(It, copy0MBB);
11948   F->insert(It, sinkMBB);
11949
11950   // If the EFLAGS register isn't dead in the terminator, then claim that it's
11951   // live into the sink and copy blocks.
11952   if (!MI->killsRegister(X86::EFLAGS)) {
11953     copy0MBB->addLiveIn(X86::EFLAGS);
11954     sinkMBB->addLiveIn(X86::EFLAGS);
11955   }
11956
11957   // Transfer the remainder of BB and its successor edges to sinkMBB.
11958   sinkMBB->splice(sinkMBB->begin(), BB,
11959                   llvm::next(MachineBasicBlock::iterator(MI)),
11960                   BB->end());
11961   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11962
11963   // Add the true and fallthrough blocks as its successors.
11964   BB->addSuccessor(copy0MBB);
11965   BB->addSuccessor(sinkMBB);
11966
11967   // Create the conditional branch instruction.
11968   unsigned Opc =
11969     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
11970   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
11971
11972   //  copy0MBB:
11973   //   %FalseValue = ...
11974   //   # fallthrough to sinkMBB
11975   copy0MBB->addSuccessor(sinkMBB);
11976
11977   //  sinkMBB:
11978   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
11979   //  ...
11980   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
11981           TII->get(X86::PHI), MI->getOperand(0).getReg())
11982     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
11983     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
11984
11985   MI->eraseFromParent();   // The pseudo instruction is gone now.
11986   return sinkMBB;
11987 }
11988
11989 MachineBasicBlock *
11990 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
11991                                         bool Is64Bit) const {
11992   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11993   DebugLoc DL = MI->getDebugLoc();
11994   MachineFunction *MF = BB->getParent();
11995   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11996
11997   assert(getTargetMachine().Options.EnableSegmentedStacks);
11998
11999   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
12000   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
12001
12002   // BB:
12003   //  ... [Till the alloca]
12004   // If stacklet is not large enough, jump to mallocMBB
12005   //
12006   // bumpMBB:
12007   //  Allocate by subtracting from RSP
12008   //  Jump to continueMBB
12009   //
12010   // mallocMBB:
12011   //  Allocate by call to runtime
12012   //
12013   // continueMBB:
12014   //  ...
12015   //  [rest of original BB]
12016   //
12017
12018   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12019   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12020   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12021
12022   MachineRegisterInfo &MRI = MF->getRegInfo();
12023   const TargetRegisterClass *AddrRegClass =
12024     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
12025
12026   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12027     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12028     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
12029     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
12030     sizeVReg = MI->getOperand(1).getReg(),
12031     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
12032
12033   MachineFunction::iterator MBBIter = BB;
12034   ++MBBIter;
12035
12036   MF->insert(MBBIter, bumpMBB);
12037   MF->insert(MBBIter, mallocMBB);
12038   MF->insert(MBBIter, continueMBB);
12039
12040   continueMBB->splice(continueMBB->begin(), BB, llvm::next
12041                       (MachineBasicBlock::iterator(MI)), BB->end());
12042   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
12043
12044   // Add code to the main basic block to check if the stack limit has been hit,
12045   // and if so, jump to mallocMBB otherwise to bumpMBB.
12046   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
12047   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
12048     .addReg(tmpSPVReg).addReg(sizeVReg);
12049   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
12050     .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg)
12051     .addReg(SPLimitVReg);
12052   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
12053
12054   // bumpMBB simply decreases the stack pointer, since we know the current
12055   // stacklet has enough space.
12056   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
12057     .addReg(SPLimitVReg);
12058   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
12059     .addReg(SPLimitVReg);
12060   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12061
12062   // Calls into a routine in libgcc to allocate more space from the heap.
12063   if (Is64Bit) {
12064     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
12065       .addReg(sizeVReg);
12066     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
12067     .addExternalSymbol("__morestack_allocate_stack_space").addReg(X86::RDI);
12068   } else {
12069     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
12070       .addImm(12);
12071     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
12072     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
12073       .addExternalSymbol("__morestack_allocate_stack_space");
12074   }
12075
12076   if (!Is64Bit)
12077     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
12078       .addImm(16);
12079
12080   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
12081     .addReg(Is64Bit ? X86::RAX : X86::EAX);
12082   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12083
12084   // Set up the CFG correctly.
12085   BB->addSuccessor(bumpMBB);
12086   BB->addSuccessor(mallocMBB);
12087   mallocMBB->addSuccessor(continueMBB);
12088   bumpMBB->addSuccessor(continueMBB);
12089
12090   // Take care of the PHI nodes.
12091   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
12092           MI->getOperand(0).getReg())
12093     .addReg(mallocPtrVReg).addMBB(mallocMBB)
12094     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
12095
12096   // Delete the original pseudo instruction.
12097   MI->eraseFromParent();
12098
12099   // And we're done.
12100   return continueMBB;
12101 }
12102
12103 MachineBasicBlock *
12104 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
12105                                           MachineBasicBlock *BB) const {
12106   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12107   DebugLoc DL = MI->getDebugLoc();
12108
12109   assert(!Subtarget->isTargetEnvMacho());
12110
12111   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
12112   // non-trivial part is impdef of ESP.
12113
12114   if (Subtarget->isTargetWin64()) {
12115     if (Subtarget->isTargetCygMing()) {
12116       // ___chkstk(Mingw64):
12117       // Clobbers R10, R11, RAX and EFLAGS.
12118       // Updates RSP.
12119       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12120         .addExternalSymbol("___chkstk")
12121         .addReg(X86::RAX, RegState::Implicit)
12122         .addReg(X86::RSP, RegState::Implicit)
12123         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
12124         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
12125         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12126     } else {
12127       // __chkstk(MSVCRT): does not update stack pointer.
12128       // Clobbers R10, R11 and EFLAGS.
12129       // FIXME: RAX(allocated size) might be reused and not killed.
12130       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12131         .addExternalSymbol("__chkstk")
12132         .addReg(X86::RAX, RegState::Implicit)
12133         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12134       // RAX has the offset to subtracted from RSP.
12135       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
12136         .addReg(X86::RSP)
12137         .addReg(X86::RAX);
12138     }
12139   } else {
12140     const char *StackProbeSymbol =
12141       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
12142
12143     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
12144       .addExternalSymbol(StackProbeSymbol)
12145       .addReg(X86::EAX, RegState::Implicit)
12146       .addReg(X86::ESP, RegState::Implicit)
12147       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
12148       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
12149       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12150   }
12151
12152   MI->eraseFromParent();   // The pseudo instruction is gone now.
12153   return BB;
12154 }
12155
12156 MachineBasicBlock *
12157 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
12158                                       MachineBasicBlock *BB) const {
12159   // This is pretty easy.  We're taking the value that we received from
12160   // our load from the relocation, sticking it in either RDI (x86-64)
12161   // or EAX and doing an indirect call.  The return value will then
12162   // be in the normal return register.
12163   const X86InstrInfo *TII
12164     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
12165   DebugLoc DL = MI->getDebugLoc();
12166   MachineFunction *F = BB->getParent();
12167
12168   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
12169   assert(MI->getOperand(3).isGlobal() && "This should be a global");
12170
12171   if (Subtarget->is64Bit()) {
12172     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12173                                       TII->get(X86::MOV64rm), X86::RDI)
12174     .addReg(X86::RIP)
12175     .addImm(0).addReg(0)
12176     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12177                       MI->getOperand(3).getTargetFlags())
12178     .addReg(0);
12179     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
12180     addDirectMem(MIB, X86::RDI);
12181   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
12182     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12183                                       TII->get(X86::MOV32rm), X86::EAX)
12184     .addReg(0)
12185     .addImm(0).addReg(0)
12186     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12187                       MI->getOperand(3).getTargetFlags())
12188     .addReg(0);
12189     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12190     addDirectMem(MIB, X86::EAX);
12191   } else {
12192     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12193                                       TII->get(X86::MOV32rm), X86::EAX)
12194     .addReg(TII->getGlobalBaseReg(F))
12195     .addImm(0).addReg(0)
12196     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12197                       MI->getOperand(3).getTargetFlags())
12198     .addReg(0);
12199     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12200     addDirectMem(MIB, X86::EAX);
12201   }
12202
12203   MI->eraseFromParent(); // The pseudo instruction is gone now.
12204   return BB;
12205 }
12206
12207 MachineBasicBlock *
12208 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
12209                                                MachineBasicBlock *BB) const {
12210   switch (MI->getOpcode()) {
12211   default: assert(0 && "Unexpected instr type to insert");
12212   case X86::TAILJMPd64:
12213   case X86::TAILJMPr64:
12214   case X86::TAILJMPm64:
12215     assert(0 && "TAILJMP64 would not be touched here.");
12216   case X86::TCRETURNdi64:
12217   case X86::TCRETURNri64:
12218   case X86::TCRETURNmi64:
12219     // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset.
12220     // On AMD64, additional defs should be added before register allocation.
12221     if (!Subtarget->isTargetWin64()) {
12222       MI->addRegisterDefined(X86::RSI);
12223       MI->addRegisterDefined(X86::RDI);
12224       MI->addRegisterDefined(X86::XMM6);
12225       MI->addRegisterDefined(X86::XMM7);
12226       MI->addRegisterDefined(X86::XMM8);
12227       MI->addRegisterDefined(X86::XMM9);
12228       MI->addRegisterDefined(X86::XMM10);
12229       MI->addRegisterDefined(X86::XMM11);
12230       MI->addRegisterDefined(X86::XMM12);
12231       MI->addRegisterDefined(X86::XMM13);
12232       MI->addRegisterDefined(X86::XMM14);
12233       MI->addRegisterDefined(X86::XMM15);
12234     }
12235     return BB;
12236   case X86::WIN_ALLOCA:
12237     return EmitLoweredWinAlloca(MI, BB);
12238   case X86::SEG_ALLOCA_32:
12239     return EmitLoweredSegAlloca(MI, BB, false);
12240   case X86::SEG_ALLOCA_64:
12241     return EmitLoweredSegAlloca(MI, BB, true);
12242   case X86::TLSCall_32:
12243   case X86::TLSCall_64:
12244     return EmitLoweredTLSCall(MI, BB);
12245   case X86::CMOV_GR8:
12246   case X86::CMOV_FR32:
12247   case X86::CMOV_FR64:
12248   case X86::CMOV_V4F32:
12249   case X86::CMOV_V2F64:
12250   case X86::CMOV_V2I64:
12251   case X86::CMOV_V8F32:
12252   case X86::CMOV_V4F64:
12253   case X86::CMOV_V4I64:
12254   case X86::CMOV_GR16:
12255   case X86::CMOV_GR32:
12256   case X86::CMOV_RFP32:
12257   case X86::CMOV_RFP64:
12258   case X86::CMOV_RFP80:
12259     return EmitLoweredSelect(MI, BB);
12260
12261   case X86::FP32_TO_INT16_IN_MEM:
12262   case X86::FP32_TO_INT32_IN_MEM:
12263   case X86::FP32_TO_INT64_IN_MEM:
12264   case X86::FP64_TO_INT16_IN_MEM:
12265   case X86::FP64_TO_INT32_IN_MEM:
12266   case X86::FP64_TO_INT64_IN_MEM:
12267   case X86::FP80_TO_INT16_IN_MEM:
12268   case X86::FP80_TO_INT32_IN_MEM:
12269   case X86::FP80_TO_INT64_IN_MEM: {
12270     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12271     DebugLoc DL = MI->getDebugLoc();
12272
12273     // Change the floating point control register to use "round towards zero"
12274     // mode when truncating to an integer value.
12275     MachineFunction *F = BB->getParent();
12276     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
12277     addFrameReference(BuildMI(*BB, MI, DL,
12278                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
12279
12280     // Load the old value of the high byte of the control word...
12281     unsigned OldCW =
12282       F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
12283     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
12284                       CWFrameIdx);
12285
12286     // Set the high part to be round to zero...
12287     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
12288       .addImm(0xC7F);
12289
12290     // Reload the modified control word now...
12291     addFrameReference(BuildMI(*BB, MI, DL,
12292                               TII->get(X86::FLDCW16m)), CWFrameIdx);
12293
12294     // Restore the memory image of control word to original value
12295     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
12296       .addReg(OldCW);
12297
12298     // Get the X86 opcode to use.
12299     unsigned Opc;
12300     switch (MI->getOpcode()) {
12301     default: llvm_unreachable("illegal opcode!");
12302     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
12303     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
12304     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
12305     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
12306     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
12307     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
12308     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
12309     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
12310     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
12311     }
12312
12313     X86AddressMode AM;
12314     MachineOperand &Op = MI->getOperand(0);
12315     if (Op.isReg()) {
12316       AM.BaseType = X86AddressMode::RegBase;
12317       AM.Base.Reg = Op.getReg();
12318     } else {
12319       AM.BaseType = X86AddressMode::FrameIndexBase;
12320       AM.Base.FrameIndex = Op.getIndex();
12321     }
12322     Op = MI->getOperand(1);
12323     if (Op.isImm())
12324       AM.Scale = Op.getImm();
12325     Op = MI->getOperand(2);
12326     if (Op.isImm())
12327       AM.IndexReg = Op.getImm();
12328     Op = MI->getOperand(3);
12329     if (Op.isGlobal()) {
12330       AM.GV = Op.getGlobal();
12331     } else {
12332       AM.Disp = Op.getImm();
12333     }
12334     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
12335                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
12336
12337     // Reload the original control word now.
12338     addFrameReference(BuildMI(*BB, MI, DL,
12339                               TII->get(X86::FLDCW16m)), CWFrameIdx);
12340
12341     MI->eraseFromParent();   // The pseudo instruction is gone now.
12342     return BB;
12343   }
12344     // String/text processing lowering.
12345   case X86::PCMPISTRM128REG:
12346   case X86::VPCMPISTRM128REG:
12347     return EmitPCMP(MI, BB, 3, false /* in-mem */);
12348   case X86::PCMPISTRM128MEM:
12349   case X86::VPCMPISTRM128MEM:
12350     return EmitPCMP(MI, BB, 3, true /* in-mem */);
12351   case X86::PCMPESTRM128REG:
12352   case X86::VPCMPESTRM128REG:
12353     return EmitPCMP(MI, BB, 5, false /* in mem */);
12354   case X86::PCMPESTRM128MEM:
12355   case X86::VPCMPESTRM128MEM:
12356     return EmitPCMP(MI, BB, 5, true /* in mem */);
12357
12358     // Thread synchronization.
12359   case X86::MONITOR:
12360     return EmitMonitor(MI, BB);
12361   case X86::MWAIT:
12362     return EmitMwait(MI, BB);
12363
12364     // Atomic Lowering.
12365   case X86::ATOMAND32:
12366     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12367                                                X86::AND32ri, X86::MOV32rm,
12368                                                X86::LCMPXCHG32,
12369                                                X86::NOT32r, X86::EAX,
12370                                                X86::GR32RegisterClass);
12371   case X86::ATOMOR32:
12372     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
12373                                                X86::OR32ri, X86::MOV32rm,
12374                                                X86::LCMPXCHG32,
12375                                                X86::NOT32r, X86::EAX,
12376                                                X86::GR32RegisterClass);
12377   case X86::ATOMXOR32:
12378     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
12379                                                X86::XOR32ri, X86::MOV32rm,
12380                                                X86::LCMPXCHG32,
12381                                                X86::NOT32r, X86::EAX,
12382                                                X86::GR32RegisterClass);
12383   case X86::ATOMNAND32:
12384     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12385                                                X86::AND32ri, X86::MOV32rm,
12386                                                X86::LCMPXCHG32,
12387                                                X86::NOT32r, X86::EAX,
12388                                                X86::GR32RegisterClass, true);
12389   case X86::ATOMMIN32:
12390     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
12391   case X86::ATOMMAX32:
12392     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
12393   case X86::ATOMUMIN32:
12394     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
12395   case X86::ATOMUMAX32:
12396     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
12397
12398   case X86::ATOMAND16:
12399     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12400                                                X86::AND16ri, X86::MOV16rm,
12401                                                X86::LCMPXCHG16,
12402                                                X86::NOT16r, X86::AX,
12403                                                X86::GR16RegisterClass);
12404   case X86::ATOMOR16:
12405     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
12406                                                X86::OR16ri, X86::MOV16rm,
12407                                                X86::LCMPXCHG16,
12408                                                X86::NOT16r, X86::AX,
12409                                                X86::GR16RegisterClass);
12410   case X86::ATOMXOR16:
12411     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
12412                                                X86::XOR16ri, X86::MOV16rm,
12413                                                X86::LCMPXCHG16,
12414                                                X86::NOT16r, X86::AX,
12415                                                X86::GR16RegisterClass);
12416   case X86::ATOMNAND16:
12417     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12418                                                X86::AND16ri, X86::MOV16rm,
12419                                                X86::LCMPXCHG16,
12420                                                X86::NOT16r, X86::AX,
12421                                                X86::GR16RegisterClass, true);
12422   case X86::ATOMMIN16:
12423     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
12424   case X86::ATOMMAX16:
12425     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
12426   case X86::ATOMUMIN16:
12427     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
12428   case X86::ATOMUMAX16:
12429     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
12430
12431   case X86::ATOMAND8:
12432     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12433                                                X86::AND8ri, X86::MOV8rm,
12434                                                X86::LCMPXCHG8,
12435                                                X86::NOT8r, X86::AL,
12436                                                X86::GR8RegisterClass);
12437   case X86::ATOMOR8:
12438     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
12439                                                X86::OR8ri, X86::MOV8rm,
12440                                                X86::LCMPXCHG8,
12441                                                X86::NOT8r, X86::AL,
12442                                                X86::GR8RegisterClass);
12443   case X86::ATOMXOR8:
12444     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
12445                                                X86::XOR8ri, X86::MOV8rm,
12446                                                X86::LCMPXCHG8,
12447                                                X86::NOT8r, X86::AL,
12448                                                X86::GR8RegisterClass);
12449   case X86::ATOMNAND8:
12450     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12451                                                X86::AND8ri, X86::MOV8rm,
12452                                                X86::LCMPXCHG8,
12453                                                X86::NOT8r, X86::AL,
12454                                                X86::GR8RegisterClass, true);
12455   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
12456   // This group is for 64-bit host.
12457   case X86::ATOMAND64:
12458     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12459                                                X86::AND64ri32, X86::MOV64rm,
12460                                                X86::LCMPXCHG64,
12461                                                X86::NOT64r, X86::RAX,
12462                                                X86::GR64RegisterClass);
12463   case X86::ATOMOR64:
12464     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
12465                                                X86::OR64ri32, X86::MOV64rm,
12466                                                X86::LCMPXCHG64,
12467                                                X86::NOT64r, X86::RAX,
12468                                                X86::GR64RegisterClass);
12469   case X86::ATOMXOR64:
12470     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
12471                                                X86::XOR64ri32, X86::MOV64rm,
12472                                                X86::LCMPXCHG64,
12473                                                X86::NOT64r, X86::RAX,
12474                                                X86::GR64RegisterClass);
12475   case X86::ATOMNAND64:
12476     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12477                                                X86::AND64ri32, X86::MOV64rm,
12478                                                X86::LCMPXCHG64,
12479                                                X86::NOT64r, X86::RAX,
12480                                                X86::GR64RegisterClass, true);
12481   case X86::ATOMMIN64:
12482     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
12483   case X86::ATOMMAX64:
12484     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
12485   case X86::ATOMUMIN64:
12486     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
12487   case X86::ATOMUMAX64:
12488     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
12489
12490   // This group does 64-bit operations on a 32-bit host.
12491   case X86::ATOMAND6432:
12492     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12493                                                X86::AND32rr, X86::AND32rr,
12494                                                X86::AND32ri, X86::AND32ri,
12495                                                false);
12496   case X86::ATOMOR6432:
12497     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12498                                                X86::OR32rr, X86::OR32rr,
12499                                                X86::OR32ri, X86::OR32ri,
12500                                                false);
12501   case X86::ATOMXOR6432:
12502     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12503                                                X86::XOR32rr, X86::XOR32rr,
12504                                                X86::XOR32ri, X86::XOR32ri,
12505                                                false);
12506   case X86::ATOMNAND6432:
12507     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12508                                                X86::AND32rr, X86::AND32rr,
12509                                                X86::AND32ri, X86::AND32ri,
12510                                                true);
12511   case X86::ATOMADD6432:
12512     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12513                                                X86::ADD32rr, X86::ADC32rr,
12514                                                X86::ADD32ri, X86::ADC32ri,
12515                                                false);
12516   case X86::ATOMSUB6432:
12517     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12518                                                X86::SUB32rr, X86::SBB32rr,
12519                                                X86::SUB32ri, X86::SBB32ri,
12520                                                false);
12521   case X86::ATOMSWAP6432:
12522     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12523                                                X86::MOV32rr, X86::MOV32rr,
12524                                                X86::MOV32ri, X86::MOV32ri,
12525                                                false);
12526   case X86::VASTART_SAVE_XMM_REGS:
12527     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
12528
12529   case X86::VAARG_64:
12530     return EmitVAARG64WithCustomInserter(MI, BB);
12531   }
12532 }
12533
12534 //===----------------------------------------------------------------------===//
12535 //                           X86 Optimization Hooks
12536 //===----------------------------------------------------------------------===//
12537
12538 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
12539                                                        const APInt &Mask,
12540                                                        APInt &KnownZero,
12541                                                        APInt &KnownOne,
12542                                                        const SelectionDAG &DAG,
12543                                                        unsigned Depth) const {
12544   unsigned Opc = Op.getOpcode();
12545   assert((Opc >= ISD::BUILTIN_OP_END ||
12546           Opc == ISD::INTRINSIC_WO_CHAIN ||
12547           Opc == ISD::INTRINSIC_W_CHAIN ||
12548           Opc == ISD::INTRINSIC_VOID) &&
12549          "Should use MaskedValueIsZero if you don't know whether Op"
12550          " is a target node!");
12551
12552   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
12553   switch (Opc) {
12554   default: break;
12555   case X86ISD::ADD:
12556   case X86ISD::SUB:
12557   case X86ISD::ADC:
12558   case X86ISD::SBB:
12559   case X86ISD::SMUL:
12560   case X86ISD::UMUL:
12561   case X86ISD::INC:
12562   case X86ISD::DEC:
12563   case X86ISD::OR:
12564   case X86ISD::XOR:
12565   case X86ISD::AND:
12566     // These nodes' second result is a boolean.
12567     if (Op.getResNo() == 0)
12568       break;
12569     // Fallthrough
12570   case X86ISD::SETCC:
12571     KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
12572                                        Mask.getBitWidth() - 1);
12573     break;
12574   case ISD::INTRINSIC_WO_CHAIN: {
12575     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12576     unsigned NumLoBits = 0;
12577     switch (IntId) {
12578     default: break;
12579     case Intrinsic::x86_sse_movmsk_ps:
12580     case Intrinsic::x86_avx_movmsk_ps_256:
12581     case Intrinsic::x86_sse2_movmsk_pd:
12582     case Intrinsic::x86_avx_movmsk_pd_256:
12583     case Intrinsic::x86_mmx_pmovmskb:
12584     case Intrinsic::x86_sse2_pmovmskb_128: {
12585       // High bits of movmskp{s|d}, pmovmskb are known zero.
12586       switch (IntId) {
12587         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
12588         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
12589         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
12590         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
12591         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
12592         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
12593       }
12594       KnownZero = APInt::getHighBitsSet(Mask.getBitWidth(),
12595                                         Mask.getBitWidth() - NumLoBits);
12596       break;
12597     }
12598     }
12599     break;
12600   }
12601   }
12602 }
12603
12604 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
12605                                                          unsigned Depth) const {
12606   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
12607   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
12608     return Op.getValueType().getScalarType().getSizeInBits();
12609
12610   // Fallback case.
12611   return 1;
12612 }
12613
12614 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
12615 /// node is a GlobalAddress + offset.
12616 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
12617                                        const GlobalValue* &GA,
12618                                        int64_t &Offset) const {
12619   if (N->getOpcode() == X86ISD::Wrapper) {
12620     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
12621       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
12622       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
12623       return true;
12624     }
12625   }
12626   return TargetLowering::isGAPlusOffset(N, GA, Offset);
12627 }
12628
12629 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
12630 /// same as extracting the high 128-bit part of 256-bit vector and then
12631 /// inserting the result into the low part of a new 256-bit vector
12632 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
12633   EVT VT = SVOp->getValueType(0);
12634   int NumElems = VT.getVectorNumElements();
12635
12636   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
12637   for (int i = 0, j = NumElems/2; i < NumElems/2; ++i, ++j)
12638     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12639         SVOp->getMaskElt(j) >= 0)
12640       return false;
12641
12642   return true;
12643 }
12644
12645 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
12646 /// same as extracting the low 128-bit part of 256-bit vector and then
12647 /// inserting the result into the high part of a new 256-bit vector
12648 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
12649   EVT VT = SVOp->getValueType(0);
12650   int NumElems = VT.getVectorNumElements();
12651
12652   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
12653   for (int i = NumElems/2, j = 0; i < NumElems; ++i, ++j)
12654     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12655         SVOp->getMaskElt(j) >= 0)
12656       return false;
12657
12658   return true;
12659 }
12660
12661 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
12662 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
12663                                         TargetLowering::DAGCombinerInfo &DCI) {
12664   DebugLoc dl = N->getDebugLoc();
12665   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
12666   SDValue V1 = SVOp->getOperand(0);
12667   SDValue V2 = SVOp->getOperand(1);
12668   EVT VT = SVOp->getValueType(0);
12669   int NumElems = VT.getVectorNumElements();
12670
12671   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
12672       V2.getOpcode() == ISD::CONCAT_VECTORS) {
12673     //
12674     //                   0,0,0,...
12675     //                      |
12676     //    V      UNDEF    BUILD_VECTOR    UNDEF
12677     //     \      /           \           /
12678     //  CONCAT_VECTOR         CONCAT_VECTOR
12679     //         \                  /
12680     //          \                /
12681     //          RESULT: V + zero extended
12682     //
12683     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
12684         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
12685         V1.getOperand(1).getOpcode() != ISD::UNDEF)
12686       return SDValue();
12687
12688     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
12689       return SDValue();
12690
12691     // To match the shuffle mask, the first half of the mask should
12692     // be exactly the first vector, and all the rest a splat with the
12693     // first element of the second one.
12694     for (int i = 0; i < NumElems/2; ++i)
12695       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
12696           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
12697         return SDValue();
12698
12699     // Emit a zeroed vector and insert the desired subvector on its
12700     // first half.
12701     SDValue Zeros = getZeroVector(VT, true /* HasXMMInt */, DAG, dl);
12702     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0),
12703                          DAG.getConstant(0, MVT::i32), DAG, dl);
12704     return DCI.CombineTo(N, InsV);
12705   }
12706
12707   //===--------------------------------------------------------------------===//
12708   // Combine some shuffles into subvector extracts and inserts:
12709   //
12710
12711   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
12712   if (isShuffleHigh128VectorInsertLow(SVOp)) {
12713     SDValue V = Extract128BitVector(V1, DAG.getConstant(NumElems/2, MVT::i32),
12714                                     DAG, dl);
12715     SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT),
12716                                       V, DAG.getConstant(0, MVT::i32), DAG, dl);
12717     return DCI.CombineTo(N, InsV);
12718   }
12719
12720   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
12721   if (isShuffleLow128VectorInsertHigh(SVOp)) {
12722     SDValue V = Extract128BitVector(V1, DAG.getConstant(0, MVT::i32), DAG, dl);
12723     SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT),
12724                              V, DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
12725     return DCI.CombineTo(N, InsV);
12726   }
12727
12728   return SDValue();
12729 }
12730
12731 /// PerformShuffleCombine - Performs several different shuffle combines.
12732 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
12733                                      TargetLowering::DAGCombinerInfo &DCI,
12734                                      const X86Subtarget *Subtarget) {
12735   DebugLoc dl = N->getDebugLoc();
12736   EVT VT = N->getValueType(0);
12737
12738   // Don't create instructions with illegal types after legalize types has run.
12739   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12740   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
12741     return SDValue();
12742
12743   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
12744   if (Subtarget->hasAVX() && VT.getSizeInBits() == 256 &&
12745       N->getOpcode() == ISD::VECTOR_SHUFFLE)
12746     return PerformShuffleCombine256(N, DAG, DCI);
12747
12748   // Only handle 128 wide vector from here on.
12749   if (VT.getSizeInBits() != 128)
12750     return SDValue();
12751
12752   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
12753   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
12754   // consecutive, non-overlapping, and in the right order.
12755   SmallVector<SDValue, 16> Elts;
12756   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
12757     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
12758
12759   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
12760 }
12761
12762 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
12763 /// generation and convert it from being a bunch of shuffles and extracts
12764 /// to a simple store and scalar loads to extract the elements.
12765 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
12766                                                 const TargetLowering &TLI) {
12767   SDValue InputVector = N->getOperand(0);
12768
12769   // Only operate on vectors of 4 elements, where the alternative shuffling
12770   // gets to be more expensive.
12771   if (InputVector.getValueType() != MVT::v4i32)
12772     return SDValue();
12773
12774   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
12775   // single use which is a sign-extend or zero-extend, and all elements are
12776   // used.
12777   SmallVector<SDNode *, 4> Uses;
12778   unsigned ExtractedElements = 0;
12779   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
12780        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
12781     if (UI.getUse().getResNo() != InputVector.getResNo())
12782       return SDValue();
12783
12784     SDNode *Extract = *UI;
12785     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12786       return SDValue();
12787
12788     if (Extract->getValueType(0) != MVT::i32)
12789       return SDValue();
12790     if (!Extract->hasOneUse())
12791       return SDValue();
12792     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
12793         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
12794       return SDValue();
12795     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
12796       return SDValue();
12797
12798     // Record which element was extracted.
12799     ExtractedElements |=
12800       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
12801
12802     Uses.push_back(Extract);
12803   }
12804
12805   // If not all the elements were used, this may not be worthwhile.
12806   if (ExtractedElements != 15)
12807     return SDValue();
12808
12809   // Ok, we've now decided to do the transformation.
12810   DebugLoc dl = InputVector.getDebugLoc();
12811
12812   // Store the value to a temporary stack slot.
12813   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
12814   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
12815                             MachinePointerInfo(), false, false, 0);
12816
12817   // Replace each use (extract) with a load of the appropriate element.
12818   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
12819        UE = Uses.end(); UI != UE; ++UI) {
12820     SDNode *Extract = *UI;
12821
12822     // cOMpute the element's address.
12823     SDValue Idx = Extract->getOperand(1);
12824     unsigned EltSize =
12825         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
12826     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
12827     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
12828
12829     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
12830                                      StackPtr, OffsetVal);
12831
12832     // Load the scalar.
12833     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
12834                                      ScalarAddr, MachinePointerInfo(),
12835                                      false, false, false, 0);
12836
12837     // Replace the exact with the load.
12838     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
12839   }
12840
12841   // The replacement was made in place; don't return anything.
12842   return SDValue();
12843 }
12844
12845 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
12846 /// nodes.
12847 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
12848                                     const X86Subtarget *Subtarget) {
12849   DebugLoc DL = N->getDebugLoc();
12850   SDValue Cond = N->getOperand(0);
12851   // Get the LHS/RHS of the select.
12852   SDValue LHS = N->getOperand(1);
12853   SDValue RHS = N->getOperand(2);
12854   EVT VT = LHS.getValueType();
12855
12856   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
12857   // instructions match the semantics of the common C idiom x<y?x:y but not
12858   // x<=y?x:y, because of how they handle negative zero (which can be
12859   // ignored in unsafe-math mode).
12860   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
12861       VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
12862       (Subtarget->hasXMMInt() ||
12863        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
12864     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
12865
12866     unsigned Opcode = 0;
12867     // Check for x CC y ? x : y.
12868     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
12869         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
12870       switch (CC) {
12871       default: break;
12872       case ISD::SETULT:
12873         // Converting this to a min would handle NaNs incorrectly, and swapping
12874         // the operands would cause it to handle comparisons between positive
12875         // and negative zero incorrectly.
12876         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
12877           if (!DAG.getTarget().Options.UnsafeFPMath &&
12878               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
12879             break;
12880           std::swap(LHS, RHS);
12881         }
12882         Opcode = X86ISD::FMIN;
12883         break;
12884       case ISD::SETOLE:
12885         // Converting this to a min would handle comparisons between positive
12886         // and negative zero incorrectly.
12887         if (!DAG.getTarget().Options.UnsafeFPMath &&
12888             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
12889           break;
12890         Opcode = X86ISD::FMIN;
12891         break;
12892       case ISD::SETULE:
12893         // Converting this to a min would handle both negative zeros and NaNs
12894         // incorrectly, but we can swap the operands to fix both.
12895         std::swap(LHS, RHS);
12896       case ISD::SETOLT:
12897       case ISD::SETLT:
12898       case ISD::SETLE:
12899         Opcode = X86ISD::FMIN;
12900         break;
12901
12902       case ISD::SETOGE:
12903         // Converting this to a max would handle comparisons between positive
12904         // and negative zero incorrectly.
12905         if (!DAG.getTarget().Options.UnsafeFPMath &&
12906             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
12907           break;
12908         Opcode = X86ISD::FMAX;
12909         break;
12910       case ISD::SETUGT:
12911         // Converting this to a max would handle NaNs incorrectly, and swapping
12912         // the operands would cause it to handle comparisons between positive
12913         // and negative zero incorrectly.
12914         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
12915           if (!DAG.getTarget().Options.UnsafeFPMath &&
12916               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
12917             break;
12918           std::swap(LHS, RHS);
12919         }
12920         Opcode = X86ISD::FMAX;
12921         break;
12922       case ISD::SETUGE:
12923         // Converting this to a max would handle both negative zeros and NaNs
12924         // incorrectly, but we can swap the operands to fix both.
12925         std::swap(LHS, RHS);
12926       case ISD::SETOGT:
12927       case ISD::SETGT:
12928       case ISD::SETGE:
12929         Opcode = X86ISD::FMAX;
12930         break;
12931       }
12932     // Check for x CC y ? y : x -- a min/max with reversed arms.
12933     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
12934                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
12935       switch (CC) {
12936       default: break;
12937       case ISD::SETOGE:
12938         // Converting this to a min would handle comparisons between positive
12939         // and negative zero incorrectly, and swapping the operands would
12940         // cause it to handle NaNs incorrectly.
12941         if (!DAG.getTarget().Options.UnsafeFPMath &&
12942             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
12943           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
12944             break;
12945           std::swap(LHS, RHS);
12946         }
12947         Opcode = X86ISD::FMIN;
12948         break;
12949       case ISD::SETUGT:
12950         // Converting this to a min would handle NaNs incorrectly.
12951         if (!DAG.getTarget().Options.UnsafeFPMath &&
12952             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
12953           break;
12954         Opcode = X86ISD::FMIN;
12955         break;
12956       case ISD::SETUGE:
12957         // Converting this to a min would handle both negative zeros and NaNs
12958         // incorrectly, but we can swap the operands to fix both.
12959         std::swap(LHS, RHS);
12960       case ISD::SETOGT:
12961       case ISD::SETGT:
12962       case ISD::SETGE:
12963         Opcode = X86ISD::FMIN;
12964         break;
12965
12966       case ISD::SETULT:
12967         // Converting this to a max would handle NaNs incorrectly.
12968         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
12969           break;
12970         Opcode = X86ISD::FMAX;
12971         break;
12972       case ISD::SETOLE:
12973         // Converting this to a max would handle comparisons between positive
12974         // and negative zero incorrectly, and swapping the operands would
12975         // cause it to handle NaNs incorrectly.
12976         if (!DAG.getTarget().Options.UnsafeFPMath &&
12977             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
12978           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
12979             break;
12980           std::swap(LHS, RHS);
12981         }
12982         Opcode = X86ISD::FMAX;
12983         break;
12984       case ISD::SETULE:
12985         // Converting this to a max would handle both negative zeros and NaNs
12986         // incorrectly, but we can swap the operands to fix both.
12987         std::swap(LHS, RHS);
12988       case ISD::SETOLT:
12989       case ISD::SETLT:
12990       case ISD::SETLE:
12991         Opcode = X86ISD::FMAX;
12992         break;
12993       }
12994     }
12995
12996     if (Opcode)
12997       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
12998   }
12999
13000   // If this is a select between two integer constants, try to do some
13001   // optimizations.
13002   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
13003     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
13004       // Don't do this for crazy integer types.
13005       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
13006         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
13007         // so that TrueC (the true value) is larger than FalseC.
13008         bool NeedsCondInvert = false;
13009
13010         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
13011             // Efficiently invertible.
13012             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
13013              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
13014               isa<ConstantSDNode>(Cond.getOperand(1))))) {
13015           NeedsCondInvert = true;
13016           std::swap(TrueC, FalseC);
13017         }
13018
13019         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
13020         if (FalseC->getAPIntValue() == 0 &&
13021             TrueC->getAPIntValue().isPowerOf2()) {
13022           if (NeedsCondInvert) // Invert the condition if needed.
13023             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13024                                DAG.getConstant(1, Cond.getValueType()));
13025
13026           // Zero extend the condition if needed.
13027           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
13028
13029           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13030           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
13031                              DAG.getConstant(ShAmt, MVT::i8));
13032         }
13033
13034         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
13035         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13036           if (NeedsCondInvert) // Invert the condition if needed.
13037             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13038                                DAG.getConstant(1, Cond.getValueType()));
13039
13040           // Zero extend the condition if needed.
13041           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13042                              FalseC->getValueType(0), Cond);
13043           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13044                              SDValue(FalseC, 0));
13045         }
13046
13047         // Optimize cases that will turn into an LEA instruction.  This requires
13048         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13049         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13050           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13051           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13052
13053           bool isFastMultiplier = false;
13054           if (Diff < 10) {
13055             switch ((unsigned char)Diff) {
13056               default: break;
13057               case 1:  // result = add base, cond
13058               case 2:  // result = lea base(    , cond*2)
13059               case 3:  // result = lea base(cond, cond*2)
13060               case 4:  // result = lea base(    , cond*4)
13061               case 5:  // result = lea base(cond, cond*4)
13062               case 8:  // result = lea base(    , cond*8)
13063               case 9:  // result = lea base(cond, cond*8)
13064                 isFastMultiplier = true;
13065                 break;
13066             }
13067           }
13068
13069           if (isFastMultiplier) {
13070             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13071             if (NeedsCondInvert) // Invert the condition if needed.
13072               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13073                                  DAG.getConstant(1, Cond.getValueType()));
13074
13075             // Zero extend the condition if needed.
13076             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13077                                Cond);
13078             // Scale the condition by the difference.
13079             if (Diff != 1)
13080               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13081                                  DAG.getConstant(Diff, Cond.getValueType()));
13082
13083             // Add the base if non-zero.
13084             if (FalseC->getAPIntValue() != 0)
13085               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13086                                  SDValue(FalseC, 0));
13087             return Cond;
13088           }
13089         }
13090       }
13091   }
13092
13093   return SDValue();
13094 }
13095
13096 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
13097 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
13098                                   TargetLowering::DAGCombinerInfo &DCI) {
13099   DebugLoc DL = N->getDebugLoc();
13100
13101   // If the flag operand isn't dead, don't touch this CMOV.
13102   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
13103     return SDValue();
13104
13105   SDValue FalseOp = N->getOperand(0);
13106   SDValue TrueOp = N->getOperand(1);
13107   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
13108   SDValue Cond = N->getOperand(3);
13109   if (CC == X86::COND_E || CC == X86::COND_NE) {
13110     switch (Cond.getOpcode()) {
13111     default: break;
13112     case X86ISD::BSR:
13113     case X86ISD::BSF:
13114       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
13115       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
13116         return (CC == X86::COND_E) ? FalseOp : TrueOp;
13117     }
13118   }
13119
13120   // If this is a select between two integer constants, try to do some
13121   // optimizations.  Note that the operands are ordered the opposite of SELECT
13122   // operands.
13123   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
13124     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
13125       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
13126       // larger than FalseC (the false value).
13127       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
13128         CC = X86::GetOppositeBranchCondition(CC);
13129         std::swap(TrueC, FalseC);
13130       }
13131
13132       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
13133       // This is efficient for any integer data type (including i8/i16) and
13134       // shift amount.
13135       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
13136         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13137                            DAG.getConstant(CC, MVT::i8), Cond);
13138
13139         // Zero extend the condition if needed.
13140         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
13141
13142         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13143         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
13144                            DAG.getConstant(ShAmt, MVT::i8));
13145         if (N->getNumValues() == 2)  // Dead flag value?
13146           return DCI.CombineTo(N, Cond, SDValue());
13147         return Cond;
13148       }
13149
13150       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
13151       // for any integer data type, including i8/i16.
13152       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13153         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13154                            DAG.getConstant(CC, MVT::i8), Cond);
13155
13156         // Zero extend the condition if needed.
13157         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13158                            FalseC->getValueType(0), Cond);
13159         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13160                            SDValue(FalseC, 0));
13161
13162         if (N->getNumValues() == 2)  // Dead flag value?
13163           return DCI.CombineTo(N, Cond, SDValue());
13164         return Cond;
13165       }
13166
13167       // Optimize cases that will turn into an LEA instruction.  This requires
13168       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13169       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13170         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13171         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13172
13173         bool isFastMultiplier = false;
13174         if (Diff < 10) {
13175           switch ((unsigned char)Diff) {
13176           default: break;
13177           case 1:  // result = add base, cond
13178           case 2:  // result = lea base(    , cond*2)
13179           case 3:  // result = lea base(cond, cond*2)
13180           case 4:  // result = lea base(    , cond*4)
13181           case 5:  // result = lea base(cond, cond*4)
13182           case 8:  // result = lea base(    , cond*8)
13183           case 9:  // result = lea base(cond, cond*8)
13184             isFastMultiplier = true;
13185             break;
13186           }
13187         }
13188
13189         if (isFastMultiplier) {
13190           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13191           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13192                              DAG.getConstant(CC, MVT::i8), Cond);
13193           // Zero extend the condition if needed.
13194           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13195                              Cond);
13196           // Scale the condition by the difference.
13197           if (Diff != 1)
13198             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13199                                DAG.getConstant(Diff, Cond.getValueType()));
13200
13201           // Add the base if non-zero.
13202           if (FalseC->getAPIntValue() != 0)
13203             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13204                                SDValue(FalseC, 0));
13205           if (N->getNumValues() == 2)  // Dead flag value?
13206             return DCI.CombineTo(N, Cond, SDValue());
13207           return Cond;
13208         }
13209       }
13210     }
13211   }
13212   return SDValue();
13213 }
13214
13215
13216 /// PerformMulCombine - Optimize a single multiply with constant into two
13217 /// in order to implement it with two cheaper instructions, e.g.
13218 /// LEA + SHL, LEA + LEA.
13219 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
13220                                  TargetLowering::DAGCombinerInfo &DCI) {
13221   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
13222     return SDValue();
13223
13224   EVT VT = N->getValueType(0);
13225   if (VT != MVT::i64)
13226     return SDValue();
13227
13228   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
13229   if (!C)
13230     return SDValue();
13231   uint64_t MulAmt = C->getZExtValue();
13232   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
13233     return SDValue();
13234
13235   uint64_t MulAmt1 = 0;
13236   uint64_t MulAmt2 = 0;
13237   if ((MulAmt % 9) == 0) {
13238     MulAmt1 = 9;
13239     MulAmt2 = MulAmt / 9;
13240   } else if ((MulAmt % 5) == 0) {
13241     MulAmt1 = 5;
13242     MulAmt2 = MulAmt / 5;
13243   } else if ((MulAmt % 3) == 0) {
13244     MulAmt1 = 3;
13245     MulAmt2 = MulAmt / 3;
13246   }
13247   if (MulAmt2 &&
13248       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
13249     DebugLoc DL = N->getDebugLoc();
13250
13251     if (isPowerOf2_64(MulAmt2) &&
13252         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
13253       // If second multiplifer is pow2, issue it first. We want the multiply by
13254       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
13255       // is an add.
13256       std::swap(MulAmt1, MulAmt2);
13257
13258     SDValue NewMul;
13259     if (isPowerOf2_64(MulAmt1))
13260       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
13261                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
13262     else
13263       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
13264                            DAG.getConstant(MulAmt1, VT));
13265
13266     if (isPowerOf2_64(MulAmt2))
13267       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
13268                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
13269     else
13270       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
13271                            DAG.getConstant(MulAmt2, VT));
13272
13273     // Do not add new nodes to DAG combiner worklist.
13274     DCI.CombineTo(N, NewMul, false);
13275   }
13276   return SDValue();
13277 }
13278
13279 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
13280   SDValue N0 = N->getOperand(0);
13281   SDValue N1 = N->getOperand(1);
13282   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
13283   EVT VT = N0.getValueType();
13284
13285   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
13286   // since the result of setcc_c is all zero's or all ones.
13287   if (VT.isInteger() && !VT.isVector() &&
13288       N1C && N0.getOpcode() == ISD::AND &&
13289       N0.getOperand(1).getOpcode() == ISD::Constant) {
13290     SDValue N00 = N0.getOperand(0);
13291     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
13292         ((N00.getOpcode() == ISD::ANY_EXTEND ||
13293           N00.getOpcode() == ISD::ZERO_EXTEND) &&
13294          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
13295       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
13296       APInt ShAmt = N1C->getAPIntValue();
13297       Mask = Mask.shl(ShAmt);
13298       if (Mask != 0)
13299         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
13300                            N00, DAG.getConstant(Mask, VT));
13301     }
13302   }
13303
13304
13305   // Hardware support for vector shifts is sparse which makes us scalarize the
13306   // vector operations in many cases. Also, on sandybridge ADD is faster than
13307   // shl.
13308   // (shl V, 1) -> add V,V
13309   if (isSplatVector(N1.getNode())) {
13310     assert(N0.getValueType().isVector() && "Invalid vector shift type");
13311     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
13312     // We shift all of the values by one. In many cases we do not have
13313     // hardware support for this operation. This is better expressed as an ADD
13314     // of two values.
13315     if (N1C && (1 == N1C->getZExtValue())) {
13316       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
13317     }
13318   }
13319
13320   return SDValue();
13321 }
13322
13323 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
13324 ///                       when possible.
13325 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
13326                                    const X86Subtarget *Subtarget) {
13327   EVT VT = N->getValueType(0);
13328   if (N->getOpcode() == ISD::SHL) {
13329     SDValue V = PerformSHLCombine(N, DAG);
13330     if (V.getNode()) return V;
13331   }
13332
13333   // On X86 with SSE2 support, we can transform this to a vector shift if
13334   // all elements are shifted by the same amount.  We can't do this in legalize
13335   // because the a constant vector is typically transformed to a constant pool
13336   // so we have no knowledge of the shift amount.
13337   if (!Subtarget->hasXMMInt())
13338     return SDValue();
13339
13340   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
13341       (!Subtarget->hasAVX2() ||
13342        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
13343     return SDValue();
13344
13345   SDValue ShAmtOp = N->getOperand(1);
13346   EVT EltVT = VT.getVectorElementType();
13347   DebugLoc DL = N->getDebugLoc();
13348   SDValue BaseShAmt = SDValue();
13349   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
13350     unsigned NumElts = VT.getVectorNumElements();
13351     unsigned i = 0;
13352     for (; i != NumElts; ++i) {
13353       SDValue Arg = ShAmtOp.getOperand(i);
13354       if (Arg.getOpcode() == ISD::UNDEF) continue;
13355       BaseShAmt = Arg;
13356       break;
13357     }
13358     for (; i != NumElts; ++i) {
13359       SDValue Arg = ShAmtOp.getOperand(i);
13360       if (Arg.getOpcode() == ISD::UNDEF) continue;
13361       if (Arg != BaseShAmt) {
13362         return SDValue();
13363       }
13364     }
13365   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
13366              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
13367     SDValue InVec = ShAmtOp.getOperand(0);
13368     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13369       unsigned NumElts = InVec.getValueType().getVectorNumElements();
13370       unsigned i = 0;
13371       for (; i != NumElts; ++i) {
13372         SDValue Arg = InVec.getOperand(i);
13373         if (Arg.getOpcode() == ISD::UNDEF) continue;
13374         BaseShAmt = Arg;
13375         break;
13376       }
13377     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13378        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13379          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
13380          if (C->getZExtValue() == SplatIdx)
13381            BaseShAmt = InVec.getOperand(1);
13382        }
13383     }
13384     if (BaseShAmt.getNode() == 0)
13385       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
13386                               DAG.getIntPtrConstant(0));
13387   } else
13388     return SDValue();
13389
13390   // The shift amount is an i32.
13391   if (EltVT.bitsGT(MVT::i32))
13392     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
13393   else if (EltVT.bitsLT(MVT::i32))
13394     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
13395
13396   // The shift amount is identical so we can do a vector shift.
13397   SDValue  ValOp = N->getOperand(0);
13398   switch (N->getOpcode()) {
13399   default:
13400     llvm_unreachable("Unknown shift opcode!");
13401     break;
13402   case ISD::SHL:
13403     if (VT == MVT::v2i64)
13404       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13405                          DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
13406                          ValOp, BaseShAmt);
13407     if (VT == MVT::v4i32)
13408       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13409                          DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
13410                          ValOp, BaseShAmt);
13411     if (VT == MVT::v8i16)
13412       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13413                          DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
13414                          ValOp, BaseShAmt);
13415     if (VT == MVT::v4i64)
13416       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13417                          DAG.getConstant(Intrinsic::x86_avx2_pslli_q, MVT::i32),
13418                          ValOp, BaseShAmt);
13419     if (VT == MVT::v8i32)
13420       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13421                          DAG.getConstant(Intrinsic::x86_avx2_pslli_d, MVT::i32),
13422                          ValOp, BaseShAmt);
13423     if (VT == MVT::v16i16)
13424       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13425                          DAG.getConstant(Intrinsic::x86_avx2_pslli_w, MVT::i32),
13426                          ValOp, BaseShAmt);
13427     break;
13428   case ISD::SRA:
13429     if (VT == MVT::v4i32)
13430       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13431                          DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
13432                          ValOp, BaseShAmt);
13433     if (VT == MVT::v8i16)
13434       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13435                          DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
13436                          ValOp, BaseShAmt);
13437     if (VT == MVT::v8i32)
13438       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13439                          DAG.getConstant(Intrinsic::x86_avx2_psrai_d, MVT::i32),
13440                          ValOp, BaseShAmt);
13441     if (VT == MVT::v16i16)
13442       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13443                          DAG.getConstant(Intrinsic::x86_avx2_psrai_w, MVT::i32),
13444                          ValOp, BaseShAmt);
13445     break;
13446   case ISD::SRL:
13447     if (VT == MVT::v2i64)
13448       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13449                          DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
13450                          ValOp, BaseShAmt);
13451     if (VT == MVT::v4i32)
13452       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13453                          DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
13454                          ValOp, BaseShAmt);
13455     if (VT ==  MVT::v8i16)
13456       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13457                          DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
13458                          ValOp, BaseShAmt);
13459     if (VT == MVT::v4i64)
13460       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13461                          DAG.getConstant(Intrinsic::x86_avx2_psrli_q, MVT::i32),
13462                          ValOp, BaseShAmt);
13463     if (VT == MVT::v8i32)
13464       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13465                          DAG.getConstant(Intrinsic::x86_avx2_psrli_d, MVT::i32),
13466                          ValOp, BaseShAmt);
13467     if (VT ==  MVT::v16i16)
13468       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13469                          DAG.getConstant(Intrinsic::x86_avx2_psrli_w, MVT::i32),
13470                          ValOp, BaseShAmt);
13471     break;
13472   }
13473   return SDValue();
13474 }
13475
13476
13477 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
13478 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
13479 // and friends.  Likewise for OR -> CMPNEQSS.
13480 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
13481                             TargetLowering::DAGCombinerInfo &DCI,
13482                             const X86Subtarget *Subtarget) {
13483   unsigned opcode;
13484
13485   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
13486   // we're requiring SSE2 for both.
13487   if (Subtarget->hasXMMInt() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
13488     SDValue N0 = N->getOperand(0);
13489     SDValue N1 = N->getOperand(1);
13490     SDValue CMP0 = N0->getOperand(1);
13491     SDValue CMP1 = N1->getOperand(1);
13492     DebugLoc DL = N->getDebugLoc();
13493
13494     // The SETCCs should both refer to the same CMP.
13495     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
13496       return SDValue();
13497
13498     SDValue CMP00 = CMP0->getOperand(0);
13499     SDValue CMP01 = CMP0->getOperand(1);
13500     EVT     VT    = CMP00.getValueType();
13501
13502     if (VT == MVT::f32 || VT == MVT::f64) {
13503       bool ExpectingFlags = false;
13504       // Check for any users that want flags:
13505       for (SDNode::use_iterator UI = N->use_begin(),
13506              UE = N->use_end();
13507            !ExpectingFlags && UI != UE; ++UI)
13508         switch (UI->getOpcode()) {
13509         default:
13510         case ISD::BR_CC:
13511         case ISD::BRCOND:
13512         case ISD::SELECT:
13513           ExpectingFlags = true;
13514           break;
13515         case ISD::CopyToReg:
13516         case ISD::SIGN_EXTEND:
13517         case ISD::ZERO_EXTEND:
13518         case ISD::ANY_EXTEND:
13519           break;
13520         }
13521
13522       if (!ExpectingFlags) {
13523         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
13524         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
13525
13526         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
13527           X86::CondCode tmp = cc0;
13528           cc0 = cc1;
13529           cc1 = tmp;
13530         }
13531
13532         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
13533             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
13534           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
13535           X86ISD::NodeType NTOperator = is64BitFP ?
13536             X86ISD::FSETCCsd : X86ISD::FSETCCss;
13537           // FIXME: need symbolic constants for these magic numbers.
13538           // See X86ATTInstPrinter.cpp:printSSECC().
13539           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
13540           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
13541                                               DAG.getConstant(x86cc, MVT::i8));
13542           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
13543                                               OnesOrZeroesF);
13544           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
13545                                       DAG.getConstant(1, MVT::i32));
13546           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
13547           return OneBitOfTruth;
13548         }
13549       }
13550     }
13551   }
13552   return SDValue();
13553 }
13554
13555 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
13556 /// so it can be folded inside ANDNP.
13557 static bool CanFoldXORWithAllOnes(const SDNode *N) {
13558   EVT VT = N->getValueType(0);
13559
13560   // Match direct AllOnes for 128 and 256-bit vectors
13561   if (ISD::isBuildVectorAllOnes(N))
13562     return true;
13563
13564   // Look through a bit convert.
13565   if (N->getOpcode() == ISD::BITCAST)
13566     N = N->getOperand(0).getNode();
13567
13568   // Sometimes the operand may come from a insert_subvector building a 256-bit
13569   // allones vector
13570   if (VT.getSizeInBits() == 256 &&
13571       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
13572     SDValue V1 = N->getOperand(0);
13573     SDValue V2 = N->getOperand(1);
13574
13575     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
13576         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
13577         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
13578         ISD::isBuildVectorAllOnes(V2.getNode()))
13579       return true;
13580   }
13581
13582   return false;
13583 }
13584
13585 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
13586                                  TargetLowering::DAGCombinerInfo &DCI,
13587                                  const X86Subtarget *Subtarget) {
13588   if (DCI.isBeforeLegalizeOps())
13589     return SDValue();
13590
13591   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
13592   if (R.getNode())
13593     return R;
13594
13595   EVT VT = N->getValueType(0);
13596
13597   // Create ANDN, BLSI, and BLSR instructions
13598   // BLSI is X & (-X)
13599   // BLSR is X & (X-1)
13600   if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
13601     SDValue N0 = N->getOperand(0);
13602     SDValue N1 = N->getOperand(1);
13603     DebugLoc DL = N->getDebugLoc();
13604
13605     // Check LHS for not
13606     if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1)))
13607       return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1);
13608     // Check RHS for not
13609     if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1)))
13610       return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
13611
13612     // Check LHS for neg
13613     if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
13614         isZero(N0.getOperand(0)))
13615       return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
13616
13617     // Check RHS for neg
13618     if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
13619         isZero(N1.getOperand(0)))
13620       return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
13621
13622     // Check LHS for X-1
13623     if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
13624         isAllOnes(N0.getOperand(1)))
13625       return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
13626
13627     // Check RHS for X-1
13628     if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
13629         isAllOnes(N1.getOperand(1)))
13630       return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
13631
13632     return SDValue();
13633   }
13634
13635   // Want to form ANDNP nodes:
13636   // 1) In the hopes of then easily combining them with OR and AND nodes
13637   //    to form PBLEND/PSIGN.
13638   // 2) To match ANDN packed intrinsics
13639   if (VT != MVT::v2i64 && VT != MVT::v4i64)
13640     return SDValue();
13641
13642   SDValue N0 = N->getOperand(0);
13643   SDValue N1 = N->getOperand(1);
13644   DebugLoc DL = N->getDebugLoc();
13645
13646   // Check LHS for vnot
13647   if (N0.getOpcode() == ISD::XOR &&
13648       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
13649       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
13650     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
13651
13652   // Check RHS for vnot
13653   if (N1.getOpcode() == ISD::XOR &&
13654       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
13655       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
13656     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
13657
13658   return SDValue();
13659 }
13660
13661 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
13662                                 TargetLowering::DAGCombinerInfo &DCI,
13663                                 const X86Subtarget *Subtarget) {
13664   if (DCI.isBeforeLegalizeOps())
13665     return SDValue();
13666
13667   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
13668   if (R.getNode())
13669     return R;
13670
13671   EVT VT = N->getValueType(0);
13672
13673   SDValue N0 = N->getOperand(0);
13674   SDValue N1 = N->getOperand(1);
13675
13676   // look for psign/blend
13677   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
13678     if (!Subtarget->hasSSSE3orAVX() ||
13679         (VT == MVT::v4i64 && !Subtarget->hasAVX2()))
13680       return SDValue();
13681
13682     // Canonicalize pandn to RHS
13683     if (N0.getOpcode() == X86ISD::ANDNP)
13684       std::swap(N0, N1);
13685     // or (and (m, x), (pandn m, y))
13686     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
13687       SDValue Mask = N1.getOperand(0);
13688       SDValue X    = N1.getOperand(1);
13689       SDValue Y;
13690       if (N0.getOperand(0) == Mask)
13691         Y = N0.getOperand(1);
13692       if (N0.getOperand(1) == Mask)
13693         Y = N0.getOperand(0);
13694
13695       // Check to see if the mask appeared in both the AND and ANDNP and
13696       if (!Y.getNode())
13697         return SDValue();
13698
13699       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
13700       if (Mask.getOpcode() != ISD::BITCAST ||
13701           X.getOpcode() != ISD::BITCAST ||
13702           Y.getOpcode() != ISD::BITCAST)
13703         return SDValue();
13704
13705       // Look through mask bitcast.
13706       Mask = Mask.getOperand(0);
13707       EVT MaskVT = Mask.getValueType();
13708
13709       // Validate that the Mask operand is a vector sra node.  The sra node
13710       // will be an intrinsic.
13711       if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
13712         return SDValue();
13713
13714       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
13715       // there is no psrai.b
13716       switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
13717       case Intrinsic::x86_sse2_psrai_w:
13718       case Intrinsic::x86_sse2_psrai_d:
13719       case Intrinsic::x86_avx2_psrai_w:
13720       case Intrinsic::x86_avx2_psrai_d:
13721         break;
13722       default: return SDValue();
13723       }
13724
13725       // Check that the SRA is all signbits.
13726       SDValue SraC = Mask.getOperand(2);
13727       unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
13728       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
13729       if ((SraAmt + 1) != EltBits)
13730         return SDValue();
13731
13732       DebugLoc DL = N->getDebugLoc();
13733
13734       // Now we know we at least have a plendvb with the mask val.  See if
13735       // we can form a psignb/w/d.
13736       // psign = x.type == y.type == mask.type && y = sub(0, x);
13737       X = X.getOperand(0);
13738       Y = Y.getOperand(0);
13739       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
13740           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
13741           X.getValueType() == MaskVT && X.getValueType() == Y.getValueType() &&
13742           (EltBits == 8 || EltBits == 16 || EltBits == 32)) {
13743         SDValue Sign = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X,
13744                                    Mask.getOperand(1));
13745         return DAG.getNode(ISD::BITCAST, DL, VT, Sign);
13746       }
13747       // PBLENDVB only available on SSE 4.1
13748       if (!Subtarget->hasSSE41orAVX())
13749         return SDValue();
13750
13751       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
13752
13753       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
13754       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
13755       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
13756       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
13757       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
13758     }
13759   }
13760
13761   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
13762     return SDValue();
13763
13764   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
13765   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
13766     std::swap(N0, N1);
13767   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
13768     return SDValue();
13769   if (!N0.hasOneUse() || !N1.hasOneUse())
13770     return SDValue();
13771
13772   SDValue ShAmt0 = N0.getOperand(1);
13773   if (ShAmt0.getValueType() != MVT::i8)
13774     return SDValue();
13775   SDValue ShAmt1 = N1.getOperand(1);
13776   if (ShAmt1.getValueType() != MVT::i8)
13777     return SDValue();
13778   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
13779     ShAmt0 = ShAmt0.getOperand(0);
13780   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
13781     ShAmt1 = ShAmt1.getOperand(0);
13782
13783   DebugLoc DL = N->getDebugLoc();
13784   unsigned Opc = X86ISD::SHLD;
13785   SDValue Op0 = N0.getOperand(0);
13786   SDValue Op1 = N1.getOperand(0);
13787   if (ShAmt0.getOpcode() == ISD::SUB) {
13788     Opc = X86ISD::SHRD;
13789     std::swap(Op0, Op1);
13790     std::swap(ShAmt0, ShAmt1);
13791   }
13792
13793   unsigned Bits = VT.getSizeInBits();
13794   if (ShAmt1.getOpcode() == ISD::SUB) {
13795     SDValue Sum = ShAmt1.getOperand(0);
13796     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
13797       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
13798       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
13799         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
13800       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
13801         return DAG.getNode(Opc, DL, VT,
13802                            Op0, Op1,
13803                            DAG.getNode(ISD::TRUNCATE, DL,
13804                                        MVT::i8, ShAmt0));
13805     }
13806   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
13807     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
13808     if (ShAmt0C &&
13809         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
13810       return DAG.getNode(Opc, DL, VT,
13811                          N0.getOperand(0), N1.getOperand(0),
13812                          DAG.getNode(ISD::TRUNCATE, DL,
13813                                        MVT::i8, ShAmt0));
13814   }
13815
13816   return SDValue();
13817 }
13818
13819 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
13820                                  TargetLowering::DAGCombinerInfo &DCI,
13821                                  const X86Subtarget *Subtarget) {
13822   if (DCI.isBeforeLegalizeOps())
13823     return SDValue();
13824
13825   EVT VT = N->getValueType(0);
13826
13827   if (VT != MVT::i32 && VT != MVT::i64)
13828     return SDValue();
13829
13830   // Create BLSMSK instructions by finding X ^ (X-1)
13831   SDValue N0 = N->getOperand(0);
13832   SDValue N1 = N->getOperand(1);
13833   DebugLoc DL = N->getDebugLoc();
13834
13835   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
13836       isAllOnes(N0.getOperand(1)))
13837     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
13838
13839   if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
13840       isAllOnes(N1.getOperand(1)))
13841     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
13842
13843   return SDValue();
13844 }
13845
13846 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
13847 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
13848                                    const X86Subtarget *Subtarget) {
13849   LoadSDNode *Ld = cast<LoadSDNode>(N);
13850   EVT RegVT = Ld->getValueType(0);
13851   EVT MemVT = Ld->getMemoryVT();
13852   DebugLoc dl = Ld->getDebugLoc();
13853   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13854
13855   ISD::LoadExtType Ext = Ld->getExtensionType();
13856
13857   // If this is a vector EXT Load then attempt to optimize it using a
13858   // shuffle. We need SSE4 for the shuffles.
13859   // TODO: It is possible to support ZExt by zeroing the undef values
13860   // during the shuffle phase or after the shuffle.
13861   if (RegVT.isVector() && Ext == ISD::EXTLOAD && Subtarget->hasSSE41()) {
13862     assert(MemVT != RegVT && "Cannot extend to the same type");
13863     assert(MemVT.isVector() && "Must load a vector from memory");
13864
13865     unsigned NumElems = RegVT.getVectorNumElements();
13866     unsigned RegSz = RegVT.getSizeInBits();
13867     unsigned MemSz = MemVT.getSizeInBits();
13868     assert(RegSz > MemSz && "Register size must be greater than the mem size");
13869     // All sizes must be a power of two
13870     if (!isPowerOf2_32(RegSz * MemSz * NumElems)) return SDValue();
13871
13872     // Attempt to load the original value using a single load op.
13873     // Find a scalar type which is equal to the loaded word size.
13874     MVT SclrLoadTy = MVT::i8;
13875     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
13876          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
13877       MVT Tp = (MVT::SimpleValueType)tp;
13878       if (TLI.isTypeLegal(Tp) &&  Tp.getSizeInBits() == MemSz) {
13879         SclrLoadTy = Tp;
13880         break;
13881       }
13882     }
13883
13884     // Proceed if a load word is found.
13885     if (SclrLoadTy.getSizeInBits() != MemSz) return SDValue();
13886
13887     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
13888       RegSz/SclrLoadTy.getSizeInBits());
13889
13890     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
13891                                   RegSz/MemVT.getScalarType().getSizeInBits());
13892     // Can't shuffle using an illegal type.
13893     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
13894
13895     // Perform a single load.
13896     SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
13897                                   Ld->getBasePtr(),
13898                                   Ld->getPointerInfo(), Ld->isVolatile(),
13899                                   Ld->isNonTemporal(), Ld->isInvariant(),
13900                                   Ld->getAlignment());
13901
13902     // Insert the word loaded into a vector.
13903     SDValue ScalarInVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
13904       LoadUnitVecVT, ScalarLoad);
13905
13906     // Bitcast the loaded value to a vector of the original element type, in
13907     // the size of the target vector type.
13908     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, ScalarInVector);
13909     unsigned SizeRatio = RegSz/MemSz;
13910
13911     // Redistribute the loaded elements into the different locations.
13912     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13913     for (unsigned i = 0; i < NumElems; i++) ShuffleVec[i*SizeRatio] = i;
13914
13915     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
13916                                 DAG.getUNDEF(SlicedVec.getValueType()),
13917                                 ShuffleVec.data());
13918
13919     // Bitcast to the requested type.
13920     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13921     // Replace the original load with the new sequence
13922     // and return the new chain.
13923     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Shuff);
13924     return SDValue(ScalarLoad.getNode(), 1);
13925   }
13926
13927   return SDValue();
13928 }
13929
13930 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
13931 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
13932                                    const X86Subtarget *Subtarget) {
13933   StoreSDNode *St = cast<StoreSDNode>(N);
13934   EVT VT = St->getValue().getValueType();
13935   EVT StVT = St->getMemoryVT();
13936   DebugLoc dl = St->getDebugLoc();
13937   SDValue StoredVal = St->getOperand(1);
13938   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13939
13940   // If we are saving a concatenation of two XMM registers, perform two stores.
13941   // This is better in Sandy Bridge cause one 256-bit mem op is done via two
13942   // 128-bit ones. If in the future the cost becomes only one memory access the
13943   // first version would be better.
13944   if (VT.getSizeInBits() == 256 &&
13945     StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
13946     StoredVal.getNumOperands() == 2) {
13947
13948     SDValue Value0 = StoredVal.getOperand(0);
13949     SDValue Value1 = StoredVal.getOperand(1);
13950
13951     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
13952     SDValue Ptr0 = St->getBasePtr();
13953     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
13954
13955     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
13956                                 St->getPointerInfo(), St->isVolatile(),
13957                                 St->isNonTemporal(), St->getAlignment());
13958     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
13959                                 St->getPointerInfo(), St->isVolatile(),
13960                                 St->isNonTemporal(), St->getAlignment());
13961     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
13962   }
13963
13964   // Optimize trunc store (of multiple scalars) to shuffle and store.
13965   // First, pack all of the elements in one place. Next, store to memory
13966   // in fewer chunks.
13967   if (St->isTruncatingStore() && VT.isVector()) {
13968     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13969     unsigned NumElems = VT.getVectorNumElements();
13970     assert(StVT != VT && "Cannot truncate to the same type");
13971     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
13972     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
13973
13974     // From, To sizes and ElemCount must be pow of two
13975     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
13976     // We are going to use the original vector elt for storing.
13977     // Accumulated smaller vector elements must be a multiple of the store size.
13978     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
13979
13980     unsigned SizeRatio  = FromSz / ToSz;
13981
13982     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
13983
13984     // Create a type on which we perform the shuffle
13985     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
13986             StVT.getScalarType(), NumElems*SizeRatio);
13987
13988     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
13989
13990     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
13991     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13992     for (unsigned i = 0; i < NumElems; i++ ) ShuffleVec[i] = i * SizeRatio;
13993
13994     // Can't shuffle using an illegal type
13995     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
13996
13997     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
13998                                 DAG.getUNDEF(WideVec.getValueType()),
13999                                 ShuffleVec.data());
14000     // At this point all of the data is stored at the bottom of the
14001     // register. We now need to save it to mem.
14002
14003     // Find the largest store unit
14004     MVT StoreType = MVT::i8;
14005     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
14006          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
14007       MVT Tp = (MVT::SimpleValueType)tp;
14008       if (TLI.isTypeLegal(Tp) && StoreType.getSizeInBits() < NumElems * ToSz)
14009         StoreType = Tp;
14010     }
14011
14012     // Bitcast the original vector into a vector of store-size units
14013     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
14014             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
14015     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
14016     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
14017     SmallVector<SDValue, 8> Chains;
14018     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
14019                                         TLI.getPointerTy());
14020     SDValue Ptr = St->getBasePtr();
14021
14022     // Perform one or more big stores into memory.
14023     for (unsigned i = 0; i < (ToSz*NumElems)/StoreType.getSizeInBits() ; i++) {
14024       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
14025                                    StoreType, ShuffWide,
14026                                    DAG.getIntPtrConstant(i));
14027       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
14028                                 St->getPointerInfo(), St->isVolatile(),
14029                                 St->isNonTemporal(), St->getAlignment());
14030       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14031       Chains.push_back(Ch);
14032     }
14033
14034     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
14035                                Chains.size());
14036   }
14037
14038
14039   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
14040   // the FP state in cases where an emms may be missing.
14041   // A preferable solution to the general problem is to figure out the right
14042   // places to insert EMMS.  This qualifies as a quick hack.
14043
14044   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
14045   if (VT.getSizeInBits() != 64)
14046     return SDValue();
14047
14048   const Function *F = DAG.getMachineFunction().getFunction();
14049   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
14050   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
14051                      && Subtarget->hasXMMInt();
14052   if ((VT.isVector() ||
14053        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
14054       isa<LoadSDNode>(St->getValue()) &&
14055       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
14056       St->getChain().hasOneUse() && !St->isVolatile()) {
14057     SDNode* LdVal = St->getValue().getNode();
14058     LoadSDNode *Ld = 0;
14059     int TokenFactorIndex = -1;
14060     SmallVector<SDValue, 8> Ops;
14061     SDNode* ChainVal = St->getChain().getNode();
14062     // Must be a store of a load.  We currently handle two cases:  the load
14063     // is a direct child, and it's under an intervening TokenFactor.  It is
14064     // possible to dig deeper under nested TokenFactors.
14065     if (ChainVal == LdVal)
14066       Ld = cast<LoadSDNode>(St->getChain());
14067     else if (St->getValue().hasOneUse() &&
14068              ChainVal->getOpcode() == ISD::TokenFactor) {
14069       for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
14070         if (ChainVal->getOperand(i).getNode() == LdVal) {
14071           TokenFactorIndex = i;
14072           Ld = cast<LoadSDNode>(St->getValue());
14073         } else
14074           Ops.push_back(ChainVal->getOperand(i));
14075       }
14076     }
14077
14078     if (!Ld || !ISD::isNormalLoad(Ld))
14079       return SDValue();
14080
14081     // If this is not the MMX case, i.e. we are just turning i64 load/store
14082     // into f64 load/store, avoid the transformation if there are multiple
14083     // uses of the loaded value.
14084     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
14085       return SDValue();
14086
14087     DebugLoc LdDL = Ld->getDebugLoc();
14088     DebugLoc StDL = N->getDebugLoc();
14089     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
14090     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
14091     // pair instead.
14092     if (Subtarget->is64Bit() || F64IsLegal) {
14093       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
14094       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
14095                                   Ld->getPointerInfo(), Ld->isVolatile(),
14096                                   Ld->isNonTemporal(), Ld->isInvariant(),
14097                                   Ld->getAlignment());
14098       SDValue NewChain = NewLd.getValue(1);
14099       if (TokenFactorIndex != -1) {
14100         Ops.push_back(NewChain);
14101         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14102                                Ops.size());
14103       }
14104       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
14105                           St->getPointerInfo(),
14106                           St->isVolatile(), St->isNonTemporal(),
14107                           St->getAlignment());
14108     }
14109
14110     // Otherwise, lower to two pairs of 32-bit loads / stores.
14111     SDValue LoAddr = Ld->getBasePtr();
14112     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
14113                                  DAG.getConstant(4, MVT::i32));
14114
14115     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
14116                                Ld->getPointerInfo(),
14117                                Ld->isVolatile(), Ld->isNonTemporal(),
14118                                Ld->isInvariant(), Ld->getAlignment());
14119     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
14120                                Ld->getPointerInfo().getWithOffset(4),
14121                                Ld->isVolatile(), Ld->isNonTemporal(),
14122                                Ld->isInvariant(),
14123                                MinAlign(Ld->getAlignment(), 4));
14124
14125     SDValue NewChain = LoLd.getValue(1);
14126     if (TokenFactorIndex != -1) {
14127       Ops.push_back(LoLd);
14128       Ops.push_back(HiLd);
14129       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14130                              Ops.size());
14131     }
14132
14133     LoAddr = St->getBasePtr();
14134     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
14135                          DAG.getConstant(4, MVT::i32));
14136
14137     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
14138                                 St->getPointerInfo(),
14139                                 St->isVolatile(), St->isNonTemporal(),
14140                                 St->getAlignment());
14141     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
14142                                 St->getPointerInfo().getWithOffset(4),
14143                                 St->isVolatile(),
14144                                 St->isNonTemporal(),
14145                                 MinAlign(St->getAlignment(), 4));
14146     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
14147   }
14148   return SDValue();
14149 }
14150
14151 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
14152 /// and return the operands for the horizontal operation in LHS and RHS.  A
14153 /// horizontal operation performs the binary operation on successive elements
14154 /// of its first operand, then on successive elements of its second operand,
14155 /// returning the resulting values in a vector.  For example, if
14156 ///   A = < float a0, float a1, float a2, float a3 >
14157 /// and
14158 ///   B = < float b0, float b1, float b2, float b3 >
14159 /// then the result of doing a horizontal operation on A and B is
14160 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
14161 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
14162 /// A horizontal-op B, for some already available A and B, and if so then LHS is
14163 /// set to A, RHS to B, and the routine returns 'true'.
14164 /// Note that the binary operation should have the property that if one of the
14165 /// operands is UNDEF then the result is UNDEF.
14166 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
14167   // Look for the following pattern: if
14168   //   A = < float a0, float a1, float a2, float a3 >
14169   //   B = < float b0, float b1, float b2, float b3 >
14170   // and
14171   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
14172   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
14173   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
14174   // which is A horizontal-op B.
14175
14176   // At least one of the operands should be a vector shuffle.
14177   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
14178       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
14179     return false;
14180
14181   EVT VT = LHS.getValueType();
14182
14183   assert((VT.is128BitVector() || VT.is256BitVector()) &&
14184          "Unsupported vector type for horizontal add/sub");
14185
14186   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
14187   // operate independently on 128-bit lanes.
14188   unsigned NumElts = VT.getVectorNumElements();
14189   unsigned NumLanes = VT.getSizeInBits()/128;
14190   unsigned NumLaneElts = NumElts / NumLanes;
14191   assert((NumLaneElts % 2 == 0) &&
14192          "Vector type should have an even number of elements in each lane");
14193   unsigned HalfLaneElts = NumLaneElts/2;
14194
14195   // View LHS in the form
14196   //   LHS = VECTOR_SHUFFLE A, B, LMask
14197   // If LHS is not a shuffle then pretend it is the shuffle
14198   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
14199   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
14200   // type VT.
14201   SDValue A, B;
14202   SmallVector<int, 16> LMask(NumElts);
14203   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
14204     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
14205       A = LHS.getOperand(0);
14206     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
14207       B = LHS.getOperand(1);
14208     cast<ShuffleVectorSDNode>(LHS.getNode())->getMask(LMask);
14209   } else {
14210     if (LHS.getOpcode() != ISD::UNDEF)
14211       A = LHS;
14212     for (unsigned i = 0; i != NumElts; ++i)
14213       LMask[i] = i;
14214   }
14215
14216   // Likewise, view RHS in the form
14217   //   RHS = VECTOR_SHUFFLE C, D, RMask
14218   SDValue C, D;
14219   SmallVector<int, 16> RMask(NumElts);
14220   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
14221     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
14222       C = RHS.getOperand(0);
14223     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
14224       D = RHS.getOperand(1);
14225     cast<ShuffleVectorSDNode>(RHS.getNode())->getMask(RMask);
14226   } else {
14227     if (RHS.getOpcode() != ISD::UNDEF)
14228       C = RHS;
14229     for (unsigned i = 0; i != NumElts; ++i)
14230       RMask[i] = i;
14231   }
14232
14233   // Check that the shuffles are both shuffling the same vectors.
14234   if (!(A == C && B == D) && !(A == D && B == C))
14235     return false;
14236
14237   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
14238   if (!A.getNode() && !B.getNode())
14239     return false;
14240
14241   // If A and B occur in reverse order in RHS, then "swap" them (which means
14242   // rewriting the mask).
14243   if (A != C)
14244     CommuteVectorShuffleMask(RMask, NumElts);
14245
14246   // At this point LHS and RHS are equivalent to
14247   //   LHS = VECTOR_SHUFFLE A, B, LMask
14248   //   RHS = VECTOR_SHUFFLE A, B, RMask
14249   // Check that the masks correspond to performing a horizontal operation.
14250   for (unsigned i = 0; i != NumElts; ++i) {
14251     int LIdx = LMask[i], RIdx = RMask[i];
14252
14253     // Ignore any UNDEF components.
14254     if (LIdx < 0 || RIdx < 0 ||
14255         (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
14256         (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
14257       continue;
14258
14259     // Check that successive elements are being operated on.  If not, this is
14260     // not a horizontal operation.
14261     unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
14262     unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
14263     int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
14264     if (!(LIdx == Index && RIdx == Index + 1) &&
14265         !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
14266       return false;
14267   }
14268
14269   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
14270   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
14271   return true;
14272 }
14273
14274 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
14275 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
14276                                   const X86Subtarget *Subtarget) {
14277   EVT VT = N->getValueType(0);
14278   SDValue LHS = N->getOperand(0);
14279   SDValue RHS = N->getOperand(1);
14280
14281   // Try to synthesize horizontal adds from adds of shuffles.
14282   if (((Subtarget->hasSSE3orAVX() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
14283        (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
14284       isHorizontalBinOp(LHS, RHS, true))
14285     return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
14286   return SDValue();
14287 }
14288
14289 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
14290 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
14291                                   const X86Subtarget *Subtarget) {
14292   EVT VT = N->getValueType(0);
14293   SDValue LHS = N->getOperand(0);
14294   SDValue RHS = N->getOperand(1);
14295
14296   // Try to synthesize horizontal subs from subs of shuffles.
14297   if (((Subtarget->hasSSE3orAVX() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
14298        (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
14299       isHorizontalBinOp(LHS, RHS, false))
14300     return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
14301   return SDValue();
14302 }
14303
14304 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
14305 /// X86ISD::FXOR nodes.
14306 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
14307   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
14308   // F[X]OR(0.0, x) -> x
14309   // F[X]OR(x, 0.0) -> x
14310   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
14311     if (C->getValueAPF().isPosZero())
14312       return N->getOperand(1);
14313   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
14314     if (C->getValueAPF().isPosZero())
14315       return N->getOperand(0);
14316   return SDValue();
14317 }
14318
14319 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
14320 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
14321   // FAND(0.0, x) -> 0.0
14322   // FAND(x, 0.0) -> 0.0
14323   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
14324     if (C->getValueAPF().isPosZero())
14325       return N->getOperand(0);
14326   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
14327     if (C->getValueAPF().isPosZero())
14328       return N->getOperand(1);
14329   return SDValue();
14330 }
14331
14332 static SDValue PerformBTCombine(SDNode *N,
14333                                 SelectionDAG &DAG,
14334                                 TargetLowering::DAGCombinerInfo &DCI) {
14335   // BT ignores high bits in the bit index operand.
14336   SDValue Op1 = N->getOperand(1);
14337   if (Op1.hasOneUse()) {
14338     unsigned BitWidth = Op1.getValueSizeInBits();
14339     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
14340     APInt KnownZero, KnownOne;
14341     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
14342                                           !DCI.isBeforeLegalizeOps());
14343     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14344     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
14345         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
14346       DCI.CommitTargetLoweringOpt(TLO);
14347   }
14348   return SDValue();
14349 }
14350
14351 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
14352   SDValue Op = N->getOperand(0);
14353   if (Op.getOpcode() == ISD::BITCAST)
14354     Op = Op.getOperand(0);
14355   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
14356   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
14357       VT.getVectorElementType().getSizeInBits() ==
14358       OpVT.getVectorElementType().getSizeInBits()) {
14359     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
14360   }
14361   return SDValue();
14362 }
14363
14364 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
14365   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
14366   //           (and (i32 x86isd::setcc_carry), 1)
14367   // This eliminates the zext. This transformation is necessary because
14368   // ISD::SETCC is always legalized to i8.
14369   DebugLoc dl = N->getDebugLoc();
14370   SDValue N0 = N->getOperand(0);
14371   EVT VT = N->getValueType(0);
14372   if (N0.getOpcode() == ISD::AND &&
14373       N0.hasOneUse() &&
14374       N0.getOperand(0).hasOneUse()) {
14375     SDValue N00 = N0.getOperand(0);
14376     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
14377       return SDValue();
14378     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
14379     if (!C || C->getZExtValue() != 1)
14380       return SDValue();
14381     return DAG.getNode(ISD::AND, dl, VT,
14382                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
14383                                    N00.getOperand(0), N00.getOperand(1)),
14384                        DAG.getConstant(1, VT));
14385   }
14386
14387   return SDValue();
14388 }
14389
14390 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
14391 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
14392   unsigned X86CC = N->getConstantOperandVal(0);
14393   SDValue EFLAG = N->getOperand(1);
14394   DebugLoc DL = N->getDebugLoc();
14395
14396   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
14397   // a zext and produces an all-ones bit which is more useful than 0/1 in some
14398   // cases.
14399   if (X86CC == X86::COND_B)
14400     return DAG.getNode(ISD::AND, DL, MVT::i8,
14401                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
14402                                    DAG.getConstant(X86CC, MVT::i8), EFLAG),
14403                        DAG.getConstant(1, MVT::i8));
14404
14405   return SDValue();
14406 }
14407
14408 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
14409                                         const X86TargetLowering *XTLI) {
14410   SDValue Op0 = N->getOperand(0);
14411   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
14412   // a 32-bit target where SSE doesn't support i64->FP operations.
14413   if (Op0.getOpcode() == ISD::LOAD) {
14414     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
14415     EVT VT = Ld->getValueType(0);
14416     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
14417         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
14418         !XTLI->getSubtarget()->is64Bit() &&
14419         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14420       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
14421                                           Ld->getChain(), Op0, DAG);
14422       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
14423       return FILDChain;
14424     }
14425   }
14426   return SDValue();
14427 }
14428
14429 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
14430 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
14431                                  X86TargetLowering::DAGCombinerInfo &DCI) {
14432   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
14433   // the result is either zero or one (depending on the input carry bit).
14434   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
14435   if (X86::isZeroNode(N->getOperand(0)) &&
14436       X86::isZeroNode(N->getOperand(1)) &&
14437       // We don't have a good way to replace an EFLAGS use, so only do this when
14438       // dead right now.
14439       SDValue(N, 1).use_empty()) {
14440     DebugLoc DL = N->getDebugLoc();
14441     EVT VT = N->getValueType(0);
14442     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
14443     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
14444                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
14445                                            DAG.getConstant(X86::COND_B,MVT::i8),
14446                                            N->getOperand(2)),
14447                                DAG.getConstant(1, VT));
14448     return DCI.CombineTo(N, Res1, CarryOut);
14449   }
14450
14451   return SDValue();
14452 }
14453
14454 // fold (add Y, (sete  X, 0)) -> adc  0, Y
14455 //      (add Y, (setne X, 0)) -> sbb -1, Y
14456 //      (sub (sete  X, 0), Y) -> sbb  0, Y
14457 //      (sub (setne X, 0), Y) -> adc -1, Y
14458 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
14459   DebugLoc DL = N->getDebugLoc();
14460
14461   // Look through ZExts.
14462   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
14463   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
14464     return SDValue();
14465
14466   SDValue SetCC = Ext.getOperand(0);
14467   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
14468     return SDValue();
14469
14470   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
14471   if (CC != X86::COND_E && CC != X86::COND_NE)
14472     return SDValue();
14473
14474   SDValue Cmp = SetCC.getOperand(1);
14475   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
14476       !X86::isZeroNode(Cmp.getOperand(1)) ||
14477       !Cmp.getOperand(0).getValueType().isInteger())
14478     return SDValue();
14479
14480   SDValue CmpOp0 = Cmp.getOperand(0);
14481   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
14482                                DAG.getConstant(1, CmpOp0.getValueType()));
14483
14484   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
14485   if (CC == X86::COND_NE)
14486     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
14487                        DL, OtherVal.getValueType(), OtherVal,
14488                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
14489   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
14490                      DL, OtherVal.getValueType(), OtherVal,
14491                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
14492 }
14493
14494 /// PerformADDCombine - Do target-specific dag combines on integer adds.
14495 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
14496                                  const X86Subtarget *Subtarget) {
14497   EVT VT = N->getValueType(0);
14498   SDValue Op0 = N->getOperand(0);
14499   SDValue Op1 = N->getOperand(1);
14500
14501   // Try to synthesize horizontal adds from adds of shuffles.
14502   if (((Subtarget->hasSSSE3orAVX() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
14503        (Subtarget->hasAVX2() && (VT == MVT::v16i16 || MVT::v8i32))) &&
14504       isHorizontalBinOp(Op0, Op1, true))
14505     return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
14506
14507   return OptimizeConditionalInDecrement(N, DAG);
14508 }
14509
14510 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
14511                                  const X86Subtarget *Subtarget) {
14512   SDValue Op0 = N->getOperand(0);
14513   SDValue Op1 = N->getOperand(1);
14514
14515   // X86 can't encode an immediate LHS of a sub. See if we can push the
14516   // negation into a preceding instruction.
14517   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
14518     // If the RHS of the sub is a XOR with one use and a constant, invert the
14519     // immediate. Then add one to the LHS of the sub so we can turn
14520     // X-Y -> X+~Y+1, saving one register.
14521     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
14522         isa<ConstantSDNode>(Op1.getOperand(1))) {
14523       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
14524       EVT VT = Op0.getValueType();
14525       SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
14526                                    Op1.getOperand(0),
14527                                    DAG.getConstant(~XorC, VT));
14528       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
14529                          DAG.getConstant(C->getAPIntValue()+1, VT));
14530     }
14531   }
14532
14533   // Try to synthesize horizontal adds from adds of shuffles.
14534   EVT VT = N->getValueType(0);
14535   if (((Subtarget->hasSSSE3orAVX() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
14536        (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
14537       isHorizontalBinOp(Op0, Op1, true))
14538     return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
14539
14540   return OptimizeConditionalInDecrement(N, DAG);
14541 }
14542
14543 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
14544                                              DAGCombinerInfo &DCI) const {
14545   SelectionDAG &DAG = DCI.DAG;
14546   switch (N->getOpcode()) {
14547   default: break;
14548   case ISD::EXTRACT_VECTOR_ELT:
14549     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
14550   case ISD::VSELECT:
14551   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
14552   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
14553   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
14554   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
14555   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
14556   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
14557   case ISD::SHL:
14558   case ISD::SRA:
14559   case ISD::SRL:            return PerformShiftCombine(N, DAG, Subtarget);
14560   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
14561   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
14562   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
14563   case ISD::LOAD:           return PerformLOADCombine(N, DAG, Subtarget);
14564   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
14565   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
14566   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
14567   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
14568   case X86ISD::FXOR:
14569   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
14570   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
14571   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
14572   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
14573   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG);
14574   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG);
14575   case X86ISD::SHUFPS:      // Handle all target specific shuffles
14576   case X86ISD::SHUFPD:
14577   case X86ISD::PALIGN:
14578   case X86ISD::UNPCKH:
14579   case X86ISD::UNPCKL:
14580   case X86ISD::MOVHLPS:
14581   case X86ISD::MOVLHPS:
14582   case X86ISD::PSHUFD:
14583   case X86ISD::PSHUFHW:
14584   case X86ISD::PSHUFLW:
14585   case X86ISD::MOVSS:
14586   case X86ISD::MOVSD:
14587   case X86ISD::VPERMILP:
14588   case X86ISD::VPERM2X128:
14589   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
14590   }
14591
14592   return SDValue();
14593 }
14594
14595 /// isTypeDesirableForOp - Return true if the target has native support for
14596 /// the specified value type and it is 'desirable' to use the type for the
14597 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
14598 /// instruction encodings are longer and some i16 instructions are slow.
14599 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
14600   if (!isTypeLegal(VT))
14601     return false;
14602   if (VT != MVT::i16)
14603     return true;
14604
14605   switch (Opc) {
14606   default:
14607     return true;
14608   case ISD::LOAD:
14609   case ISD::SIGN_EXTEND:
14610   case ISD::ZERO_EXTEND:
14611   case ISD::ANY_EXTEND:
14612   case ISD::SHL:
14613   case ISD::SRL:
14614   case ISD::SUB:
14615   case ISD::ADD:
14616   case ISD::MUL:
14617   case ISD::AND:
14618   case ISD::OR:
14619   case ISD::XOR:
14620     return false;
14621   }
14622 }
14623
14624 /// IsDesirableToPromoteOp - This method query the target whether it is
14625 /// beneficial for dag combiner to promote the specified node. If true, it
14626 /// should return the desired promotion type by reference.
14627 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
14628   EVT VT = Op.getValueType();
14629   if (VT != MVT::i16)
14630     return false;
14631
14632   bool Promote = false;
14633   bool Commute = false;
14634   switch (Op.getOpcode()) {
14635   default: break;
14636   case ISD::LOAD: {
14637     LoadSDNode *LD = cast<LoadSDNode>(Op);
14638     // If the non-extending load has a single use and it's not live out, then it
14639     // might be folded.
14640     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
14641                                                      Op.hasOneUse()*/) {
14642       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
14643              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
14644         // The only case where we'd want to promote LOAD (rather then it being
14645         // promoted as an operand is when it's only use is liveout.
14646         if (UI->getOpcode() != ISD::CopyToReg)
14647           return false;
14648       }
14649     }
14650     Promote = true;
14651     break;
14652   }
14653   case ISD::SIGN_EXTEND:
14654   case ISD::ZERO_EXTEND:
14655   case ISD::ANY_EXTEND:
14656     Promote = true;
14657     break;
14658   case ISD::SHL:
14659   case ISD::SRL: {
14660     SDValue N0 = Op.getOperand(0);
14661     // Look out for (store (shl (load), x)).
14662     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
14663       return false;
14664     Promote = true;
14665     break;
14666   }
14667   case ISD::ADD:
14668   case ISD::MUL:
14669   case ISD::AND:
14670   case ISD::OR:
14671   case ISD::XOR:
14672     Commute = true;
14673     // fallthrough
14674   case ISD::SUB: {
14675     SDValue N0 = Op.getOperand(0);
14676     SDValue N1 = Op.getOperand(1);
14677     if (!Commute && MayFoldLoad(N1))
14678       return false;
14679     // Avoid disabling potential load folding opportunities.
14680     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
14681       return false;
14682     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
14683       return false;
14684     Promote = true;
14685   }
14686   }
14687
14688   PVT = MVT::i32;
14689   return Promote;
14690 }
14691
14692 //===----------------------------------------------------------------------===//
14693 //                           X86 Inline Assembly Support
14694 //===----------------------------------------------------------------------===//
14695
14696 namespace {
14697   // Helper to match a string separated by whitespace.
14698   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
14699     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
14700
14701     for (unsigned i = 0, e = args.size(); i != e; ++i) {
14702       StringRef piece(*args[i]);
14703       if (!s.startswith(piece)) // Check if the piece matches.
14704         return false;
14705
14706       s = s.substr(piece.size());
14707       StringRef::size_type pos = s.find_first_not_of(" \t");
14708       if (pos == 0) // We matched a prefix.
14709         return false;
14710
14711       s = s.substr(pos);
14712     }
14713
14714     return s.empty();
14715   }
14716   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
14717 }
14718
14719 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
14720   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
14721
14722   std::string AsmStr = IA->getAsmString();
14723
14724   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14725   if (!Ty || Ty->getBitWidth() % 16 != 0)
14726     return false;
14727
14728   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
14729   SmallVector<StringRef, 4> AsmPieces;
14730   SplitString(AsmStr, AsmPieces, ";\n");
14731
14732   switch (AsmPieces.size()) {
14733   default: return false;
14734   case 1:
14735     // FIXME: this should verify that we are targeting a 486 or better.  If not,
14736     // we will turn this bswap into something that will be lowered to logical
14737     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
14738     // lower so don't worry about this.
14739     // bswap $0
14740     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
14741         matchAsm(AsmPieces[0], "bswapl", "$0") ||
14742         matchAsm(AsmPieces[0], "bswapq", "$0") ||
14743         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
14744         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
14745         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
14746       // No need to check constraints, nothing other than the equivalent of
14747       // "=r,0" would be valid here.
14748       return IntrinsicLowering::LowerToByteSwap(CI);
14749     }
14750
14751     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
14752     if (CI->getType()->isIntegerTy(16) &&
14753         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
14754         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
14755          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
14756       AsmPieces.clear();
14757       const std::string &ConstraintsStr = IA->getConstraintString();
14758       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
14759       std::sort(AsmPieces.begin(), AsmPieces.end());
14760       if (AsmPieces.size() == 4 &&
14761           AsmPieces[0] == "~{cc}" &&
14762           AsmPieces[1] == "~{dirflag}" &&
14763           AsmPieces[2] == "~{flags}" &&
14764           AsmPieces[3] == "~{fpsr}")
14765       return IntrinsicLowering::LowerToByteSwap(CI);
14766     }
14767     break;
14768   case 3:
14769     if (CI->getType()->isIntegerTy(32) &&
14770         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
14771         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
14772         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
14773         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
14774       AsmPieces.clear();
14775       const std::string &ConstraintsStr = IA->getConstraintString();
14776       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
14777       std::sort(AsmPieces.begin(), AsmPieces.end());
14778       if (AsmPieces.size() == 4 &&
14779           AsmPieces[0] == "~{cc}" &&
14780           AsmPieces[1] == "~{dirflag}" &&
14781           AsmPieces[2] == "~{flags}" &&
14782           AsmPieces[3] == "~{fpsr}")
14783         return IntrinsicLowering::LowerToByteSwap(CI);
14784     }
14785
14786     if (CI->getType()->isIntegerTy(64)) {
14787       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
14788       if (Constraints.size() >= 2 &&
14789           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
14790           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
14791         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
14792         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
14793             matchAsm(AsmPieces[1], "bswap", "%edx") &&
14794             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
14795           return IntrinsicLowering::LowerToByteSwap(CI);
14796       }
14797     }
14798     break;
14799   }
14800   return false;
14801 }
14802
14803
14804
14805 /// getConstraintType - Given a constraint letter, return the type of
14806 /// constraint it is for this target.
14807 X86TargetLowering::ConstraintType
14808 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
14809   if (Constraint.size() == 1) {
14810     switch (Constraint[0]) {
14811     case 'R':
14812     case 'q':
14813     case 'Q':
14814     case 'f':
14815     case 't':
14816     case 'u':
14817     case 'y':
14818     case 'x':
14819     case 'Y':
14820     case 'l':
14821       return C_RegisterClass;
14822     case 'a':
14823     case 'b':
14824     case 'c':
14825     case 'd':
14826     case 'S':
14827     case 'D':
14828     case 'A':
14829       return C_Register;
14830     case 'I':
14831     case 'J':
14832     case 'K':
14833     case 'L':
14834     case 'M':
14835     case 'N':
14836     case 'G':
14837     case 'C':
14838     case 'e':
14839     case 'Z':
14840       return C_Other;
14841     default:
14842       break;
14843     }
14844   }
14845   return TargetLowering::getConstraintType(Constraint);
14846 }
14847
14848 /// Examine constraint type and operand type and determine a weight value.
14849 /// This object must already have been set up with the operand type
14850 /// and the current alternative constraint selected.
14851 TargetLowering::ConstraintWeight
14852   X86TargetLowering::getSingleConstraintMatchWeight(
14853     AsmOperandInfo &info, const char *constraint) const {
14854   ConstraintWeight weight = CW_Invalid;
14855   Value *CallOperandVal = info.CallOperandVal;
14856     // If we don't have a value, we can't do a match,
14857     // but allow it at the lowest weight.
14858   if (CallOperandVal == NULL)
14859     return CW_Default;
14860   Type *type = CallOperandVal->getType();
14861   // Look at the constraint type.
14862   switch (*constraint) {
14863   default:
14864     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
14865   case 'R':
14866   case 'q':
14867   case 'Q':
14868   case 'a':
14869   case 'b':
14870   case 'c':
14871   case 'd':
14872   case 'S':
14873   case 'D':
14874   case 'A':
14875     if (CallOperandVal->getType()->isIntegerTy())
14876       weight = CW_SpecificReg;
14877     break;
14878   case 'f':
14879   case 't':
14880   case 'u':
14881       if (type->isFloatingPointTy())
14882         weight = CW_SpecificReg;
14883       break;
14884   case 'y':
14885       if (type->isX86_MMXTy() && Subtarget->hasMMX())
14886         weight = CW_SpecificReg;
14887       break;
14888   case 'x':
14889   case 'Y':
14890     if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
14891       weight = CW_Register;
14892     break;
14893   case 'I':
14894     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
14895       if (C->getZExtValue() <= 31)
14896         weight = CW_Constant;
14897     }
14898     break;
14899   case 'J':
14900     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14901       if (C->getZExtValue() <= 63)
14902         weight = CW_Constant;
14903     }
14904     break;
14905   case 'K':
14906     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14907       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
14908         weight = CW_Constant;
14909     }
14910     break;
14911   case 'L':
14912     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14913       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
14914         weight = CW_Constant;
14915     }
14916     break;
14917   case 'M':
14918     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14919       if (C->getZExtValue() <= 3)
14920         weight = CW_Constant;
14921     }
14922     break;
14923   case 'N':
14924     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14925       if (C->getZExtValue() <= 0xff)
14926         weight = CW_Constant;
14927     }
14928     break;
14929   case 'G':
14930   case 'C':
14931     if (dyn_cast<ConstantFP>(CallOperandVal)) {
14932       weight = CW_Constant;
14933     }
14934     break;
14935   case 'e':
14936     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14937       if ((C->getSExtValue() >= -0x80000000LL) &&
14938           (C->getSExtValue() <= 0x7fffffffLL))
14939         weight = CW_Constant;
14940     }
14941     break;
14942   case 'Z':
14943     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14944       if (C->getZExtValue() <= 0xffffffff)
14945         weight = CW_Constant;
14946     }
14947     break;
14948   }
14949   return weight;
14950 }
14951
14952 /// LowerXConstraint - try to replace an X constraint, which matches anything,
14953 /// with another that has more specific requirements based on the type of the
14954 /// corresponding operand.
14955 const char *X86TargetLowering::
14956 LowerXConstraint(EVT ConstraintVT) const {
14957   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
14958   // 'f' like normal targets.
14959   if (ConstraintVT.isFloatingPoint()) {
14960     if (Subtarget->hasXMMInt())
14961       return "Y";
14962     if (Subtarget->hasXMM())
14963       return "x";
14964   }
14965
14966   return TargetLowering::LowerXConstraint(ConstraintVT);
14967 }
14968
14969 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
14970 /// vector.  If it is invalid, don't add anything to Ops.
14971 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
14972                                                      std::string &Constraint,
14973                                                      std::vector<SDValue>&Ops,
14974                                                      SelectionDAG &DAG) const {
14975   SDValue Result(0, 0);
14976
14977   // Only support length 1 constraints for now.
14978   if (Constraint.length() > 1) return;
14979
14980   char ConstraintLetter = Constraint[0];
14981   switch (ConstraintLetter) {
14982   default: break;
14983   case 'I':
14984     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14985       if (C->getZExtValue() <= 31) {
14986         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
14987         break;
14988       }
14989     }
14990     return;
14991   case 'J':
14992     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14993       if (C->getZExtValue() <= 63) {
14994         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
14995         break;
14996       }
14997     }
14998     return;
14999   case 'K':
15000     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15001       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
15002         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15003         break;
15004       }
15005     }
15006     return;
15007   case 'N':
15008     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15009       if (C->getZExtValue() <= 255) {
15010         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15011         break;
15012       }
15013     }
15014     return;
15015   case 'e': {
15016     // 32-bit signed value
15017     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15018       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
15019                                            C->getSExtValue())) {
15020         // Widen to 64 bits here to get it sign extended.
15021         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
15022         break;
15023       }
15024     // FIXME gcc accepts some relocatable values here too, but only in certain
15025     // memory models; it's complicated.
15026     }
15027     return;
15028   }
15029   case 'Z': {
15030     // 32-bit unsigned value
15031     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15032       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
15033                                            C->getZExtValue())) {
15034         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15035         break;
15036       }
15037     }
15038     // FIXME gcc accepts some relocatable values here too, but only in certain
15039     // memory models; it's complicated.
15040     return;
15041   }
15042   case 'i': {
15043     // Literal immediates are always ok.
15044     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
15045       // Widen to 64 bits here to get it sign extended.
15046       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
15047       break;
15048     }
15049
15050     // In any sort of PIC mode addresses need to be computed at runtime by
15051     // adding in a register or some sort of table lookup.  These can't
15052     // be used as immediates.
15053     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
15054       return;
15055
15056     // If we are in non-pic codegen mode, we allow the address of a global (with
15057     // an optional displacement) to be used with 'i'.
15058     GlobalAddressSDNode *GA = 0;
15059     int64_t Offset = 0;
15060
15061     // Match either (GA), (GA+C), (GA+C1+C2), etc.
15062     while (1) {
15063       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
15064         Offset += GA->getOffset();
15065         break;
15066       } else if (Op.getOpcode() == ISD::ADD) {
15067         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
15068           Offset += C->getZExtValue();
15069           Op = Op.getOperand(0);
15070           continue;
15071         }
15072       } else if (Op.getOpcode() == ISD::SUB) {
15073         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
15074           Offset += -C->getZExtValue();
15075           Op = Op.getOperand(0);
15076           continue;
15077         }
15078       }
15079
15080       // Otherwise, this isn't something we can handle, reject it.
15081       return;
15082     }
15083
15084     const GlobalValue *GV = GA->getGlobal();
15085     // If we require an extra load to get this address, as in PIC mode, we
15086     // can't accept it.
15087     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
15088                                                         getTargetMachine())))
15089       return;
15090
15091     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
15092                                         GA->getValueType(0), Offset);
15093     break;
15094   }
15095   }
15096
15097   if (Result.getNode()) {
15098     Ops.push_back(Result);
15099     return;
15100   }
15101   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
15102 }
15103
15104 std::pair<unsigned, const TargetRegisterClass*>
15105 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
15106                                                 EVT VT) const {
15107   // First, see if this is a constraint that directly corresponds to an LLVM
15108   // register class.
15109   if (Constraint.size() == 1) {
15110     // GCC Constraint Letters
15111     switch (Constraint[0]) {
15112     default: break;
15113       // TODO: Slight differences here in allocation order and leaving
15114       // RIP in the class. Do they matter any more here than they do
15115       // in the normal allocation?
15116     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
15117       if (Subtarget->is64Bit()) {
15118         if (VT == MVT::i32 || VT == MVT::f32)
15119           return std::make_pair(0U, X86::GR32RegisterClass);
15120         else if (VT == MVT::i16)
15121           return std::make_pair(0U, X86::GR16RegisterClass);
15122         else if (VT == MVT::i8 || VT == MVT::i1)
15123           return std::make_pair(0U, X86::GR8RegisterClass);
15124         else if (VT == MVT::i64 || VT == MVT::f64)
15125           return std::make_pair(0U, X86::GR64RegisterClass);
15126         break;
15127       }
15128       // 32-bit fallthrough
15129     case 'Q':   // Q_REGS
15130       if (VT == MVT::i32 || VT == MVT::f32)
15131         return std::make_pair(0U, X86::GR32_ABCDRegisterClass);
15132       else if (VT == MVT::i16)
15133         return std::make_pair(0U, X86::GR16_ABCDRegisterClass);
15134       else if (VT == MVT::i8 || VT == MVT::i1)
15135         return std::make_pair(0U, X86::GR8_ABCD_LRegisterClass);
15136       else if (VT == MVT::i64)
15137         return std::make_pair(0U, X86::GR64_ABCDRegisterClass);
15138       break;
15139     case 'r':   // GENERAL_REGS
15140     case 'l':   // INDEX_REGS
15141       if (VT == MVT::i8 || VT == MVT::i1)
15142         return std::make_pair(0U, X86::GR8RegisterClass);
15143       if (VT == MVT::i16)
15144         return std::make_pair(0U, X86::GR16RegisterClass);
15145       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
15146         return std::make_pair(0U, X86::GR32RegisterClass);
15147       return std::make_pair(0U, X86::GR64RegisterClass);
15148     case 'R':   // LEGACY_REGS
15149       if (VT == MVT::i8 || VT == MVT::i1)
15150         return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
15151       if (VT == MVT::i16)
15152         return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
15153       if (VT == MVT::i32 || !Subtarget->is64Bit())
15154         return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
15155       return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
15156     case 'f':  // FP Stack registers.
15157       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
15158       // value to the correct fpstack register class.
15159       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
15160         return std::make_pair(0U, X86::RFP32RegisterClass);
15161       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
15162         return std::make_pair(0U, X86::RFP64RegisterClass);
15163       return std::make_pair(0U, X86::RFP80RegisterClass);
15164     case 'y':   // MMX_REGS if MMX allowed.
15165       if (!Subtarget->hasMMX()) break;
15166       return std::make_pair(0U, X86::VR64RegisterClass);
15167     case 'Y':   // SSE_REGS if SSE2 allowed
15168       if (!Subtarget->hasXMMInt()) break;
15169       // FALL THROUGH.
15170     case 'x':   // SSE_REGS if SSE1 allowed
15171       if (!Subtarget->hasXMM()) break;
15172
15173       switch (VT.getSimpleVT().SimpleTy) {
15174       default: break;
15175       // Scalar SSE types.
15176       case MVT::f32:
15177       case MVT::i32:
15178         return std::make_pair(0U, X86::FR32RegisterClass);
15179       case MVT::f64:
15180       case MVT::i64:
15181         return std::make_pair(0U, X86::FR64RegisterClass);
15182       // Vector types.
15183       case MVT::v16i8:
15184       case MVT::v8i16:
15185       case MVT::v4i32:
15186       case MVT::v2i64:
15187       case MVT::v4f32:
15188       case MVT::v2f64:
15189         return std::make_pair(0U, X86::VR128RegisterClass);
15190       }
15191       break;
15192     }
15193   }
15194
15195   // Use the default implementation in TargetLowering to convert the register
15196   // constraint into a member of a register class.
15197   std::pair<unsigned, const TargetRegisterClass*> Res;
15198   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
15199
15200   // Not found as a standard register?
15201   if (Res.second == 0) {
15202     // Map st(0) -> st(7) -> ST0
15203     if (Constraint.size() == 7 && Constraint[0] == '{' &&
15204         tolower(Constraint[1]) == 's' &&
15205         tolower(Constraint[2]) == 't' &&
15206         Constraint[3] == '(' &&
15207         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
15208         Constraint[5] == ')' &&
15209         Constraint[6] == '}') {
15210
15211       Res.first = X86::ST0+Constraint[4]-'0';
15212       Res.second = X86::RFP80RegisterClass;
15213       return Res;
15214     }
15215
15216     // GCC allows "st(0)" to be called just plain "st".
15217     if (StringRef("{st}").equals_lower(Constraint)) {
15218       Res.first = X86::ST0;
15219       Res.second = X86::RFP80RegisterClass;
15220       return Res;
15221     }
15222
15223     // flags -> EFLAGS
15224     if (StringRef("{flags}").equals_lower(Constraint)) {
15225       Res.first = X86::EFLAGS;
15226       Res.second = X86::CCRRegisterClass;
15227       return Res;
15228     }
15229
15230     // 'A' means EAX + EDX.
15231     if (Constraint == "A") {
15232       Res.first = X86::EAX;
15233       Res.second = X86::GR32_ADRegisterClass;
15234       return Res;
15235     }
15236     return Res;
15237   }
15238
15239   // Otherwise, check to see if this is a register class of the wrong value
15240   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
15241   // turn into {ax},{dx}.
15242   if (Res.second->hasType(VT))
15243     return Res;   // Correct type already, nothing to do.
15244
15245   // All of the single-register GCC register classes map their values onto
15246   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
15247   // really want an 8-bit or 32-bit register, map to the appropriate register
15248   // class and return the appropriate register.
15249   if (Res.second == X86::GR16RegisterClass) {
15250     if (VT == MVT::i8) {
15251       unsigned DestReg = 0;
15252       switch (Res.first) {
15253       default: break;
15254       case X86::AX: DestReg = X86::AL; break;
15255       case X86::DX: DestReg = X86::DL; break;
15256       case X86::CX: DestReg = X86::CL; break;
15257       case X86::BX: DestReg = X86::BL; break;
15258       }
15259       if (DestReg) {
15260         Res.first = DestReg;
15261         Res.second = X86::GR8RegisterClass;
15262       }
15263     } else if (VT == MVT::i32) {
15264       unsigned DestReg = 0;
15265       switch (Res.first) {
15266       default: break;
15267       case X86::AX: DestReg = X86::EAX; break;
15268       case X86::DX: DestReg = X86::EDX; break;
15269       case X86::CX: DestReg = X86::ECX; break;
15270       case X86::BX: DestReg = X86::EBX; break;
15271       case X86::SI: DestReg = X86::ESI; break;
15272       case X86::DI: DestReg = X86::EDI; break;
15273       case X86::BP: DestReg = X86::EBP; break;
15274       case X86::SP: DestReg = X86::ESP; break;
15275       }
15276       if (DestReg) {
15277         Res.first = DestReg;
15278         Res.second = X86::GR32RegisterClass;
15279       }
15280     } else if (VT == MVT::i64) {
15281       unsigned DestReg = 0;
15282       switch (Res.first) {
15283       default: break;
15284       case X86::AX: DestReg = X86::RAX; break;
15285       case X86::DX: DestReg = X86::RDX; break;
15286       case X86::CX: DestReg = X86::RCX; break;
15287       case X86::BX: DestReg = X86::RBX; break;
15288       case X86::SI: DestReg = X86::RSI; break;
15289       case X86::DI: DestReg = X86::RDI; break;
15290       case X86::BP: DestReg = X86::RBP; break;
15291       case X86::SP: DestReg = X86::RSP; break;
15292       }
15293       if (DestReg) {
15294         Res.first = DestReg;
15295         Res.second = X86::GR64RegisterClass;
15296       }
15297     }
15298   } else if (Res.second == X86::FR32RegisterClass ||
15299              Res.second == X86::FR64RegisterClass ||
15300              Res.second == X86::VR128RegisterClass) {
15301     // Handle references to XMM physical registers that got mapped into the
15302     // wrong class.  This can happen with constraints like {xmm0} where the
15303     // target independent register mapper will just pick the first match it can
15304     // find, ignoring the required type.
15305     if (VT == MVT::f32)
15306       Res.second = X86::FR32RegisterClass;
15307     else if (VT == MVT::f64)
15308       Res.second = X86::FR64RegisterClass;
15309     else if (X86::VR128RegisterClass->hasType(VT))
15310       Res.second = X86::VR128RegisterClass;
15311   }
15312
15313   return Res;
15314 }