Begin teaching the X86 target how to efficiently codegen patterns that
[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::BUILD_VECTOR);
1194   setTargetDAGCombine(ISD::VSELECT);
1195   setTargetDAGCombine(ISD::SELECT);
1196   setTargetDAGCombine(ISD::SHL);
1197   setTargetDAGCombine(ISD::SRA);
1198   setTargetDAGCombine(ISD::SRL);
1199   setTargetDAGCombine(ISD::OR);
1200   setTargetDAGCombine(ISD::AND);
1201   setTargetDAGCombine(ISD::ADD);
1202   setTargetDAGCombine(ISD::FADD);
1203   setTargetDAGCombine(ISD::FSUB);
1204   setTargetDAGCombine(ISD::SUB);
1205   setTargetDAGCombine(ISD::LOAD);
1206   setTargetDAGCombine(ISD::STORE);
1207   setTargetDAGCombine(ISD::ZERO_EXTEND);
1208   setTargetDAGCombine(ISD::SINT_TO_FP);
1209   if (Subtarget->is64Bit())
1210     setTargetDAGCombine(ISD::MUL);
1211   if (Subtarget->hasBMI())
1212     setTargetDAGCombine(ISD::XOR);
1213
1214   computeRegisterProperties();
1215
1216   // On Darwin, -Os means optimize for size without hurting performance,
1217   // do not reduce the limit.
1218   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1219   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1220   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1221   maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1222   maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1223   maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1224   setPrefLoopAlignment(4); // 2^4 bytes.
1225   benefitFromCodePlacementOpt = true;
1226
1227   setPrefFunctionAlignment(4); // 2^4 bytes.
1228 }
1229
1230
1231 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1232   if (!VT.isVector()) return MVT::i8;
1233   return VT.changeVectorElementTypeToInteger();
1234 }
1235
1236
1237 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1238 /// the desired ByVal argument alignment.
1239 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1240   if (MaxAlign == 16)
1241     return;
1242   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1243     if (VTy->getBitWidth() == 128)
1244       MaxAlign = 16;
1245   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1246     unsigned EltAlign = 0;
1247     getMaxByValAlign(ATy->getElementType(), EltAlign);
1248     if (EltAlign > MaxAlign)
1249       MaxAlign = EltAlign;
1250   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1251     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1252       unsigned EltAlign = 0;
1253       getMaxByValAlign(STy->getElementType(i), EltAlign);
1254       if (EltAlign > MaxAlign)
1255         MaxAlign = EltAlign;
1256       if (MaxAlign == 16)
1257         break;
1258     }
1259   }
1260   return;
1261 }
1262
1263 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1264 /// function arguments in the caller parameter area. For X86, aggregates
1265 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1266 /// are at 4-byte boundaries.
1267 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1268   if (Subtarget->is64Bit()) {
1269     // Max of 8 and alignment of type.
1270     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1271     if (TyAlign > 8)
1272       return TyAlign;
1273     return 8;
1274   }
1275
1276   unsigned Align = 4;
1277   if (Subtarget->hasXMM())
1278     getMaxByValAlign(Ty, Align);
1279   return Align;
1280 }
1281
1282 /// getOptimalMemOpType - Returns the target specific optimal type for load
1283 /// and store operations as a result of memset, memcpy, and memmove
1284 /// lowering. If DstAlign is zero that means it's safe to destination
1285 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1286 /// means there isn't a need to check it against alignment requirement,
1287 /// probably because the source does not need to be loaded. If
1288 /// 'IsZeroVal' is true, that means it's safe to return a
1289 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1290 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1291 /// constant so it does not need to be loaded.
1292 /// It returns EVT::Other if the type should be determined using generic
1293 /// target-independent logic.
1294 EVT
1295 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1296                                        unsigned DstAlign, unsigned SrcAlign,
1297                                        bool IsZeroVal,
1298                                        bool MemcpyStrSrc,
1299                                        MachineFunction &MF) const {
1300   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1301   // linux.  This is because the stack realignment code can't handle certain
1302   // cases like PR2962.  This should be removed when PR2962 is fixed.
1303   const Function *F = MF.getFunction();
1304   if (IsZeroVal &&
1305       !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1306     if (Size >= 16 &&
1307         (Subtarget->isUnalignedMemAccessFast() ||
1308          ((DstAlign == 0 || DstAlign >= 16) &&
1309           (SrcAlign == 0 || SrcAlign >= 16))) &&
1310         Subtarget->getStackAlignment() >= 16) {
1311       if (Subtarget->hasAVX() &&
1312           Subtarget->getStackAlignment() >= 32)
1313         return MVT::v8f32;
1314       if (Subtarget->hasXMMInt())
1315         return MVT::v4i32;
1316       if (Subtarget->hasXMM())
1317         return MVT::v4f32;
1318     } else if (!MemcpyStrSrc && Size >= 8 &&
1319                !Subtarget->is64Bit() &&
1320                Subtarget->getStackAlignment() >= 8 &&
1321                Subtarget->hasXMMInt()) {
1322       // Do not use f64 to lower memcpy if source is string constant. It's
1323       // better to use i32 to avoid the loads.
1324       return MVT::f64;
1325     }
1326   }
1327   if (Subtarget->is64Bit() && Size >= 8)
1328     return MVT::i64;
1329   return MVT::i32;
1330 }
1331
1332 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1333 /// current function.  The returned value is a member of the
1334 /// MachineJumpTableInfo::JTEntryKind enum.
1335 unsigned X86TargetLowering::getJumpTableEncoding() const {
1336   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1337   // symbol.
1338   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1339       Subtarget->isPICStyleGOT())
1340     return MachineJumpTableInfo::EK_Custom32;
1341
1342   // Otherwise, use the normal jump table encoding heuristics.
1343   return TargetLowering::getJumpTableEncoding();
1344 }
1345
1346 const MCExpr *
1347 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1348                                              const MachineBasicBlock *MBB,
1349                                              unsigned uid,MCContext &Ctx) const{
1350   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1351          Subtarget->isPICStyleGOT());
1352   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1353   // entries.
1354   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1355                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1356 }
1357
1358 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1359 /// jumptable.
1360 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1361                                                     SelectionDAG &DAG) const {
1362   if (!Subtarget->is64Bit())
1363     // This doesn't have DebugLoc associated with it, but is not really the
1364     // same as a Register.
1365     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1366   return Table;
1367 }
1368
1369 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1370 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1371 /// MCExpr.
1372 const MCExpr *X86TargetLowering::
1373 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1374                              MCContext &Ctx) const {
1375   // X86-64 uses RIP relative addressing based on the jump table label.
1376   if (Subtarget->isPICStyleRIPRel())
1377     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1378
1379   // Otherwise, the reference is relative to the PIC base.
1380   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1381 }
1382
1383 // FIXME: Why this routine is here? Move to RegInfo!
1384 std::pair<const TargetRegisterClass*, uint8_t>
1385 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1386   const TargetRegisterClass *RRC = 0;
1387   uint8_t Cost = 1;
1388   switch (VT.getSimpleVT().SimpleTy) {
1389   default:
1390     return TargetLowering::findRepresentativeClass(VT);
1391   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1392     RRC = (Subtarget->is64Bit()
1393            ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1394     break;
1395   case MVT::x86mmx:
1396     RRC = X86::VR64RegisterClass;
1397     break;
1398   case MVT::f32: case MVT::f64:
1399   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1400   case MVT::v4f32: case MVT::v2f64:
1401   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1402   case MVT::v4f64:
1403     RRC = X86::VR128RegisterClass;
1404     break;
1405   }
1406   return std::make_pair(RRC, Cost);
1407 }
1408
1409 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1410                                                unsigned &Offset) const {
1411   if (!Subtarget->isTargetLinux())
1412     return false;
1413
1414   if (Subtarget->is64Bit()) {
1415     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1416     Offset = 0x28;
1417     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1418       AddressSpace = 256;
1419     else
1420       AddressSpace = 257;
1421   } else {
1422     // %gs:0x14 on i386
1423     Offset = 0x14;
1424     AddressSpace = 256;
1425   }
1426   return true;
1427 }
1428
1429
1430 //===----------------------------------------------------------------------===//
1431 //               Return Value Calling Convention Implementation
1432 //===----------------------------------------------------------------------===//
1433
1434 #include "X86GenCallingConv.inc"
1435
1436 bool
1437 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1438                                   MachineFunction &MF, bool isVarArg,
1439                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1440                         LLVMContext &Context) const {
1441   SmallVector<CCValAssign, 16> RVLocs;
1442   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1443                  RVLocs, Context);
1444   return CCInfo.CheckReturn(Outs, RetCC_X86);
1445 }
1446
1447 SDValue
1448 X86TargetLowering::LowerReturn(SDValue Chain,
1449                                CallingConv::ID CallConv, bool isVarArg,
1450                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1451                                const SmallVectorImpl<SDValue> &OutVals,
1452                                DebugLoc dl, SelectionDAG &DAG) const {
1453   MachineFunction &MF = DAG.getMachineFunction();
1454   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1455
1456   SmallVector<CCValAssign, 16> RVLocs;
1457   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1458                  RVLocs, *DAG.getContext());
1459   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1460
1461   // Add the regs to the liveout set for the function.
1462   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1463   for (unsigned i = 0; i != RVLocs.size(); ++i)
1464     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1465       MRI.addLiveOut(RVLocs[i].getLocReg());
1466
1467   SDValue Flag;
1468
1469   SmallVector<SDValue, 6> RetOps;
1470   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1471   // Operand #1 = Bytes To Pop
1472   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1473                    MVT::i16));
1474
1475   // Copy the result values into the output registers.
1476   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1477     CCValAssign &VA = RVLocs[i];
1478     assert(VA.isRegLoc() && "Can only return in registers!");
1479     SDValue ValToCopy = OutVals[i];
1480     EVT ValVT = ValToCopy.getValueType();
1481
1482     // If this is x86-64, and we disabled SSE, we can't return FP values,
1483     // or SSE or MMX vectors.
1484     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1485          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1486           (Subtarget->is64Bit() && !Subtarget->hasXMM())) {
1487       report_fatal_error("SSE register return with SSE disabled");
1488     }
1489     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1490     // llvm-gcc has never done it right and no one has noticed, so this
1491     // should be OK for now.
1492     if (ValVT == MVT::f64 &&
1493         (Subtarget->is64Bit() && !Subtarget->hasXMMInt()))
1494       report_fatal_error("SSE2 register return with SSE2 disabled");
1495
1496     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1497     // the RET instruction and handled by the FP Stackifier.
1498     if (VA.getLocReg() == X86::ST0 ||
1499         VA.getLocReg() == X86::ST1) {
1500       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1501       // change the value to the FP stack register class.
1502       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1503         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1504       RetOps.push_back(ValToCopy);
1505       // Don't emit a copytoreg.
1506       continue;
1507     }
1508
1509     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1510     // which is returned in RAX / RDX.
1511     if (Subtarget->is64Bit()) {
1512       if (ValVT == MVT::x86mmx) {
1513         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1514           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1515           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1516                                   ValToCopy);
1517           // If we don't have SSE2 available, convert to v4f32 so the generated
1518           // register is legal.
1519           if (!Subtarget->hasXMMInt())
1520             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1521         }
1522       }
1523     }
1524
1525     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1526     Flag = Chain.getValue(1);
1527   }
1528
1529   // The x86-64 ABI for returning structs by value requires that we copy
1530   // the sret argument into %rax for the return. We saved the argument into
1531   // a virtual register in the entry block, so now we copy the value out
1532   // and into %rax.
1533   if (Subtarget->is64Bit() &&
1534       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1535     MachineFunction &MF = DAG.getMachineFunction();
1536     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1537     unsigned Reg = FuncInfo->getSRetReturnReg();
1538     assert(Reg &&
1539            "SRetReturnReg should have been set in LowerFormalArguments().");
1540     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1541
1542     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1543     Flag = Chain.getValue(1);
1544
1545     // RAX now acts like a return value.
1546     MRI.addLiveOut(X86::RAX);
1547   }
1548
1549   RetOps[0] = Chain;  // Update chain.
1550
1551   // Add the flag if we have it.
1552   if (Flag.getNode())
1553     RetOps.push_back(Flag);
1554
1555   return DAG.getNode(X86ISD::RET_FLAG, dl,
1556                      MVT::Other, &RetOps[0], RetOps.size());
1557 }
1558
1559 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1560   if (N->getNumValues() != 1)
1561     return false;
1562   if (!N->hasNUsesOfValue(1, 0))
1563     return false;
1564
1565   SDNode *Copy = *N->use_begin();
1566   if (Copy->getOpcode() != ISD::CopyToReg &&
1567       Copy->getOpcode() != ISD::FP_EXTEND)
1568     return false;
1569
1570   bool HasRet = false;
1571   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1572        UI != UE; ++UI) {
1573     if (UI->getOpcode() != X86ISD::RET_FLAG)
1574       return false;
1575     HasRet = true;
1576   }
1577
1578   return HasRet;
1579 }
1580
1581 EVT
1582 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1583                                             ISD::NodeType ExtendKind) const {
1584   MVT ReturnMVT;
1585   // TODO: Is this also valid on 32-bit?
1586   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1587     ReturnMVT = MVT::i8;
1588   else
1589     ReturnMVT = MVT::i32;
1590
1591   EVT MinVT = getRegisterType(Context, ReturnMVT);
1592   return VT.bitsLT(MinVT) ? MinVT : VT;
1593 }
1594
1595 /// LowerCallResult - Lower the result values of a call into the
1596 /// appropriate copies out of appropriate physical registers.
1597 ///
1598 SDValue
1599 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1600                                    CallingConv::ID CallConv, bool isVarArg,
1601                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1602                                    DebugLoc dl, SelectionDAG &DAG,
1603                                    SmallVectorImpl<SDValue> &InVals) const {
1604
1605   // Assign locations to each value returned by this call.
1606   SmallVector<CCValAssign, 16> RVLocs;
1607   bool Is64Bit = Subtarget->is64Bit();
1608   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1609                  getTargetMachine(), RVLocs, *DAG.getContext());
1610   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1611
1612   // Copy all of the result registers out of their specified physreg.
1613   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1614     CCValAssign &VA = RVLocs[i];
1615     EVT CopyVT = VA.getValVT();
1616
1617     // If this is x86-64, and we disabled SSE, we can't return FP values
1618     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1619         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) {
1620       report_fatal_error("SSE register return with SSE disabled");
1621     }
1622
1623     SDValue Val;
1624
1625     // If this is a call to a function that returns an fp value on the floating
1626     // point stack, we must guarantee the the value is popped from the stack, so
1627     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1628     // if the return value is not used. We use the FpPOP_RETVAL instruction
1629     // instead.
1630     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1631       // If we prefer to use the value in xmm registers, copy it out as f80 and
1632       // use a truncate to move it from fp stack reg to xmm reg.
1633       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1634       SDValue Ops[] = { Chain, InFlag };
1635       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1636                                          MVT::Other, MVT::Glue, Ops, 2), 1);
1637       Val = Chain.getValue(0);
1638
1639       // Round the f80 to the right size, which also moves it to the appropriate
1640       // xmm register.
1641       if (CopyVT != VA.getValVT())
1642         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1643                           // This truncation won't change the value.
1644                           DAG.getIntPtrConstant(1));
1645     } else {
1646       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1647                                  CopyVT, InFlag).getValue(1);
1648       Val = Chain.getValue(0);
1649     }
1650     InFlag = Chain.getValue(2);
1651     InVals.push_back(Val);
1652   }
1653
1654   return Chain;
1655 }
1656
1657
1658 //===----------------------------------------------------------------------===//
1659 //                C & StdCall & Fast Calling Convention implementation
1660 //===----------------------------------------------------------------------===//
1661 //  StdCall calling convention seems to be standard for many Windows' API
1662 //  routines and around. It differs from C calling convention just a little:
1663 //  callee should clean up the stack, not caller. Symbols should be also
1664 //  decorated in some fancy way :) It doesn't support any vector arguments.
1665 //  For info on fast calling convention see Fast Calling Convention (tail call)
1666 //  implementation LowerX86_32FastCCCallTo.
1667
1668 /// CallIsStructReturn - Determines whether a call uses struct return
1669 /// semantics.
1670 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1671   if (Outs.empty())
1672     return false;
1673
1674   return Outs[0].Flags.isSRet();
1675 }
1676
1677 /// ArgsAreStructReturn - Determines whether a function uses struct
1678 /// return semantics.
1679 static bool
1680 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1681   if (Ins.empty())
1682     return false;
1683
1684   return Ins[0].Flags.isSRet();
1685 }
1686
1687 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1688 /// by "Src" to address "Dst" with size and alignment information specified by
1689 /// the specific parameter attribute. The copy will be passed as a byval
1690 /// function parameter.
1691 static SDValue
1692 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1693                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1694                           DebugLoc dl) {
1695   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1696
1697   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1698                        /*isVolatile*/false, /*AlwaysInline=*/true,
1699                        MachinePointerInfo(), MachinePointerInfo());
1700 }
1701
1702 /// IsTailCallConvention - Return true if the calling convention is one that
1703 /// supports tail call optimization.
1704 static bool IsTailCallConvention(CallingConv::ID CC) {
1705   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1706 }
1707
1708 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1709   if (!CI->isTailCall())
1710     return false;
1711
1712   CallSite CS(CI);
1713   CallingConv::ID CalleeCC = CS.getCallingConv();
1714   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1715     return false;
1716
1717   return true;
1718 }
1719
1720 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1721 /// a tailcall target by changing its ABI.
1722 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1723                                    bool GuaranteedTailCallOpt) {
1724   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1725 }
1726
1727 SDValue
1728 X86TargetLowering::LowerMemArgument(SDValue Chain,
1729                                     CallingConv::ID CallConv,
1730                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1731                                     DebugLoc dl, SelectionDAG &DAG,
1732                                     const CCValAssign &VA,
1733                                     MachineFrameInfo *MFI,
1734                                     unsigned i) const {
1735   // Create the nodes corresponding to a load from this parameter slot.
1736   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1737   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1738                               getTargetMachine().Options.GuaranteedTailCallOpt);
1739   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1740   EVT ValVT;
1741
1742   // If value is passed by pointer we have address passed instead of the value
1743   // itself.
1744   if (VA.getLocInfo() == CCValAssign::Indirect)
1745     ValVT = VA.getLocVT();
1746   else
1747     ValVT = VA.getValVT();
1748
1749   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1750   // changed with more analysis.
1751   // In case of tail call optimization mark all arguments mutable. Since they
1752   // could be overwritten by lowering of arguments in case of a tail call.
1753   if (Flags.isByVal()) {
1754     unsigned Bytes = Flags.getByValSize();
1755     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1756     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1757     return DAG.getFrameIndex(FI, getPointerTy());
1758   } else {
1759     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1760                                     VA.getLocMemOffset(), isImmutable);
1761     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1762     return DAG.getLoad(ValVT, dl, Chain, FIN,
1763                        MachinePointerInfo::getFixedStack(FI),
1764                        false, false, false, 0);
1765   }
1766 }
1767
1768 SDValue
1769 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1770                                         CallingConv::ID CallConv,
1771                                         bool isVarArg,
1772                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1773                                         DebugLoc dl,
1774                                         SelectionDAG &DAG,
1775                                         SmallVectorImpl<SDValue> &InVals)
1776                                           const {
1777   MachineFunction &MF = DAG.getMachineFunction();
1778   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1779
1780   const Function* Fn = MF.getFunction();
1781   if (Fn->hasExternalLinkage() &&
1782       Subtarget->isTargetCygMing() &&
1783       Fn->getName() == "main")
1784     FuncInfo->setForceFramePointer(true);
1785
1786   MachineFrameInfo *MFI = MF.getFrameInfo();
1787   bool Is64Bit = Subtarget->is64Bit();
1788   bool IsWin64 = Subtarget->isTargetWin64();
1789
1790   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1791          "Var args not supported with calling convention fastcc or ghc");
1792
1793   // Assign locations to all of the incoming arguments.
1794   SmallVector<CCValAssign, 16> ArgLocs;
1795   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1796                  ArgLocs, *DAG.getContext());
1797
1798   // Allocate shadow area for Win64
1799   if (IsWin64) {
1800     CCInfo.AllocateStack(32, 8);
1801   }
1802
1803   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1804
1805   unsigned LastVal = ~0U;
1806   SDValue ArgValue;
1807   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1808     CCValAssign &VA = ArgLocs[i];
1809     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1810     // places.
1811     assert(VA.getValNo() != LastVal &&
1812            "Don't support value assigned to multiple locs yet");
1813     (void)LastVal;
1814     LastVal = VA.getValNo();
1815
1816     if (VA.isRegLoc()) {
1817       EVT RegVT = VA.getLocVT();
1818       TargetRegisterClass *RC = NULL;
1819       if (RegVT == MVT::i32)
1820         RC = X86::GR32RegisterClass;
1821       else if (Is64Bit && RegVT == MVT::i64)
1822         RC = X86::GR64RegisterClass;
1823       else if (RegVT == MVT::f32)
1824         RC = X86::FR32RegisterClass;
1825       else if (RegVT == MVT::f64)
1826         RC = X86::FR64RegisterClass;
1827       else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1828         RC = X86::VR256RegisterClass;
1829       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1830         RC = X86::VR128RegisterClass;
1831       else if (RegVT == MVT::x86mmx)
1832         RC = X86::VR64RegisterClass;
1833       else
1834         llvm_unreachable("Unknown argument type!");
1835
1836       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1837       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1838
1839       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1840       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1841       // right size.
1842       if (VA.getLocInfo() == CCValAssign::SExt)
1843         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1844                                DAG.getValueType(VA.getValVT()));
1845       else if (VA.getLocInfo() == CCValAssign::ZExt)
1846         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1847                                DAG.getValueType(VA.getValVT()));
1848       else if (VA.getLocInfo() == CCValAssign::BCvt)
1849         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1850
1851       if (VA.isExtInLoc()) {
1852         // Handle MMX values passed in XMM regs.
1853         if (RegVT.isVector()) {
1854           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1855                                  ArgValue);
1856         } else
1857           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1858       }
1859     } else {
1860       assert(VA.isMemLoc());
1861       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1862     }
1863
1864     // If value is passed via pointer - do a load.
1865     if (VA.getLocInfo() == CCValAssign::Indirect)
1866       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1867                              MachinePointerInfo(), false, false, false, 0);
1868
1869     InVals.push_back(ArgValue);
1870   }
1871
1872   // The x86-64 ABI for returning structs by value requires that we copy
1873   // the sret argument into %rax for the return. Save the argument into
1874   // a virtual register so that we can access it from the return points.
1875   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1876     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1877     unsigned Reg = FuncInfo->getSRetReturnReg();
1878     if (!Reg) {
1879       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1880       FuncInfo->setSRetReturnReg(Reg);
1881     }
1882     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1883     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1884   }
1885
1886   unsigned StackSize = CCInfo.getNextStackOffset();
1887   // Align stack specially for tail calls.
1888   if (FuncIsMadeTailCallSafe(CallConv,
1889                              MF.getTarget().Options.GuaranteedTailCallOpt))
1890     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1891
1892   // If the function takes variable number of arguments, make a frame index for
1893   // the start of the first vararg value... for expansion of llvm.va_start.
1894   if (isVarArg) {
1895     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1896                     CallConv != CallingConv::X86_ThisCall)) {
1897       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1898     }
1899     if (Is64Bit) {
1900       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1901
1902       // FIXME: We should really autogenerate these arrays
1903       static const unsigned GPR64ArgRegsWin64[] = {
1904         X86::RCX, X86::RDX, X86::R8,  X86::R9
1905       };
1906       static const unsigned GPR64ArgRegs64Bit[] = {
1907         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1908       };
1909       static const unsigned XMMArgRegs64Bit[] = {
1910         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1911         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1912       };
1913       const unsigned *GPR64ArgRegs;
1914       unsigned NumXMMRegs = 0;
1915
1916       if (IsWin64) {
1917         // The XMM registers which might contain var arg parameters are shadowed
1918         // in their paired GPR.  So we only need to save the GPR to their home
1919         // slots.
1920         TotalNumIntRegs = 4;
1921         GPR64ArgRegs = GPR64ArgRegsWin64;
1922       } else {
1923         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1924         GPR64ArgRegs = GPR64ArgRegs64Bit;
1925
1926         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1927       }
1928       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1929                                                        TotalNumIntRegs);
1930
1931       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1932       assert(!(NumXMMRegs && !Subtarget->hasXMM()) &&
1933              "SSE register cannot be used when SSE is disabled!");
1934       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
1935                NoImplicitFloatOps) &&
1936              "SSE register cannot be used when SSE is disabled!");
1937       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
1938           !Subtarget->hasXMM())
1939         // Kernel mode asks for SSE to be disabled, so don't push them
1940         // on the stack.
1941         TotalNumXMMRegs = 0;
1942
1943       if (IsWin64) {
1944         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1945         // Get to the caller-allocated home save location.  Add 8 to account
1946         // for the return address.
1947         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1948         FuncInfo->setRegSaveFrameIndex(
1949           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1950         // Fixup to set vararg frame on shadow area (4 x i64).
1951         if (NumIntRegs < 4)
1952           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1953       } else {
1954         // For X86-64, if there are vararg parameters that are passed via
1955         // registers, then we must store them to their spots on the stack so they
1956         // may be loaded by deferencing the result of va_next.
1957         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1958         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1959         FuncInfo->setRegSaveFrameIndex(
1960           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1961                                false));
1962       }
1963
1964       // Store the integer parameter registers.
1965       SmallVector<SDValue, 8> MemOps;
1966       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1967                                         getPointerTy());
1968       unsigned Offset = FuncInfo->getVarArgsGPOffset();
1969       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1970         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1971                                   DAG.getIntPtrConstant(Offset));
1972         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1973                                      X86::GR64RegisterClass);
1974         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1975         SDValue Store =
1976           DAG.getStore(Val.getValue(1), dl, Val, FIN,
1977                        MachinePointerInfo::getFixedStack(
1978                          FuncInfo->getRegSaveFrameIndex(), Offset),
1979                        false, false, 0);
1980         MemOps.push_back(Store);
1981         Offset += 8;
1982       }
1983
1984       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1985         // Now store the XMM (fp + vector) parameter registers.
1986         SmallVector<SDValue, 11> SaveXMMOps;
1987         SaveXMMOps.push_back(Chain);
1988
1989         unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1990         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1991         SaveXMMOps.push_back(ALVal);
1992
1993         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1994                                FuncInfo->getRegSaveFrameIndex()));
1995         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1996                                FuncInfo->getVarArgsFPOffset()));
1997
1998         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1999           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2000                                        X86::VR128RegisterClass);
2001           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2002           SaveXMMOps.push_back(Val);
2003         }
2004         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2005                                      MVT::Other,
2006                                      &SaveXMMOps[0], SaveXMMOps.size()));
2007       }
2008
2009       if (!MemOps.empty())
2010         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2011                             &MemOps[0], MemOps.size());
2012     }
2013   }
2014
2015   // Some CCs need callee pop.
2016   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2017                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2018     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2019   } else {
2020     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2021     // If this is an sret function, the return should pop the hidden pointer.
2022     if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
2023       FuncInfo->setBytesToPopOnReturn(4);
2024   }
2025
2026   if (!Is64Bit) {
2027     // RegSaveFrameIndex is X86-64 only.
2028     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2029     if (CallConv == CallingConv::X86_FastCall ||
2030         CallConv == CallingConv::X86_ThisCall)
2031       // fastcc functions can't have varargs.
2032       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2033   }
2034
2035   FuncInfo->setArgumentStackSize(StackSize);
2036
2037   return Chain;
2038 }
2039
2040 SDValue
2041 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2042                                     SDValue StackPtr, SDValue Arg,
2043                                     DebugLoc dl, SelectionDAG &DAG,
2044                                     const CCValAssign &VA,
2045                                     ISD::ArgFlagsTy Flags) const {
2046   unsigned LocMemOffset = VA.getLocMemOffset();
2047   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2048   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2049   if (Flags.isByVal())
2050     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2051
2052   return DAG.getStore(Chain, dl, Arg, PtrOff,
2053                       MachinePointerInfo::getStack(LocMemOffset),
2054                       false, false, 0);
2055 }
2056
2057 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2058 /// optimization is performed and it is required.
2059 SDValue
2060 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2061                                            SDValue &OutRetAddr, SDValue Chain,
2062                                            bool IsTailCall, bool Is64Bit,
2063                                            int FPDiff, DebugLoc dl) const {
2064   // Adjust the Return address stack slot.
2065   EVT VT = getPointerTy();
2066   OutRetAddr = getReturnAddressFrameIndex(DAG);
2067
2068   // Load the "old" Return address.
2069   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2070                            false, false, false, 0);
2071   return SDValue(OutRetAddr.getNode(), 1);
2072 }
2073
2074 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2075 /// optimization is performed and it is required (FPDiff!=0).
2076 static SDValue
2077 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2078                          SDValue Chain, SDValue RetAddrFrIdx,
2079                          bool Is64Bit, int FPDiff, DebugLoc dl) {
2080   // Store the return address to the appropriate stack slot.
2081   if (!FPDiff) return Chain;
2082   // Calculate the new stack slot for the return address.
2083   int SlotSize = Is64Bit ? 8 : 4;
2084   int NewReturnAddrFI =
2085     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2086   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2087   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
2088   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2089                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2090                        false, false, 0);
2091   return Chain;
2092 }
2093
2094 SDValue
2095 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
2096                              CallingConv::ID CallConv, bool isVarArg,
2097                              bool &isTailCall,
2098                              const SmallVectorImpl<ISD::OutputArg> &Outs,
2099                              const SmallVectorImpl<SDValue> &OutVals,
2100                              const SmallVectorImpl<ISD::InputArg> &Ins,
2101                              DebugLoc dl, SelectionDAG &DAG,
2102                              SmallVectorImpl<SDValue> &InVals) const {
2103   MachineFunction &MF = DAG.getMachineFunction();
2104   bool Is64Bit        = Subtarget->is64Bit();
2105   bool IsWin64        = Subtarget->isTargetWin64();
2106   bool IsStructRet    = CallIsStructReturn(Outs);
2107   bool IsSibcall      = false;
2108
2109   if (isTailCall) {
2110     // Check if it's really possible to do a tail call.
2111     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2112                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
2113                                                    Outs, OutVals, Ins, DAG);
2114
2115     // Sibcalls are automatically detected tailcalls which do not require
2116     // ABI changes.
2117     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2118       IsSibcall = true;
2119
2120     if (isTailCall)
2121       ++NumTailCalls;
2122   }
2123
2124   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2125          "Var args not supported with calling convention fastcc or ghc");
2126
2127   // Analyze operands of the call, assigning locations to each operand.
2128   SmallVector<CCValAssign, 16> ArgLocs;
2129   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2130                  ArgLocs, *DAG.getContext());
2131
2132   // Allocate shadow area for Win64
2133   if (IsWin64) {
2134     CCInfo.AllocateStack(32, 8);
2135   }
2136
2137   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2138
2139   // Get a count of how many bytes are to be pushed on the stack.
2140   unsigned NumBytes = CCInfo.getNextStackOffset();
2141   if (IsSibcall)
2142     // This is a sibcall. The memory operands are available in caller's
2143     // own caller's stack.
2144     NumBytes = 0;
2145   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2146            IsTailCallConvention(CallConv))
2147     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2148
2149   int FPDiff = 0;
2150   if (isTailCall && !IsSibcall) {
2151     // Lower arguments at fp - stackoffset + fpdiff.
2152     unsigned NumBytesCallerPushed =
2153       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2154     FPDiff = NumBytesCallerPushed - NumBytes;
2155
2156     // Set the delta of movement of the returnaddr stackslot.
2157     // But only set if delta is greater than previous delta.
2158     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2159       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2160   }
2161
2162   if (!IsSibcall)
2163     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2164
2165   SDValue RetAddrFrIdx;
2166   // Load return address for tail calls.
2167   if (isTailCall && FPDiff)
2168     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2169                                     Is64Bit, FPDiff, dl);
2170
2171   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2172   SmallVector<SDValue, 8> MemOpChains;
2173   SDValue StackPtr;
2174
2175   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2176   // of tail call optimization arguments are handle later.
2177   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2178     CCValAssign &VA = ArgLocs[i];
2179     EVT RegVT = VA.getLocVT();
2180     SDValue Arg = OutVals[i];
2181     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2182     bool isByVal = Flags.isByVal();
2183
2184     // Promote the value if needed.
2185     switch (VA.getLocInfo()) {
2186     default: llvm_unreachable("Unknown loc info!");
2187     case CCValAssign::Full: break;
2188     case CCValAssign::SExt:
2189       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2190       break;
2191     case CCValAssign::ZExt:
2192       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2193       break;
2194     case CCValAssign::AExt:
2195       if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2196         // Special case: passing MMX values in XMM registers.
2197         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2198         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2199         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2200       } else
2201         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2202       break;
2203     case CCValAssign::BCvt:
2204       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2205       break;
2206     case CCValAssign::Indirect: {
2207       // Store the argument.
2208       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2209       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2210       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2211                            MachinePointerInfo::getFixedStack(FI),
2212                            false, false, 0);
2213       Arg = SpillSlot;
2214       break;
2215     }
2216     }
2217
2218     if (VA.isRegLoc()) {
2219       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2220       if (isVarArg && IsWin64) {
2221         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2222         // shadow reg if callee is a varargs function.
2223         unsigned ShadowReg = 0;
2224         switch (VA.getLocReg()) {
2225         case X86::XMM0: ShadowReg = X86::RCX; break;
2226         case X86::XMM1: ShadowReg = X86::RDX; break;
2227         case X86::XMM2: ShadowReg = X86::R8; break;
2228         case X86::XMM3: ShadowReg = X86::R9; break;
2229         }
2230         if (ShadowReg)
2231           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2232       }
2233     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2234       assert(VA.isMemLoc());
2235       if (StackPtr.getNode() == 0)
2236         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2237       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2238                                              dl, DAG, VA, Flags));
2239     }
2240   }
2241
2242   if (!MemOpChains.empty())
2243     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2244                         &MemOpChains[0], MemOpChains.size());
2245
2246   // Build a sequence of copy-to-reg nodes chained together with token chain
2247   // and flag operands which copy the outgoing args into registers.
2248   SDValue InFlag;
2249   // Tail call byval lowering might overwrite argument registers so in case of
2250   // tail call optimization the copies to registers are lowered later.
2251   if (!isTailCall)
2252     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2253       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2254                                RegsToPass[i].second, InFlag);
2255       InFlag = Chain.getValue(1);
2256     }
2257
2258   if (Subtarget->isPICStyleGOT()) {
2259     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2260     // GOT pointer.
2261     if (!isTailCall) {
2262       Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2263                                DAG.getNode(X86ISD::GlobalBaseReg,
2264                                            DebugLoc(), getPointerTy()),
2265                                InFlag);
2266       InFlag = Chain.getValue(1);
2267     } else {
2268       // If we are tail calling and generating PIC/GOT style code load the
2269       // address of the callee into ECX. The value in ecx is used as target of
2270       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2271       // for tail calls on PIC/GOT architectures. Normally we would just put the
2272       // address of GOT into ebx and then call target@PLT. But for tail calls
2273       // ebx would be restored (since ebx is callee saved) before jumping to the
2274       // target@PLT.
2275
2276       // Note: The actual moving to ECX is done further down.
2277       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2278       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2279           !G->getGlobal()->hasProtectedVisibility())
2280         Callee = LowerGlobalAddress(Callee, DAG);
2281       else if (isa<ExternalSymbolSDNode>(Callee))
2282         Callee = LowerExternalSymbol(Callee, DAG);
2283     }
2284   }
2285
2286   if (Is64Bit && isVarArg && !IsWin64) {
2287     // From AMD64 ABI document:
2288     // For calls that may call functions that use varargs or stdargs
2289     // (prototype-less calls or calls to functions containing ellipsis (...) in
2290     // the declaration) %al is used as hidden argument to specify the number
2291     // of SSE registers used. The contents of %al do not need to match exactly
2292     // the number of registers, but must be an ubound on the number of SSE
2293     // registers used and is in the range 0 - 8 inclusive.
2294
2295     // Count the number of XMM registers allocated.
2296     static const unsigned XMMArgRegs[] = {
2297       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2298       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2299     };
2300     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2301     assert((Subtarget->hasXMM() || !NumXMMRegs)
2302            && "SSE registers cannot be used when SSE is disabled");
2303
2304     Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2305                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2306     InFlag = Chain.getValue(1);
2307   }
2308
2309
2310   // For tail calls lower the arguments to the 'real' stack slot.
2311   if (isTailCall) {
2312     // Force all the incoming stack arguments to be loaded from the stack
2313     // before any new outgoing arguments are stored to the stack, because the
2314     // outgoing stack slots may alias the incoming argument stack slots, and
2315     // the alias isn't otherwise explicit. This is slightly more conservative
2316     // than necessary, because it means that each store effectively depends
2317     // on every argument instead of just those arguments it would clobber.
2318     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2319
2320     SmallVector<SDValue, 8> MemOpChains2;
2321     SDValue FIN;
2322     int FI = 0;
2323     // Do not flag preceding copytoreg stuff together with the following stuff.
2324     InFlag = SDValue();
2325     if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2326       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2327         CCValAssign &VA = ArgLocs[i];
2328         if (VA.isRegLoc())
2329           continue;
2330         assert(VA.isMemLoc());
2331         SDValue Arg = OutVals[i];
2332         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2333         // Create frame index.
2334         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2335         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2336         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2337         FIN = DAG.getFrameIndex(FI, getPointerTy());
2338
2339         if (Flags.isByVal()) {
2340           // Copy relative to framepointer.
2341           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2342           if (StackPtr.getNode() == 0)
2343             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2344                                           getPointerTy());
2345           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2346
2347           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2348                                                            ArgChain,
2349                                                            Flags, DAG, dl));
2350         } else {
2351           // Store relative to framepointer.
2352           MemOpChains2.push_back(
2353             DAG.getStore(ArgChain, dl, Arg, FIN,
2354                          MachinePointerInfo::getFixedStack(FI),
2355                          false, false, 0));
2356         }
2357       }
2358     }
2359
2360     if (!MemOpChains2.empty())
2361       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2362                           &MemOpChains2[0], MemOpChains2.size());
2363
2364     // Copy arguments to their registers.
2365     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2366       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2367                                RegsToPass[i].second, InFlag);
2368       InFlag = Chain.getValue(1);
2369     }
2370     InFlag =SDValue();
2371
2372     // Store the return address to the appropriate stack slot.
2373     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2374                                      FPDiff, dl);
2375   }
2376
2377   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2378     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2379     // In the 64-bit large code model, we have to make all calls
2380     // through a register, since the call instruction's 32-bit
2381     // pc-relative offset may not be large enough to hold the whole
2382     // address.
2383   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2384     // If the callee is a GlobalAddress node (quite common, every direct call
2385     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2386     // it.
2387
2388     // We should use extra load for direct calls to dllimported functions in
2389     // non-JIT mode.
2390     const GlobalValue *GV = G->getGlobal();
2391     if (!GV->hasDLLImportLinkage()) {
2392       unsigned char OpFlags = 0;
2393       bool ExtraLoad = false;
2394       unsigned WrapperKind = ISD::DELETED_NODE;
2395
2396       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2397       // external symbols most go through the PLT in PIC mode.  If the symbol
2398       // has hidden or protected visibility, or if it is static or local, then
2399       // we don't need to use the PLT - we can directly call it.
2400       if (Subtarget->isTargetELF() &&
2401           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2402           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2403         OpFlags = X86II::MO_PLT;
2404       } else if (Subtarget->isPICStyleStubAny() &&
2405                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2406                  (!Subtarget->getTargetTriple().isMacOSX() ||
2407                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2408         // PC-relative references to external symbols should go through $stub,
2409         // unless we're building with the leopard linker or later, which
2410         // automatically synthesizes these stubs.
2411         OpFlags = X86II::MO_DARWIN_STUB;
2412       } else if (Subtarget->isPICStyleRIPRel() &&
2413                  isa<Function>(GV) &&
2414                  cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2415         // If the function is marked as non-lazy, generate an indirect call
2416         // which loads from the GOT directly. This avoids runtime overhead
2417         // at the cost of eager binding (and one extra byte of encoding).
2418         OpFlags = X86II::MO_GOTPCREL;
2419         WrapperKind = X86ISD::WrapperRIP;
2420         ExtraLoad = true;
2421       }
2422
2423       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2424                                           G->getOffset(), OpFlags);
2425
2426       // Add a wrapper if needed.
2427       if (WrapperKind != ISD::DELETED_NODE)
2428         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2429       // Add extra indirection if needed.
2430       if (ExtraLoad)
2431         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2432                              MachinePointerInfo::getGOT(),
2433                              false, false, false, 0);
2434     }
2435   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2436     unsigned char OpFlags = 0;
2437
2438     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2439     // external symbols should go through the PLT.
2440     if (Subtarget->isTargetELF() &&
2441         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2442       OpFlags = X86II::MO_PLT;
2443     } else if (Subtarget->isPICStyleStubAny() &&
2444                (!Subtarget->getTargetTriple().isMacOSX() ||
2445                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2446       // PC-relative references to external symbols should go through $stub,
2447       // unless we're building with the leopard linker or later, which
2448       // automatically synthesizes these stubs.
2449       OpFlags = X86II::MO_DARWIN_STUB;
2450     }
2451
2452     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2453                                          OpFlags);
2454   }
2455
2456   // Returns a chain & a flag for retval copy to use.
2457   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2458   SmallVector<SDValue, 8> Ops;
2459
2460   if (!IsSibcall && isTailCall) {
2461     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2462                            DAG.getIntPtrConstant(0, true), InFlag);
2463     InFlag = Chain.getValue(1);
2464   }
2465
2466   Ops.push_back(Chain);
2467   Ops.push_back(Callee);
2468
2469   if (isTailCall)
2470     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2471
2472   // Add argument registers to the end of the list so that they are known live
2473   // into the call.
2474   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2475     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2476                                   RegsToPass[i].second.getValueType()));
2477
2478   // Add an implicit use GOT pointer in EBX.
2479   if (!isTailCall && Subtarget->isPICStyleGOT())
2480     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2481
2482   // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2483   if (Is64Bit && isVarArg && !IsWin64)
2484     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2485
2486   if (InFlag.getNode())
2487     Ops.push_back(InFlag);
2488
2489   if (isTailCall) {
2490     // We used to do:
2491     //// If this is the first return lowered for this function, add the regs
2492     //// to the liveout set for the function.
2493     // This isn't right, although it's probably harmless on x86; liveouts
2494     // should be computed from returns not tail calls.  Consider a void
2495     // function making a tail call to a function returning int.
2496     return DAG.getNode(X86ISD::TC_RETURN, dl,
2497                        NodeTys, &Ops[0], Ops.size());
2498   }
2499
2500   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2501   InFlag = Chain.getValue(1);
2502
2503   // Create the CALLSEQ_END node.
2504   unsigned NumBytesForCalleeToPush;
2505   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2506                        getTargetMachine().Options.GuaranteedTailCallOpt))
2507     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2508   else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2509     // If this is a call to a struct-return function, the callee
2510     // pops the hidden struct pointer, so we have to push it back.
2511     // This is common for Darwin/X86, Linux & Mingw32 targets.
2512     NumBytesForCalleeToPush = 4;
2513   else
2514     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2515
2516   // Returns a flag for retval copy to use.
2517   if (!IsSibcall) {
2518     Chain = DAG.getCALLSEQ_END(Chain,
2519                                DAG.getIntPtrConstant(NumBytes, true),
2520                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2521                                                      true),
2522                                InFlag);
2523     InFlag = Chain.getValue(1);
2524   }
2525
2526   // Handle result values, copying them out of physregs into vregs that we
2527   // return.
2528   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2529                          Ins, dl, DAG, InVals);
2530 }
2531
2532
2533 //===----------------------------------------------------------------------===//
2534 //                Fast Calling Convention (tail call) implementation
2535 //===----------------------------------------------------------------------===//
2536
2537 //  Like std call, callee cleans arguments, convention except that ECX is
2538 //  reserved for storing the tail called function address. Only 2 registers are
2539 //  free for argument passing (inreg). Tail call optimization is performed
2540 //  provided:
2541 //                * tailcallopt is enabled
2542 //                * caller/callee are fastcc
2543 //  On X86_64 architecture with GOT-style position independent code only local
2544 //  (within module) calls are supported at the moment.
2545 //  To keep the stack aligned according to platform abi the function
2546 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2547 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2548 //  If a tail called function callee has more arguments than the caller the
2549 //  caller needs to make sure that there is room to move the RETADDR to. This is
2550 //  achieved by reserving an area the size of the argument delta right after the
2551 //  original REtADDR, but before the saved framepointer or the spilled registers
2552 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2553 //  stack layout:
2554 //    arg1
2555 //    arg2
2556 //    RETADDR
2557 //    [ new RETADDR
2558 //      move area ]
2559 //    (possible EBP)
2560 //    ESI
2561 //    EDI
2562 //    local1 ..
2563
2564 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2565 /// for a 16 byte align requirement.
2566 unsigned
2567 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2568                                                SelectionDAG& DAG) const {
2569   MachineFunction &MF = DAG.getMachineFunction();
2570   const TargetMachine &TM = MF.getTarget();
2571   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2572   unsigned StackAlignment = TFI.getStackAlignment();
2573   uint64_t AlignMask = StackAlignment - 1;
2574   int64_t Offset = StackSize;
2575   uint64_t SlotSize = TD->getPointerSize();
2576   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2577     // Number smaller than 12 so just add the difference.
2578     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2579   } else {
2580     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2581     Offset = ((~AlignMask) & Offset) + StackAlignment +
2582       (StackAlignment-SlotSize);
2583   }
2584   return Offset;
2585 }
2586
2587 /// MatchingStackOffset - Return true if the given stack call argument is
2588 /// already available in the same position (relatively) of the caller's
2589 /// incoming argument stack.
2590 static
2591 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2592                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2593                          const X86InstrInfo *TII) {
2594   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2595   int FI = INT_MAX;
2596   if (Arg.getOpcode() == ISD::CopyFromReg) {
2597     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2598     if (!TargetRegisterInfo::isVirtualRegister(VR))
2599       return false;
2600     MachineInstr *Def = MRI->getVRegDef(VR);
2601     if (!Def)
2602       return false;
2603     if (!Flags.isByVal()) {
2604       if (!TII->isLoadFromStackSlot(Def, FI))
2605         return false;
2606     } else {
2607       unsigned Opcode = Def->getOpcode();
2608       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2609           Def->getOperand(1).isFI()) {
2610         FI = Def->getOperand(1).getIndex();
2611         Bytes = Flags.getByValSize();
2612       } else
2613         return false;
2614     }
2615   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2616     if (Flags.isByVal())
2617       // ByVal argument is passed in as a pointer but it's now being
2618       // dereferenced. e.g.
2619       // define @foo(%struct.X* %A) {
2620       //   tail call @bar(%struct.X* byval %A)
2621       // }
2622       return false;
2623     SDValue Ptr = Ld->getBasePtr();
2624     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2625     if (!FINode)
2626       return false;
2627     FI = FINode->getIndex();
2628   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2629     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2630     FI = FINode->getIndex();
2631     Bytes = Flags.getByValSize();
2632   } else
2633     return false;
2634
2635   assert(FI != INT_MAX);
2636   if (!MFI->isFixedObjectIndex(FI))
2637     return false;
2638   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2639 }
2640
2641 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2642 /// for tail call optimization. Targets which want to do tail call
2643 /// optimization should implement this function.
2644 bool
2645 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2646                                                      CallingConv::ID CalleeCC,
2647                                                      bool isVarArg,
2648                                                      bool isCalleeStructRet,
2649                                                      bool isCallerStructRet,
2650                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2651                                     const SmallVectorImpl<SDValue> &OutVals,
2652                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2653                                                      SelectionDAG& DAG) const {
2654   if (!IsTailCallConvention(CalleeCC) &&
2655       CalleeCC != CallingConv::C)
2656     return false;
2657
2658   // If -tailcallopt is specified, make fastcc functions tail-callable.
2659   const MachineFunction &MF = DAG.getMachineFunction();
2660   const Function *CallerF = DAG.getMachineFunction().getFunction();
2661   CallingConv::ID CallerCC = CallerF->getCallingConv();
2662   bool CCMatch = CallerCC == CalleeCC;
2663
2664   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2665     if (IsTailCallConvention(CalleeCC) && CCMatch)
2666       return true;
2667     return false;
2668   }
2669
2670   // Look for obvious safe cases to perform tail call optimization that do not
2671   // require ABI changes. This is what gcc calls sibcall.
2672
2673   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2674   // emit a special epilogue.
2675   if (RegInfo->needsStackRealignment(MF))
2676     return false;
2677
2678   // Also avoid sibcall optimization if either caller or callee uses struct
2679   // return semantics.
2680   if (isCalleeStructRet || isCallerStructRet)
2681     return false;
2682
2683   // An stdcall caller is expected to clean up its arguments; the callee
2684   // isn't going to do that.
2685   if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2686     return false;
2687
2688   // Do not sibcall optimize vararg calls unless all arguments are passed via
2689   // registers.
2690   if (isVarArg && !Outs.empty()) {
2691
2692     // Optimizing for varargs on Win64 is unlikely to be safe without
2693     // additional testing.
2694     if (Subtarget->isTargetWin64())
2695       return false;
2696
2697     SmallVector<CCValAssign, 16> ArgLocs;
2698     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2699                    getTargetMachine(), ArgLocs, *DAG.getContext());
2700
2701     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2702     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2703       if (!ArgLocs[i].isRegLoc())
2704         return false;
2705   }
2706
2707   // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2708   // Therefore if it's not used by the call it is not safe to optimize this into
2709   // a sibcall.
2710   bool Unused = false;
2711   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2712     if (!Ins[i].Used) {
2713       Unused = true;
2714       break;
2715     }
2716   }
2717   if (Unused) {
2718     SmallVector<CCValAssign, 16> RVLocs;
2719     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2720                    getTargetMachine(), RVLocs, *DAG.getContext());
2721     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2722     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2723       CCValAssign &VA = RVLocs[i];
2724       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2725         return false;
2726     }
2727   }
2728
2729   // If the calling conventions do not match, then we'd better make sure the
2730   // results are returned in the same way as what the caller expects.
2731   if (!CCMatch) {
2732     SmallVector<CCValAssign, 16> RVLocs1;
2733     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2734                     getTargetMachine(), RVLocs1, *DAG.getContext());
2735     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2736
2737     SmallVector<CCValAssign, 16> RVLocs2;
2738     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2739                     getTargetMachine(), RVLocs2, *DAG.getContext());
2740     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2741
2742     if (RVLocs1.size() != RVLocs2.size())
2743       return false;
2744     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2745       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2746         return false;
2747       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2748         return false;
2749       if (RVLocs1[i].isRegLoc()) {
2750         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2751           return false;
2752       } else {
2753         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2754           return false;
2755       }
2756     }
2757   }
2758
2759   // If the callee takes no arguments then go on to check the results of the
2760   // call.
2761   if (!Outs.empty()) {
2762     // Check if stack adjustment is needed. For now, do not do this if any
2763     // argument is passed on the stack.
2764     SmallVector<CCValAssign, 16> ArgLocs;
2765     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2766                    getTargetMachine(), ArgLocs, *DAG.getContext());
2767
2768     // Allocate shadow area for Win64
2769     if (Subtarget->isTargetWin64()) {
2770       CCInfo.AllocateStack(32, 8);
2771     }
2772
2773     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2774     if (CCInfo.getNextStackOffset()) {
2775       MachineFunction &MF = DAG.getMachineFunction();
2776       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2777         return false;
2778
2779       // Check if the arguments are already laid out in the right way as
2780       // the caller's fixed stack objects.
2781       MachineFrameInfo *MFI = MF.getFrameInfo();
2782       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2783       const X86InstrInfo *TII =
2784         ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2785       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2786         CCValAssign &VA = ArgLocs[i];
2787         SDValue Arg = OutVals[i];
2788         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2789         if (VA.getLocInfo() == CCValAssign::Indirect)
2790           return false;
2791         if (!VA.isRegLoc()) {
2792           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2793                                    MFI, MRI, TII))
2794             return false;
2795         }
2796       }
2797     }
2798
2799     // If the tailcall address may be in a register, then make sure it's
2800     // possible to register allocate for it. In 32-bit, the call address can
2801     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2802     // callee-saved registers are restored. These happen to be the same
2803     // registers used to pass 'inreg' arguments so watch out for those.
2804     if (!Subtarget->is64Bit() &&
2805         !isa<GlobalAddressSDNode>(Callee) &&
2806         !isa<ExternalSymbolSDNode>(Callee)) {
2807       unsigned NumInRegs = 0;
2808       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2809         CCValAssign &VA = ArgLocs[i];
2810         if (!VA.isRegLoc())
2811           continue;
2812         unsigned Reg = VA.getLocReg();
2813         switch (Reg) {
2814         default: break;
2815         case X86::EAX: case X86::EDX: case X86::ECX:
2816           if (++NumInRegs == 3)
2817             return false;
2818           break;
2819         }
2820       }
2821     }
2822   }
2823
2824   return true;
2825 }
2826
2827 FastISel *
2828 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2829   return X86::createFastISel(funcInfo);
2830 }
2831
2832
2833 //===----------------------------------------------------------------------===//
2834 //                           Other Lowering Hooks
2835 //===----------------------------------------------------------------------===//
2836
2837 static bool MayFoldLoad(SDValue Op) {
2838   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2839 }
2840
2841 static bool MayFoldIntoStore(SDValue Op) {
2842   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2843 }
2844
2845 static bool isTargetShuffle(unsigned Opcode) {
2846   switch(Opcode) {
2847   default: return false;
2848   case X86ISD::PSHUFD:
2849   case X86ISD::PSHUFHW:
2850   case X86ISD::PSHUFLW:
2851   case X86ISD::SHUFPD:
2852   case X86ISD::PALIGN:
2853   case X86ISD::SHUFPS:
2854   case X86ISD::MOVLHPS:
2855   case X86ISD::MOVLHPD:
2856   case X86ISD::MOVHLPS:
2857   case X86ISD::MOVLPS:
2858   case X86ISD::MOVLPD:
2859   case X86ISD::MOVSHDUP:
2860   case X86ISD::MOVSLDUP:
2861   case X86ISD::MOVDDUP:
2862   case X86ISD::MOVSS:
2863   case X86ISD::MOVSD:
2864   case X86ISD::UNPCKL:
2865   case X86ISD::UNPCKH:
2866   case X86ISD::VPERMILP:
2867   case X86ISD::VPERM2X128:
2868     return true;
2869   }
2870   return false;
2871 }
2872
2873 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2874                                                SDValue V1, SelectionDAG &DAG) {
2875   switch(Opc) {
2876   default: llvm_unreachable("Unknown x86 shuffle node");
2877   case X86ISD::MOVSHDUP:
2878   case X86ISD::MOVSLDUP:
2879   case X86ISD::MOVDDUP:
2880     return DAG.getNode(Opc, dl, VT, V1);
2881   }
2882
2883   return SDValue();
2884 }
2885
2886 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2887                           SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2888   switch(Opc) {
2889   default: llvm_unreachable("Unknown x86 shuffle node");
2890   case X86ISD::PSHUFD:
2891   case X86ISD::PSHUFHW:
2892   case X86ISD::PSHUFLW:
2893   case X86ISD::VPERMILP:
2894     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2895   }
2896
2897   return SDValue();
2898 }
2899
2900 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2901                SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2902   switch(Opc) {
2903   default: llvm_unreachable("Unknown x86 shuffle node");
2904   case X86ISD::PALIGN:
2905   case X86ISD::SHUFPD:
2906   case X86ISD::SHUFPS:
2907   case X86ISD::VPERM2X128:
2908     return DAG.getNode(Opc, dl, VT, V1, V2,
2909                        DAG.getConstant(TargetMask, MVT::i8));
2910   }
2911   return SDValue();
2912 }
2913
2914 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2915                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
2916   switch(Opc) {
2917   default: llvm_unreachable("Unknown x86 shuffle node");
2918   case X86ISD::MOVLHPS:
2919   case X86ISD::MOVLHPD:
2920   case X86ISD::MOVHLPS:
2921   case X86ISD::MOVLPS:
2922   case X86ISD::MOVLPD:
2923   case X86ISD::MOVSS:
2924   case X86ISD::MOVSD:
2925   case X86ISD::UNPCKL:
2926   case X86ISD::UNPCKH:
2927     return DAG.getNode(Opc, dl, VT, V1, V2);
2928   }
2929   return SDValue();
2930 }
2931
2932 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2933   MachineFunction &MF = DAG.getMachineFunction();
2934   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2935   int ReturnAddrIndex = FuncInfo->getRAIndex();
2936
2937   if (ReturnAddrIndex == 0) {
2938     // Set up a frame object for the return address.
2939     uint64_t SlotSize = TD->getPointerSize();
2940     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2941                                                            false);
2942     FuncInfo->setRAIndex(ReturnAddrIndex);
2943   }
2944
2945   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2946 }
2947
2948
2949 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2950                                        bool hasSymbolicDisplacement) {
2951   // Offset should fit into 32 bit immediate field.
2952   if (!isInt<32>(Offset))
2953     return false;
2954
2955   // If we don't have a symbolic displacement - we don't have any extra
2956   // restrictions.
2957   if (!hasSymbolicDisplacement)
2958     return true;
2959
2960   // FIXME: Some tweaks might be needed for medium code model.
2961   if (M != CodeModel::Small && M != CodeModel::Kernel)
2962     return false;
2963
2964   // For small code model we assume that latest object is 16MB before end of 31
2965   // bits boundary. We may also accept pretty large negative constants knowing
2966   // that all objects are in the positive half of address space.
2967   if (M == CodeModel::Small && Offset < 16*1024*1024)
2968     return true;
2969
2970   // For kernel code model we know that all object resist in the negative half
2971   // of 32bits address space. We may not accept negative offsets, since they may
2972   // be just off and we may accept pretty large positive ones.
2973   if (M == CodeModel::Kernel && Offset > 0)
2974     return true;
2975
2976   return false;
2977 }
2978
2979 /// isCalleePop - Determines whether the callee is required to pop its
2980 /// own arguments. Callee pop is necessary to support tail calls.
2981 bool X86::isCalleePop(CallingConv::ID CallingConv,
2982                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
2983   if (IsVarArg)
2984     return false;
2985
2986   switch (CallingConv) {
2987   default:
2988     return false;
2989   case CallingConv::X86_StdCall:
2990     return !is64Bit;
2991   case CallingConv::X86_FastCall:
2992     return !is64Bit;
2993   case CallingConv::X86_ThisCall:
2994     return !is64Bit;
2995   case CallingConv::Fast:
2996     return TailCallOpt;
2997   case CallingConv::GHC:
2998     return TailCallOpt;
2999   }
3000 }
3001
3002 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3003 /// specific condition code, returning the condition code and the LHS/RHS of the
3004 /// comparison to make.
3005 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3006                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3007   if (!isFP) {
3008     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3009       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3010         // X > -1   -> X == 0, jump !sign.
3011         RHS = DAG.getConstant(0, RHS.getValueType());
3012         return X86::COND_NS;
3013       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3014         // X < 0   -> X == 0, jump on sign.
3015         return X86::COND_S;
3016       } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3017         // X < 1   -> X <= 0
3018         RHS = DAG.getConstant(0, RHS.getValueType());
3019         return X86::COND_LE;
3020       }
3021     }
3022
3023     switch (SetCCOpcode) {
3024     default: llvm_unreachable("Invalid integer condition!");
3025     case ISD::SETEQ:  return X86::COND_E;
3026     case ISD::SETGT:  return X86::COND_G;
3027     case ISD::SETGE:  return X86::COND_GE;
3028     case ISD::SETLT:  return X86::COND_L;
3029     case ISD::SETLE:  return X86::COND_LE;
3030     case ISD::SETNE:  return X86::COND_NE;
3031     case ISD::SETULT: return X86::COND_B;
3032     case ISD::SETUGT: return X86::COND_A;
3033     case ISD::SETULE: return X86::COND_BE;
3034     case ISD::SETUGE: return X86::COND_AE;
3035     }
3036   }
3037
3038   // First determine if it is required or is profitable to flip the operands.
3039
3040   // If LHS is a foldable load, but RHS is not, flip the condition.
3041   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3042       !ISD::isNON_EXTLoad(RHS.getNode())) {
3043     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3044     std::swap(LHS, RHS);
3045   }
3046
3047   switch (SetCCOpcode) {
3048   default: break;
3049   case ISD::SETOLT:
3050   case ISD::SETOLE:
3051   case ISD::SETUGT:
3052   case ISD::SETUGE:
3053     std::swap(LHS, RHS);
3054     break;
3055   }
3056
3057   // On a floating point condition, the flags are set as follows:
3058   // ZF  PF  CF   op
3059   //  0 | 0 | 0 | X > Y
3060   //  0 | 0 | 1 | X < Y
3061   //  1 | 0 | 0 | X == Y
3062   //  1 | 1 | 1 | unordered
3063   switch (SetCCOpcode) {
3064   default: llvm_unreachable("Condcode should be pre-legalized away");
3065   case ISD::SETUEQ:
3066   case ISD::SETEQ:   return X86::COND_E;
3067   case ISD::SETOLT:              // flipped
3068   case ISD::SETOGT:
3069   case ISD::SETGT:   return X86::COND_A;
3070   case ISD::SETOLE:              // flipped
3071   case ISD::SETOGE:
3072   case ISD::SETGE:   return X86::COND_AE;
3073   case ISD::SETUGT:              // flipped
3074   case ISD::SETULT:
3075   case ISD::SETLT:   return X86::COND_B;
3076   case ISD::SETUGE:              // flipped
3077   case ISD::SETULE:
3078   case ISD::SETLE:   return X86::COND_BE;
3079   case ISD::SETONE:
3080   case ISD::SETNE:   return X86::COND_NE;
3081   case ISD::SETUO:   return X86::COND_P;
3082   case ISD::SETO:    return X86::COND_NP;
3083   case ISD::SETOEQ:
3084   case ISD::SETUNE:  return X86::COND_INVALID;
3085   }
3086 }
3087
3088 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3089 /// code. Current x86 isa includes the following FP cmov instructions:
3090 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3091 static bool hasFPCMov(unsigned X86CC) {
3092   switch (X86CC) {
3093   default:
3094     return false;
3095   case X86::COND_B:
3096   case X86::COND_BE:
3097   case X86::COND_E:
3098   case X86::COND_P:
3099   case X86::COND_A:
3100   case X86::COND_AE:
3101   case X86::COND_NE:
3102   case X86::COND_NP:
3103     return true;
3104   }
3105 }
3106
3107 /// isFPImmLegal - Returns true if the target can instruction select the
3108 /// specified FP immediate natively. If false, the legalizer will
3109 /// materialize the FP immediate as a load from a constant pool.
3110 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3111   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3112     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3113       return true;
3114   }
3115   return false;
3116 }
3117
3118 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3119 /// the specified range (L, H].
3120 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3121   return (Val < 0) || (Val >= Low && Val < Hi);
3122 }
3123
3124 /// isUndefOrInRange - Return true if every element in Mask, begining
3125 /// from position Pos and ending in Pos+Size, falls within the specified
3126 /// range (L, L+Pos]. or is undef.
3127 static bool isUndefOrInRange(const SmallVectorImpl<int> &Mask,
3128                              int Pos, int Size, int Low, int Hi) {
3129   for (int i = Pos, e = Pos+Size; i != e; ++i)
3130     if (!isUndefOrInRange(Mask[i], Low, Hi))
3131       return false;
3132   return true;
3133 }
3134
3135 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3136 /// specified value.
3137 static bool isUndefOrEqual(int Val, int CmpVal) {
3138   if (Val < 0 || Val == CmpVal)
3139     return true;
3140   return false;
3141 }
3142
3143 /// isSequentialOrUndefInRange - Return true if every element in Mask, begining
3144 /// from position Pos and ending in Pos+Size, falls within the specified
3145 /// sequential range (L, L+Pos]. or is undef.
3146 static bool isSequentialOrUndefInRange(const SmallVectorImpl<int> &Mask,
3147                                        int Pos, int Size, int Low) {
3148   for (int i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3149     if (!isUndefOrEqual(Mask[i], Low))
3150       return false;
3151   return true;
3152 }
3153
3154 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3155 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3156 /// the second operand.
3157 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3158   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3159     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3160   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3161     return (Mask[0] < 2 && Mask[1] < 2);
3162   return false;
3163 }
3164
3165 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
3166   SmallVector<int, 8> M;
3167   N->getMask(M);
3168   return ::isPSHUFDMask(M, N->getValueType(0));
3169 }
3170
3171 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3172 /// is suitable for input to PSHUFHW.
3173 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3174   if (VT != MVT::v8i16)
3175     return false;
3176
3177   // Lower quadword copied in order or undef.
3178   for (int i = 0; i != 4; ++i)
3179     if (Mask[i] >= 0 && Mask[i] != i)
3180       return false;
3181
3182   // Upper quadword shuffled.
3183   for (int i = 4; i != 8; ++i)
3184     if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
3185       return false;
3186
3187   return true;
3188 }
3189
3190 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
3191   SmallVector<int, 8> M;
3192   N->getMask(M);
3193   return ::isPSHUFHWMask(M, N->getValueType(0));
3194 }
3195
3196 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3197 /// is suitable for input to PSHUFLW.
3198 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3199   if (VT != MVT::v8i16)
3200     return false;
3201
3202   // Upper quadword copied in order.
3203   for (int i = 4; i != 8; ++i)
3204     if (Mask[i] >= 0 && Mask[i] != i)
3205       return false;
3206
3207   // Lower quadword shuffled.
3208   for (int i = 0; i != 4; ++i)
3209     if (Mask[i] >= 4)
3210       return false;
3211
3212   return true;
3213 }
3214
3215 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
3216   SmallVector<int, 8> M;
3217   N->getMask(M);
3218   return ::isPSHUFLWMask(M, N->getValueType(0));
3219 }
3220
3221 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3222 /// is suitable for input to PALIGNR.
3223 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
3224                           bool hasSSSE3OrAVX) {
3225   int i, e = VT.getVectorNumElements();
3226   if (VT.getSizeInBits() != 128)
3227     return false;
3228
3229   // Do not handle v2i64 / v2f64 shuffles with palignr.
3230   if (e < 4 || !hasSSSE3OrAVX)
3231     return false;
3232
3233   for (i = 0; i != e; ++i)
3234     if (Mask[i] >= 0)
3235       break;
3236
3237   // All undef, not a palignr.
3238   if (i == e)
3239     return false;
3240
3241   // Make sure we're shifting in the right direction.
3242   if (Mask[i] <= i)
3243     return false;
3244
3245   int s = Mask[i] - i;
3246
3247   // Check the rest of the elements to see if they are consecutive.
3248   for (++i; i != e; ++i) {
3249     int m = Mask[i];
3250     if (m >= 0 && m != s+i)
3251       return false;
3252   }
3253   return true;
3254 }
3255
3256 /// isVSHUFPYMask - Return true if the specified VECTOR_SHUFFLE operand
3257 /// specifies a shuffle of elements that is suitable for input to 256-bit
3258 /// VSHUFPSY.
3259 static bool isVSHUFPYMask(const SmallVectorImpl<int> &Mask, EVT VT,
3260                           bool HasAVX, bool Commuted = false) {
3261   int NumElems = VT.getVectorNumElements();
3262
3263   if (!HasAVX || VT.getSizeInBits() != 256)
3264     return false;
3265
3266   if (NumElems != 4 && NumElems != 8)
3267     return false;
3268
3269   // VSHUFPSY divides the resulting vector into 4 chunks.
3270   // The sources are also splitted into 4 chunks, and each destination
3271   // chunk must come from a different source chunk.
3272   //
3273   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3274   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3275   //
3276   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3277   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3278   //
3279   // VSHUFPDY divides the resulting vector into 4 chunks.
3280   // The sources are also splitted into 4 chunks, and each destination
3281   // chunk must come from a different source chunk.
3282   //
3283   //  SRC1 =>      X3       X2       X1       X0
3284   //  SRC2 =>      Y3       Y2       Y1       Y0
3285   //
3286   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3287   //
3288   unsigned QuarterSize = NumElems/4;
3289   unsigned HalfSize = QuarterSize*2;
3290   for (unsigned l = 0; l != 2; ++l) {
3291     unsigned LaneStart = l*HalfSize;
3292     for (unsigned s = 0; s != 2; ++s) {
3293       unsigned QuarterStart = s*QuarterSize;
3294       unsigned Src = (Commuted) ? (1-s) : s;
3295       unsigned SrcStart = Src*NumElems + LaneStart;
3296       for (unsigned i = 0; i != QuarterSize; ++i) {
3297         int Idx = Mask[i+QuarterStart+LaneStart];
3298         if (!isUndefOrInRange(Idx, SrcStart, SrcStart+HalfSize))
3299           return false;
3300         // For VSHUFPSY, the mask of the second half must be the same as the first
3301         // but with the appropriate offsets. This works in the same way as
3302         // VPERMILPS works with masks.
3303         if (NumElems == 4 || l == 0 || Mask[i+QuarterStart] < 0)
3304           continue;
3305         if (!isUndefOrEqual(Idx, Mask[i+QuarterStart]+HalfSize))
3306           return false;
3307       }
3308     }
3309   }
3310
3311   return true;
3312 }
3313
3314 /// getShuffleVSHUFPYImmediate - Return the appropriate immediate to shuffle
3315 /// the specified VECTOR_MASK mask with VSHUFPSY/VSHUFPDY instructions.
3316 static unsigned getShuffleVSHUFPYImmediate(SDNode *N) {
3317   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3318   EVT VT = SVOp->getValueType(0);
3319   int NumElems = VT.getVectorNumElements();
3320
3321   assert(VT.getSizeInBits() == 256 && "Only supports 256-bit types");
3322   assert((NumElems == 4 || NumElems == 8) && "Only supports v4 and v8 types");
3323
3324   int HalfSize = NumElems/2;
3325   unsigned Mul = (NumElems == 8) ? 2 : 1;
3326   unsigned Mask = 0;
3327   for (int i = 0; i != NumElems; ++i) {
3328     int Elt = SVOp->getMaskElt(i);
3329     if (Elt < 0)
3330       continue;
3331     Elt %= HalfSize;
3332     unsigned Shamt = i;
3333     // For VSHUFPSY, the mask of the first half must be equal to the second one.
3334     if (NumElems == 8) Shamt %= HalfSize;
3335     Mask |= Elt << (Shamt*Mul);
3336   }
3337
3338   return Mask;
3339 }
3340
3341 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3342 /// the two vector operands have swapped position.
3343 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3344                                      unsigned NumElems) {
3345   for (unsigned i = 0; i != NumElems; ++i) {
3346     int idx = Mask[i];
3347     if (idx < 0)
3348       continue;
3349     else if (idx < (int)NumElems)
3350       Mask[i] = idx + NumElems;
3351     else
3352       Mask[i] = idx - NumElems;
3353   }
3354 }
3355
3356 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3357 /// specifies a shuffle of elements that is suitable for input to 128-bit
3358 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3359 /// reverse of what x86 shuffles want.
3360 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT,
3361                         bool Commuted = false) {
3362   unsigned NumElems = VT.getVectorNumElements();
3363
3364   if (VT.getSizeInBits() != 128)
3365     return false;
3366
3367   if (NumElems != 2 && NumElems != 4)
3368     return false;
3369
3370   unsigned Half = NumElems / 2;
3371   unsigned SrcStart = Commuted ? NumElems : 0;
3372   for (unsigned i = 0; i != Half; ++i)
3373     if (!isUndefOrInRange(Mask[i], SrcStart, SrcStart+NumElems))
3374       return false;
3375   SrcStart = Commuted ? 0 : NumElems;
3376   for (unsigned i = Half; i != NumElems; ++i)
3377     if (!isUndefOrInRange(Mask[i], SrcStart, SrcStart+NumElems))
3378       return false;
3379
3380   return true;
3381 }
3382
3383 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
3384   SmallVector<int, 8> M;
3385   N->getMask(M);
3386   return ::isSHUFPMask(M, N->getValueType(0));
3387 }
3388
3389 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3390 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3391 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3392   EVT VT = N->getValueType(0);
3393   unsigned NumElems = VT.getVectorNumElements();
3394
3395   if (VT.getSizeInBits() != 128)
3396     return false;
3397
3398   if (NumElems != 4)
3399     return false;
3400
3401   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3402   return isUndefOrEqual(N->getMaskElt(0), 6) &&
3403          isUndefOrEqual(N->getMaskElt(1), 7) &&
3404          isUndefOrEqual(N->getMaskElt(2), 2) &&
3405          isUndefOrEqual(N->getMaskElt(3), 3);
3406 }
3407
3408 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3409 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3410 /// <2, 3, 2, 3>
3411 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3412   EVT VT = N->getValueType(0);
3413   unsigned NumElems = VT.getVectorNumElements();
3414
3415   if (VT.getSizeInBits() != 128)
3416     return false;
3417
3418   if (NumElems != 4)
3419     return false;
3420
3421   return isUndefOrEqual(N->getMaskElt(0), 2) &&
3422          isUndefOrEqual(N->getMaskElt(1), 3) &&
3423          isUndefOrEqual(N->getMaskElt(2), 2) &&
3424          isUndefOrEqual(N->getMaskElt(3), 3);
3425 }
3426
3427 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3428 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3429 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3430   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3431
3432   if (NumElems != 2 && NumElems != 4)
3433     return false;
3434
3435   for (unsigned i = 0; i < NumElems/2; ++i)
3436     if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3437       return false;
3438
3439   for (unsigned i = NumElems/2; i < NumElems; ++i)
3440     if (!isUndefOrEqual(N->getMaskElt(i), i))
3441       return false;
3442
3443   return true;
3444 }
3445
3446 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3447 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3448 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3449   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3450
3451   if ((NumElems != 2 && NumElems != 4)
3452       || N->getValueType(0).getSizeInBits() > 128)
3453     return false;
3454
3455   for (unsigned i = 0; i < NumElems/2; ++i)
3456     if (!isUndefOrEqual(N->getMaskElt(i), i))
3457       return false;
3458
3459   for (unsigned i = 0; i < NumElems/2; ++i)
3460     if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3461       return false;
3462
3463   return true;
3464 }
3465
3466 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3467 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3468 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3469                          bool HasAVX2, bool V2IsSplat = false) {
3470   unsigned NumElts = VT.getVectorNumElements();
3471
3472   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3473          "Unsupported vector type for unpckh");
3474
3475   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3476       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3477     return false;
3478
3479   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3480   // independently on 128-bit lanes.
3481   unsigned NumLanes = VT.getSizeInBits()/128;
3482   unsigned NumLaneElts = NumElts/NumLanes;
3483
3484   for (unsigned l = 0; l != NumLanes; ++l) {
3485     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3486          i != (l+1)*NumLaneElts;
3487          i += 2, ++j) {
3488       int BitI  = Mask[i];
3489       int BitI1 = Mask[i+1];
3490       if (!isUndefOrEqual(BitI, j))
3491         return false;
3492       if (V2IsSplat) {
3493         if (!isUndefOrEqual(BitI1, NumElts))
3494           return false;
3495       } else {
3496         if (!isUndefOrEqual(BitI1, j + NumElts))
3497           return false;
3498       }
3499     }
3500   }
3501
3502   return true;
3503 }
3504
3505 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool HasAVX2, bool V2IsSplat) {
3506   SmallVector<int, 8> M;
3507   N->getMask(M);
3508   return ::isUNPCKLMask(M, N->getValueType(0), HasAVX2, V2IsSplat);
3509 }
3510
3511 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3512 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3513 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3514                          bool HasAVX2, bool V2IsSplat = false) {
3515   unsigned NumElts = VT.getVectorNumElements();
3516
3517   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3518          "Unsupported vector type for unpckh");
3519
3520   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3521       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3522     return false;
3523
3524   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3525   // independently on 128-bit lanes.
3526   unsigned NumLanes = VT.getSizeInBits()/128;
3527   unsigned NumLaneElts = NumElts/NumLanes;
3528
3529   for (unsigned l = 0; l != NumLanes; ++l) {
3530     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3531          i != (l+1)*NumLaneElts; i += 2, ++j) {
3532       int BitI  = Mask[i];
3533       int BitI1 = Mask[i+1];
3534       if (!isUndefOrEqual(BitI, j))
3535         return false;
3536       if (V2IsSplat) {
3537         if (isUndefOrEqual(BitI1, NumElts))
3538           return false;
3539       } else {
3540         if (!isUndefOrEqual(BitI1, j+NumElts))
3541           return false;
3542       }
3543     }
3544   }
3545   return true;
3546 }
3547
3548 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool HasAVX2, bool V2IsSplat) {
3549   SmallVector<int, 8> M;
3550   N->getMask(M);
3551   return ::isUNPCKHMask(M, N->getValueType(0), HasAVX2, V2IsSplat);
3552 }
3553
3554 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3555 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3556 /// <0, 0, 1, 1>
3557 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT,
3558                                   bool HasAVX2) {
3559   unsigned NumElts = VT.getVectorNumElements();
3560
3561   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3562          "Unsupported vector type for unpckh");
3563
3564   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3565       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3566     return false;
3567
3568   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3569   // FIXME: Need a better way to get rid of this, there's no latency difference
3570   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3571   // the former later. We should also remove the "_undef" special mask.
3572   if (NumElts == 4 && VT.getSizeInBits() == 256)
3573     return false;
3574
3575   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3576   // independently on 128-bit lanes.
3577   unsigned NumLanes = VT.getSizeInBits()/128;
3578   unsigned NumLaneElts = NumElts/NumLanes;
3579
3580   for (unsigned l = 0; l != NumLanes; ++l) {
3581     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3582          i != (l+1)*NumLaneElts;
3583          i += 2, ++j) {
3584       int BitI  = Mask[i];
3585       int BitI1 = Mask[i+1];
3586
3587       if (!isUndefOrEqual(BitI, j))
3588         return false;
3589       if (!isUndefOrEqual(BitI1, j))
3590         return false;
3591     }
3592   }
3593
3594   return true;
3595 }
3596
3597 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N, bool HasAVX2) {
3598   SmallVector<int, 8> M;
3599   N->getMask(M);
3600   return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0), HasAVX2);
3601 }
3602
3603 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3604 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3605 /// <2, 2, 3, 3>
3606 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT,
3607                                   bool HasAVX2) {
3608   unsigned NumElts = VT.getVectorNumElements();
3609
3610   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3611          "Unsupported vector type for unpckh");
3612
3613   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3614       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3615     return false;
3616
3617   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3618   // independently on 128-bit lanes.
3619   unsigned NumLanes = VT.getSizeInBits()/128;
3620   unsigned NumLaneElts = NumElts/NumLanes;
3621
3622   for (unsigned l = 0; l != NumLanes; ++l) {
3623     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3624          i != (l+1)*NumLaneElts; i += 2, ++j) {
3625       int BitI  = Mask[i];
3626       int BitI1 = Mask[i+1];
3627       if (!isUndefOrEqual(BitI, j))
3628         return false;
3629       if (!isUndefOrEqual(BitI1, j))
3630         return false;
3631     }
3632   }
3633   return true;
3634 }
3635
3636 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N, bool HasAVX2) {
3637   SmallVector<int, 8> M;
3638   N->getMask(M);
3639   return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0), HasAVX2);
3640 }
3641
3642 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3643 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3644 /// MOVSD, and MOVD, i.e. setting the lowest element.
3645 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3646   if (VT.getVectorElementType().getSizeInBits() < 32)
3647     return false;
3648
3649   int NumElts = VT.getVectorNumElements();
3650
3651   if (!isUndefOrEqual(Mask[0], NumElts))
3652     return false;
3653
3654   for (int i = 1; i < NumElts; ++i)
3655     if (!isUndefOrEqual(Mask[i], i))
3656       return false;
3657
3658   return true;
3659 }
3660
3661 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3662   SmallVector<int, 8> M;
3663   N->getMask(M);
3664   return ::isMOVLMask(M, N->getValueType(0));
3665 }
3666
3667 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3668 /// as permutations between 128-bit chunks or halves. As an example: this
3669 /// shuffle bellow:
3670 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3671 /// The first half comes from the second half of V1 and the second half from the
3672 /// the second half of V2.
3673 static bool isVPERM2X128Mask(const SmallVectorImpl<int> &Mask, EVT VT,
3674                              bool HasAVX) {
3675   if (!HasAVX || VT.getSizeInBits() != 256)
3676     return false;
3677
3678   // The shuffle result is divided into half A and half B. In total the two
3679   // sources have 4 halves, namely: C, D, E, F. The final values of A and
3680   // B must come from C, D, E or F.
3681   int HalfSize = VT.getVectorNumElements()/2;
3682   bool MatchA = false, MatchB = false;
3683
3684   // Check if A comes from one of C, D, E, F.
3685   for (int Half = 0; Half < 4; ++Half) {
3686     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3687       MatchA = true;
3688       break;
3689     }
3690   }
3691
3692   // Check if B comes from one of C, D, E, F.
3693   for (int Half = 0; Half < 4; ++Half) {
3694     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3695       MatchB = true;
3696       break;
3697     }
3698   }
3699
3700   return MatchA && MatchB;
3701 }
3702
3703 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3704 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3705 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3706   EVT VT = SVOp->getValueType(0);
3707
3708   int HalfSize = VT.getVectorNumElements()/2;
3709
3710   int FstHalf = 0, SndHalf = 0;
3711   for (int i = 0; i < HalfSize; ++i) {
3712     if (SVOp->getMaskElt(i) > 0) {
3713       FstHalf = SVOp->getMaskElt(i)/HalfSize;
3714       break;
3715     }
3716   }
3717   for (int i = HalfSize; i < HalfSize*2; ++i) {
3718     if (SVOp->getMaskElt(i) > 0) {
3719       SndHalf = SVOp->getMaskElt(i)/HalfSize;
3720       break;
3721     }
3722   }
3723
3724   return (FstHalf | (SndHalf << 4));
3725 }
3726
3727 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3728 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3729 /// Note that VPERMIL mask matching is different depending whether theunderlying
3730 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3731 /// to the same elements of the low, but to the higher half of the source.
3732 /// In VPERMILPD the two lanes could be shuffled independently of each other
3733 /// with the same restriction that lanes can't be crossed.
3734 static bool isVPERMILPMask(const SmallVectorImpl<int> &Mask, EVT VT,
3735                            bool HasAVX) {
3736   int NumElts = VT.getVectorNumElements();
3737   int NumLanes = VT.getSizeInBits()/128;
3738
3739   if (!HasAVX)
3740     return false;
3741
3742   // Only match 256-bit with 32/64-bit types
3743   if (VT.getSizeInBits() != 256 || (NumElts != 4 && NumElts != 8))
3744     return false;
3745
3746   int LaneSize = NumElts/NumLanes;
3747   for (int l = 0; l != NumLanes; ++l) {
3748     int LaneStart = l*LaneSize;
3749     for (int i = 0; i != LaneSize; ++i) {
3750       if (!isUndefOrInRange(Mask[i+LaneStart], LaneStart, LaneStart+LaneSize))
3751         return false;
3752       if (NumElts == 4 || l == 0)
3753         continue;
3754       // VPERMILPS handling
3755       if (Mask[i] < 0)
3756         continue;
3757       if (!isUndefOrEqual(Mask[i+LaneStart], Mask[i]+LaneSize))
3758         return false;
3759     }
3760   }
3761
3762   return true;
3763 }
3764
3765 /// getShuffleVPERMILPImmediate - Return the appropriate immediate to shuffle
3766 /// the specified VECTOR_MASK mask with VPERMILPS/D* instructions.
3767 static unsigned getShuffleVPERMILPImmediate(ShuffleVectorSDNode *SVOp) {
3768   EVT VT = SVOp->getValueType(0);
3769
3770   int NumElts = VT.getVectorNumElements();
3771   int NumLanes = VT.getSizeInBits()/128;
3772   int LaneSize = NumElts/NumLanes;
3773
3774   // Although the mask is equal for both lanes do it twice to get the cases
3775   // where a mask will match because the same mask element is undef on the
3776   // first half but valid on the second. This would get pathological cases
3777   // such as: shuffle <u, 0, 1, 2, 4, 4, 5, 6>, which is completely valid.
3778   unsigned Shift = (LaneSize == 4) ? 2 : 1;
3779   unsigned Mask = 0;
3780   for (int i = 0; i != NumElts; ++i) {
3781     int MaskElt = SVOp->getMaskElt(i);
3782     if (MaskElt < 0)
3783       continue;
3784     MaskElt %= LaneSize;
3785     unsigned Shamt = i;
3786     // VPERMILPSY, the mask of the first half must be equal to the second one
3787     if (NumElts == 8) Shamt %= LaneSize;
3788     Mask |= MaskElt << (Shamt*Shift);
3789   }
3790
3791   return Mask;
3792 }
3793
3794 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3795 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3796 /// element of vector 2 and the other elements to come from vector 1 in order.
3797 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3798                                bool V2IsSplat = false, bool V2IsUndef = false) {
3799   int NumOps = VT.getVectorNumElements();
3800   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3801     return false;
3802
3803   if (!isUndefOrEqual(Mask[0], 0))
3804     return false;
3805
3806   for (int i = 1; i < NumOps; ++i)
3807     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3808           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3809           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3810       return false;
3811
3812   return true;
3813 }
3814
3815 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3816                            bool V2IsUndef = false) {
3817   SmallVector<int, 8> M;
3818   N->getMask(M);
3819   return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3820 }
3821
3822 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3823 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3824 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3825 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N,
3826                          const X86Subtarget *Subtarget) {
3827   if (!Subtarget->hasSSE3orAVX())
3828     return false;
3829
3830   // The second vector must be undef
3831   if (N->getOperand(1).getOpcode() != ISD::UNDEF)
3832     return false;
3833
3834   EVT VT = N->getValueType(0);
3835   unsigned NumElems = VT.getVectorNumElements();
3836
3837   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3838       (VT.getSizeInBits() == 256 && NumElems != 8))
3839     return false;
3840
3841   // "i+1" is the value the indexed mask element must have
3842   for (unsigned i = 0; i < NumElems; i += 2)
3843     if (!isUndefOrEqual(N->getMaskElt(i), i+1) ||
3844         !isUndefOrEqual(N->getMaskElt(i+1), i+1))
3845       return false;
3846
3847   return true;
3848 }
3849
3850 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3851 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3852 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3853 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N,
3854                          const X86Subtarget *Subtarget) {
3855   if (!Subtarget->hasSSE3orAVX())
3856     return false;
3857
3858   // The second vector must be undef
3859   if (N->getOperand(1).getOpcode() != ISD::UNDEF)
3860     return false;
3861
3862   EVT VT = N->getValueType(0);
3863   unsigned NumElems = VT.getVectorNumElements();
3864
3865   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3866       (VT.getSizeInBits() == 256 && NumElems != 8))
3867     return false;
3868
3869   // "i" is the value the indexed mask element must have
3870   for (unsigned i = 0; i < NumElems; i += 2)
3871     if (!isUndefOrEqual(N->getMaskElt(i), i) ||
3872         !isUndefOrEqual(N->getMaskElt(i+1), i))
3873       return false;
3874
3875   return true;
3876 }
3877
3878 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3879 /// specifies a shuffle of elements that is suitable for input to 256-bit
3880 /// version of MOVDDUP.
3881 static bool isMOVDDUPYMask(const SmallVectorImpl<int> &Mask, EVT VT,
3882                            bool HasAVX) {
3883   int NumElts = VT.getVectorNumElements();
3884
3885   if (!HasAVX || VT.getSizeInBits() != 256 || NumElts != 4)
3886     return false;
3887
3888   for (int i = 0; i != NumElts/2; ++i)
3889     if (!isUndefOrEqual(Mask[i], 0))
3890       return false;
3891   for (int i = NumElts/2; i != NumElts; ++i)
3892     if (!isUndefOrEqual(Mask[i], NumElts/2))
3893       return false;
3894   return true;
3895 }
3896
3897 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3898 /// specifies a shuffle of elements that is suitable for input to 128-bit
3899 /// version of MOVDDUP.
3900 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3901   EVT VT = N->getValueType(0);
3902
3903   if (VT.getSizeInBits() != 128)
3904     return false;
3905
3906   int e = VT.getVectorNumElements() / 2;
3907   for (int i = 0; i < e; ++i)
3908     if (!isUndefOrEqual(N->getMaskElt(i), i))
3909       return false;
3910   for (int i = 0; i < e; ++i)
3911     if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3912       return false;
3913   return true;
3914 }
3915
3916 /// isVEXTRACTF128Index - Return true if the specified
3917 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3918 /// suitable for input to VEXTRACTF128.
3919 bool X86::isVEXTRACTF128Index(SDNode *N) {
3920   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3921     return false;
3922
3923   // The index should be aligned on a 128-bit boundary.
3924   uint64_t Index =
3925     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3926
3927   unsigned VL = N->getValueType(0).getVectorNumElements();
3928   unsigned VBits = N->getValueType(0).getSizeInBits();
3929   unsigned ElSize = VBits / VL;
3930   bool Result = (Index * ElSize) % 128 == 0;
3931
3932   return Result;
3933 }
3934
3935 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3936 /// operand specifies a subvector insert that is suitable for input to
3937 /// VINSERTF128.
3938 bool X86::isVINSERTF128Index(SDNode *N) {
3939   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3940     return false;
3941
3942   // The index should be aligned on a 128-bit boundary.
3943   uint64_t Index =
3944     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3945
3946   unsigned VL = N->getValueType(0).getVectorNumElements();
3947   unsigned VBits = N->getValueType(0).getSizeInBits();
3948   unsigned ElSize = VBits / VL;
3949   bool Result = (Index * ElSize) % 128 == 0;
3950
3951   return Result;
3952 }
3953
3954 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3955 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3956 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3957   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3958   int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3959
3960   unsigned Shift = (NumOperands == 4) ? 2 : 1;
3961   unsigned Mask = 0;
3962   for (int i = 0; i < NumOperands; ++i) {
3963     int Val = SVOp->getMaskElt(NumOperands-i-1);
3964     if (Val < 0) Val = 0;
3965     if (Val >= NumOperands) Val -= NumOperands;
3966     Mask |= Val;
3967     if (i != NumOperands - 1)
3968       Mask <<= Shift;
3969   }
3970   return Mask;
3971 }
3972
3973 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3974 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3975 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3976   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3977   unsigned Mask = 0;
3978   // 8 nodes, but we only care about the last 4.
3979   for (unsigned i = 7; i >= 4; --i) {
3980     int Val = SVOp->getMaskElt(i);
3981     if (Val >= 0)
3982       Mask |= (Val - 4);
3983     if (i != 4)
3984       Mask <<= 2;
3985   }
3986   return Mask;
3987 }
3988
3989 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3990 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3991 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3992   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3993   unsigned Mask = 0;
3994   // 8 nodes, but we only care about the first 4.
3995   for (int i = 3; i >= 0; --i) {
3996     int Val = SVOp->getMaskElt(i);
3997     if (Val >= 0)
3998       Mask |= Val;
3999     if (i != 0)
4000       Mask <<= 2;
4001   }
4002   return Mask;
4003 }
4004
4005 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4006 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4007 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4008   EVT VT = SVOp->getValueType(0);
4009   unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4010   int Val = 0;
4011
4012   unsigned i, e;
4013   for (i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
4014     Val = SVOp->getMaskElt(i);
4015     if (Val >= 0)
4016       break;
4017   }
4018   assert(Val - i > 0 && "PALIGNR imm should be positive");
4019   return (Val - i) * EltSize;
4020 }
4021
4022 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4023 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4024 /// instructions.
4025 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4026   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4027     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4028
4029   uint64_t Index =
4030     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4031
4032   EVT VecVT = N->getOperand(0).getValueType();
4033   EVT ElVT = VecVT.getVectorElementType();
4034
4035   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4036   return Index / NumElemsPerChunk;
4037 }
4038
4039 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4040 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4041 /// instructions.
4042 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4043   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4044     llvm_unreachable("Illegal insert subvector for VINSERTF128");
4045
4046   uint64_t Index =
4047     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4048
4049   EVT VecVT = N->getValueType(0);
4050   EVT ElVT = VecVT.getVectorElementType();
4051
4052   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4053   return Index / NumElemsPerChunk;
4054 }
4055
4056 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4057 /// constant +0.0.
4058 bool X86::isZeroNode(SDValue Elt) {
4059   return ((isa<ConstantSDNode>(Elt) &&
4060            cast<ConstantSDNode>(Elt)->isNullValue()) ||
4061           (isa<ConstantFPSDNode>(Elt) &&
4062            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4063 }
4064
4065 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4066 /// their permute mask.
4067 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4068                                     SelectionDAG &DAG) {
4069   EVT VT = SVOp->getValueType(0);
4070   unsigned NumElems = VT.getVectorNumElements();
4071   SmallVector<int, 8> MaskVec;
4072
4073   for (unsigned i = 0; i != NumElems; ++i) {
4074     int idx = SVOp->getMaskElt(i);
4075     if (idx < 0)
4076       MaskVec.push_back(idx);
4077     else if (idx < (int)NumElems)
4078       MaskVec.push_back(idx + NumElems);
4079     else
4080       MaskVec.push_back(idx - NumElems);
4081   }
4082   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4083                               SVOp->getOperand(0), &MaskVec[0]);
4084 }
4085
4086 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4087 /// match movhlps. The lower half elements should come from upper half of
4088 /// V1 (and in order), and the upper half elements should come from the upper
4089 /// half of V2 (and in order).
4090 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
4091   EVT VT = Op->getValueType(0);
4092   if (VT.getSizeInBits() != 128)
4093     return false;
4094   if (VT.getVectorNumElements() != 4)
4095     return false;
4096   for (unsigned i = 0, e = 2; i != e; ++i)
4097     if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
4098       return false;
4099   for (unsigned i = 2; i != 4; ++i)
4100     if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
4101       return false;
4102   return true;
4103 }
4104
4105 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4106 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4107 /// required.
4108 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4109   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4110     return false;
4111   N = N->getOperand(0).getNode();
4112   if (!ISD::isNON_EXTLoad(N))
4113     return false;
4114   if (LD)
4115     *LD = cast<LoadSDNode>(N);
4116   return true;
4117 }
4118
4119 // Test whether the given value is a vector value which will be legalized
4120 // into a load.
4121 static bool WillBeConstantPoolLoad(SDNode *N) {
4122   if (N->getOpcode() != ISD::BUILD_VECTOR)
4123     return false;
4124
4125   // Check for any non-constant elements.
4126   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4127     switch (N->getOperand(i).getNode()->getOpcode()) {
4128     case ISD::UNDEF:
4129     case ISD::ConstantFP:
4130     case ISD::Constant:
4131       break;
4132     default:
4133       return false;
4134     }
4135
4136   // Vectors of all-zeros and all-ones are materialized with special
4137   // instructions rather than being loaded.
4138   return !ISD::isBuildVectorAllZeros(N) &&
4139          !ISD::isBuildVectorAllOnes(N);
4140 }
4141
4142 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4143 /// match movlp{s|d}. The lower half elements should come from lower half of
4144 /// V1 (and in order), and the upper half elements should come from the upper
4145 /// half of V2 (and in order). And since V1 will become the source of the
4146 /// MOVLP, it must be either a vector load or a scalar load to vector.
4147 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4148                                ShuffleVectorSDNode *Op) {
4149   EVT VT = Op->getValueType(0);
4150   if (VT.getSizeInBits() != 128)
4151     return false;
4152
4153   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4154     return false;
4155   // Is V2 is a vector load, don't do this transformation. We will try to use
4156   // load folding shufps op.
4157   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4158     return false;
4159
4160   unsigned NumElems = VT.getVectorNumElements();
4161
4162   if (NumElems != 2 && NumElems != 4)
4163     return false;
4164   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4165     if (!isUndefOrEqual(Op->getMaskElt(i), i))
4166       return false;
4167   for (unsigned i = NumElems/2; i != NumElems; ++i)
4168     if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
4169       return false;
4170   return true;
4171 }
4172
4173 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4174 /// all the same.
4175 static bool isSplatVector(SDNode *N) {
4176   if (N->getOpcode() != ISD::BUILD_VECTOR)
4177     return false;
4178
4179   SDValue SplatValue = N->getOperand(0);
4180   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4181     if (N->getOperand(i) != SplatValue)
4182       return false;
4183   return true;
4184 }
4185
4186 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4187 /// to an zero vector.
4188 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4189 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4190   SDValue V1 = N->getOperand(0);
4191   SDValue V2 = N->getOperand(1);
4192   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4193   for (unsigned i = 0; i != NumElems; ++i) {
4194     int Idx = N->getMaskElt(i);
4195     if (Idx >= (int)NumElems) {
4196       unsigned Opc = V2.getOpcode();
4197       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4198         continue;
4199       if (Opc != ISD::BUILD_VECTOR ||
4200           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4201         return false;
4202     } else if (Idx >= 0) {
4203       unsigned Opc = V1.getOpcode();
4204       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4205         continue;
4206       if (Opc != ISD::BUILD_VECTOR ||
4207           !X86::isZeroNode(V1.getOperand(Idx)))
4208         return false;
4209     }
4210   }
4211   return true;
4212 }
4213
4214 /// getZeroVector - Returns a vector of specified type with all zero elements.
4215 ///
4216 static SDValue getZeroVector(EVT VT, bool HasXMMInt, SelectionDAG &DAG,
4217                              DebugLoc dl) {
4218   assert(VT.isVector() && "Expected a vector type");
4219
4220   // Always build SSE zero vectors as <4 x i32> bitcasted
4221   // to their dest type. This ensures they get CSE'd.
4222   SDValue Vec;
4223   if (VT.getSizeInBits() == 128) {  // SSE
4224     if (HasXMMInt) {  // SSE2
4225       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4226       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4227     } else { // SSE1
4228       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4229       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4230     }
4231   } else if (VT.getSizeInBits() == 256) { // AVX
4232     // 256-bit logic and arithmetic instructions in AVX are
4233     // all floating-point, no support for integer ops. Default
4234     // to emitting fp zeroed vectors then.
4235     SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4236     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4237     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4238   }
4239   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4240 }
4241
4242 /// getOnesVector - Returns a vector of specified type with all bits set.
4243 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4244 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4245 /// Then bitcast to their original type, ensuring they get CSE'd.
4246 static SDValue getOnesVector(EVT VT, bool HasAVX2, SelectionDAG &DAG,
4247                              DebugLoc dl) {
4248   assert(VT.isVector() && "Expected a vector type");
4249   assert((VT.is128BitVector() || VT.is256BitVector())
4250          && "Expected a 128-bit or 256-bit vector type");
4251
4252   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4253   SDValue Vec;
4254   if (VT.getSizeInBits() == 256) {
4255     if (HasAVX2) { // AVX2
4256       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4257       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4258     } else { // AVX
4259       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4260       SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, MVT::v8i32),
4261                                 Vec, DAG.getConstant(0, MVT::i32), DAG, dl);
4262       Vec = Insert128BitVector(InsV, Vec,
4263                     DAG.getConstant(4 /* NumElems/2 */, MVT::i32), DAG, dl);
4264     }
4265   } else {
4266     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4267   }
4268
4269   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4270 }
4271
4272 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4273 /// that point to V2 points to its first element.
4274 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4275   EVT VT = SVOp->getValueType(0);
4276   unsigned NumElems = VT.getVectorNumElements();
4277
4278   bool Changed = false;
4279   SmallVector<int, 8> MaskVec;
4280   SVOp->getMask(MaskVec);
4281
4282   for (unsigned i = 0; i != NumElems; ++i) {
4283     if (MaskVec[i] > (int)NumElems) {
4284       MaskVec[i] = NumElems;
4285       Changed = true;
4286     }
4287   }
4288   if (Changed)
4289     return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
4290                                 SVOp->getOperand(1), &MaskVec[0]);
4291   return SDValue(SVOp, 0);
4292 }
4293
4294 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4295 /// operation of specified width.
4296 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4297                        SDValue V2) {
4298   unsigned NumElems = VT.getVectorNumElements();
4299   SmallVector<int, 8> Mask;
4300   Mask.push_back(NumElems);
4301   for (unsigned i = 1; i != NumElems; ++i)
4302     Mask.push_back(i);
4303   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4304 }
4305
4306 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4307 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4308                           SDValue V2) {
4309   unsigned NumElems = VT.getVectorNumElements();
4310   SmallVector<int, 8> Mask;
4311   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4312     Mask.push_back(i);
4313     Mask.push_back(i + NumElems);
4314   }
4315   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4316 }
4317
4318 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4319 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4320                           SDValue V2) {
4321   unsigned NumElems = VT.getVectorNumElements();
4322   unsigned Half = NumElems/2;
4323   SmallVector<int, 8> Mask;
4324   for (unsigned i = 0; i != Half; ++i) {
4325     Mask.push_back(i + Half);
4326     Mask.push_back(i + NumElems + Half);
4327   }
4328   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4329 }
4330
4331 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4332 // a generic shuffle instruction because the target has no such instructions.
4333 // Generate shuffles which repeat i16 and i8 several times until they can be
4334 // represented by v4f32 and then be manipulated by target suported shuffles.
4335 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4336   EVT VT = V.getValueType();
4337   int NumElems = VT.getVectorNumElements();
4338   DebugLoc dl = V.getDebugLoc();
4339
4340   while (NumElems > 4) {
4341     if (EltNo < NumElems/2) {
4342       V = getUnpackl(DAG, dl, VT, V, V);
4343     } else {
4344       V = getUnpackh(DAG, dl, VT, V, V);
4345       EltNo -= NumElems/2;
4346     }
4347     NumElems >>= 1;
4348   }
4349   return V;
4350 }
4351
4352 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4353 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4354   EVT VT = V.getValueType();
4355   DebugLoc dl = V.getDebugLoc();
4356   assert((VT.getSizeInBits() == 128 || VT.getSizeInBits() == 256)
4357          && "Vector size not supported");
4358
4359   if (VT.getSizeInBits() == 128) {
4360     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4361     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4362     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4363                              &SplatMask[0]);
4364   } else {
4365     // To use VPERMILPS to splat scalars, the second half of indicies must
4366     // refer to the higher part, which is a duplication of the lower one,
4367     // because VPERMILPS can only handle in-lane permutations.
4368     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4369                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4370
4371     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4372     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4373                              &SplatMask[0]);
4374   }
4375
4376   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4377 }
4378
4379 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4380 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4381   EVT SrcVT = SV->getValueType(0);
4382   SDValue V1 = SV->getOperand(0);
4383   DebugLoc dl = SV->getDebugLoc();
4384
4385   int EltNo = SV->getSplatIndex();
4386   int NumElems = SrcVT.getVectorNumElements();
4387   unsigned Size = SrcVT.getSizeInBits();
4388
4389   assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4390           "Unknown how to promote splat for type");
4391
4392   // Extract the 128-bit part containing the splat element and update
4393   // the splat element index when it refers to the higher register.
4394   if (Size == 256) {
4395     unsigned Idx = (EltNo > NumElems/2) ? NumElems/2 : 0;
4396     V1 = Extract128BitVector(V1, DAG.getConstant(Idx, MVT::i32), DAG, dl);
4397     if (Idx > 0)
4398       EltNo -= NumElems/2;
4399   }
4400
4401   // All i16 and i8 vector types can't be used directly by a generic shuffle
4402   // instruction because the target has no such instruction. Generate shuffles
4403   // which repeat i16 and i8 several times until they fit in i32, and then can
4404   // be manipulated by target suported shuffles.
4405   EVT EltVT = SrcVT.getVectorElementType();
4406   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4407     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4408
4409   // Recreate the 256-bit vector and place the same 128-bit vector
4410   // into the low and high part. This is necessary because we want
4411   // to use VPERM* to shuffle the vectors
4412   if (Size == 256) {
4413     SDValue InsV = Insert128BitVector(DAG.getUNDEF(SrcVT), V1,
4414                          DAG.getConstant(0, MVT::i32), DAG, dl);
4415     V1 = Insert128BitVector(InsV, V1,
4416                DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
4417   }
4418
4419   return getLegalSplat(DAG, V1, EltNo);
4420 }
4421
4422 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4423 /// vector of zero or undef vector.  This produces a shuffle where the low
4424 /// element of V2 is swizzled into the zero/undef vector, landing at element
4425 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4426 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4427                                            bool isZero, bool HasXMMInt,
4428                                            SelectionDAG &DAG) {
4429   EVT VT = V2.getValueType();
4430   SDValue V1 = isZero
4431     ? getZeroVector(VT, HasXMMInt, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4432   unsigned NumElems = VT.getVectorNumElements();
4433   SmallVector<int, 16> MaskVec;
4434   for (unsigned i = 0; i != NumElems; ++i)
4435     // If this is the insertion idx, put the low elt of V2 here.
4436     MaskVec.push_back(i == Idx ? NumElems : i);
4437   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4438 }
4439
4440 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4441 /// element of the result of the vector shuffle.
4442 static SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
4443                                    unsigned Depth) {
4444   if (Depth == 6)
4445     return SDValue();  // Limit search depth.
4446
4447   SDValue V = SDValue(N, 0);
4448   EVT VT = V.getValueType();
4449   unsigned Opcode = V.getOpcode();
4450
4451   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4452   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4453     Index = SV->getMaskElt(Index);
4454
4455     if (Index < 0)
4456       return DAG.getUNDEF(VT.getVectorElementType());
4457
4458     int NumElems = VT.getVectorNumElements();
4459     SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
4460     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
4461   }
4462
4463   // Recurse into target specific vector shuffles to find scalars.
4464   if (isTargetShuffle(Opcode)) {
4465     int NumElems = VT.getVectorNumElements();
4466     SmallVector<unsigned, 16> ShuffleMask;
4467     SDValue ImmN;
4468
4469     switch(Opcode) {
4470     case X86ISD::SHUFPS:
4471     case X86ISD::SHUFPD:
4472       ImmN = N->getOperand(N->getNumOperands()-1);
4473       DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4474                       ShuffleMask);
4475       break;
4476     case X86ISD::UNPCKH:
4477       DecodeUNPCKHMask(VT, ShuffleMask);
4478       break;
4479     case X86ISD::UNPCKL:
4480       DecodeUNPCKLMask(VT, ShuffleMask);
4481       break;
4482     case X86ISD::MOVHLPS:
4483       DecodeMOVHLPSMask(NumElems, ShuffleMask);
4484       break;
4485     case X86ISD::MOVLHPS:
4486       DecodeMOVLHPSMask(NumElems, ShuffleMask);
4487       break;
4488     case X86ISD::PSHUFD:
4489       ImmN = N->getOperand(N->getNumOperands()-1);
4490       DecodePSHUFMask(NumElems,
4491                       cast<ConstantSDNode>(ImmN)->getZExtValue(),
4492                       ShuffleMask);
4493       break;
4494     case X86ISD::PSHUFHW:
4495       ImmN = N->getOperand(N->getNumOperands()-1);
4496       DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4497                         ShuffleMask);
4498       break;
4499     case X86ISD::PSHUFLW:
4500       ImmN = N->getOperand(N->getNumOperands()-1);
4501       DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4502                         ShuffleMask);
4503       break;
4504     case X86ISD::MOVSS:
4505     case X86ISD::MOVSD: {
4506       // The index 0 always comes from the first element of the second source,
4507       // this is why MOVSS and MOVSD are used in the first place. The other
4508       // elements come from the other positions of the first source vector.
4509       unsigned OpNum = (Index == 0) ? 1 : 0;
4510       return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
4511                                  Depth+1);
4512     }
4513     case X86ISD::VPERMILP:
4514       ImmN = N->getOperand(N->getNumOperands()-1);
4515       DecodeVPERMILPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4516                         ShuffleMask);
4517       break;
4518     case X86ISD::VPERM2X128:
4519       ImmN = N->getOperand(N->getNumOperands()-1);
4520       DecodeVPERM2F128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4521                            ShuffleMask);
4522       break;
4523     case X86ISD::MOVDDUP:
4524     case X86ISD::MOVLHPD:
4525     case X86ISD::MOVLPD:
4526     case X86ISD::MOVLPS:
4527     case X86ISD::MOVSHDUP:
4528     case X86ISD::MOVSLDUP:
4529     case X86ISD::PALIGN:
4530       return SDValue(); // Not yet implemented.
4531     default:
4532       assert(0 && "unknown target shuffle node");
4533       return SDValue();
4534     }
4535
4536     Index = ShuffleMask[Index];
4537     if (Index < 0)
4538       return DAG.getUNDEF(VT.getVectorElementType());
4539
4540     SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
4541     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
4542                                Depth+1);
4543   }
4544
4545   // Actual nodes that may contain scalar elements
4546   if (Opcode == ISD::BITCAST) {
4547     V = V.getOperand(0);
4548     EVT SrcVT = V.getValueType();
4549     unsigned NumElems = VT.getVectorNumElements();
4550
4551     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4552       return SDValue();
4553   }
4554
4555   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4556     return (Index == 0) ? V.getOperand(0)
4557                           : DAG.getUNDEF(VT.getVectorElementType());
4558
4559   if (V.getOpcode() == ISD::BUILD_VECTOR)
4560     return V.getOperand(Index);
4561
4562   return SDValue();
4563 }
4564
4565 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4566 /// shuffle operation which come from a consecutively from a zero. The
4567 /// search can start in two different directions, from left or right.
4568 static
4569 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
4570                                   bool ZerosFromLeft, SelectionDAG &DAG) {
4571   int i = 0;
4572
4573   while (i < NumElems) {
4574     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4575     SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
4576     if (!(Elt.getNode() &&
4577          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4578       break;
4579     ++i;
4580   }
4581
4582   return i;
4583 }
4584
4585 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
4586 /// MaskE correspond consecutively to elements from one of the vector operands,
4587 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4588 static
4589 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
4590                               int OpIdx, int NumElems, unsigned &OpNum) {
4591   bool SeenV1 = false;
4592   bool SeenV2 = false;
4593
4594   for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
4595     int Idx = SVOp->getMaskElt(i);
4596     // Ignore undef indicies
4597     if (Idx < 0)
4598       continue;
4599
4600     if (Idx < NumElems)
4601       SeenV1 = true;
4602     else
4603       SeenV2 = true;
4604
4605     // Only accept consecutive elements from the same vector
4606     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4607       return false;
4608   }
4609
4610   OpNum = SeenV1 ? 0 : 1;
4611   return true;
4612 }
4613
4614 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4615 /// logical left shift of a vector.
4616 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4617                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4618   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4619   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4620               false /* check zeros from right */, DAG);
4621   unsigned OpSrc;
4622
4623   if (!NumZeros)
4624     return false;
4625
4626   // Considering the elements in the mask that are not consecutive zeros,
4627   // check if they consecutively come from only one of the source vectors.
4628   //
4629   //               V1 = {X, A, B, C}     0
4630   //                         \  \  \    /
4631   //   vector_shuffle V1, V2 <1, 2, 3, X>
4632   //
4633   if (!isShuffleMaskConsecutive(SVOp,
4634             0,                   // Mask Start Index
4635             NumElems-NumZeros-1, // Mask End Index
4636             NumZeros,            // Where to start looking in the src vector
4637             NumElems,            // Number of elements in vector
4638             OpSrc))              // Which source operand ?
4639     return false;
4640
4641   isLeft = false;
4642   ShAmt = NumZeros;
4643   ShVal = SVOp->getOperand(OpSrc);
4644   return true;
4645 }
4646
4647 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4648 /// logical left shift of a vector.
4649 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4650                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4651   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4652   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4653               true /* check zeros from left */, DAG);
4654   unsigned OpSrc;
4655
4656   if (!NumZeros)
4657     return false;
4658
4659   // Considering the elements in the mask that are not consecutive zeros,
4660   // check if they consecutively come from only one of the source vectors.
4661   //
4662   //                           0    { A, B, X, X } = V2
4663   //                          / \    /  /
4664   //   vector_shuffle V1, V2 <X, X, 4, 5>
4665   //
4666   if (!isShuffleMaskConsecutive(SVOp,
4667             NumZeros,     // Mask Start Index
4668             NumElems-1,   // Mask End Index
4669             0,            // Where to start looking in the src vector
4670             NumElems,     // Number of elements in vector
4671             OpSrc))       // Which source operand ?
4672     return false;
4673
4674   isLeft = true;
4675   ShAmt = NumZeros;
4676   ShVal = SVOp->getOperand(OpSrc);
4677   return true;
4678 }
4679
4680 /// isVectorShift - Returns true if the shuffle can be implemented as a
4681 /// logical left or right shift of a vector.
4682 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4683                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4684   // Although the logic below support any bitwidth size, there are no
4685   // shift instructions which handle more than 128-bit vectors.
4686   if (SVOp->getValueType(0).getSizeInBits() > 128)
4687     return false;
4688
4689   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4690       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4691     return true;
4692
4693   return false;
4694 }
4695
4696 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4697 ///
4698 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4699                                        unsigned NumNonZero, unsigned NumZero,
4700                                        SelectionDAG &DAG,
4701                                        const TargetLowering &TLI) {
4702   if (NumNonZero > 8)
4703     return SDValue();
4704
4705   DebugLoc dl = Op.getDebugLoc();
4706   SDValue V(0, 0);
4707   bool First = true;
4708   for (unsigned i = 0; i < 16; ++i) {
4709     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4710     if (ThisIsNonZero && First) {
4711       if (NumZero)
4712         V = getZeroVector(MVT::v8i16, true, DAG, dl);
4713       else
4714         V = DAG.getUNDEF(MVT::v8i16);
4715       First = false;
4716     }
4717
4718     if ((i & 1) != 0) {
4719       SDValue ThisElt(0, 0), LastElt(0, 0);
4720       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4721       if (LastIsNonZero) {
4722         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4723                               MVT::i16, Op.getOperand(i-1));
4724       }
4725       if (ThisIsNonZero) {
4726         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4727         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4728                               ThisElt, DAG.getConstant(8, MVT::i8));
4729         if (LastIsNonZero)
4730           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4731       } else
4732         ThisElt = LastElt;
4733
4734       if (ThisElt.getNode())
4735         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4736                         DAG.getIntPtrConstant(i/2));
4737     }
4738   }
4739
4740   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4741 }
4742
4743 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4744 ///
4745 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4746                                      unsigned NumNonZero, unsigned NumZero,
4747                                      SelectionDAG &DAG,
4748                                      const TargetLowering &TLI) {
4749   if (NumNonZero > 4)
4750     return SDValue();
4751
4752   DebugLoc dl = Op.getDebugLoc();
4753   SDValue V(0, 0);
4754   bool First = true;
4755   for (unsigned i = 0; i < 8; ++i) {
4756     bool isNonZero = (NonZeros & (1 << i)) != 0;
4757     if (isNonZero) {
4758       if (First) {
4759         if (NumZero)
4760           V = getZeroVector(MVT::v8i16, true, DAG, dl);
4761         else
4762           V = DAG.getUNDEF(MVT::v8i16);
4763         First = false;
4764       }
4765       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4766                       MVT::v8i16, V, Op.getOperand(i),
4767                       DAG.getIntPtrConstant(i));
4768     }
4769   }
4770
4771   return V;
4772 }
4773
4774 /// getVShift - Return a vector logical shift node.
4775 ///
4776 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4777                          unsigned NumBits, SelectionDAG &DAG,
4778                          const TargetLowering &TLI, DebugLoc dl) {
4779   assert(VT.getSizeInBits() == 128 && "Unknown type for VShift");
4780   EVT ShVT = MVT::v2i64;
4781   unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
4782   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4783   return DAG.getNode(ISD::BITCAST, dl, VT,
4784                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4785                              DAG.getConstant(NumBits,
4786                                   TLI.getShiftAmountTy(SrcOp.getValueType()))));
4787 }
4788
4789 SDValue
4790 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4791                                           SelectionDAG &DAG) const {
4792
4793   // Check if the scalar load can be widened into a vector load. And if
4794   // the address is "base + cst" see if the cst can be "absorbed" into
4795   // the shuffle mask.
4796   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4797     SDValue Ptr = LD->getBasePtr();
4798     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4799       return SDValue();
4800     EVT PVT = LD->getValueType(0);
4801     if (PVT != MVT::i32 && PVT != MVT::f32)
4802       return SDValue();
4803
4804     int FI = -1;
4805     int64_t Offset = 0;
4806     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4807       FI = FINode->getIndex();
4808       Offset = 0;
4809     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4810                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4811       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4812       Offset = Ptr.getConstantOperandVal(1);
4813       Ptr = Ptr.getOperand(0);
4814     } else {
4815       return SDValue();
4816     }
4817
4818     // FIXME: 256-bit vector instructions don't require a strict alignment,
4819     // improve this code to support it better.
4820     unsigned RequiredAlign = VT.getSizeInBits()/8;
4821     SDValue Chain = LD->getChain();
4822     // Make sure the stack object alignment is at least 16 or 32.
4823     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4824     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4825       if (MFI->isFixedObjectIndex(FI)) {
4826         // Can't change the alignment. FIXME: It's possible to compute
4827         // the exact stack offset and reference FI + adjust offset instead.
4828         // If someone *really* cares about this. That's the way to implement it.
4829         return SDValue();
4830       } else {
4831         MFI->setObjectAlignment(FI, RequiredAlign);
4832       }
4833     }
4834
4835     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4836     // Ptr + (Offset & ~15).
4837     if (Offset < 0)
4838       return SDValue();
4839     if ((Offset % RequiredAlign) & 3)
4840       return SDValue();
4841     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4842     if (StartOffset)
4843       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4844                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4845
4846     int EltNo = (Offset - StartOffset) >> 2;
4847     int NumElems = VT.getVectorNumElements();
4848
4849     EVT CanonVT = VT.getSizeInBits() == 128 ? MVT::v4i32 : MVT::v8i32;
4850     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4851     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4852                              LD->getPointerInfo().getWithOffset(StartOffset),
4853                              false, false, false, 0);
4854
4855     // Canonicalize it to a v4i32 or v8i32 shuffle.
4856     SmallVector<int, 8> Mask;
4857     for (int i = 0; i < NumElems; ++i)
4858       Mask.push_back(EltNo);
4859
4860     V1 = DAG.getNode(ISD::BITCAST, dl, CanonVT, V1);
4861     return DAG.getNode(ISD::BITCAST, dl, NVT,
4862                        DAG.getVectorShuffle(CanonVT, dl, V1,
4863                                             DAG.getUNDEF(CanonVT),&Mask[0]));
4864   }
4865
4866   return SDValue();
4867 }
4868
4869 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4870 /// vector of type 'VT', see if the elements can be replaced by a single large
4871 /// load which has the same value as a build_vector whose operands are 'elts'.
4872 ///
4873 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4874 ///
4875 /// FIXME: we'd also like to handle the case where the last elements are zero
4876 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4877 /// There's even a handy isZeroNode for that purpose.
4878 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4879                                         DebugLoc &DL, SelectionDAG &DAG) {
4880   EVT EltVT = VT.getVectorElementType();
4881   unsigned NumElems = Elts.size();
4882
4883   LoadSDNode *LDBase = NULL;
4884   unsigned LastLoadedElt = -1U;
4885
4886   // For each element in the initializer, see if we've found a load or an undef.
4887   // If we don't find an initial load element, or later load elements are
4888   // non-consecutive, bail out.
4889   for (unsigned i = 0; i < NumElems; ++i) {
4890     SDValue Elt = Elts[i];
4891
4892     if (!Elt.getNode() ||
4893         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4894       return SDValue();
4895     if (!LDBase) {
4896       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4897         return SDValue();
4898       LDBase = cast<LoadSDNode>(Elt.getNode());
4899       LastLoadedElt = i;
4900       continue;
4901     }
4902     if (Elt.getOpcode() == ISD::UNDEF)
4903       continue;
4904
4905     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4906     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4907       return SDValue();
4908     LastLoadedElt = i;
4909   }
4910
4911   // If we have found an entire vector of loads and undefs, then return a large
4912   // load of the entire vector width starting at the base pointer.  If we found
4913   // consecutive loads for the low half, generate a vzext_load node.
4914   if (LastLoadedElt == NumElems - 1) {
4915     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4916       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4917                          LDBase->getPointerInfo(),
4918                          LDBase->isVolatile(), LDBase->isNonTemporal(),
4919                          LDBase->isInvariant(), 0);
4920     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4921                        LDBase->getPointerInfo(),
4922                        LDBase->isVolatile(), LDBase->isNonTemporal(),
4923                        LDBase->isInvariant(), LDBase->getAlignment());
4924   } else if (NumElems == 4 && LastLoadedElt == 1 &&
4925              DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4926     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4927     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4928     SDValue ResNode =
4929         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
4930                                 LDBase->getPointerInfo(),
4931                                 LDBase->getAlignment(),
4932                                 false/*isVolatile*/, true/*ReadMem*/,
4933                                 false/*WriteMem*/);
4934     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4935   }
4936   return SDValue();
4937 }
4938
4939 /// isVectorBroadcast - Check if the node chain is suitable to be xformed to
4940 /// a vbroadcast node. We support two patterns:
4941 /// 1. A splat BUILD_VECTOR which uses a single scalar load.
4942 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
4943 /// a scalar load.
4944 /// The scalar load node is returned when a pattern is found,
4945 /// or SDValue() otherwise.
4946 static SDValue isVectorBroadcast(SDValue &Op, bool hasAVX2) {
4947   EVT VT = Op.getValueType();
4948   SDValue V = Op;
4949
4950   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
4951     V = V.getOperand(0);
4952
4953   //A suspected load to be broadcasted.
4954   SDValue Ld;
4955
4956   switch (V.getOpcode()) {
4957     default:
4958       // Unknown pattern found.
4959       return SDValue();
4960
4961     case ISD::BUILD_VECTOR: {
4962       // The BUILD_VECTOR node must be a splat.
4963       if (!isSplatVector(V.getNode()))
4964         return SDValue();
4965
4966       Ld = V.getOperand(0);
4967
4968       // The suspected load node has several users. Make sure that all
4969       // of its users are from the BUILD_VECTOR node.
4970       if (!Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
4971         return SDValue();
4972       break;
4973     }
4974
4975     case ISD::VECTOR_SHUFFLE: {
4976       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4977
4978       // Shuffles must have a splat mask where the first element is
4979       // broadcasted.
4980       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
4981         return SDValue();
4982
4983       SDValue Sc = Op.getOperand(0);
4984       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR)
4985         return SDValue();
4986
4987       Ld = Sc.getOperand(0);
4988
4989       // The scalar_to_vector node and the suspected
4990       // load node must have exactly one user.
4991       if (!Sc.hasOneUse() || !Ld.hasOneUse())
4992         return SDValue();
4993       break;
4994     }
4995   }
4996
4997   // The scalar source must be a normal load.
4998   if (!ISD::isNormalLoad(Ld.getNode()))
4999     return SDValue();
5000
5001   bool Is256 = VT.getSizeInBits() == 256;
5002   bool Is128 = VT.getSizeInBits() == 128;
5003   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5004
5005   if (hasAVX2) {
5006     // VBroadcast to YMM
5007     if (Is256 && (ScalarSize == 8  || ScalarSize == 16 ||
5008                   ScalarSize == 32 || ScalarSize == 64 ))
5009       return Ld;
5010
5011     // VBroadcast to XMM
5012     if (Is128 && (ScalarSize ==  8 || ScalarSize == 32 ||
5013                   ScalarSize == 16 || ScalarSize == 64 ))
5014       return Ld;
5015   }
5016
5017   // VBroadcast to YMM
5018   if (Is256 && (ScalarSize == 32 || ScalarSize == 64))
5019     return Ld;
5020
5021   // VBroadcast to XMM
5022   if (Is128 && (ScalarSize == 32))
5023     return Ld;
5024
5025
5026   // Unsupported broadcast.
5027   return SDValue();
5028 }
5029
5030 SDValue
5031 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5032   DebugLoc dl = Op.getDebugLoc();
5033
5034   EVT VT = Op.getValueType();
5035   EVT ExtVT = VT.getVectorElementType();
5036   unsigned NumElems = Op.getNumOperands();
5037
5038   // Vectors containing all zeros can be matched by pxor and xorps later
5039   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5040     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5041     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5042     if (Op.getValueType() == MVT::v4i32 ||
5043         Op.getValueType() == MVT::v8i32)
5044       return Op;
5045
5046     return getZeroVector(Op.getValueType(), Subtarget->hasXMMInt(), DAG, dl);
5047   }
5048
5049   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5050   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5051   // vpcmpeqd on 256-bit vectors.
5052   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5053     if (Op.getValueType() == MVT::v4i32 ||
5054         (Op.getValueType() == MVT::v8i32 && Subtarget->hasAVX2()))
5055       return Op;
5056
5057     return getOnesVector(Op.getValueType(), Subtarget->hasAVX2(), DAG, dl);
5058   }
5059
5060   SDValue LD = isVectorBroadcast(Op, Subtarget->hasAVX2());
5061   if (Subtarget->hasAVX() && LD.getNode())
5062       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, LD);
5063
5064   unsigned EVTBits = ExtVT.getSizeInBits();
5065
5066   unsigned NumZero  = 0;
5067   unsigned NumNonZero = 0;
5068   unsigned NonZeros = 0;
5069   bool IsAllConstants = true;
5070   SmallSet<SDValue, 8> Values;
5071   for (unsigned i = 0; i < NumElems; ++i) {
5072     SDValue Elt = Op.getOperand(i);
5073     if (Elt.getOpcode() == ISD::UNDEF)
5074       continue;
5075     Values.insert(Elt);
5076     if (Elt.getOpcode() != ISD::Constant &&
5077         Elt.getOpcode() != ISD::ConstantFP)
5078       IsAllConstants = false;
5079     if (X86::isZeroNode(Elt))
5080       NumZero++;
5081     else {
5082       NonZeros |= (1 << i);
5083       NumNonZero++;
5084     }
5085   }
5086
5087   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5088   if (NumNonZero == 0)
5089     return DAG.getUNDEF(VT);
5090
5091   // Special case for single non-zero, non-undef, element.
5092   if (NumNonZero == 1) {
5093     unsigned Idx = CountTrailingZeros_32(NonZeros);
5094     SDValue Item = Op.getOperand(Idx);
5095
5096     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5097     // the value are obviously zero, truncate the value to i32 and do the
5098     // insertion that way.  Only do this if the value is non-constant or if the
5099     // value is a constant being inserted into element 0.  It is cheaper to do
5100     // a constant pool load than it is to do a movd + shuffle.
5101     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5102         (!IsAllConstants || Idx == 0)) {
5103       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5104         // Handle SSE only.
5105         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5106         EVT VecVT = MVT::v4i32;
5107         unsigned VecElts = 4;
5108
5109         // Truncate the value (which may itself be a constant) to i32, and
5110         // convert it to a vector with movd (S2V+shuffle to zero extend).
5111         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5112         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5113         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
5114                                            Subtarget->hasXMMInt(), DAG);
5115
5116         // Now we have our 32-bit value zero extended in the low element of
5117         // a vector.  If Idx != 0, swizzle it into place.
5118         if (Idx != 0) {
5119           SmallVector<int, 4> Mask;
5120           Mask.push_back(Idx);
5121           for (unsigned i = 1; i != VecElts; ++i)
5122             Mask.push_back(i);
5123           Item = DAG.getVectorShuffle(VecVT, dl, Item,
5124                                       DAG.getUNDEF(Item.getValueType()),
5125                                       &Mask[0]);
5126         }
5127         return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
5128       }
5129     }
5130
5131     // If we have a constant or non-constant insertion into the low element of
5132     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5133     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5134     // depending on what the source datatype is.
5135     if (Idx == 0) {
5136       if (NumZero == 0) {
5137         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5138       } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5139           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5140         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5141         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5142         return getShuffleVectorZeroOrUndef(Item, 0, true,Subtarget->hasXMMInt(),
5143                                            DAG);
5144       } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5145         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5146         unsigned NumBits = VT.getSizeInBits();
5147         assert((NumBits == 128 || NumBits == 256) && 
5148                "Expected an SSE or AVX value type!");
5149         EVT MiddleVT = NumBits == 128 ? MVT::v4i32 : MVT::v8i32;
5150         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
5151         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
5152                                            Subtarget->hasXMMInt(), DAG);
5153         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5154       }
5155     }
5156
5157     // Is it a vector logical left shift?
5158     if (NumElems == 2 && Idx == 1 &&
5159         X86::isZeroNode(Op.getOperand(0)) &&
5160         !X86::isZeroNode(Op.getOperand(1))) {
5161       unsigned NumBits = VT.getSizeInBits();
5162       return getVShift(true, VT,
5163                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5164                                    VT, Op.getOperand(1)),
5165                        NumBits/2, DAG, *this, dl);
5166     }
5167
5168     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5169       return SDValue();
5170
5171     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5172     // is a non-constant being inserted into an element other than the low one,
5173     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5174     // movd/movss) to move this into the low element, then shuffle it into
5175     // place.
5176     if (EVTBits == 32) {
5177       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5178
5179       // Turn it into a shuffle of zero and zero-extended scalar to vector.
5180       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
5181                                          Subtarget->hasXMMInt(), DAG);
5182       SmallVector<int, 8> MaskVec;
5183       for (unsigned i = 0; i < NumElems; i++)
5184         MaskVec.push_back(i == Idx ? 0 : 1);
5185       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5186     }
5187   }
5188
5189   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5190   if (Values.size() == 1) {
5191     if (EVTBits == 32) {
5192       // Instead of a shuffle like this:
5193       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5194       // Check if it's possible to issue this instead.
5195       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5196       unsigned Idx = CountTrailingZeros_32(NonZeros);
5197       SDValue Item = Op.getOperand(Idx);
5198       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5199         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5200     }
5201     return SDValue();
5202   }
5203
5204   // A vector full of immediates; various special cases are already
5205   // handled, so this is best done with a single constant-pool load.
5206   if (IsAllConstants)
5207     return SDValue();
5208
5209   // For AVX-length vectors, build the individual 128-bit pieces and use
5210   // shuffles to put them in place.
5211   if (VT.getSizeInBits() == 256 && !ISD::isBuildVectorAllZeros(Op.getNode())) {
5212     SmallVector<SDValue, 32> V;
5213     for (unsigned i = 0; i < NumElems; ++i)
5214       V.push_back(Op.getOperand(i));
5215
5216     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5217
5218     // Build both the lower and upper subvector.
5219     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5220     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5221                                 NumElems/2);
5222
5223     // Recreate the wider vector with the lower and upper part.
5224     SDValue Vec = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), Lower,
5225                                 DAG.getConstant(0, MVT::i32), DAG, dl);
5226     return Insert128BitVector(Vec, Upper, DAG.getConstant(NumElems/2, MVT::i32),
5227                               DAG, dl);
5228   }
5229
5230   // Let legalizer expand 2-wide build_vectors.
5231   if (EVTBits == 64) {
5232     if (NumNonZero == 1) {
5233       // One half is zero or undef.
5234       unsigned Idx = CountTrailingZeros_32(NonZeros);
5235       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5236                                  Op.getOperand(Idx));
5237       return getShuffleVectorZeroOrUndef(V2, Idx, true,
5238                                          Subtarget->hasXMMInt(), DAG);
5239     }
5240     return SDValue();
5241   }
5242
5243   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5244   if (EVTBits == 8 && NumElems == 16) {
5245     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5246                                         *this);
5247     if (V.getNode()) return V;
5248   }
5249
5250   if (EVTBits == 16 && NumElems == 8) {
5251     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5252                                       *this);
5253     if (V.getNode()) return V;
5254   }
5255
5256   // If element VT is == 32 bits, turn it into a number of shuffles.
5257   SmallVector<SDValue, 8> V;
5258   V.resize(NumElems);
5259   if (NumElems == 4 && NumZero > 0) {
5260     for (unsigned i = 0; i < 4; ++i) {
5261       bool isZero = !(NonZeros & (1 << i));
5262       if (isZero)
5263         V[i] = getZeroVector(VT, Subtarget->hasXMMInt(), DAG, dl);
5264       else
5265         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5266     }
5267
5268     for (unsigned i = 0; i < 2; ++i) {
5269       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5270         default: break;
5271         case 0:
5272           V[i] = V[i*2];  // Must be a zero vector.
5273           break;
5274         case 1:
5275           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5276           break;
5277         case 2:
5278           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5279           break;
5280         case 3:
5281           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5282           break;
5283       }
5284     }
5285
5286     SmallVector<int, 8> MaskVec;
5287     bool Reverse = (NonZeros & 0x3) == 2;
5288     for (unsigned i = 0; i < 2; ++i)
5289       MaskVec.push_back(Reverse ? 1-i : i);
5290     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5291     for (unsigned i = 0; i < 2; ++i)
5292       MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
5293     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5294   }
5295
5296   if (Values.size() > 1 && VT.getSizeInBits() == 128) {
5297     // Check for a build vector of consecutive loads.
5298     for (unsigned i = 0; i < NumElems; ++i)
5299       V[i] = Op.getOperand(i);
5300
5301     // Check for elements which are consecutive loads.
5302     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5303     if (LD.getNode())
5304       return LD;
5305
5306     // For SSE 4.1, use insertps to put the high elements into the low element.
5307     if (getSubtarget()->hasSSE41orAVX()) {
5308       SDValue Result;
5309       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5310         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5311       else
5312         Result = DAG.getUNDEF(VT);
5313
5314       for (unsigned i = 1; i < NumElems; ++i) {
5315         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5316         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5317                              Op.getOperand(i), DAG.getIntPtrConstant(i));
5318       }
5319       return Result;
5320     }
5321
5322     // Otherwise, expand into a number of unpckl*, start by extending each of
5323     // our (non-undef) elements to the full vector width with the element in the
5324     // bottom slot of the vector (which generates no code for SSE).
5325     for (unsigned i = 0; i < NumElems; ++i) {
5326       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5327         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5328       else
5329         V[i] = DAG.getUNDEF(VT);
5330     }
5331
5332     // Next, we iteratively mix elements, e.g. for v4f32:
5333     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5334     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5335     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5336     unsigned EltStride = NumElems >> 1;
5337     while (EltStride != 0) {
5338       for (unsigned i = 0; i < EltStride; ++i) {
5339         // If V[i+EltStride] is undef and this is the first round of mixing,
5340         // then it is safe to just drop this shuffle: V[i] is already in the
5341         // right place, the one element (since it's the first round) being
5342         // inserted as undef can be dropped.  This isn't safe for successive
5343         // rounds because they will permute elements within both vectors.
5344         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5345             EltStride == NumElems/2)
5346           continue;
5347
5348         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5349       }
5350       EltStride >>= 1;
5351     }
5352     return V[0];
5353   }
5354   return SDValue();
5355 }
5356
5357 // LowerMMXCONCAT_VECTORS - We support concatenate two MMX registers and place
5358 // them in a MMX register.  This is better than doing a stack convert.
5359 static SDValue LowerMMXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5360   DebugLoc dl = Op.getDebugLoc();
5361   EVT ResVT = Op.getValueType();
5362
5363   assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
5364          ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
5365   int Mask[2];
5366   SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
5367   SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5368   InVec = Op.getOperand(1);
5369   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5370     unsigned NumElts = ResVT.getVectorNumElements();
5371     VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5372     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
5373                        InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
5374   } else {
5375     InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
5376     SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5377     Mask[0] = 0; Mask[1] = 2;
5378     VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
5379   }
5380   return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5381 }
5382
5383 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5384 // to create 256-bit vectors from two other 128-bit ones.
5385 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5386   DebugLoc dl = Op.getDebugLoc();
5387   EVT ResVT = Op.getValueType();
5388
5389   assert(ResVT.getSizeInBits() == 256 && "Value type must be 256-bit wide");
5390
5391   SDValue V1 = Op.getOperand(0);
5392   SDValue V2 = Op.getOperand(1);
5393   unsigned NumElems = ResVT.getVectorNumElements();
5394
5395   SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, ResVT), V1,
5396                                  DAG.getConstant(0, MVT::i32), DAG, dl);
5397   return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32),
5398                             DAG, dl);
5399 }
5400
5401 SDValue
5402 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
5403   EVT ResVT = Op.getValueType();
5404
5405   assert(Op.getNumOperands() == 2);
5406   assert((ResVT.getSizeInBits() == 128 || ResVT.getSizeInBits() == 256) &&
5407          "Unsupported CONCAT_VECTORS for value type");
5408
5409   // We support concatenate two MMX registers and place them in a MMX register.
5410   // This is better than doing a stack convert.
5411   if (ResVT.is128BitVector())
5412     return LowerMMXCONCAT_VECTORS(Op, DAG);
5413
5414   // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5415   // from two other 128-bit ones.
5416   return LowerAVXCONCAT_VECTORS(Op, DAG);
5417 }
5418
5419 // v8i16 shuffles - Prefer shuffles in the following order:
5420 // 1. [all]   pshuflw, pshufhw, optional move
5421 // 2. [ssse3] 1 x pshufb
5422 // 3. [ssse3] 2 x pshufb + 1 x por
5423 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5424 SDValue
5425 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
5426                                             SelectionDAG &DAG) const {
5427   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5428   SDValue V1 = SVOp->getOperand(0);
5429   SDValue V2 = SVOp->getOperand(1);
5430   DebugLoc dl = SVOp->getDebugLoc();
5431   SmallVector<int, 8> MaskVals;
5432
5433   // Determine if more than 1 of the words in each of the low and high quadwords
5434   // of the result come from the same quadword of one of the two inputs.  Undef
5435   // mask values count as coming from any quadword, for better codegen.
5436   unsigned LoQuad[] = { 0, 0, 0, 0 };
5437   unsigned HiQuad[] = { 0, 0, 0, 0 };
5438   BitVector InputQuads(4);
5439   for (unsigned i = 0; i < 8; ++i) {
5440     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5441     int EltIdx = SVOp->getMaskElt(i);
5442     MaskVals.push_back(EltIdx);
5443     if (EltIdx < 0) {
5444       ++Quad[0];
5445       ++Quad[1];
5446       ++Quad[2];
5447       ++Quad[3];
5448       continue;
5449     }
5450     ++Quad[EltIdx / 4];
5451     InputQuads.set(EltIdx / 4);
5452   }
5453
5454   int BestLoQuad = -1;
5455   unsigned MaxQuad = 1;
5456   for (unsigned i = 0; i < 4; ++i) {
5457     if (LoQuad[i] > MaxQuad) {
5458       BestLoQuad = i;
5459       MaxQuad = LoQuad[i];
5460     }
5461   }
5462
5463   int BestHiQuad = -1;
5464   MaxQuad = 1;
5465   for (unsigned i = 0; i < 4; ++i) {
5466     if (HiQuad[i] > MaxQuad) {
5467       BestHiQuad = i;
5468       MaxQuad = HiQuad[i];
5469     }
5470   }
5471
5472   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5473   // of the two input vectors, shuffle them into one input vector so only a
5474   // single pshufb instruction is necessary. If There are more than 2 input
5475   // quads, disable the next transformation since it does not help SSSE3.
5476   bool V1Used = InputQuads[0] || InputQuads[1];
5477   bool V2Used = InputQuads[2] || InputQuads[3];
5478   if (Subtarget->hasSSSE3orAVX()) {
5479     if (InputQuads.count() == 2 && V1Used && V2Used) {
5480       BestLoQuad = InputQuads.find_first();
5481       BestHiQuad = InputQuads.find_next(BestLoQuad);
5482     }
5483     if (InputQuads.count() > 2) {
5484       BestLoQuad = -1;
5485       BestHiQuad = -1;
5486     }
5487   }
5488
5489   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5490   // the shuffle mask.  If a quad is scored as -1, that means that it contains
5491   // words from all 4 input quadwords.
5492   SDValue NewV;
5493   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5494     SmallVector<int, 8> MaskV;
5495     MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
5496     MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
5497     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5498                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5499                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5500     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5501
5502     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5503     // source words for the shuffle, to aid later transformations.
5504     bool AllWordsInNewV = true;
5505     bool InOrder[2] = { true, true };
5506     for (unsigned i = 0; i != 8; ++i) {
5507       int idx = MaskVals[i];
5508       if (idx != (int)i)
5509         InOrder[i/4] = false;
5510       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5511         continue;
5512       AllWordsInNewV = false;
5513       break;
5514     }
5515
5516     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5517     if (AllWordsInNewV) {
5518       for (int i = 0; i != 8; ++i) {
5519         int idx = MaskVals[i];
5520         if (idx < 0)
5521           continue;
5522         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5523         if ((idx != i) && idx < 4)
5524           pshufhw = false;
5525         if ((idx != i) && idx > 3)
5526           pshuflw = false;
5527       }
5528       V1 = NewV;
5529       V2Used = false;
5530       BestLoQuad = 0;
5531       BestHiQuad = 1;
5532     }
5533
5534     // If we've eliminated the use of V2, and the new mask is a pshuflw or
5535     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
5536     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5537       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5538       unsigned TargetMask = 0;
5539       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5540                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5541       TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
5542                              X86::getShufflePSHUFLWImmediate(NewV.getNode());
5543       V1 = NewV.getOperand(0);
5544       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5545     }
5546   }
5547
5548   // If we have SSSE3, and all words of the result are from 1 input vector,
5549   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5550   // is present, fall back to case 4.
5551   if (Subtarget->hasSSSE3orAVX()) {
5552     SmallVector<SDValue,16> pshufbMask;
5553
5554     // If we have elements from both input vectors, set the high bit of the
5555     // shuffle mask element to zero out elements that come from V2 in the V1
5556     // mask, and elements that come from V1 in the V2 mask, so that the two
5557     // results can be OR'd together.
5558     bool TwoInputs = V1Used && V2Used;
5559     for (unsigned i = 0; i != 8; ++i) {
5560       int EltIdx = MaskVals[i] * 2;
5561       if (TwoInputs && (EltIdx >= 16)) {
5562         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5563         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5564         continue;
5565       }
5566       pshufbMask.push_back(DAG.getConstant(EltIdx,   MVT::i8));
5567       pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
5568     }
5569     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5570     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5571                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5572                                  MVT::v16i8, &pshufbMask[0], 16));
5573     if (!TwoInputs)
5574       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5575
5576     // Calculate the shuffle mask for the second input, shuffle it, and
5577     // OR it with the first shuffled input.
5578     pshufbMask.clear();
5579     for (unsigned i = 0; i != 8; ++i) {
5580       int EltIdx = MaskVals[i] * 2;
5581       if (EltIdx < 16) {
5582         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5583         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5584         continue;
5585       }
5586       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5587       pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
5588     }
5589     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5590     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5591                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5592                                  MVT::v16i8, &pshufbMask[0], 16));
5593     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5594     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5595   }
5596
5597   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5598   // and update MaskVals with new element order.
5599   BitVector InOrder(8);
5600   if (BestLoQuad >= 0) {
5601     SmallVector<int, 8> MaskV;
5602     for (int i = 0; i != 4; ++i) {
5603       int idx = MaskVals[i];
5604       if (idx < 0) {
5605         MaskV.push_back(-1);
5606         InOrder.set(i);
5607       } else if ((idx / 4) == BestLoQuad) {
5608         MaskV.push_back(idx & 3);
5609         InOrder.set(i);
5610       } else {
5611         MaskV.push_back(-1);
5612       }
5613     }
5614     for (unsigned i = 4; i != 8; ++i)
5615       MaskV.push_back(i);
5616     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5617                                 &MaskV[0]);
5618
5619     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3orAVX())
5620       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5621                                NewV.getOperand(0),
5622                                X86::getShufflePSHUFLWImmediate(NewV.getNode()),
5623                                DAG);
5624   }
5625
5626   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5627   // and update MaskVals with the new element order.
5628   if (BestHiQuad >= 0) {
5629     SmallVector<int, 8> MaskV;
5630     for (unsigned i = 0; i != 4; ++i)
5631       MaskV.push_back(i);
5632     for (unsigned i = 4; i != 8; ++i) {
5633       int idx = MaskVals[i];
5634       if (idx < 0) {
5635         MaskV.push_back(-1);
5636         InOrder.set(i);
5637       } else if ((idx / 4) == BestHiQuad) {
5638         MaskV.push_back((idx & 3) + 4);
5639         InOrder.set(i);
5640       } else {
5641         MaskV.push_back(-1);
5642       }
5643     }
5644     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5645                                 &MaskV[0]);
5646
5647     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3orAVX())
5648       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5649                               NewV.getOperand(0),
5650                               X86::getShufflePSHUFHWImmediate(NewV.getNode()),
5651                               DAG);
5652   }
5653
5654   // In case BestHi & BestLo were both -1, which means each quadword has a word
5655   // from each of the four input quadwords, calculate the InOrder bitvector now
5656   // before falling through to the insert/extract cleanup.
5657   if (BestLoQuad == -1 && BestHiQuad == -1) {
5658     NewV = V1;
5659     for (int i = 0; i != 8; ++i)
5660       if (MaskVals[i] < 0 || MaskVals[i] == i)
5661         InOrder.set(i);
5662   }
5663
5664   // The other elements are put in the right place using pextrw and pinsrw.
5665   for (unsigned i = 0; i != 8; ++i) {
5666     if (InOrder[i])
5667       continue;
5668     int EltIdx = MaskVals[i];
5669     if (EltIdx < 0)
5670       continue;
5671     SDValue ExtOp = (EltIdx < 8)
5672     ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5673                   DAG.getIntPtrConstant(EltIdx))
5674     : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5675                   DAG.getIntPtrConstant(EltIdx - 8));
5676     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5677                        DAG.getIntPtrConstant(i));
5678   }
5679   return NewV;
5680 }
5681
5682 // v16i8 shuffles - Prefer shuffles in the following order:
5683 // 1. [ssse3] 1 x pshufb
5684 // 2. [ssse3] 2 x pshufb + 1 x por
5685 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
5686 static
5687 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5688                                  SelectionDAG &DAG,
5689                                  const X86TargetLowering &TLI) {
5690   SDValue V1 = SVOp->getOperand(0);
5691   SDValue V2 = SVOp->getOperand(1);
5692   DebugLoc dl = SVOp->getDebugLoc();
5693   SmallVector<int, 16> MaskVals;
5694   SVOp->getMask(MaskVals);
5695
5696   // If we have SSSE3, case 1 is generated when all result bytes come from
5697   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
5698   // present, fall back to case 3.
5699   // FIXME: kill V2Only once shuffles are canonizalized by getNode.
5700   bool V1Only = true;
5701   bool V2Only = true;
5702   for (unsigned i = 0; i < 16; ++i) {
5703     int EltIdx = MaskVals[i];
5704     if (EltIdx < 0)
5705       continue;
5706     if (EltIdx < 16)
5707       V2Only = false;
5708     else
5709       V1Only = false;
5710   }
5711
5712   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5713   if (TLI.getSubtarget()->hasSSSE3orAVX()) {
5714     SmallVector<SDValue,16> pshufbMask;
5715
5716     // If all result elements are from one input vector, then only translate
5717     // undef mask values to 0x80 (zero out result) in the pshufb mask.
5718     //
5719     // Otherwise, we have elements from both input vectors, and must zero out
5720     // elements that come from V2 in the first mask, and V1 in the second mask
5721     // so that we can OR them together.
5722     bool TwoInputs = !(V1Only || V2Only);
5723     for (unsigned i = 0; i != 16; ++i) {
5724       int EltIdx = MaskVals[i];
5725       if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
5726         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5727         continue;
5728       }
5729       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5730     }
5731     // If all the elements are from V2, assign it to V1 and return after
5732     // building the first pshufb.
5733     if (V2Only)
5734       V1 = V2;
5735     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5736                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5737                                  MVT::v16i8, &pshufbMask[0], 16));
5738     if (!TwoInputs)
5739       return V1;
5740
5741     // Calculate the shuffle mask for the second input, shuffle it, and
5742     // OR it with the first shuffled input.
5743     pshufbMask.clear();
5744     for (unsigned i = 0; i != 16; ++i) {
5745       int EltIdx = MaskVals[i];
5746       if (EltIdx < 16) {
5747         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5748         continue;
5749       }
5750       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5751     }
5752     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5753                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5754                                  MVT::v16i8, &pshufbMask[0], 16));
5755     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5756   }
5757
5758   // No SSSE3 - Calculate in place words and then fix all out of place words
5759   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
5760   // the 16 different words that comprise the two doublequadword input vectors.
5761   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5762   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5763   SDValue NewV = V2Only ? V2 : V1;
5764   for (int i = 0; i != 8; ++i) {
5765     int Elt0 = MaskVals[i*2];
5766     int Elt1 = MaskVals[i*2+1];
5767
5768     // This word of the result is all undef, skip it.
5769     if (Elt0 < 0 && Elt1 < 0)
5770       continue;
5771
5772     // This word of the result is already in the correct place, skip it.
5773     if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
5774       continue;
5775     if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
5776       continue;
5777
5778     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5779     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5780     SDValue InsElt;
5781
5782     // If Elt0 and Elt1 are defined, are consecutive, and can be load
5783     // using a single extract together, load it and store it.
5784     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5785       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5786                            DAG.getIntPtrConstant(Elt1 / 2));
5787       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5788                         DAG.getIntPtrConstant(i));
5789       continue;
5790     }
5791
5792     // If Elt1 is defined, extract it from the appropriate source.  If the
5793     // source byte is not also odd, shift the extracted word left 8 bits
5794     // otherwise clear the bottom 8 bits if we need to do an or.
5795     if (Elt1 >= 0) {
5796       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5797                            DAG.getIntPtrConstant(Elt1 / 2));
5798       if ((Elt1 & 1) == 0)
5799         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5800                              DAG.getConstant(8,
5801                                   TLI.getShiftAmountTy(InsElt.getValueType())));
5802       else if (Elt0 >= 0)
5803         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5804                              DAG.getConstant(0xFF00, MVT::i16));
5805     }
5806     // If Elt0 is defined, extract it from the appropriate source.  If the
5807     // source byte is not also even, shift the extracted word right 8 bits. If
5808     // Elt1 was also defined, OR the extracted values together before
5809     // inserting them in the result.
5810     if (Elt0 >= 0) {
5811       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5812                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5813       if ((Elt0 & 1) != 0)
5814         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5815                               DAG.getConstant(8,
5816                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
5817       else if (Elt1 >= 0)
5818         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5819                              DAG.getConstant(0x00FF, MVT::i16));
5820       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5821                          : InsElt0;
5822     }
5823     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5824                        DAG.getIntPtrConstant(i));
5825   }
5826   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5827 }
5828
5829 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5830 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5831 /// done when every pair / quad of shuffle mask elements point to elements in
5832 /// the right sequence. e.g.
5833 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5834 static
5835 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5836                                  SelectionDAG &DAG, DebugLoc dl) {
5837   EVT VT = SVOp->getValueType(0);
5838   SDValue V1 = SVOp->getOperand(0);
5839   SDValue V2 = SVOp->getOperand(1);
5840   unsigned NumElems = VT.getVectorNumElements();
5841   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
5842   EVT NewVT;
5843   switch (VT.getSimpleVT().SimpleTy) {
5844   default: assert(false && "Unexpected!");
5845   case MVT::v4f32: NewVT = MVT::v2f64; break;
5846   case MVT::v4i32: NewVT = MVT::v2i64; break;
5847   case MVT::v8i16: NewVT = MVT::v4i32; break;
5848   case MVT::v16i8: NewVT = MVT::v4i32; break;
5849   }
5850
5851   int Scale = NumElems / NewWidth;
5852   SmallVector<int, 8> MaskVec;
5853   for (unsigned i = 0; i < NumElems; i += Scale) {
5854     int StartIdx = -1;
5855     for (int j = 0; j < Scale; ++j) {
5856       int EltIdx = SVOp->getMaskElt(i+j);
5857       if (EltIdx < 0)
5858         continue;
5859       if (StartIdx == -1)
5860         StartIdx = EltIdx - (EltIdx % Scale);
5861       if (EltIdx != StartIdx + j)
5862         return SDValue();
5863     }
5864     if (StartIdx == -1)
5865       MaskVec.push_back(-1);
5866     else
5867       MaskVec.push_back(StartIdx / Scale);
5868   }
5869
5870   V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
5871   V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
5872   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5873 }
5874
5875 /// getVZextMovL - Return a zero-extending vector move low node.
5876 ///
5877 static SDValue getVZextMovL(EVT VT, EVT OpVT,
5878                             SDValue SrcOp, SelectionDAG &DAG,
5879                             const X86Subtarget *Subtarget, DebugLoc dl) {
5880   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
5881     LoadSDNode *LD = NULL;
5882     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
5883       LD = dyn_cast<LoadSDNode>(SrcOp);
5884     if (!LD) {
5885       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
5886       // instead.
5887       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
5888       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
5889           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5890           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
5891           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
5892         // PR2108
5893         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
5894         return DAG.getNode(ISD::BITCAST, dl, VT,
5895                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5896                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5897                                                    OpVT,
5898                                                    SrcOp.getOperand(0)
5899                                                           .getOperand(0))));
5900       }
5901     }
5902   }
5903
5904   return DAG.getNode(ISD::BITCAST, dl, VT,
5905                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5906                                  DAG.getNode(ISD::BITCAST, dl,
5907                                              OpVT, SrcOp)));
5908 }
5909
5910 /// areShuffleHalvesWithinDisjointLanes - Check whether each half of a vector
5911 /// shuffle node referes to only one lane in the sources.
5912 static bool areShuffleHalvesWithinDisjointLanes(ShuffleVectorSDNode *SVOp) {
5913   EVT VT = SVOp->getValueType(0);
5914   int NumElems = VT.getVectorNumElements();
5915   int HalfSize = NumElems/2;
5916   SmallVector<int, 16> M;
5917   SVOp->getMask(M);
5918   bool MatchA = false, MatchB = false;
5919
5920   for (int l = 0; l < NumElems*2; l += HalfSize) {
5921     if (isUndefOrInRange(M, 0, HalfSize, l, l+HalfSize)) {
5922       MatchA = true;
5923       break;
5924     }
5925   }
5926
5927   for (int l = 0; l < NumElems*2; l += HalfSize) {
5928     if (isUndefOrInRange(M, HalfSize, HalfSize, l, l+HalfSize)) {
5929       MatchB = true;
5930       break;
5931     }
5932   }
5933
5934   return MatchA && MatchB;
5935 }
5936
5937 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
5938 /// which could not be matched by any known target speficic shuffle
5939 static SDValue
5940 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5941   if (areShuffleHalvesWithinDisjointLanes(SVOp)) {
5942     // If each half of a vector shuffle node referes to only one lane in the
5943     // source vectors, extract each used 128-bit lane and shuffle them using
5944     // 128-bit shuffles. Then, concatenate the results. Otherwise leave
5945     // the work to the legalizer.
5946     DebugLoc dl = SVOp->getDebugLoc();
5947     EVT VT = SVOp->getValueType(0);
5948     int NumElems = VT.getVectorNumElements();
5949     int HalfSize = NumElems/2;
5950
5951     // Extract the reference for each half
5952     int FstVecExtractIdx = 0, SndVecExtractIdx = 0;
5953     int FstVecOpNum = 0, SndVecOpNum = 0;
5954     for (int i = 0; i < HalfSize; ++i) {
5955       int Elt = SVOp->getMaskElt(i);
5956       if (SVOp->getMaskElt(i) < 0)
5957         continue;
5958       FstVecOpNum = Elt/NumElems;
5959       FstVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize;
5960       break;
5961     }
5962     for (int i = HalfSize; i < NumElems; ++i) {
5963       int Elt = SVOp->getMaskElt(i);
5964       if (SVOp->getMaskElt(i) < 0)
5965         continue;
5966       SndVecOpNum = Elt/NumElems;
5967       SndVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize;
5968       break;
5969     }
5970
5971     // Extract the subvectors
5972     SDValue V1 = Extract128BitVector(SVOp->getOperand(FstVecOpNum),
5973                       DAG.getConstant(FstVecExtractIdx, MVT::i32), DAG, dl);
5974     SDValue V2 = Extract128BitVector(SVOp->getOperand(SndVecOpNum),
5975                       DAG.getConstant(SndVecExtractIdx, MVT::i32), DAG, dl);
5976
5977     // Generate 128-bit shuffles
5978     SmallVector<int, 16> MaskV1, MaskV2;
5979     for (int i = 0; i < HalfSize; ++i) {
5980       int Elt = SVOp->getMaskElt(i);
5981       MaskV1.push_back(Elt < 0 ? Elt : Elt % HalfSize);
5982     }
5983     for (int i = HalfSize; i < NumElems; ++i) {
5984       int Elt = SVOp->getMaskElt(i);
5985       MaskV2.push_back(Elt < 0 ? Elt : Elt % HalfSize);
5986     }
5987
5988     EVT NVT = V1.getValueType();
5989     V1 = DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &MaskV1[0]);
5990     V2 = DAG.getVectorShuffle(NVT, dl, V2, DAG.getUNDEF(NVT), &MaskV2[0]);
5991
5992     // Concatenate the result back
5993     SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), V1,
5994                                    DAG.getConstant(0, MVT::i32), DAG, dl);
5995     return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32),
5996                               DAG, dl);
5997   }
5998
5999   return SDValue();
6000 }
6001
6002 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6003 /// 4 elements, and match them with several different shuffle types.
6004 static SDValue
6005 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6006   SDValue V1 = SVOp->getOperand(0);
6007   SDValue V2 = SVOp->getOperand(1);
6008   DebugLoc dl = SVOp->getDebugLoc();
6009   EVT VT = SVOp->getValueType(0);
6010
6011   assert(VT.getSizeInBits() == 128 && "Unsupported vector size");
6012
6013   SmallVector<std::pair<int, int>, 8> Locs;
6014   Locs.resize(4);
6015   SmallVector<int, 8> Mask1(4U, -1);
6016   SmallVector<int, 8> PermMask;
6017   SVOp->getMask(PermMask);
6018
6019   unsigned NumHi = 0;
6020   unsigned NumLo = 0;
6021   for (unsigned i = 0; i != 4; ++i) {
6022     int Idx = PermMask[i];
6023     if (Idx < 0) {
6024       Locs[i] = std::make_pair(-1, -1);
6025     } else {
6026       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6027       if (Idx < 4) {
6028         Locs[i] = std::make_pair(0, NumLo);
6029         Mask1[NumLo] = Idx;
6030         NumLo++;
6031       } else {
6032         Locs[i] = std::make_pair(1, NumHi);
6033         if (2+NumHi < 4)
6034           Mask1[2+NumHi] = Idx;
6035         NumHi++;
6036       }
6037     }
6038   }
6039
6040   if (NumLo <= 2 && NumHi <= 2) {
6041     // If no more than two elements come from either vector. This can be
6042     // implemented with two shuffles. First shuffle gather the elements.
6043     // The second shuffle, which takes the first shuffle as both of its
6044     // vector operands, put the elements into the right order.
6045     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6046
6047     SmallVector<int, 8> Mask2(4U, -1);
6048
6049     for (unsigned i = 0; i != 4; ++i) {
6050       if (Locs[i].first == -1)
6051         continue;
6052       else {
6053         unsigned Idx = (i < 2) ? 0 : 4;
6054         Idx += Locs[i].first * 2 + Locs[i].second;
6055         Mask2[i] = Idx;
6056       }
6057     }
6058
6059     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6060   } else if (NumLo == 3 || NumHi == 3) {
6061     // Otherwise, we must have three elements from one vector, call it X, and
6062     // one element from the other, call it Y.  First, use a shufps to build an
6063     // intermediate vector with the one element from Y and the element from X
6064     // that will be in the same half in the final destination (the indexes don't
6065     // matter). Then, use a shufps to build the final vector, taking the half
6066     // containing the element from Y from the intermediate, and the other half
6067     // from X.
6068     if (NumHi == 3) {
6069       // Normalize it so the 3 elements come from V1.
6070       CommuteVectorShuffleMask(PermMask, 4);
6071       std::swap(V1, V2);
6072     }
6073
6074     // Find the element from V2.
6075     unsigned HiIndex;
6076     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6077       int Val = PermMask[HiIndex];
6078       if (Val < 0)
6079         continue;
6080       if (Val >= 4)
6081         break;
6082     }
6083
6084     Mask1[0] = PermMask[HiIndex];
6085     Mask1[1] = -1;
6086     Mask1[2] = PermMask[HiIndex^1];
6087     Mask1[3] = -1;
6088     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6089
6090     if (HiIndex >= 2) {
6091       Mask1[0] = PermMask[0];
6092       Mask1[1] = PermMask[1];
6093       Mask1[2] = HiIndex & 1 ? 6 : 4;
6094       Mask1[3] = HiIndex & 1 ? 4 : 6;
6095       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6096     } else {
6097       Mask1[0] = HiIndex & 1 ? 2 : 0;
6098       Mask1[1] = HiIndex & 1 ? 0 : 2;
6099       Mask1[2] = PermMask[2];
6100       Mask1[3] = PermMask[3];
6101       if (Mask1[2] >= 0)
6102         Mask1[2] += 4;
6103       if (Mask1[3] >= 0)
6104         Mask1[3] += 4;
6105       return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6106     }
6107   }
6108
6109   // Break it into (shuffle shuffle_hi, shuffle_lo).
6110   Locs.clear();
6111   Locs.resize(4);
6112   SmallVector<int,8> LoMask(4U, -1);
6113   SmallVector<int,8> HiMask(4U, -1);
6114
6115   SmallVector<int,8> *MaskPtr = &LoMask;
6116   unsigned MaskIdx = 0;
6117   unsigned LoIdx = 0;
6118   unsigned HiIdx = 2;
6119   for (unsigned i = 0; i != 4; ++i) {
6120     if (i == 2) {
6121       MaskPtr = &HiMask;
6122       MaskIdx = 1;
6123       LoIdx = 0;
6124       HiIdx = 2;
6125     }
6126     int Idx = PermMask[i];
6127     if (Idx < 0) {
6128       Locs[i] = std::make_pair(-1, -1);
6129     } else if (Idx < 4) {
6130       Locs[i] = std::make_pair(MaskIdx, LoIdx);
6131       (*MaskPtr)[LoIdx] = Idx;
6132       LoIdx++;
6133     } else {
6134       Locs[i] = std::make_pair(MaskIdx, HiIdx);
6135       (*MaskPtr)[HiIdx] = Idx;
6136       HiIdx++;
6137     }
6138   }
6139
6140   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6141   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6142   SmallVector<int, 8> MaskOps;
6143   for (unsigned i = 0; i != 4; ++i) {
6144     if (Locs[i].first == -1) {
6145       MaskOps.push_back(-1);
6146     } else {
6147       unsigned Idx = Locs[i].first * 4 + Locs[i].second;
6148       MaskOps.push_back(Idx);
6149     }
6150   }
6151   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6152 }
6153
6154 static bool MayFoldVectorLoad(SDValue V) {
6155   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6156     V = V.getOperand(0);
6157   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6158     V = V.getOperand(0);
6159   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6160       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6161     // BUILD_VECTOR (load), undef
6162     V = V.getOperand(0);
6163   if (MayFoldLoad(V))
6164     return true;
6165   return false;
6166 }
6167
6168 // FIXME: the version above should always be used. Since there's
6169 // a bug where several vector shuffles can't be folded because the
6170 // DAG is not updated during lowering and a node claims to have two
6171 // uses while it only has one, use this version, and let isel match
6172 // another instruction if the load really happens to have more than
6173 // one use. Remove this version after this bug get fixed.
6174 // rdar://8434668, PR8156
6175 static bool RelaxedMayFoldVectorLoad(SDValue V) {
6176   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6177     V = V.getOperand(0);
6178   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6179     V = V.getOperand(0);
6180   if (ISD::isNormalLoad(V.getNode()))
6181     return true;
6182   return false;
6183 }
6184
6185 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
6186 /// a vector extract, and if both can be later optimized into a single load.
6187 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
6188 /// here because otherwise a target specific shuffle node is going to be
6189 /// emitted for this shuffle, and the optimization not done.
6190 /// FIXME: This is probably not the best approach, but fix the problem
6191 /// until the right path is decided.
6192 static
6193 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
6194                                          const TargetLowering &TLI) {
6195   EVT VT = V.getValueType();
6196   ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
6197
6198   // Be sure that the vector shuffle is present in a pattern like this:
6199   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
6200   if (!V.hasOneUse())
6201     return false;
6202
6203   SDNode *N = *V.getNode()->use_begin();
6204   if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
6205     return false;
6206
6207   SDValue EltNo = N->getOperand(1);
6208   if (!isa<ConstantSDNode>(EltNo))
6209     return false;
6210
6211   // If the bit convert changed the number of elements, it is unsafe
6212   // to examine the mask.
6213   bool HasShuffleIntoBitcast = false;
6214   if (V.getOpcode() == ISD::BITCAST) {
6215     EVT SrcVT = V.getOperand(0).getValueType();
6216     if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
6217       return false;
6218     V = V.getOperand(0);
6219     HasShuffleIntoBitcast = true;
6220   }
6221
6222   // Select the input vector, guarding against out of range extract vector.
6223   unsigned NumElems = VT.getVectorNumElements();
6224   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6225   int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
6226   V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
6227
6228   // Skip one more bit_convert if necessary
6229   if (V.getOpcode() == ISD::BITCAST)
6230     V = V.getOperand(0);
6231
6232   if (ISD::isNormalLoad(V.getNode())) {
6233     // Is the original load suitable?
6234     LoadSDNode *LN0 = cast<LoadSDNode>(V);
6235
6236     // FIXME: avoid the multi-use bug that is preventing lots of
6237     // of foldings to be detected, this is still wrong of course, but
6238     // give the temporary desired behavior, and if it happens that
6239     // the load has real more uses, during isel it will not fold, and
6240     // will generate poor code.
6241     if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
6242       return false;
6243
6244     if (!HasShuffleIntoBitcast)
6245       return true;
6246
6247     // If there's a bitcast before the shuffle, check if the load type and
6248     // alignment is valid.
6249     unsigned Align = LN0->getAlignment();
6250     unsigned NewAlign =
6251       TLI.getTargetData()->getABITypeAlignment(
6252                                     VT.getTypeForEVT(*DAG.getContext()));
6253
6254     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
6255       return false;
6256   }
6257
6258   return true;
6259 }
6260
6261 static
6262 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6263   EVT VT = Op.getValueType();
6264
6265   // Canonizalize to v2f64.
6266   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6267   return DAG.getNode(ISD::BITCAST, dl, VT,
6268                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6269                                           V1, DAG));
6270 }
6271
6272 static
6273 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6274                         bool HasXMMInt) {
6275   SDValue V1 = Op.getOperand(0);
6276   SDValue V2 = Op.getOperand(1);
6277   EVT VT = Op.getValueType();
6278
6279   assert(VT != MVT::v2i64 && "unsupported shuffle type");
6280
6281   if (HasXMMInt && VT == MVT::v2f64)
6282     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6283
6284   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6285   return DAG.getNode(ISD::BITCAST, dl, VT,
6286                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6287                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6288                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6289 }
6290
6291 static
6292 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6293   SDValue V1 = Op.getOperand(0);
6294   SDValue V2 = Op.getOperand(1);
6295   EVT VT = Op.getValueType();
6296
6297   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6298          "unsupported shuffle type");
6299
6300   if (V2.getOpcode() == ISD::UNDEF)
6301     V2 = V1;
6302
6303   // v4i32 or v4f32
6304   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6305 }
6306
6307 static inline unsigned getSHUFPOpcode(EVT VT) {
6308   switch(VT.getSimpleVT().SimpleTy) {
6309   case MVT::v8i32: // Use fp unit for int unpack.
6310   case MVT::v8f32:
6311   case MVT::v4i32: // Use fp unit for int unpack.
6312   case MVT::v4f32: return X86ISD::SHUFPS;
6313   case MVT::v4i64: // Use fp unit for int unpack.
6314   case MVT::v4f64:
6315   case MVT::v2i64: // Use fp unit for int unpack.
6316   case MVT::v2f64: return X86ISD::SHUFPD;
6317   default:
6318     llvm_unreachable("Unknown type for shufp*");
6319   }
6320   return 0;
6321 }
6322
6323 static
6324 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasXMMInt) {
6325   SDValue V1 = Op.getOperand(0);
6326   SDValue V2 = Op.getOperand(1);
6327   EVT VT = Op.getValueType();
6328   unsigned NumElems = VT.getVectorNumElements();
6329
6330   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6331   // operand of these instructions is only memory, so check if there's a
6332   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6333   // same masks.
6334   bool CanFoldLoad = false;
6335
6336   // Trivial case, when V2 comes from a load.
6337   if (MayFoldVectorLoad(V2))
6338     CanFoldLoad = true;
6339
6340   // When V1 is a load, it can be folded later into a store in isel, example:
6341   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6342   //    turns into:
6343   //  (MOVLPSmr addr:$src1, VR128:$src2)
6344   // So, recognize this potential and also use MOVLPS or MOVLPD
6345   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6346     CanFoldLoad = true;
6347
6348   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6349   if (CanFoldLoad) {
6350     if (HasXMMInt && NumElems == 2)
6351       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6352
6353     if (NumElems == 4)
6354       // If we don't care about the second element, procede to use movss.
6355       if (SVOp->getMaskElt(1) != -1)
6356         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6357   }
6358
6359   // movl and movlp will both match v2i64, but v2i64 is never matched by
6360   // movl earlier because we make it strict to avoid messing with the movlp load
6361   // folding logic (see the code above getMOVLP call). Match it here then,
6362   // this is horrible, but will stay like this until we move all shuffle
6363   // matching to x86 specific nodes. Note that for the 1st condition all
6364   // types are matched with movsd.
6365   if (HasXMMInt) {
6366     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6367     // as to remove this logic from here, as much as possible
6368     if (NumElems == 2 || !X86::isMOVLMask(SVOp))
6369       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6370     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6371   }
6372
6373   assert(VT != MVT::v4i32 && "unsupported shuffle type");
6374
6375   // Invert the operand order and use SHUFPS to match it.
6376   return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V2, V1,
6377                               X86::getShuffleSHUFImmediate(SVOp), DAG);
6378 }
6379
6380 static
6381 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
6382                                const TargetLowering &TLI,
6383                                const X86Subtarget *Subtarget) {
6384   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6385   EVT VT = Op.getValueType();
6386   DebugLoc dl = Op.getDebugLoc();
6387   SDValue V1 = Op.getOperand(0);
6388   SDValue V2 = Op.getOperand(1);
6389
6390   if (isZeroShuffle(SVOp))
6391     return getZeroVector(VT, Subtarget->hasXMMInt(), DAG, dl);
6392
6393   // Handle splat operations
6394   if (SVOp->isSplat()) {
6395     unsigned NumElem = VT.getVectorNumElements();
6396     int Size = VT.getSizeInBits();
6397     // Special case, this is the only place now where it's allowed to return
6398     // a vector_shuffle operation without using a target specific node, because
6399     // *hopefully* it will be optimized away by the dag combiner. FIXME: should
6400     // this be moved to DAGCombine instead?
6401     if (NumElem <= 4 && CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
6402       return Op;
6403
6404     // Use vbroadcast whenever the splat comes from a foldable load
6405     SDValue LD = isVectorBroadcast(Op, Subtarget->hasAVX2());
6406     if (Subtarget->hasAVX() && LD.getNode())
6407       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, LD);
6408
6409     // Handle splats by matching through known shuffle masks
6410     if ((Size == 128 && NumElem <= 4) ||
6411         (Size == 256 && NumElem < 8))
6412       return SDValue();
6413
6414     // All remaning splats are promoted to target supported vector shuffles.
6415     return PromoteSplat(SVOp, DAG);
6416   }
6417
6418   // If the shuffle can be profitably rewritten as a narrower shuffle, then
6419   // do it!
6420   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
6421     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6422     if (NewOp.getNode())
6423       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6424   } else if ((VT == MVT::v4i32 ||
6425              (VT == MVT::v4f32 && Subtarget->hasXMMInt()))) {
6426     // FIXME: Figure out a cleaner way to do this.
6427     // Try to make use of movq to zero out the top part.
6428     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6429       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6430       if (NewOp.getNode()) {
6431         if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
6432           return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
6433                               DAG, Subtarget, dl);
6434       }
6435     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6436       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6437       if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
6438         return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
6439                             DAG, Subtarget, dl);
6440     }
6441   }
6442   return SDValue();
6443 }
6444
6445 SDValue
6446 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6447   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6448   SDValue V1 = Op.getOperand(0);
6449   SDValue V2 = Op.getOperand(1);
6450   EVT VT = Op.getValueType();
6451   DebugLoc dl = Op.getDebugLoc();
6452   unsigned NumElems = VT.getVectorNumElements();
6453   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6454   bool V1IsSplat = false;
6455   bool V2IsSplat = false;
6456   bool HasXMMInt = Subtarget->hasXMMInt();
6457   bool HasAVX    = Subtarget->hasAVX();
6458   bool HasAVX2   = Subtarget->hasAVX2();
6459   MachineFunction &MF = DAG.getMachineFunction();
6460   bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
6461
6462   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6463
6464   assert(V1.getOpcode() != ISD::UNDEF && "Op 1 of shuffle should not be undef");
6465
6466   // Vector shuffle lowering takes 3 steps:
6467   //
6468   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6469   //    narrowing and commutation of operands should be handled.
6470   // 2) Matching of shuffles with known shuffle masks to x86 target specific
6471   //    shuffle nodes.
6472   // 3) Rewriting of unmatched masks into new generic shuffle operations,
6473   //    so the shuffle can be broken into other shuffles and the legalizer can
6474   //    try the lowering again.
6475   //
6476   // The general idea is that no vector_shuffle operation should be left to
6477   // be matched during isel, all of them must be converted to a target specific
6478   // node here.
6479
6480   // Normalize the input vectors. Here splats, zeroed vectors, profitable
6481   // narrowing and commutation of operands should be handled. The actual code
6482   // doesn't include all of those, work in progress...
6483   SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
6484   if (NewOp.getNode())
6485     return NewOp;
6486
6487   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6488   // unpckh_undef). Only use pshufd if speed is more important than size.
6489   if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp, HasAVX2))
6490     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6491   if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp, HasAVX2))
6492     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6493
6494   if (X86::isMOVDDUPMask(SVOp) && Subtarget->hasSSE3orAVX() &&
6495       V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6496     return getMOVDDup(Op, dl, V1, DAG);
6497
6498   if (X86::isMOVHLPS_v_undef_Mask(SVOp))
6499     return getMOVHighToLow(Op, dl, DAG);
6500
6501   // Use to match splats
6502   if (HasXMMInt && X86::isUNPCKHMask(SVOp, HasAVX2) && V2IsUndef &&
6503       (VT == MVT::v2f64 || VT == MVT::v2i64))
6504     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6505
6506   if (X86::isPSHUFDMask(SVOp)) {
6507     // The actual implementation will match the mask in the if above and then
6508     // during isel it can match several different instructions, not only pshufd
6509     // as its name says, sad but true, emulate the behavior for now...
6510     if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6511         return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6512
6513     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
6514
6515     if (HasXMMInt && (VT == MVT::v4f32 || VT == MVT::v4i32))
6516       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6517
6518     return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V1,
6519                                 TargetMask, DAG);
6520   }
6521
6522   // Check if this can be converted into a logical shift.
6523   bool isLeft = false;
6524   unsigned ShAmt = 0;
6525   SDValue ShVal;
6526   bool isShift = HasXMMInt && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6527   if (isShift && ShVal.hasOneUse()) {
6528     // If the shifted value has multiple uses, it may be cheaper to use
6529     // v_set0 + movlhps or movhlps, etc.
6530     EVT EltVT = VT.getVectorElementType();
6531     ShAmt *= EltVT.getSizeInBits();
6532     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6533   }
6534
6535   if (X86::isMOVLMask(SVOp)) {
6536     if (ISD::isBuildVectorAllZeros(V1.getNode()))
6537       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6538     if (!X86::isMOVLPMask(SVOp)) {
6539       if (HasXMMInt && (VT == MVT::v2i64 || VT == MVT::v2f64))
6540         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6541
6542       if (VT == MVT::v4i32 || VT == MVT::v4f32)
6543         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6544     }
6545   }
6546
6547   // FIXME: fold these into legal mask.
6548   if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp, HasAVX2))
6549     return getMOVLowToHigh(Op, dl, DAG, HasXMMInt);
6550
6551   if (X86::isMOVHLPSMask(SVOp))
6552     return getMOVHighToLow(Op, dl, DAG);
6553
6554   if (X86::isMOVSHDUPMask(SVOp, Subtarget))
6555     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6556
6557   if (X86::isMOVSLDUPMask(SVOp, Subtarget))
6558     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6559
6560   if (X86::isMOVLPMask(SVOp))
6561     return getMOVLP(Op, dl, DAG, HasXMMInt);
6562
6563   if (ShouldXformToMOVHLPS(SVOp) ||
6564       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
6565     return CommuteVectorShuffle(SVOp, DAG);
6566
6567   if (isShift) {
6568     // No better options. Use a vshl / vsrl.
6569     EVT EltVT = VT.getVectorElementType();
6570     ShAmt *= EltVT.getSizeInBits();
6571     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6572   }
6573
6574   bool Commuted = false;
6575   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
6576   // 1,1,1,1 -> v8i16 though.
6577   V1IsSplat = isSplatVector(V1.getNode());
6578   V2IsSplat = isSplatVector(V2.getNode());
6579
6580   // Canonicalize the splat or undef, if present, to be on the RHS.
6581   if (V1IsSplat && !V2IsSplat) {
6582     Op = CommuteVectorShuffle(SVOp, DAG);
6583     SVOp = cast<ShuffleVectorSDNode>(Op);
6584     V1 = SVOp->getOperand(0);
6585     V2 = SVOp->getOperand(1);
6586     std::swap(V1IsSplat, V2IsSplat);
6587     Commuted = true;
6588   }
6589
6590   SmallVector<int, 32> M;
6591   SVOp->getMask(M);
6592
6593   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6594     // Shuffling low element of v1 into undef, just return v1.
6595     if (V2IsUndef)
6596       return V1;
6597     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6598     // the instruction selector will not match, so get a canonical MOVL with
6599     // swapped operands to undo the commute.
6600     return getMOVL(DAG, dl, VT, V2, V1);
6601   }
6602
6603   if (isUNPCKLMask(M, VT, HasAVX2))
6604     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6605
6606   if (isUNPCKHMask(M, VT, HasAVX2))
6607     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6608
6609   if (V2IsSplat) {
6610     // Normalize mask so all entries that point to V2 points to its first
6611     // element then try to match unpck{h|l} again. If match, return a
6612     // new vector_shuffle with the corrected mask.
6613     SDValue NewMask = NormalizeMask(SVOp, DAG);
6614     ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
6615     if (NSVOp != SVOp) {
6616       if (X86::isUNPCKLMask(NSVOp, HasAVX2, true)) {
6617         return NewMask;
6618       } else if (X86::isUNPCKHMask(NSVOp, HasAVX2, true)) {
6619         return NewMask;
6620       }
6621     }
6622   }
6623
6624   if (Commuted) {
6625     // Commute is back and try unpck* again.
6626     // FIXME: this seems wrong.
6627     SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
6628     ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
6629
6630     if (X86::isUNPCKLMask(NewSVOp, HasAVX2))
6631       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V2, V1, DAG);
6632
6633     if (X86::isUNPCKHMask(NewSVOp, HasAVX2))
6634       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V2, V1, DAG);
6635   }
6636
6637   // Normalize the node to match x86 shuffle ops if needed
6638   if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true) ||
6639                      isVSHUFPYMask(M, VT, HasAVX, /* Commuted */ true)))
6640     return CommuteVectorShuffle(SVOp, DAG);
6641
6642   // The checks below are all present in isShuffleMaskLegal, but they are
6643   // inlined here right now to enable us to directly emit target specific
6644   // nodes, and remove one by one until they don't return Op anymore.
6645
6646   if (isPALIGNRMask(M, VT, Subtarget->hasSSSE3orAVX()))
6647     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6648                                 getShufflePALIGNRImmediate(SVOp),
6649                                 DAG);
6650
6651   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6652       SVOp->getSplatIndex() == 0 && V2IsUndef) {
6653     if (VT == MVT::v2f64 || VT == MVT::v2i64)
6654       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6655   }
6656
6657   if (isPSHUFHWMask(M, VT))
6658     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6659                                 X86::getShufflePSHUFHWImmediate(SVOp),
6660                                 DAG);
6661
6662   if (isPSHUFLWMask(M, VT))
6663     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6664                                 X86::getShufflePSHUFLWImmediate(SVOp),
6665                                 DAG);
6666
6667   if (isSHUFPMask(M, VT))
6668     return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6669                                 X86::getShuffleSHUFImmediate(SVOp), DAG);
6670
6671   if (isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6672     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6673   if (isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6674     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6675
6676   //===--------------------------------------------------------------------===//
6677   // Generate target specific nodes for 128 or 256-bit shuffles only
6678   // supported in the AVX instruction set.
6679   //
6680
6681   // Handle VMOVDDUPY permutations
6682   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasAVX))
6683     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6684
6685   // Handle VPERMILPS/D* permutations
6686   if (isVPERMILPMask(M, VT, HasAVX))
6687     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
6688                                 getShuffleVPERMILPImmediate(SVOp), DAG);
6689
6690   // Handle VPERM2F128/VPERM2I128 permutations
6691   if (isVPERM2X128Mask(M, VT, HasAVX))
6692     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
6693                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
6694
6695   // Handle VSHUFPS/DY permutations
6696   if (isVSHUFPYMask(M, VT, HasAVX))
6697     return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6698                                 getShuffleVSHUFPYImmediate(SVOp), DAG);
6699
6700   //===--------------------------------------------------------------------===//
6701   // Since no target specific shuffle was selected for this generic one,
6702   // lower it into other known shuffles. FIXME: this isn't true yet, but
6703   // this is the plan.
6704   //
6705
6706   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6707   if (VT == MVT::v8i16) {
6708     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
6709     if (NewOp.getNode())
6710       return NewOp;
6711   }
6712
6713   if (VT == MVT::v16i8) {
6714     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6715     if (NewOp.getNode())
6716       return NewOp;
6717   }
6718
6719   // Handle all 128-bit wide vectors with 4 elements, and match them with
6720   // several different shuffle types.
6721   if (NumElems == 4 && VT.getSizeInBits() == 128)
6722     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6723
6724   // Handle general 256-bit shuffles
6725   if (VT.is256BitVector())
6726     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6727
6728   return SDValue();
6729 }
6730
6731 SDValue
6732 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6733                                                 SelectionDAG &DAG) const {
6734   EVT VT = Op.getValueType();
6735   DebugLoc dl = Op.getDebugLoc();
6736
6737   if (Op.getOperand(0).getValueType().getSizeInBits() != 128)
6738     return SDValue();
6739
6740   if (VT.getSizeInBits() == 8) {
6741     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6742                                     Op.getOperand(0), Op.getOperand(1));
6743     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6744                                     DAG.getValueType(VT));
6745     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6746   } else if (VT.getSizeInBits() == 16) {
6747     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6748     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6749     if (Idx == 0)
6750       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6751                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6752                                      DAG.getNode(ISD::BITCAST, dl,
6753                                                  MVT::v4i32,
6754                                                  Op.getOperand(0)),
6755                                      Op.getOperand(1)));
6756     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6757                                     Op.getOperand(0), Op.getOperand(1));
6758     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6759                                     DAG.getValueType(VT));
6760     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6761   } else if (VT == MVT::f32) {
6762     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6763     // the result back to FR32 register. It's only worth matching if the
6764     // result has a single use which is a store or a bitcast to i32.  And in
6765     // the case of a store, it's not worth it if the index is a constant 0,
6766     // because a MOVSSmr can be used instead, which is smaller and faster.
6767     if (!Op.hasOneUse())
6768       return SDValue();
6769     SDNode *User = *Op.getNode()->use_begin();
6770     if ((User->getOpcode() != ISD::STORE ||
6771          (isa<ConstantSDNode>(Op.getOperand(1)) &&
6772           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6773         (User->getOpcode() != ISD::BITCAST ||
6774          User->getValueType(0) != MVT::i32))
6775       return SDValue();
6776     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6777                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6778                                               Op.getOperand(0)),
6779                                               Op.getOperand(1));
6780     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6781   } else if (VT == MVT::i32 || VT == MVT::i64) {
6782     // ExtractPS/pextrq works with constant index.
6783     if (isa<ConstantSDNode>(Op.getOperand(1)))
6784       return Op;
6785   }
6786   return SDValue();
6787 }
6788
6789
6790 SDValue
6791 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6792                                            SelectionDAG &DAG) const {
6793   if (!isa<ConstantSDNode>(Op.getOperand(1)))
6794     return SDValue();
6795
6796   SDValue Vec = Op.getOperand(0);
6797   EVT VecVT = Vec.getValueType();
6798
6799   // If this is a 256-bit vector result, first extract the 128-bit vector and
6800   // then extract the element from the 128-bit vector.
6801   if (VecVT.getSizeInBits() == 256) {
6802     DebugLoc dl = Op.getNode()->getDebugLoc();
6803     unsigned NumElems = VecVT.getVectorNumElements();
6804     SDValue Idx = Op.getOperand(1);
6805     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6806
6807     // Get the 128-bit vector.
6808     bool Upper = IdxVal >= NumElems/2;
6809     Vec = Extract128BitVector(Vec,
6810                     DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32), DAG, dl);
6811
6812     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6813                     Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : Idx);
6814   }
6815
6816   assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
6817
6818   if (Subtarget->hasSSE41orAVX()) {
6819     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6820     if (Res.getNode())
6821       return Res;
6822   }
6823
6824   EVT VT = Op.getValueType();
6825   DebugLoc dl = Op.getDebugLoc();
6826   // TODO: handle v16i8.
6827   if (VT.getSizeInBits() == 16) {
6828     SDValue Vec = Op.getOperand(0);
6829     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6830     if (Idx == 0)
6831       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6832                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6833                                      DAG.getNode(ISD::BITCAST, dl,
6834                                                  MVT::v4i32, Vec),
6835                                      Op.getOperand(1)));
6836     // Transform it so it match pextrw which produces a 32-bit result.
6837     EVT EltVT = MVT::i32;
6838     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6839                                     Op.getOperand(0), Op.getOperand(1));
6840     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6841                                     DAG.getValueType(VT));
6842     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6843   } else if (VT.getSizeInBits() == 32) {
6844     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6845     if (Idx == 0)
6846       return Op;
6847
6848     // SHUFPS the element to the lowest double word, then movss.
6849     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
6850     EVT VVT = Op.getOperand(0).getValueType();
6851     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6852                                        DAG.getUNDEF(VVT), Mask);
6853     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6854                        DAG.getIntPtrConstant(0));
6855   } else if (VT.getSizeInBits() == 64) {
6856     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6857     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6858     //        to match extract_elt for f64.
6859     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6860     if (Idx == 0)
6861       return Op;
6862
6863     // UNPCKHPD the element to the lowest double word, then movsd.
6864     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
6865     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
6866     int Mask[2] = { 1, -1 };
6867     EVT VVT = Op.getOperand(0).getValueType();
6868     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6869                                        DAG.getUNDEF(VVT), Mask);
6870     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6871                        DAG.getIntPtrConstant(0));
6872   }
6873
6874   return SDValue();
6875 }
6876
6877 SDValue
6878 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
6879                                                SelectionDAG &DAG) const {
6880   EVT VT = Op.getValueType();
6881   EVT EltVT = VT.getVectorElementType();
6882   DebugLoc dl = Op.getDebugLoc();
6883
6884   SDValue N0 = Op.getOperand(0);
6885   SDValue N1 = Op.getOperand(1);
6886   SDValue N2 = Op.getOperand(2);
6887
6888   if (VT.getSizeInBits() == 256)
6889     return SDValue();
6890
6891   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
6892       isa<ConstantSDNode>(N2)) {
6893     unsigned Opc;
6894     if (VT == MVT::v8i16)
6895       Opc = X86ISD::PINSRW;
6896     else if (VT == MVT::v16i8)
6897       Opc = X86ISD::PINSRB;
6898     else
6899       Opc = X86ISD::PINSRB;
6900
6901     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
6902     // argument.
6903     if (N1.getValueType() != MVT::i32)
6904       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6905     if (N2.getValueType() != MVT::i32)
6906       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6907     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
6908   } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
6909     // Bits [7:6] of the constant are the source select.  This will always be
6910     //  zero here.  The DAG Combiner may combine an extract_elt index into these
6911     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
6912     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
6913     // Bits [5:4] of the constant are the destination select.  This is the
6914     //  value of the incoming immediate.
6915     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
6916     //   combine either bitwise AND or insert of float 0.0 to set these bits.
6917     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
6918     // Create this as a scalar to vector..
6919     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
6920     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
6921   } else if ((EltVT == MVT::i32 || EltVT == MVT::i64) && 
6922              isa<ConstantSDNode>(N2)) {
6923     // PINSR* works with constant index.
6924     return Op;
6925   }
6926   return SDValue();
6927 }
6928
6929 SDValue
6930 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
6931   EVT VT = Op.getValueType();
6932   EVT EltVT = VT.getVectorElementType();
6933
6934   DebugLoc dl = Op.getDebugLoc();
6935   SDValue N0 = Op.getOperand(0);
6936   SDValue N1 = Op.getOperand(1);
6937   SDValue N2 = Op.getOperand(2);
6938
6939   // If this is a 256-bit vector result, first extract the 128-bit vector,
6940   // insert the element into the extracted half and then place it back.
6941   if (VT.getSizeInBits() == 256) {
6942     if (!isa<ConstantSDNode>(N2))
6943       return SDValue();
6944
6945     // Get the desired 128-bit vector half.
6946     unsigned NumElems = VT.getVectorNumElements();
6947     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
6948     bool Upper = IdxVal >= NumElems/2;
6949     SDValue Ins128Idx = DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32);
6950     SDValue V = Extract128BitVector(N0, Ins128Idx, DAG, dl);
6951
6952     // Insert the element into the desired half.
6953     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V,
6954                  N1, Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : N2);
6955
6956     // Insert the changed part back to the 256-bit vector
6957     return Insert128BitVector(N0, V, Ins128Idx, DAG, dl);
6958   }
6959
6960   if (Subtarget->hasSSE41orAVX())
6961     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
6962
6963   if (EltVT == MVT::i8)
6964     return SDValue();
6965
6966   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
6967     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
6968     // as its second argument.
6969     if (N1.getValueType() != MVT::i32)
6970       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6971     if (N2.getValueType() != MVT::i32)
6972       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6973     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
6974   }
6975   return SDValue();
6976 }
6977
6978 SDValue
6979 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6980   LLVMContext *Context = DAG.getContext();
6981   DebugLoc dl = Op.getDebugLoc();
6982   EVT OpVT = Op.getValueType();
6983
6984   // If this is a 256-bit vector result, first insert into a 128-bit
6985   // vector and then insert into the 256-bit vector.
6986   if (OpVT.getSizeInBits() > 128) {
6987     // Insert into a 128-bit vector.
6988     EVT VT128 = EVT::getVectorVT(*Context,
6989                                  OpVT.getVectorElementType(),
6990                                  OpVT.getVectorNumElements() / 2);
6991
6992     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
6993
6994     // Insert the 128-bit vector.
6995     return Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, OpVT), Op,
6996                               DAG.getConstant(0, MVT::i32),
6997                               DAG, dl);
6998   }
6999
7000   if (Op.getValueType() == MVT::v1i64 &&
7001       Op.getOperand(0).getValueType() == MVT::i64)
7002     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7003
7004   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7005   assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
7006          "Expected an SSE type!");
7007   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
7008                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7009 }
7010
7011 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7012 // a simple subregister reference or explicit instructions to grab
7013 // upper bits of a vector.
7014 SDValue
7015 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7016   if (Subtarget->hasAVX()) {
7017     DebugLoc dl = Op.getNode()->getDebugLoc();
7018     SDValue Vec = Op.getNode()->getOperand(0);
7019     SDValue Idx = Op.getNode()->getOperand(1);
7020
7021     if (Op.getNode()->getValueType(0).getSizeInBits() == 128
7022         && Vec.getNode()->getValueType(0).getSizeInBits() == 256) {
7023         return Extract128BitVector(Vec, Idx, DAG, dl);
7024     }
7025   }
7026   return SDValue();
7027 }
7028
7029 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7030 // simple superregister reference or explicit instructions to insert
7031 // the upper bits of a vector.
7032 SDValue
7033 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7034   if (Subtarget->hasAVX()) {
7035     DebugLoc dl = Op.getNode()->getDebugLoc();
7036     SDValue Vec = Op.getNode()->getOperand(0);
7037     SDValue SubVec = Op.getNode()->getOperand(1);
7038     SDValue Idx = Op.getNode()->getOperand(2);
7039
7040     if (Op.getNode()->getValueType(0).getSizeInBits() == 256
7041         && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) {
7042       return Insert128BitVector(Vec, SubVec, Idx, DAG, dl);
7043     }
7044   }
7045   return SDValue();
7046 }
7047
7048 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7049 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7050 // one of the above mentioned nodes. It has to be wrapped because otherwise
7051 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7052 // be used to form addressing mode. These wrapped nodes will be selected
7053 // into MOV32ri.
7054 SDValue
7055 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7056   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7057
7058   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7059   // global base reg.
7060   unsigned char OpFlag = 0;
7061   unsigned WrapperKind = X86ISD::Wrapper;
7062   CodeModel::Model M = getTargetMachine().getCodeModel();
7063
7064   if (Subtarget->isPICStyleRIPRel() &&
7065       (M == CodeModel::Small || M == CodeModel::Kernel))
7066     WrapperKind = X86ISD::WrapperRIP;
7067   else if (Subtarget->isPICStyleGOT())
7068     OpFlag = X86II::MO_GOTOFF;
7069   else if (Subtarget->isPICStyleStubPIC())
7070     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7071
7072   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7073                                              CP->getAlignment(),
7074                                              CP->getOffset(), OpFlag);
7075   DebugLoc DL = CP->getDebugLoc();
7076   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7077   // With PIC, the address is actually $g + Offset.
7078   if (OpFlag) {
7079     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7080                          DAG.getNode(X86ISD::GlobalBaseReg,
7081                                      DebugLoc(), getPointerTy()),
7082                          Result);
7083   }
7084
7085   return Result;
7086 }
7087
7088 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7089   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7090
7091   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7092   // global base reg.
7093   unsigned char OpFlag = 0;
7094   unsigned WrapperKind = X86ISD::Wrapper;
7095   CodeModel::Model M = getTargetMachine().getCodeModel();
7096
7097   if (Subtarget->isPICStyleRIPRel() &&
7098       (M == CodeModel::Small || M == CodeModel::Kernel))
7099     WrapperKind = X86ISD::WrapperRIP;
7100   else if (Subtarget->isPICStyleGOT())
7101     OpFlag = X86II::MO_GOTOFF;
7102   else if (Subtarget->isPICStyleStubPIC())
7103     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7104
7105   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7106                                           OpFlag);
7107   DebugLoc DL = JT->getDebugLoc();
7108   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7109
7110   // With PIC, the address is actually $g + Offset.
7111   if (OpFlag)
7112     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7113                          DAG.getNode(X86ISD::GlobalBaseReg,
7114                                      DebugLoc(), getPointerTy()),
7115                          Result);
7116
7117   return Result;
7118 }
7119
7120 SDValue
7121 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7122   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7123
7124   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7125   // global base reg.
7126   unsigned char OpFlag = 0;
7127   unsigned WrapperKind = X86ISD::Wrapper;
7128   CodeModel::Model M = getTargetMachine().getCodeModel();
7129
7130   if (Subtarget->isPICStyleRIPRel() &&
7131       (M == CodeModel::Small || M == CodeModel::Kernel)) {
7132     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7133       OpFlag = X86II::MO_GOTPCREL;
7134     WrapperKind = X86ISD::WrapperRIP;
7135   } else if (Subtarget->isPICStyleGOT()) {
7136     OpFlag = X86II::MO_GOT;
7137   } else if (Subtarget->isPICStyleStubPIC()) {
7138     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7139   } else if (Subtarget->isPICStyleStubNoDynamic()) {
7140     OpFlag = X86II::MO_DARWIN_NONLAZY;
7141   }
7142
7143   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7144
7145   DebugLoc DL = Op.getDebugLoc();
7146   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7147
7148
7149   // With PIC, the address is actually $g + Offset.
7150   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7151       !Subtarget->is64Bit()) {
7152     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7153                          DAG.getNode(X86ISD::GlobalBaseReg,
7154                                      DebugLoc(), getPointerTy()),
7155                          Result);
7156   }
7157
7158   // For symbols that require a load from a stub to get the address, emit the
7159   // load.
7160   if (isGlobalStubReference(OpFlag))
7161     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7162                          MachinePointerInfo::getGOT(), false, false, false, 0);
7163
7164   return Result;
7165 }
7166
7167 SDValue
7168 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7169   // Create the TargetBlockAddressAddress node.
7170   unsigned char OpFlags =
7171     Subtarget->ClassifyBlockAddressReference();
7172   CodeModel::Model M = getTargetMachine().getCodeModel();
7173   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7174   DebugLoc dl = Op.getDebugLoc();
7175   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
7176                                        /*isTarget=*/true, OpFlags);
7177
7178   if (Subtarget->isPICStyleRIPRel() &&
7179       (M == CodeModel::Small || M == CodeModel::Kernel))
7180     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7181   else
7182     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7183
7184   // With PIC, the address is actually $g + Offset.
7185   if (isGlobalRelativeToPICBase(OpFlags)) {
7186     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7187                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7188                          Result);
7189   }
7190
7191   return Result;
7192 }
7193
7194 SDValue
7195 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7196                                       int64_t Offset,
7197                                       SelectionDAG &DAG) const {
7198   // Create the TargetGlobalAddress node, folding in the constant
7199   // offset if it is legal.
7200   unsigned char OpFlags =
7201     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7202   CodeModel::Model M = getTargetMachine().getCodeModel();
7203   SDValue Result;
7204   if (OpFlags == X86II::MO_NO_FLAG &&
7205       X86::isOffsetSuitableForCodeModel(Offset, M)) {
7206     // A direct static reference to a global.
7207     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7208     Offset = 0;
7209   } else {
7210     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7211   }
7212
7213   if (Subtarget->isPICStyleRIPRel() &&
7214       (M == CodeModel::Small || M == CodeModel::Kernel))
7215     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7216   else
7217     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7218
7219   // With PIC, the address is actually $g + Offset.
7220   if (isGlobalRelativeToPICBase(OpFlags)) {
7221     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7222                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7223                          Result);
7224   }
7225
7226   // For globals that require a load from a stub to get the address, emit the
7227   // load.
7228   if (isGlobalStubReference(OpFlags))
7229     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7230                          MachinePointerInfo::getGOT(), false, false, false, 0);
7231
7232   // If there was a non-zero offset that we didn't fold, create an explicit
7233   // addition for it.
7234   if (Offset != 0)
7235     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7236                          DAG.getConstant(Offset, getPointerTy()));
7237
7238   return Result;
7239 }
7240
7241 SDValue
7242 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7243   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7244   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7245   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7246 }
7247
7248 static SDValue
7249 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7250            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7251            unsigned char OperandFlags) {
7252   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7253   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7254   DebugLoc dl = GA->getDebugLoc();
7255   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7256                                            GA->getValueType(0),
7257                                            GA->getOffset(),
7258                                            OperandFlags);
7259   if (InFlag) {
7260     SDValue Ops[] = { Chain,  TGA, *InFlag };
7261     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
7262   } else {
7263     SDValue Ops[]  = { Chain, TGA };
7264     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
7265   }
7266
7267   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7268   MFI->setAdjustsStack(true);
7269
7270   SDValue Flag = Chain.getValue(1);
7271   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7272 }
7273
7274 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7275 static SDValue
7276 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7277                                 const EVT PtrVT) {
7278   SDValue InFlag;
7279   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
7280   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7281                                      DAG.getNode(X86ISD::GlobalBaseReg,
7282                                                  DebugLoc(), PtrVT), InFlag);
7283   InFlag = Chain.getValue(1);
7284
7285   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7286 }
7287
7288 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7289 static SDValue
7290 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7291                                 const EVT PtrVT) {
7292   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7293                     X86::RAX, X86II::MO_TLSGD);
7294 }
7295
7296 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
7297 // "local exec" model.
7298 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7299                                    const EVT PtrVT, TLSModel::Model model,
7300                                    bool is64Bit) {
7301   DebugLoc dl = GA->getDebugLoc();
7302
7303   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7304   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7305                                                          is64Bit ? 257 : 256));
7306
7307   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7308                                       DAG.getIntPtrConstant(0),
7309                                       MachinePointerInfo(Ptr),
7310                                       false, false, false, 0);
7311
7312   unsigned char OperandFlags = 0;
7313   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
7314   // initialexec.
7315   unsigned WrapperKind = X86ISD::Wrapper;
7316   if (model == TLSModel::LocalExec) {
7317     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7318   } else if (is64Bit) {
7319     assert(model == TLSModel::InitialExec);
7320     OperandFlags = X86II::MO_GOTTPOFF;
7321     WrapperKind = X86ISD::WrapperRIP;
7322   } else {
7323     assert(model == TLSModel::InitialExec);
7324     OperandFlags = X86II::MO_INDNTPOFF;
7325   }
7326
7327   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
7328   // exec)
7329   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7330                                            GA->getValueType(0),
7331                                            GA->getOffset(), OperandFlags);
7332   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7333
7334   if (model == TLSModel::InitialExec)
7335     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7336                          MachinePointerInfo::getGOT(), false, false, false, 0);
7337
7338   // The address of the thread local variable is the add of the thread
7339   // pointer with the offset of the variable.
7340   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7341 }
7342
7343 SDValue
7344 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7345
7346   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7347   const GlobalValue *GV = GA->getGlobal();
7348
7349   if (Subtarget->isTargetELF()) {
7350     // TODO: implement the "local dynamic" model
7351     // TODO: implement the "initial exec"model for pic executables
7352
7353     // If GV is an alias then use the aliasee for determining
7354     // thread-localness.
7355     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7356       GV = GA->resolveAliasedGlobal(false);
7357
7358     TLSModel::Model model
7359       = getTLSModel(GV, getTargetMachine().getRelocationModel());
7360
7361     switch (model) {
7362       case TLSModel::GeneralDynamic:
7363       case TLSModel::LocalDynamic: // not implemented
7364         if (Subtarget->is64Bit())
7365           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7366         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7367
7368       case TLSModel::InitialExec:
7369       case TLSModel::LocalExec:
7370         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7371                                    Subtarget->is64Bit());
7372     }
7373   } else if (Subtarget->isTargetDarwin()) {
7374     // Darwin only has one model of TLS.  Lower to that.
7375     unsigned char OpFlag = 0;
7376     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7377                            X86ISD::WrapperRIP : X86ISD::Wrapper;
7378
7379     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7380     // global base reg.
7381     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7382                   !Subtarget->is64Bit();
7383     if (PIC32)
7384       OpFlag = X86II::MO_TLVP_PIC_BASE;
7385     else
7386       OpFlag = X86II::MO_TLVP;
7387     DebugLoc DL = Op.getDebugLoc();
7388     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7389                                                 GA->getValueType(0),
7390                                                 GA->getOffset(), OpFlag);
7391     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7392
7393     // With PIC32, the address is actually $g + Offset.
7394     if (PIC32)
7395       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7396                            DAG.getNode(X86ISD::GlobalBaseReg,
7397                                        DebugLoc(), getPointerTy()),
7398                            Offset);
7399
7400     // Lowering the machine isd will make sure everything is in the right
7401     // location.
7402     SDValue Chain = DAG.getEntryNode();
7403     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7404     SDValue Args[] = { Chain, Offset };
7405     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7406
7407     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7408     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7409     MFI->setAdjustsStack(true);
7410
7411     // And our return value (tls address) is in the standard call return value
7412     // location.
7413     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7414     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7415                               Chain.getValue(1));
7416   }
7417
7418   assert(false &&
7419          "TLS not implemented for this target.");
7420
7421   llvm_unreachable("Unreachable");
7422   return SDValue();
7423 }
7424
7425
7426 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values and
7427 /// take a 2 x i32 value to shift plus a shift amount.
7428 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const {
7429   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7430   EVT VT = Op.getValueType();
7431   unsigned VTBits = VT.getSizeInBits();
7432   DebugLoc dl = Op.getDebugLoc();
7433   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7434   SDValue ShOpLo = Op.getOperand(0);
7435   SDValue ShOpHi = Op.getOperand(1);
7436   SDValue ShAmt  = Op.getOperand(2);
7437   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7438                                      DAG.getConstant(VTBits - 1, MVT::i8))
7439                        : DAG.getConstant(0, VT);
7440
7441   SDValue Tmp2, Tmp3;
7442   if (Op.getOpcode() == ISD::SHL_PARTS) {
7443     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7444     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7445   } else {
7446     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7447     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7448   }
7449
7450   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7451                                 DAG.getConstant(VTBits, MVT::i8));
7452   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7453                              AndNode, DAG.getConstant(0, MVT::i8));
7454
7455   SDValue Hi, Lo;
7456   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7457   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7458   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7459
7460   if (Op.getOpcode() == ISD::SHL_PARTS) {
7461     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7462     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7463   } else {
7464     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7465     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7466   }
7467
7468   SDValue Ops[2] = { Lo, Hi };
7469   return DAG.getMergeValues(Ops, 2, dl);
7470 }
7471
7472 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7473                                            SelectionDAG &DAG) const {
7474   EVT SrcVT = Op.getOperand(0).getValueType();
7475
7476   if (SrcVT.isVector())
7477     return SDValue();
7478
7479   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7480          "Unknown SINT_TO_FP to lower!");
7481
7482   // These are really Legal; return the operand so the caller accepts it as
7483   // Legal.
7484   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7485     return Op;
7486   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7487       Subtarget->is64Bit()) {
7488     return Op;
7489   }
7490
7491   DebugLoc dl = Op.getDebugLoc();
7492   unsigned Size = SrcVT.getSizeInBits()/8;
7493   MachineFunction &MF = DAG.getMachineFunction();
7494   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7495   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7496   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7497                                StackSlot,
7498                                MachinePointerInfo::getFixedStack(SSFI),
7499                                false, false, 0);
7500   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7501 }
7502
7503 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7504                                      SDValue StackSlot,
7505                                      SelectionDAG &DAG) const {
7506   // Build the FILD
7507   DebugLoc DL = Op.getDebugLoc();
7508   SDVTList Tys;
7509   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7510   if (useSSE)
7511     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7512   else
7513     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7514
7515   unsigned ByteSize = SrcVT.getSizeInBits()/8;
7516
7517   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7518   MachineMemOperand *MMO;
7519   if (FI) {
7520     int SSFI = FI->getIndex();
7521     MMO =
7522       DAG.getMachineFunction()
7523       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7524                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
7525   } else {
7526     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7527     StackSlot = StackSlot.getOperand(1);
7528   }
7529   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7530   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7531                                            X86ISD::FILD, DL,
7532                                            Tys, Ops, array_lengthof(Ops),
7533                                            SrcVT, MMO);
7534
7535   if (useSSE) {
7536     Chain = Result.getValue(1);
7537     SDValue InFlag = Result.getValue(2);
7538
7539     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7540     // shouldn't be necessary except that RFP cannot be live across
7541     // multiple blocks. When stackifier is fixed, they can be uncoupled.
7542     MachineFunction &MF = DAG.getMachineFunction();
7543     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7544     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7545     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7546     Tys = DAG.getVTList(MVT::Other);
7547     SDValue Ops[] = {
7548       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7549     };
7550     MachineMemOperand *MMO =
7551       DAG.getMachineFunction()
7552       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7553                             MachineMemOperand::MOStore, SSFISize, SSFISize);
7554
7555     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7556                                     Ops, array_lengthof(Ops),
7557                                     Op.getValueType(), MMO);
7558     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7559                          MachinePointerInfo::getFixedStack(SSFI),
7560                          false, false, false, 0);
7561   }
7562
7563   return Result;
7564 }
7565
7566 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7567 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7568                                                SelectionDAG &DAG) const {
7569   // This algorithm is not obvious. Here it is in C code, more or less:
7570   /*
7571     double uint64_to_double( uint32_t hi, uint32_t lo ) {
7572       static const __m128i exp = { 0x4330000045300000ULL, 0 };
7573       static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
7574
7575       // Copy ints to xmm registers.
7576       __m128i xh = _mm_cvtsi32_si128( hi );
7577       __m128i xl = _mm_cvtsi32_si128( lo );
7578
7579       // Combine into low half of a single xmm register.
7580       __m128i x = _mm_unpacklo_epi32( xh, xl );
7581       __m128d d;
7582       double sd;
7583
7584       // Merge in appropriate exponents to give the integer bits the right
7585       // magnitude.
7586       x = _mm_unpacklo_epi32( x, exp );
7587
7588       // Subtract away the biases to deal with the IEEE-754 double precision
7589       // implicit 1.
7590       d = _mm_sub_pd( (__m128d) x, bias );
7591
7592       // All conversions up to here are exact. The correctly rounded result is
7593       // calculated using the current rounding mode using the following
7594       // horizontal add.
7595       d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
7596       _mm_store_sd( &sd, d );   // Because we are returning doubles in XMM, this
7597                                 // store doesn't really need to be here (except
7598                                 // maybe to zero the other double)
7599       return sd;
7600     }
7601   */
7602
7603   DebugLoc dl = Op.getDebugLoc();
7604   LLVMContext *Context = DAG.getContext();
7605
7606   // Build some magic constants.
7607   SmallVector<Constant*,4> CV0;
7608   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
7609   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
7610   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7611   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7612   Constant *C0 = ConstantVector::get(CV0);
7613   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7614
7615   SmallVector<Constant*,2> CV1;
7616   CV1.push_back(
7617     ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7618   CV1.push_back(
7619     ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7620   Constant *C1 = ConstantVector::get(CV1);
7621   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7622
7623   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7624                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7625                                         Op.getOperand(0),
7626                                         DAG.getIntPtrConstant(1)));
7627   SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7628                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7629                                         Op.getOperand(0),
7630                                         DAG.getIntPtrConstant(0)));
7631   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
7632   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7633                               MachinePointerInfo::getConstantPool(),
7634                               false, false, false, 16);
7635   SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
7636   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
7637   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7638                               MachinePointerInfo::getConstantPool(),
7639                               false, false, false, 16);
7640   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7641
7642   // Add the halves; easiest way is to swap them into another reg first.
7643   int ShufMask[2] = { 1, -1 };
7644   SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
7645                                       DAG.getUNDEF(MVT::v2f64), ShufMask);
7646   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
7647   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
7648                      DAG.getIntPtrConstant(0));
7649 }
7650
7651 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7652 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7653                                                SelectionDAG &DAG) const {
7654   DebugLoc dl = Op.getDebugLoc();
7655   // FP constant to bias correct the final result.
7656   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7657                                    MVT::f64);
7658
7659   // Load the 32-bit value into an XMM register.
7660   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7661                              Op.getOperand(0));
7662
7663   // Zero out the upper parts of the register.
7664   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget->hasXMMInt(),
7665                                      DAG);
7666
7667   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7668                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7669                      DAG.getIntPtrConstant(0));
7670
7671   // Or the load with the bias.
7672   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7673                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7674                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7675                                                    MVT::v2f64, Load)),
7676                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7677                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7678                                                    MVT::v2f64, Bias)));
7679   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7680                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7681                    DAG.getIntPtrConstant(0));
7682
7683   // Subtract the bias.
7684   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7685
7686   // Handle final rounding.
7687   EVT DestVT = Op.getValueType();
7688
7689   if (DestVT.bitsLT(MVT::f64)) {
7690     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7691                        DAG.getIntPtrConstant(0));
7692   } else if (DestVT.bitsGT(MVT::f64)) {
7693     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7694   }
7695
7696   // Handle final rounding.
7697   return Sub;
7698 }
7699
7700 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7701                                            SelectionDAG &DAG) const {
7702   SDValue N0 = Op.getOperand(0);
7703   DebugLoc dl = Op.getDebugLoc();
7704
7705   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
7706   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
7707   // the optimization here.
7708   if (DAG.SignBitIsZero(N0))
7709     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
7710
7711   EVT SrcVT = N0.getValueType();
7712   EVT DstVT = Op.getValueType();
7713   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
7714     return LowerUINT_TO_FP_i64(Op, DAG);
7715   else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
7716     return LowerUINT_TO_FP_i32(Op, DAG);
7717
7718   // Make a 64-bit buffer, and use it to build an FILD.
7719   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
7720   if (SrcVT == MVT::i32) {
7721     SDValue WordOff = DAG.getConstant(4, getPointerTy());
7722     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
7723                                      getPointerTy(), StackSlot, WordOff);
7724     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7725                                   StackSlot, MachinePointerInfo(),
7726                                   false, false, 0);
7727     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
7728                                   OffsetSlot, MachinePointerInfo(),
7729                                   false, false, 0);
7730     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
7731     return Fild;
7732   }
7733
7734   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
7735   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7736                                 StackSlot, MachinePointerInfo(),
7737                                false, false, 0);
7738   // For i64 source, we need to add the appropriate power of 2 if the input
7739   // was negative.  This is the same as the optimization in
7740   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
7741   // we must be careful to do the computation in x87 extended precision, not
7742   // in SSE. (The generic code can't know it's OK to do this, or how to.)
7743   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
7744   MachineMemOperand *MMO =
7745     DAG.getMachineFunction()
7746     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7747                           MachineMemOperand::MOLoad, 8, 8);
7748
7749   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
7750   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
7751   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
7752                                          MVT::i64, MMO);
7753
7754   APInt FF(32, 0x5F800000ULL);
7755
7756   // Check whether the sign bit is set.
7757   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
7758                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
7759                                  ISD::SETLT);
7760
7761   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
7762   SDValue FudgePtr = DAG.getConstantPool(
7763                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
7764                                          getPointerTy());
7765
7766   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
7767   SDValue Zero = DAG.getIntPtrConstant(0);
7768   SDValue Four = DAG.getIntPtrConstant(4);
7769   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
7770                                Zero, Four);
7771   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
7772
7773   // Load the value out, extending it from f32 to f80.
7774   // FIXME: Avoid the extend by constructing the right constant pool?
7775   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
7776                                  FudgePtr, MachinePointerInfo::getConstantPool(),
7777                                  MVT::f32, false, false, 4);
7778   // Extend everything to 80 bits to force it to be done on x87.
7779   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
7780   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
7781 }
7782
7783 std::pair<SDValue,SDValue> X86TargetLowering::
7784 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
7785   DebugLoc DL = Op.getDebugLoc();
7786
7787   EVT DstTy = Op.getValueType();
7788
7789   if (!IsSigned) {
7790     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
7791     DstTy = MVT::i64;
7792   }
7793
7794   assert(DstTy.getSimpleVT() <= MVT::i64 &&
7795          DstTy.getSimpleVT() >= MVT::i16 &&
7796          "Unknown FP_TO_SINT to lower!");
7797
7798   // These are really Legal.
7799   if (DstTy == MVT::i32 &&
7800       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7801     return std::make_pair(SDValue(), SDValue());
7802   if (Subtarget->is64Bit() &&
7803       DstTy == MVT::i64 &&
7804       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7805     return std::make_pair(SDValue(), SDValue());
7806
7807   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
7808   // stack slot.
7809   MachineFunction &MF = DAG.getMachineFunction();
7810   unsigned MemSize = DstTy.getSizeInBits()/8;
7811   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7812   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7813
7814
7815
7816   unsigned Opc;
7817   switch (DstTy.getSimpleVT().SimpleTy) {
7818   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
7819   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
7820   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
7821   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
7822   }
7823
7824   SDValue Chain = DAG.getEntryNode();
7825   SDValue Value = Op.getOperand(0);
7826   EVT TheVT = Op.getOperand(0).getValueType();
7827   if (isScalarFPTypeInSSEReg(TheVT)) {
7828     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
7829     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
7830                          MachinePointerInfo::getFixedStack(SSFI),
7831                          false, false, 0);
7832     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
7833     SDValue Ops[] = {
7834       Chain, StackSlot, DAG.getValueType(TheVT)
7835     };
7836
7837     MachineMemOperand *MMO =
7838       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7839                               MachineMemOperand::MOLoad, MemSize, MemSize);
7840     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
7841                                     DstTy, MMO);
7842     Chain = Value.getValue(1);
7843     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7844     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7845   }
7846
7847   MachineMemOperand *MMO =
7848     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7849                             MachineMemOperand::MOStore, MemSize, MemSize);
7850
7851   // Build the FP_TO_INT*_IN_MEM
7852   SDValue Ops[] = { Chain, Value, StackSlot };
7853   SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
7854                                          Ops, 3, DstTy, MMO);
7855
7856   return std::make_pair(FIST, StackSlot);
7857 }
7858
7859 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
7860                                            SelectionDAG &DAG) const {
7861   if (Op.getValueType().isVector())
7862     return SDValue();
7863
7864   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
7865   SDValue FIST = Vals.first, StackSlot = Vals.second;
7866   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
7867   if (FIST.getNode() == 0) return Op;
7868
7869   // Load the result.
7870   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7871                      FIST, StackSlot, MachinePointerInfo(),
7872                      false, false, false, 0);
7873 }
7874
7875 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
7876                                            SelectionDAG &DAG) const {
7877   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
7878   SDValue FIST = Vals.first, StackSlot = Vals.second;
7879   assert(FIST.getNode() && "Unexpected failure");
7880
7881   // Load the result.
7882   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7883                      FIST, StackSlot, MachinePointerInfo(),
7884                      false, false, false, 0);
7885 }
7886
7887 SDValue X86TargetLowering::LowerFABS(SDValue Op,
7888                                      SelectionDAG &DAG) const {
7889   LLVMContext *Context = DAG.getContext();
7890   DebugLoc dl = Op.getDebugLoc();
7891   EVT VT = Op.getValueType();
7892   EVT EltVT = VT;
7893   if (VT.isVector())
7894     EltVT = VT.getVectorElementType();
7895   SmallVector<Constant*,4> CV;
7896   if (EltVT == MVT::f64) {
7897     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
7898     CV.assign(2, C);
7899   } else {
7900     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
7901     CV.assign(4, C);
7902   }
7903   Constant *C = ConstantVector::get(CV);
7904   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7905   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7906                              MachinePointerInfo::getConstantPool(),
7907                              false, false, false, 16);
7908   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
7909 }
7910
7911 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
7912   LLVMContext *Context = DAG.getContext();
7913   DebugLoc dl = Op.getDebugLoc();
7914   EVT VT = Op.getValueType();
7915   EVT EltVT = VT;
7916   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
7917   if (VT.isVector()) {
7918     EltVT = VT.getVectorElementType();
7919     NumElts = VT.getVectorNumElements();
7920   }
7921   SmallVector<Constant*,8> CV;
7922   if (EltVT == MVT::f64) {
7923     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
7924     CV.assign(NumElts, C);
7925   } else {
7926     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
7927     CV.assign(NumElts, C);
7928   }
7929   Constant *C = ConstantVector::get(CV);
7930   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7931   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7932                              MachinePointerInfo::getConstantPool(),
7933                              false, false, false, 16);
7934   if (VT.isVector()) {
7935     MVT XORVT = VT.getSizeInBits() == 128 ? MVT::v2i64 : MVT::v4i64;
7936     return DAG.getNode(ISD::BITCAST, dl, VT,
7937                        DAG.getNode(ISD::XOR, dl, XORVT,
7938                     DAG.getNode(ISD::BITCAST, dl, XORVT,
7939                                 Op.getOperand(0)),
7940                     DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
7941   } else {
7942     return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
7943   }
7944 }
7945
7946 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
7947   LLVMContext *Context = DAG.getContext();
7948   SDValue Op0 = Op.getOperand(0);
7949   SDValue Op1 = Op.getOperand(1);
7950   DebugLoc dl = Op.getDebugLoc();
7951   EVT VT = Op.getValueType();
7952   EVT SrcVT = Op1.getValueType();
7953
7954   // If second operand is smaller, extend it first.
7955   if (SrcVT.bitsLT(VT)) {
7956     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
7957     SrcVT = VT;
7958   }
7959   // And if it is bigger, shrink it first.
7960   if (SrcVT.bitsGT(VT)) {
7961     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
7962     SrcVT = VT;
7963   }
7964
7965   // At this point the operands and the result should have the same
7966   // type, and that won't be f80 since that is not custom lowered.
7967
7968   // First get the sign bit of second operand.
7969   SmallVector<Constant*,4> CV;
7970   if (SrcVT == MVT::f64) {
7971     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
7972     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7973   } else {
7974     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
7975     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7976     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7977     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7978   }
7979   Constant *C = ConstantVector::get(CV);
7980   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7981   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
7982                               MachinePointerInfo::getConstantPool(),
7983                               false, false, false, 16);
7984   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
7985
7986   // Shift sign bit right or left if the two operands have different types.
7987   if (SrcVT.bitsGT(VT)) {
7988     // Op0 is MVT::f32, Op1 is MVT::f64.
7989     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
7990     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
7991                           DAG.getConstant(32, MVT::i32));
7992     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
7993     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
7994                           DAG.getIntPtrConstant(0));
7995   }
7996
7997   // Clear first operand sign bit.
7998   CV.clear();
7999   if (VT == MVT::f64) {
8000     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8001     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8002   } else {
8003     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8004     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8005     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8006     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8007   }
8008   C = ConstantVector::get(CV);
8009   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8010   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8011                               MachinePointerInfo::getConstantPool(),
8012                               false, false, false, 16);
8013   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8014
8015   // Or the value with the sign bit.
8016   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8017 }
8018
8019 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
8020   SDValue N0 = Op.getOperand(0);
8021   DebugLoc dl = Op.getDebugLoc();
8022   EVT VT = Op.getValueType();
8023
8024   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8025   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8026                                   DAG.getConstant(1, VT));
8027   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8028 }
8029
8030 /// Emit nodes that will be selected as "test Op0,Op0", or something
8031 /// equivalent.
8032 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8033                                     SelectionDAG &DAG) const {
8034   DebugLoc dl = Op.getDebugLoc();
8035
8036   // CF and OF aren't always set the way we want. Determine which
8037   // of these we need.
8038   bool NeedCF = false;
8039   bool NeedOF = false;
8040   switch (X86CC) {
8041   default: break;
8042   case X86::COND_A: case X86::COND_AE:
8043   case X86::COND_B: case X86::COND_BE:
8044     NeedCF = true;
8045     break;
8046   case X86::COND_G: case X86::COND_GE:
8047   case X86::COND_L: case X86::COND_LE:
8048   case X86::COND_O: case X86::COND_NO:
8049     NeedOF = true;
8050     break;
8051   }
8052
8053   // See if we can use the EFLAGS value from the operand instead of
8054   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8055   // we prove that the arithmetic won't overflow, we can't use OF or CF.
8056   if (Op.getResNo() != 0 || NeedOF || NeedCF)
8057     // Emit a CMP with 0, which is the TEST pattern.
8058     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8059                        DAG.getConstant(0, Op.getValueType()));
8060
8061   unsigned Opcode = 0;
8062   unsigned NumOperands = 0;
8063   switch (Op.getNode()->getOpcode()) {
8064   case ISD::ADD:
8065     // Due to an isel shortcoming, be conservative if this add is likely to be
8066     // selected as part of a load-modify-store instruction. When the root node
8067     // in a match is a store, isel doesn't know how to remap non-chain non-flag
8068     // uses of other nodes in the match, such as the ADD in this case. This
8069     // leads to the ADD being left around and reselected, with the result being
8070     // two adds in the output.  Alas, even if none our users are stores, that
8071     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
8072     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
8073     // climbing the DAG back to the root, and it doesn't seem to be worth the
8074     // effort.
8075     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8076          UE = Op.getNode()->use_end(); UI != UE; ++UI)
8077       if (UI->getOpcode() != ISD::CopyToReg &&
8078           UI->getOpcode() != ISD::SETCC &&
8079           UI->getOpcode() != ISD::STORE)
8080         goto default_case;
8081
8082     if (ConstantSDNode *C =
8083         dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
8084       // An add of one will be selected as an INC.
8085       if (C->getAPIntValue() == 1) {
8086         Opcode = X86ISD::INC;
8087         NumOperands = 1;
8088         break;
8089       }
8090
8091       // An add of negative one (subtract of one) will be selected as a DEC.
8092       if (C->getAPIntValue().isAllOnesValue()) {
8093         Opcode = X86ISD::DEC;
8094         NumOperands = 1;
8095         break;
8096       }
8097     }
8098
8099     // Otherwise use a regular EFLAGS-setting add.
8100     Opcode = X86ISD::ADD;
8101     NumOperands = 2;
8102     break;
8103   case ISD::AND: {
8104     // If the primary and result isn't used, don't bother using X86ISD::AND,
8105     // because a TEST instruction will be better.
8106     bool NonFlagUse = false;
8107     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8108            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8109       SDNode *User = *UI;
8110       unsigned UOpNo = UI.getOperandNo();
8111       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8112         // Look pass truncate.
8113         UOpNo = User->use_begin().getOperandNo();
8114         User = *User->use_begin();
8115       }
8116
8117       if (User->getOpcode() != ISD::BRCOND &&
8118           User->getOpcode() != ISD::SETCC &&
8119           (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
8120         NonFlagUse = true;
8121         break;
8122       }
8123     }
8124
8125     if (!NonFlagUse)
8126       break;
8127   }
8128     // FALL THROUGH
8129   case ISD::SUB:
8130   case ISD::OR:
8131   case ISD::XOR:
8132     // Due to the ISEL shortcoming noted above, be conservative if this op is
8133     // likely to be selected as part of a load-modify-store instruction.
8134     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8135            UE = Op.getNode()->use_end(); UI != UE; ++UI)
8136       if (UI->getOpcode() == ISD::STORE)
8137         goto default_case;
8138
8139     // Otherwise use a regular EFLAGS-setting instruction.
8140     switch (Op.getNode()->getOpcode()) {
8141     default: llvm_unreachable("unexpected operator!");
8142     case ISD::SUB: Opcode = X86ISD::SUB; break;
8143     case ISD::OR:  Opcode = X86ISD::OR;  break;
8144     case ISD::XOR: Opcode = X86ISD::XOR; break;
8145     case ISD::AND: Opcode = X86ISD::AND; break;
8146     }
8147
8148     NumOperands = 2;
8149     break;
8150   case X86ISD::ADD:
8151   case X86ISD::SUB:
8152   case X86ISD::INC:
8153   case X86ISD::DEC:
8154   case X86ISD::OR:
8155   case X86ISD::XOR:
8156   case X86ISD::AND:
8157     return SDValue(Op.getNode(), 1);
8158   default:
8159   default_case:
8160     break;
8161   }
8162
8163   if (Opcode == 0)
8164     // Emit a CMP with 0, which is the TEST pattern.
8165     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8166                        DAG.getConstant(0, Op.getValueType()));
8167
8168   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8169   SmallVector<SDValue, 4> Ops;
8170   for (unsigned i = 0; i != NumOperands; ++i)
8171     Ops.push_back(Op.getOperand(i));
8172
8173   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8174   DAG.ReplaceAllUsesWith(Op, New);
8175   return SDValue(New.getNode(), 1);
8176 }
8177
8178 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8179 /// equivalent.
8180 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8181                                    SelectionDAG &DAG) const {
8182   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8183     if (C->getAPIntValue() == 0)
8184       return EmitTest(Op0, X86CC, DAG);
8185
8186   DebugLoc dl = Op0.getDebugLoc();
8187   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8188 }
8189
8190 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8191 /// if it's possible.
8192 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8193                                      DebugLoc dl, SelectionDAG &DAG) const {
8194   SDValue Op0 = And.getOperand(0);
8195   SDValue Op1 = And.getOperand(1);
8196   if (Op0.getOpcode() == ISD::TRUNCATE)
8197     Op0 = Op0.getOperand(0);
8198   if (Op1.getOpcode() == ISD::TRUNCATE)
8199     Op1 = Op1.getOperand(0);
8200
8201   SDValue LHS, RHS;
8202   if (Op1.getOpcode() == ISD::SHL)
8203     std::swap(Op0, Op1);
8204   if (Op0.getOpcode() == ISD::SHL) {
8205     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8206       if (And00C->getZExtValue() == 1) {
8207         // If we looked past a truncate, check that it's only truncating away
8208         // known zeros.
8209         unsigned BitWidth = Op0.getValueSizeInBits();
8210         unsigned AndBitWidth = And.getValueSizeInBits();
8211         if (BitWidth > AndBitWidth) {
8212           APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
8213           DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
8214           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8215             return SDValue();
8216         }
8217         LHS = Op1;
8218         RHS = Op0.getOperand(1);
8219       }
8220   } else if (Op1.getOpcode() == ISD::Constant) {
8221     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8222     uint64_t AndRHSVal = AndRHS->getZExtValue();
8223     SDValue AndLHS = Op0;
8224
8225     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
8226       LHS = AndLHS.getOperand(0);
8227       RHS = AndLHS.getOperand(1);
8228     }
8229
8230     // Use BT if the immediate can't be encoded in a TEST instruction.
8231     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
8232       LHS = AndLHS;
8233       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
8234     }
8235   }
8236
8237   if (LHS.getNode()) {
8238     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
8239     // instruction.  Since the shift amount is in-range-or-undefined, we know
8240     // that doing a bittest on the i32 value is ok.  We extend to i32 because
8241     // the encoding for the i16 version is larger than the i32 version.
8242     // Also promote i16 to i32 for performance / code size reason.
8243     if (LHS.getValueType() == MVT::i8 ||
8244         LHS.getValueType() == MVT::i16)
8245       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8246
8247     // If the operand types disagree, extend the shift amount to match.  Since
8248     // BT ignores high bits (like shifts) we can use anyextend.
8249     if (LHS.getValueType() != RHS.getValueType())
8250       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8251
8252     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8253     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8254     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8255                        DAG.getConstant(Cond, MVT::i8), BT);
8256   }
8257
8258   return SDValue();
8259 }
8260
8261 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8262
8263   if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8264
8265   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8266   SDValue Op0 = Op.getOperand(0);
8267   SDValue Op1 = Op.getOperand(1);
8268   DebugLoc dl = Op.getDebugLoc();
8269   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8270
8271   // Optimize to BT if possible.
8272   // Lower (X & (1 << N)) == 0 to BT(X, N).
8273   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8274   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8275   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8276       Op1.getOpcode() == ISD::Constant &&
8277       cast<ConstantSDNode>(Op1)->isNullValue() &&
8278       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8279     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8280     if (NewSetCC.getNode())
8281       return NewSetCC;
8282   }
8283
8284   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
8285   // these.
8286   if (Op1.getOpcode() == ISD::Constant &&
8287       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8288        cast<ConstantSDNode>(Op1)->isNullValue()) &&
8289       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8290
8291     // If the input is a setcc, then reuse the input setcc or use a new one with
8292     // the inverted condition.
8293     if (Op0.getOpcode() == X86ISD::SETCC) {
8294       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8295       bool Invert = (CC == ISD::SETNE) ^
8296         cast<ConstantSDNode>(Op1)->isNullValue();
8297       if (!Invert) return Op0;
8298
8299       CCode = X86::GetOppositeBranchCondition(CCode);
8300       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8301                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8302     }
8303   }
8304
8305   bool isFP = Op1.getValueType().isFloatingPoint();
8306   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8307   if (X86CC == X86::COND_INVALID)
8308     return SDValue();
8309
8310   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8311   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8312                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8313 }
8314
8315 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8316 // ones, and then concatenate the result back.
8317 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
8318   EVT VT = Op.getValueType();
8319
8320   assert(VT.getSizeInBits() == 256 && Op.getOpcode() == ISD::SETCC &&
8321          "Unsupported value type for operation");
8322
8323   int NumElems = VT.getVectorNumElements();
8324   DebugLoc dl = Op.getDebugLoc();
8325   SDValue CC = Op.getOperand(2);
8326   SDValue Idx0 = DAG.getConstant(0, MVT::i32);
8327   SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
8328
8329   // Extract the LHS vectors
8330   SDValue LHS = Op.getOperand(0);
8331   SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
8332   SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
8333
8334   // Extract the RHS vectors
8335   SDValue RHS = Op.getOperand(1);
8336   SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl);
8337   SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl);
8338
8339   // Issue the operation on the smaller types and concatenate the result back
8340   MVT EltVT = VT.getVectorElementType().getSimpleVT();
8341   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8342   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8343                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8344                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8345 }
8346
8347
8348 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8349   SDValue Cond;
8350   SDValue Op0 = Op.getOperand(0);
8351   SDValue Op1 = Op.getOperand(1);
8352   SDValue CC = Op.getOperand(2);
8353   EVT VT = Op.getValueType();
8354   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8355   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8356   DebugLoc dl = Op.getDebugLoc();
8357
8358   if (isFP) {
8359     unsigned SSECC = 8;
8360     EVT EltVT = Op0.getValueType().getVectorElementType();
8361     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
8362
8363     unsigned Opc = EltVT == MVT::f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
8364     bool Swap = false;
8365
8366     // SSE Condition code mapping:
8367     //  0 - EQ
8368     //  1 - LT
8369     //  2 - LE
8370     //  3 - UNORD
8371     //  4 - NEQ
8372     //  5 - NLT
8373     //  6 - NLE
8374     //  7 - ORD
8375     switch (SetCCOpcode) {
8376     default: break;
8377     case ISD::SETOEQ:
8378     case ISD::SETEQ:  SSECC = 0; break;
8379     case ISD::SETOGT:
8380     case ISD::SETGT: Swap = true; // Fallthrough
8381     case ISD::SETLT:
8382     case ISD::SETOLT: SSECC = 1; break;
8383     case ISD::SETOGE:
8384     case ISD::SETGE: Swap = true; // Fallthrough
8385     case ISD::SETLE:
8386     case ISD::SETOLE: SSECC = 2; break;
8387     case ISD::SETUO:  SSECC = 3; break;
8388     case ISD::SETUNE:
8389     case ISD::SETNE:  SSECC = 4; break;
8390     case ISD::SETULE: Swap = true;
8391     case ISD::SETUGE: SSECC = 5; break;
8392     case ISD::SETULT: Swap = true;
8393     case ISD::SETUGT: SSECC = 6; break;
8394     case ISD::SETO:   SSECC = 7; break;
8395     }
8396     if (Swap)
8397       std::swap(Op0, Op1);
8398
8399     // In the two special cases we can't handle, emit two comparisons.
8400     if (SSECC == 8) {
8401       if (SetCCOpcode == ISD::SETUEQ) {
8402         SDValue UNORD, EQ;
8403         UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
8404         EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
8405         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
8406       } else if (SetCCOpcode == ISD::SETONE) {
8407         SDValue ORD, NEQ;
8408         ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
8409         NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
8410         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
8411       }
8412       llvm_unreachable("Illegal FP comparison");
8413     }
8414     // Handle all other FP comparisons here.
8415     return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
8416   }
8417
8418   // Break 256-bit integer vector compare into smaller ones.
8419   if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2())
8420     return Lower256IntVSETCC(Op, DAG);
8421
8422   // We are handling one of the integer comparisons here.  Since SSE only has
8423   // GT and EQ comparisons for integer, swapping operands and multiple
8424   // operations may be required for some comparisons.
8425   unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
8426   bool Swap = false, Invert = false, FlipSigns = false;
8427
8428   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
8429   default: break;
8430   case MVT::i8:   EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
8431   case MVT::i16:  EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
8432   case MVT::i32:  EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
8433   case MVT::i64:  EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
8434   }
8435
8436   switch (SetCCOpcode) {
8437   default: break;
8438   case ISD::SETNE:  Invert = true;
8439   case ISD::SETEQ:  Opc = EQOpc; break;
8440   case ISD::SETLT:  Swap = true;
8441   case ISD::SETGT:  Opc = GTOpc; break;
8442   case ISD::SETGE:  Swap = true;
8443   case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
8444   case ISD::SETULT: Swap = true;
8445   case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
8446   case ISD::SETUGE: Swap = true;
8447   case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
8448   }
8449   if (Swap)
8450     std::swap(Op0, Op1);
8451
8452   // Check that the operation in question is available (most are plain SSE2,
8453   // but PCMPGTQ and PCMPEQQ have different requirements).
8454   if (Opc == X86ISD::PCMPGTQ && !Subtarget->hasSSE42orAVX())
8455     return SDValue();
8456   if (Opc == X86ISD::PCMPEQQ && !Subtarget->hasSSE41orAVX())
8457     return SDValue();
8458
8459   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
8460   // bits of the inputs before performing those operations.
8461   if (FlipSigns) {
8462     EVT EltVT = VT.getVectorElementType();
8463     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
8464                                       EltVT);
8465     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
8466     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
8467                                     SignBits.size());
8468     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
8469     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
8470   }
8471
8472   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
8473
8474   // If the logical-not of the result is required, perform that now.
8475   if (Invert)
8476     Result = DAG.getNOT(dl, Result, VT);
8477
8478   return Result;
8479 }
8480
8481 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
8482 static bool isX86LogicalCmp(SDValue Op) {
8483   unsigned Opc = Op.getNode()->getOpcode();
8484   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
8485     return true;
8486   if (Op.getResNo() == 1 &&
8487       (Opc == X86ISD::ADD ||
8488        Opc == X86ISD::SUB ||
8489        Opc == X86ISD::ADC ||
8490        Opc == X86ISD::SBB ||
8491        Opc == X86ISD::SMUL ||
8492        Opc == X86ISD::UMUL ||
8493        Opc == X86ISD::INC ||
8494        Opc == X86ISD::DEC ||
8495        Opc == X86ISD::OR ||
8496        Opc == X86ISD::XOR ||
8497        Opc == X86ISD::AND))
8498     return true;
8499
8500   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
8501     return true;
8502
8503   return false;
8504 }
8505
8506 static bool isZero(SDValue V) {
8507   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8508   return C && C->isNullValue();
8509 }
8510
8511 static bool isAllOnes(SDValue V) {
8512   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8513   return C && C->isAllOnesValue();
8514 }
8515
8516 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8517   bool addTest = true;
8518   SDValue Cond  = Op.getOperand(0);
8519   SDValue Op1 = Op.getOperand(1);
8520   SDValue Op2 = Op.getOperand(2);
8521   DebugLoc DL = Op.getDebugLoc();
8522   SDValue CC;
8523
8524   if (Cond.getOpcode() == ISD::SETCC) {
8525     SDValue NewCond = LowerSETCC(Cond, DAG);
8526     if (NewCond.getNode())
8527       Cond = NewCond;
8528   }
8529
8530   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
8531   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
8532   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
8533   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
8534   if (Cond.getOpcode() == X86ISD::SETCC &&
8535       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
8536       isZero(Cond.getOperand(1).getOperand(1))) {
8537     SDValue Cmp = Cond.getOperand(1);
8538
8539     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
8540
8541     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
8542         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
8543       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
8544
8545       SDValue CmpOp0 = Cmp.getOperand(0);
8546       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
8547                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
8548
8549       SDValue Res =   // Res = 0 or -1.
8550         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8551                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
8552
8553       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
8554         Res = DAG.getNOT(DL, Res, Res.getValueType());
8555
8556       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
8557       if (N2C == 0 || !N2C->isNullValue())
8558         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
8559       return Res;
8560     }
8561   }
8562
8563   // Look past (and (setcc_carry (cmp ...)), 1).
8564   if (Cond.getOpcode() == ISD::AND &&
8565       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8566     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8567     if (C && C->getAPIntValue() == 1)
8568       Cond = Cond.getOperand(0);
8569   }
8570
8571   // If condition flag is set by a X86ISD::CMP, then use it as the condition
8572   // setting operand in place of the X86ISD::SETCC.
8573   unsigned CondOpcode = Cond.getOpcode();
8574   if (CondOpcode == X86ISD::SETCC ||
8575       CondOpcode == X86ISD::SETCC_CARRY) {
8576     CC = Cond.getOperand(0);
8577
8578     SDValue Cmp = Cond.getOperand(1);
8579     unsigned Opc = Cmp.getOpcode();
8580     EVT VT = Op.getValueType();
8581
8582     bool IllegalFPCMov = false;
8583     if (VT.isFloatingPoint() && !VT.isVector() &&
8584         !isScalarFPTypeInSSEReg(VT))  // FPStack?
8585       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
8586
8587     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
8588         Opc == X86ISD::BT) { // FIXME
8589       Cond = Cmp;
8590       addTest = false;
8591     }
8592   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
8593              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
8594              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
8595               Cond.getOperand(0).getValueType() != MVT::i8)) {
8596     SDValue LHS = Cond.getOperand(0);
8597     SDValue RHS = Cond.getOperand(1);
8598     unsigned X86Opcode;
8599     unsigned X86Cond;
8600     SDVTList VTs;
8601     switch (CondOpcode) {
8602     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
8603     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
8604     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
8605     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
8606     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
8607     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
8608     default: llvm_unreachable("unexpected overflowing operator");
8609     }
8610     if (CondOpcode == ISD::UMULO)
8611       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
8612                           MVT::i32);
8613     else
8614       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
8615
8616     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
8617
8618     if (CondOpcode == ISD::UMULO)
8619       Cond = X86Op.getValue(2);
8620     else
8621       Cond = X86Op.getValue(1);
8622
8623     CC = DAG.getConstant(X86Cond, MVT::i8);
8624     addTest = false;
8625   }
8626
8627   if (addTest) {
8628     // Look pass the truncate.
8629     if (Cond.getOpcode() == ISD::TRUNCATE)
8630       Cond = Cond.getOperand(0);
8631
8632     // We know the result of AND is compared against zero. Try to match
8633     // it to BT.
8634     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8635       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
8636       if (NewSetCC.getNode()) {
8637         CC = NewSetCC.getOperand(0);
8638         Cond = NewSetCC.getOperand(1);
8639         addTest = false;
8640       }
8641     }
8642   }
8643
8644   if (addTest) {
8645     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8646     Cond = EmitTest(Cond, X86::COND_NE, DAG);
8647   }
8648
8649   // a <  b ? -1 :  0 -> RES = ~setcc_carry
8650   // a <  b ?  0 : -1 -> RES = setcc_carry
8651   // a >= b ? -1 :  0 -> RES = setcc_carry
8652   // a >= b ?  0 : -1 -> RES = ~setcc_carry
8653   if (Cond.getOpcode() == X86ISD::CMP) {
8654     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
8655
8656     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
8657         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
8658       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8659                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
8660       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
8661         return DAG.getNOT(DL, Res, Res.getValueType());
8662       return Res;
8663     }
8664   }
8665
8666   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
8667   // condition is true.
8668   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
8669   SDValue Ops[] = { Op2, Op1, CC, Cond };
8670   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
8671 }
8672
8673 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
8674 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
8675 // from the AND / OR.
8676 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
8677   Opc = Op.getOpcode();
8678   if (Opc != ISD::OR && Opc != ISD::AND)
8679     return false;
8680   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8681           Op.getOperand(0).hasOneUse() &&
8682           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
8683           Op.getOperand(1).hasOneUse());
8684 }
8685
8686 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
8687 // 1 and that the SETCC node has a single use.
8688 static bool isXor1OfSetCC(SDValue Op) {
8689   if (Op.getOpcode() != ISD::XOR)
8690     return false;
8691   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8692   if (N1C && N1C->getAPIntValue() == 1) {
8693     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8694       Op.getOperand(0).hasOneUse();
8695   }
8696   return false;
8697 }
8698
8699 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
8700   bool addTest = true;
8701   SDValue Chain = Op.getOperand(0);
8702   SDValue Cond  = Op.getOperand(1);
8703   SDValue Dest  = Op.getOperand(2);
8704   DebugLoc dl = Op.getDebugLoc();
8705   SDValue CC;
8706   bool Inverted = false;
8707
8708   if (Cond.getOpcode() == ISD::SETCC) {
8709     // Check for setcc([su]{add,sub,mul}o == 0).
8710     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
8711         isa<ConstantSDNode>(Cond.getOperand(1)) &&
8712         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
8713         Cond.getOperand(0).getResNo() == 1 &&
8714         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
8715          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
8716          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
8717          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
8718          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
8719          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
8720       Inverted = true;
8721       Cond = Cond.getOperand(0);
8722     } else {
8723       SDValue NewCond = LowerSETCC(Cond, DAG);
8724       if (NewCond.getNode())
8725         Cond = NewCond;
8726     }
8727   }
8728 #if 0
8729   // FIXME: LowerXALUO doesn't handle these!!
8730   else if (Cond.getOpcode() == X86ISD::ADD  ||
8731            Cond.getOpcode() == X86ISD::SUB  ||
8732            Cond.getOpcode() == X86ISD::SMUL ||
8733            Cond.getOpcode() == X86ISD::UMUL)
8734     Cond = LowerXALUO(Cond, DAG);
8735 #endif
8736
8737   // Look pass (and (setcc_carry (cmp ...)), 1).
8738   if (Cond.getOpcode() == ISD::AND &&
8739       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8740     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8741     if (C && C->getAPIntValue() == 1)
8742       Cond = Cond.getOperand(0);
8743   }
8744
8745   // If condition flag is set by a X86ISD::CMP, then use it as the condition
8746   // setting operand in place of the X86ISD::SETCC.
8747   unsigned CondOpcode = Cond.getOpcode();
8748   if (CondOpcode == X86ISD::SETCC ||
8749       CondOpcode == X86ISD::SETCC_CARRY) {
8750     CC = Cond.getOperand(0);
8751
8752     SDValue Cmp = Cond.getOperand(1);
8753     unsigned Opc = Cmp.getOpcode();
8754     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
8755     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
8756       Cond = Cmp;
8757       addTest = false;
8758     } else {
8759       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
8760       default: break;
8761       case X86::COND_O:
8762       case X86::COND_B:
8763         // These can only come from an arithmetic instruction with overflow,
8764         // e.g. SADDO, UADDO.
8765         Cond = Cond.getNode()->getOperand(1);
8766         addTest = false;
8767         break;
8768       }
8769     }
8770   }
8771   CondOpcode = Cond.getOpcode();
8772   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
8773       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
8774       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
8775        Cond.getOperand(0).getValueType() != MVT::i8)) {
8776     SDValue LHS = Cond.getOperand(0);
8777     SDValue RHS = Cond.getOperand(1);
8778     unsigned X86Opcode;
8779     unsigned X86Cond;
8780     SDVTList VTs;
8781     switch (CondOpcode) {
8782     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
8783     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
8784     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
8785     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
8786     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
8787     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
8788     default: llvm_unreachable("unexpected overflowing operator");
8789     }
8790     if (Inverted)
8791       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
8792     if (CondOpcode == ISD::UMULO)
8793       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
8794                           MVT::i32);
8795     else
8796       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
8797
8798     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
8799
8800     if (CondOpcode == ISD::UMULO)
8801       Cond = X86Op.getValue(2);
8802     else
8803       Cond = X86Op.getValue(1);
8804
8805     CC = DAG.getConstant(X86Cond, MVT::i8);
8806     addTest = false;
8807   } else {
8808     unsigned CondOpc;
8809     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
8810       SDValue Cmp = Cond.getOperand(0).getOperand(1);
8811       if (CondOpc == ISD::OR) {
8812         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
8813         // two branches instead of an explicit OR instruction with a
8814         // separate test.
8815         if (Cmp == Cond.getOperand(1).getOperand(1) &&
8816             isX86LogicalCmp(Cmp)) {
8817           CC = Cond.getOperand(0).getOperand(0);
8818           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8819                               Chain, Dest, CC, Cmp);
8820           CC = Cond.getOperand(1).getOperand(0);
8821           Cond = Cmp;
8822           addTest = false;
8823         }
8824       } else { // ISD::AND
8825         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
8826         // two branches instead of an explicit AND instruction with a
8827         // separate test. However, we only do this if this block doesn't
8828         // have a fall-through edge, because this requires an explicit
8829         // jmp when the condition is false.
8830         if (Cmp == Cond.getOperand(1).getOperand(1) &&
8831             isX86LogicalCmp(Cmp) &&
8832             Op.getNode()->hasOneUse()) {
8833           X86::CondCode CCode =
8834             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
8835           CCode = X86::GetOppositeBranchCondition(CCode);
8836           CC = DAG.getConstant(CCode, MVT::i8);
8837           SDNode *User = *Op.getNode()->use_begin();
8838           // Look for an unconditional branch following this conditional branch.
8839           // We need this because we need to reverse the successors in order
8840           // to implement FCMP_OEQ.
8841           if (User->getOpcode() == ISD::BR) {
8842             SDValue FalseBB = User->getOperand(1);
8843             SDNode *NewBR =
8844               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
8845             assert(NewBR == User);
8846             (void)NewBR;
8847             Dest = FalseBB;
8848
8849             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8850                                 Chain, Dest, CC, Cmp);
8851             X86::CondCode CCode =
8852               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
8853             CCode = X86::GetOppositeBranchCondition(CCode);
8854             CC = DAG.getConstant(CCode, MVT::i8);
8855             Cond = Cmp;
8856             addTest = false;
8857           }
8858         }
8859       }
8860     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
8861       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
8862       // It should be transformed during dag combiner except when the condition
8863       // is set by a arithmetics with overflow node.
8864       X86::CondCode CCode =
8865         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
8866       CCode = X86::GetOppositeBranchCondition(CCode);
8867       CC = DAG.getConstant(CCode, MVT::i8);
8868       Cond = Cond.getOperand(0).getOperand(1);
8869       addTest = false;
8870     } else if (Cond.getOpcode() == ISD::SETCC &&
8871                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
8872       // For FCMP_OEQ, we can emit
8873       // two branches instead of an explicit AND instruction with a
8874       // separate test. However, we only do this if this block doesn't
8875       // have a fall-through edge, because this requires an explicit
8876       // jmp when the condition is false.
8877       if (Op.getNode()->hasOneUse()) {
8878         SDNode *User = *Op.getNode()->use_begin();
8879         // Look for an unconditional branch following this conditional branch.
8880         // We need this because we need to reverse the successors in order
8881         // to implement FCMP_OEQ.
8882         if (User->getOpcode() == ISD::BR) {
8883           SDValue FalseBB = User->getOperand(1);
8884           SDNode *NewBR =
8885             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
8886           assert(NewBR == User);
8887           (void)NewBR;
8888           Dest = FalseBB;
8889
8890           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8891                                     Cond.getOperand(0), Cond.getOperand(1));
8892           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8893           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8894                               Chain, Dest, CC, Cmp);
8895           CC = DAG.getConstant(X86::COND_P, MVT::i8);
8896           Cond = Cmp;
8897           addTest = false;
8898         }
8899       }
8900     } else if (Cond.getOpcode() == ISD::SETCC &&
8901                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
8902       // For FCMP_UNE, we can emit
8903       // two branches instead of an explicit AND instruction with a
8904       // separate test. However, we only do this if this block doesn't
8905       // have a fall-through edge, because this requires an explicit
8906       // jmp when the condition is false.
8907       if (Op.getNode()->hasOneUse()) {
8908         SDNode *User = *Op.getNode()->use_begin();
8909         // Look for an unconditional branch following this conditional branch.
8910         // We need this because we need to reverse the successors in order
8911         // to implement FCMP_UNE.
8912         if (User->getOpcode() == ISD::BR) {
8913           SDValue FalseBB = User->getOperand(1);
8914           SDNode *NewBR =
8915             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
8916           assert(NewBR == User);
8917           (void)NewBR;
8918
8919           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8920                                     Cond.getOperand(0), Cond.getOperand(1));
8921           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8922           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8923                               Chain, Dest, CC, Cmp);
8924           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
8925           Cond = Cmp;
8926           addTest = false;
8927           Dest = FalseBB;
8928         }
8929       }
8930     }
8931   }
8932
8933   if (addTest) {
8934     // Look pass the truncate.
8935     if (Cond.getOpcode() == ISD::TRUNCATE)
8936       Cond = Cond.getOperand(0);
8937
8938     // We know the result of AND is compared against zero. Try to match
8939     // it to BT.
8940     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8941       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
8942       if (NewSetCC.getNode()) {
8943         CC = NewSetCC.getOperand(0);
8944         Cond = NewSetCC.getOperand(1);
8945         addTest = false;
8946       }
8947     }
8948   }
8949
8950   if (addTest) {
8951     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8952     Cond = EmitTest(Cond, X86::COND_NE, DAG);
8953   }
8954   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8955                      Chain, Dest, CC, Cond);
8956 }
8957
8958
8959 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
8960 // Calls to _alloca is needed to probe the stack when allocating more than 4k
8961 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
8962 // that the guard pages used by the OS virtual memory manager are allocated in
8963 // correct sequence.
8964 SDValue
8965 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
8966                                            SelectionDAG &DAG) const {
8967   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
8968           getTargetMachine().Options.EnableSegmentedStacks) &&
8969          "This should be used only on Windows targets or when segmented stacks "
8970          "are being used");
8971   assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
8972   DebugLoc dl = Op.getDebugLoc();
8973
8974   // Get the inputs.
8975   SDValue Chain = Op.getOperand(0);
8976   SDValue Size  = Op.getOperand(1);
8977   // FIXME: Ensure alignment here
8978
8979   bool Is64Bit = Subtarget->is64Bit();
8980   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
8981
8982   if (getTargetMachine().Options.EnableSegmentedStacks) {
8983     MachineFunction &MF = DAG.getMachineFunction();
8984     MachineRegisterInfo &MRI = MF.getRegInfo();
8985
8986     if (Is64Bit) {
8987       // The 64 bit implementation of segmented stacks needs to clobber both r10
8988       // r11. This makes it impossible to use it along with nested parameters.
8989       const Function *F = MF.getFunction();
8990
8991       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
8992            I != E; I++)
8993         if (I->hasNestAttr())
8994           report_fatal_error("Cannot use segmented stacks with functions that "
8995                              "have nested arguments.");
8996     }
8997
8998     const TargetRegisterClass *AddrRegClass =
8999       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9000     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9001     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9002     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9003                                 DAG.getRegister(Vreg, SPTy));
9004     SDValue Ops1[2] = { Value, Chain };
9005     return DAG.getMergeValues(Ops1, 2, dl);
9006   } else {
9007     SDValue Flag;
9008     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9009
9010     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9011     Flag = Chain.getValue(1);
9012     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9013
9014     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
9015     Flag = Chain.getValue(1);
9016
9017     Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
9018
9019     SDValue Ops1[2] = { Chain.getValue(0), Chain };
9020     return DAG.getMergeValues(Ops1, 2, dl);
9021   }
9022 }
9023
9024 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9025   MachineFunction &MF = DAG.getMachineFunction();
9026   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9027
9028   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9029   DebugLoc DL = Op.getDebugLoc();
9030
9031   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9032     // vastart just stores the address of the VarArgsFrameIndex slot into the
9033     // memory location argument.
9034     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9035                                    getPointerTy());
9036     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9037                         MachinePointerInfo(SV), false, false, 0);
9038   }
9039
9040   // __va_list_tag:
9041   //   gp_offset         (0 - 6 * 8)
9042   //   fp_offset         (48 - 48 + 8 * 16)
9043   //   overflow_arg_area (point to parameters coming in memory).
9044   //   reg_save_area
9045   SmallVector<SDValue, 8> MemOps;
9046   SDValue FIN = Op.getOperand(1);
9047   // Store gp_offset
9048   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9049                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9050                                                MVT::i32),
9051                                FIN, MachinePointerInfo(SV), false, false, 0);
9052   MemOps.push_back(Store);
9053
9054   // Store fp_offset
9055   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9056                     FIN, DAG.getIntPtrConstant(4));
9057   Store = DAG.getStore(Op.getOperand(0), DL,
9058                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9059                                        MVT::i32),
9060                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
9061   MemOps.push_back(Store);
9062
9063   // Store ptr to overflow_arg_area
9064   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9065                     FIN, DAG.getIntPtrConstant(4));
9066   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9067                                     getPointerTy());
9068   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9069                        MachinePointerInfo(SV, 8),
9070                        false, false, 0);
9071   MemOps.push_back(Store);
9072
9073   // Store ptr to reg_save_area.
9074   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9075                     FIN, DAG.getIntPtrConstant(8));
9076   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9077                                     getPointerTy());
9078   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9079                        MachinePointerInfo(SV, 16), false, false, 0);
9080   MemOps.push_back(Store);
9081   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9082                      &MemOps[0], MemOps.size());
9083 }
9084
9085 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9086   assert(Subtarget->is64Bit() &&
9087          "LowerVAARG only handles 64-bit va_arg!");
9088   assert((Subtarget->isTargetLinux() ||
9089           Subtarget->isTargetDarwin()) &&
9090           "Unhandled target in LowerVAARG");
9091   assert(Op.getNode()->getNumOperands() == 4);
9092   SDValue Chain = Op.getOperand(0);
9093   SDValue SrcPtr = Op.getOperand(1);
9094   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9095   unsigned Align = Op.getConstantOperandVal(3);
9096   DebugLoc dl = Op.getDebugLoc();
9097
9098   EVT ArgVT = Op.getNode()->getValueType(0);
9099   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9100   uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
9101   uint8_t ArgMode;
9102
9103   // Decide which area this value should be read from.
9104   // TODO: Implement the AMD64 ABI in its entirety. This simple
9105   // selection mechanism works only for the basic types.
9106   if (ArgVT == MVT::f80) {
9107     llvm_unreachable("va_arg for f80 not yet implemented");
9108   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9109     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
9110   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9111     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
9112   } else {
9113     llvm_unreachable("Unhandled argument type in LowerVAARG");
9114   }
9115
9116   if (ArgMode == 2) {
9117     // Sanity Check: Make sure using fp_offset makes sense.
9118     assert(!getTargetMachine().Options.UseSoftFloat &&
9119            !(DAG.getMachineFunction()
9120                 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
9121            Subtarget->hasXMM());
9122   }
9123
9124   // Insert VAARG_64 node into the DAG
9125   // VAARG_64 returns two values: Variable Argument Address, Chain
9126   SmallVector<SDValue, 11> InstOps;
9127   InstOps.push_back(Chain);
9128   InstOps.push_back(SrcPtr);
9129   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9130   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9131   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9132   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9133   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9134                                           VTs, &InstOps[0], InstOps.size(),
9135                                           MVT::i64,
9136                                           MachinePointerInfo(SV),
9137                                           /*Align=*/0,
9138                                           /*Volatile=*/false,
9139                                           /*ReadMem=*/true,
9140                                           /*WriteMem=*/true);
9141   Chain = VAARG.getValue(1);
9142
9143   // Load the next argument and return it
9144   return DAG.getLoad(ArgVT, dl,
9145                      Chain,
9146                      VAARG,
9147                      MachinePointerInfo(),
9148                      false, false, false, 0);
9149 }
9150
9151 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
9152   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9153   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9154   SDValue Chain = Op.getOperand(0);
9155   SDValue DstPtr = Op.getOperand(1);
9156   SDValue SrcPtr = Op.getOperand(2);
9157   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9158   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9159   DebugLoc DL = Op.getDebugLoc();
9160
9161   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9162                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9163                        false,
9164                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9165 }
9166
9167 SDValue
9168 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
9169   DebugLoc dl = Op.getDebugLoc();
9170   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9171   switch (IntNo) {
9172   default: return SDValue();    // Don't custom lower most intrinsics.
9173   // Comparison intrinsics.
9174   case Intrinsic::x86_sse_comieq_ss:
9175   case Intrinsic::x86_sse_comilt_ss:
9176   case Intrinsic::x86_sse_comile_ss:
9177   case Intrinsic::x86_sse_comigt_ss:
9178   case Intrinsic::x86_sse_comige_ss:
9179   case Intrinsic::x86_sse_comineq_ss:
9180   case Intrinsic::x86_sse_ucomieq_ss:
9181   case Intrinsic::x86_sse_ucomilt_ss:
9182   case Intrinsic::x86_sse_ucomile_ss:
9183   case Intrinsic::x86_sse_ucomigt_ss:
9184   case Intrinsic::x86_sse_ucomige_ss:
9185   case Intrinsic::x86_sse_ucomineq_ss:
9186   case Intrinsic::x86_sse2_comieq_sd:
9187   case Intrinsic::x86_sse2_comilt_sd:
9188   case Intrinsic::x86_sse2_comile_sd:
9189   case Intrinsic::x86_sse2_comigt_sd:
9190   case Intrinsic::x86_sse2_comige_sd:
9191   case Intrinsic::x86_sse2_comineq_sd:
9192   case Intrinsic::x86_sse2_ucomieq_sd:
9193   case Intrinsic::x86_sse2_ucomilt_sd:
9194   case Intrinsic::x86_sse2_ucomile_sd:
9195   case Intrinsic::x86_sse2_ucomigt_sd:
9196   case Intrinsic::x86_sse2_ucomige_sd:
9197   case Intrinsic::x86_sse2_ucomineq_sd: {
9198     unsigned Opc = 0;
9199     ISD::CondCode CC = ISD::SETCC_INVALID;
9200     switch (IntNo) {
9201     default: break;
9202     case Intrinsic::x86_sse_comieq_ss:
9203     case Intrinsic::x86_sse2_comieq_sd:
9204       Opc = X86ISD::COMI;
9205       CC = ISD::SETEQ;
9206       break;
9207     case Intrinsic::x86_sse_comilt_ss:
9208     case Intrinsic::x86_sse2_comilt_sd:
9209       Opc = X86ISD::COMI;
9210       CC = ISD::SETLT;
9211       break;
9212     case Intrinsic::x86_sse_comile_ss:
9213     case Intrinsic::x86_sse2_comile_sd:
9214       Opc = X86ISD::COMI;
9215       CC = ISD::SETLE;
9216       break;
9217     case Intrinsic::x86_sse_comigt_ss:
9218     case Intrinsic::x86_sse2_comigt_sd:
9219       Opc = X86ISD::COMI;
9220       CC = ISD::SETGT;
9221       break;
9222     case Intrinsic::x86_sse_comige_ss:
9223     case Intrinsic::x86_sse2_comige_sd:
9224       Opc = X86ISD::COMI;
9225       CC = ISD::SETGE;
9226       break;
9227     case Intrinsic::x86_sse_comineq_ss:
9228     case Intrinsic::x86_sse2_comineq_sd:
9229       Opc = X86ISD::COMI;
9230       CC = ISD::SETNE;
9231       break;
9232     case Intrinsic::x86_sse_ucomieq_ss:
9233     case Intrinsic::x86_sse2_ucomieq_sd:
9234       Opc = X86ISD::UCOMI;
9235       CC = ISD::SETEQ;
9236       break;
9237     case Intrinsic::x86_sse_ucomilt_ss:
9238     case Intrinsic::x86_sse2_ucomilt_sd:
9239       Opc = X86ISD::UCOMI;
9240       CC = ISD::SETLT;
9241       break;
9242     case Intrinsic::x86_sse_ucomile_ss:
9243     case Intrinsic::x86_sse2_ucomile_sd:
9244       Opc = X86ISD::UCOMI;
9245       CC = ISD::SETLE;
9246       break;
9247     case Intrinsic::x86_sse_ucomigt_ss:
9248     case Intrinsic::x86_sse2_ucomigt_sd:
9249       Opc = X86ISD::UCOMI;
9250       CC = ISD::SETGT;
9251       break;
9252     case Intrinsic::x86_sse_ucomige_ss:
9253     case Intrinsic::x86_sse2_ucomige_sd:
9254       Opc = X86ISD::UCOMI;
9255       CC = ISD::SETGE;
9256       break;
9257     case Intrinsic::x86_sse_ucomineq_ss:
9258     case Intrinsic::x86_sse2_ucomineq_sd:
9259       Opc = X86ISD::UCOMI;
9260       CC = ISD::SETNE;
9261       break;
9262     }
9263
9264     SDValue LHS = Op.getOperand(1);
9265     SDValue RHS = Op.getOperand(2);
9266     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
9267     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
9268     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
9269     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9270                                 DAG.getConstant(X86CC, MVT::i8), Cond);
9271     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9272   }
9273   // Arithmetic intrinsics.
9274   case Intrinsic::x86_sse3_hadd_ps:
9275   case Intrinsic::x86_sse3_hadd_pd:
9276   case Intrinsic::x86_avx_hadd_ps_256:
9277   case Intrinsic::x86_avx_hadd_pd_256:
9278     return DAG.getNode(X86ISD::FHADD, dl, Op.getValueType(),
9279                        Op.getOperand(1), Op.getOperand(2));
9280   case Intrinsic::x86_sse3_hsub_ps:
9281   case Intrinsic::x86_sse3_hsub_pd:
9282   case Intrinsic::x86_avx_hsub_ps_256:
9283   case Intrinsic::x86_avx_hsub_pd_256:
9284     return DAG.getNode(X86ISD::FHSUB, dl, Op.getValueType(),
9285                        Op.getOperand(1), Op.getOperand(2));
9286   case Intrinsic::x86_avx2_psllv_d:
9287   case Intrinsic::x86_avx2_psllv_q:
9288   case Intrinsic::x86_avx2_psllv_d_256:
9289   case Intrinsic::x86_avx2_psllv_q_256:
9290     return DAG.getNode(ISD::SHL, dl, Op.getValueType(),
9291                       Op.getOperand(1), Op.getOperand(2));
9292   case Intrinsic::x86_avx2_psrlv_d:
9293   case Intrinsic::x86_avx2_psrlv_q:
9294   case Intrinsic::x86_avx2_psrlv_d_256:
9295   case Intrinsic::x86_avx2_psrlv_q_256:
9296     return DAG.getNode(ISD::SRL, dl, Op.getValueType(),
9297                       Op.getOperand(1), Op.getOperand(2));
9298   case Intrinsic::x86_avx2_psrav_d:
9299   case Intrinsic::x86_avx2_psrav_d_256:
9300     return DAG.getNode(ISD::SRA, dl, Op.getValueType(),
9301                       Op.getOperand(1), Op.getOperand(2));
9302
9303   // ptest and testp intrinsics. The intrinsic these come from are designed to
9304   // return an integer value, not just an instruction so lower it to the ptest
9305   // or testp pattern and a setcc for the result.
9306   case Intrinsic::x86_sse41_ptestz:
9307   case Intrinsic::x86_sse41_ptestc:
9308   case Intrinsic::x86_sse41_ptestnzc:
9309   case Intrinsic::x86_avx_ptestz_256:
9310   case Intrinsic::x86_avx_ptestc_256:
9311   case Intrinsic::x86_avx_ptestnzc_256:
9312   case Intrinsic::x86_avx_vtestz_ps:
9313   case Intrinsic::x86_avx_vtestc_ps:
9314   case Intrinsic::x86_avx_vtestnzc_ps:
9315   case Intrinsic::x86_avx_vtestz_pd:
9316   case Intrinsic::x86_avx_vtestc_pd:
9317   case Intrinsic::x86_avx_vtestnzc_pd:
9318   case Intrinsic::x86_avx_vtestz_ps_256:
9319   case Intrinsic::x86_avx_vtestc_ps_256:
9320   case Intrinsic::x86_avx_vtestnzc_ps_256:
9321   case Intrinsic::x86_avx_vtestz_pd_256:
9322   case Intrinsic::x86_avx_vtestc_pd_256:
9323   case Intrinsic::x86_avx_vtestnzc_pd_256: {
9324     bool IsTestPacked = false;
9325     unsigned X86CC = 0;
9326     switch (IntNo) {
9327     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
9328     case Intrinsic::x86_avx_vtestz_ps:
9329     case Intrinsic::x86_avx_vtestz_pd:
9330     case Intrinsic::x86_avx_vtestz_ps_256:
9331     case Intrinsic::x86_avx_vtestz_pd_256:
9332       IsTestPacked = true; // Fallthrough
9333     case Intrinsic::x86_sse41_ptestz:
9334     case Intrinsic::x86_avx_ptestz_256:
9335       // ZF = 1
9336       X86CC = X86::COND_E;
9337       break;
9338     case Intrinsic::x86_avx_vtestc_ps:
9339     case Intrinsic::x86_avx_vtestc_pd:
9340     case Intrinsic::x86_avx_vtestc_ps_256:
9341     case Intrinsic::x86_avx_vtestc_pd_256:
9342       IsTestPacked = true; // Fallthrough
9343     case Intrinsic::x86_sse41_ptestc:
9344     case Intrinsic::x86_avx_ptestc_256:
9345       // CF = 1
9346       X86CC = X86::COND_B;
9347       break;
9348     case Intrinsic::x86_avx_vtestnzc_ps:
9349     case Intrinsic::x86_avx_vtestnzc_pd:
9350     case Intrinsic::x86_avx_vtestnzc_ps_256:
9351     case Intrinsic::x86_avx_vtestnzc_pd_256:
9352       IsTestPacked = true; // Fallthrough
9353     case Intrinsic::x86_sse41_ptestnzc:
9354     case Intrinsic::x86_avx_ptestnzc_256:
9355       // ZF and CF = 0
9356       X86CC = X86::COND_A;
9357       break;
9358     }
9359
9360     SDValue LHS = Op.getOperand(1);
9361     SDValue RHS = Op.getOperand(2);
9362     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
9363     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
9364     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
9365     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
9366     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9367   }
9368
9369   // Fix vector shift instructions where the last operand is a non-immediate
9370   // i32 value.
9371   case Intrinsic::x86_avx2_pslli_w:
9372   case Intrinsic::x86_avx2_pslli_d:
9373   case Intrinsic::x86_avx2_pslli_q:
9374   case Intrinsic::x86_avx2_psrli_w:
9375   case Intrinsic::x86_avx2_psrli_d:
9376   case Intrinsic::x86_avx2_psrli_q:
9377   case Intrinsic::x86_avx2_psrai_w:
9378   case Intrinsic::x86_avx2_psrai_d:
9379   case Intrinsic::x86_sse2_pslli_w:
9380   case Intrinsic::x86_sse2_pslli_d:
9381   case Intrinsic::x86_sse2_pslli_q:
9382   case Intrinsic::x86_sse2_psrli_w:
9383   case Intrinsic::x86_sse2_psrli_d:
9384   case Intrinsic::x86_sse2_psrli_q:
9385   case Intrinsic::x86_sse2_psrai_w:
9386   case Intrinsic::x86_sse2_psrai_d:
9387   case Intrinsic::x86_mmx_pslli_w:
9388   case Intrinsic::x86_mmx_pslli_d:
9389   case Intrinsic::x86_mmx_pslli_q:
9390   case Intrinsic::x86_mmx_psrli_w:
9391   case Intrinsic::x86_mmx_psrli_d:
9392   case Intrinsic::x86_mmx_psrli_q:
9393   case Intrinsic::x86_mmx_psrai_w:
9394   case Intrinsic::x86_mmx_psrai_d: {
9395     SDValue ShAmt = Op.getOperand(2);
9396     if (isa<ConstantSDNode>(ShAmt))
9397       return SDValue();
9398
9399     unsigned NewIntNo = 0;
9400     EVT ShAmtVT = MVT::v4i32;
9401     switch (IntNo) {
9402     case Intrinsic::x86_sse2_pslli_w:
9403       NewIntNo = Intrinsic::x86_sse2_psll_w;
9404       break;
9405     case Intrinsic::x86_sse2_pslli_d:
9406       NewIntNo = Intrinsic::x86_sse2_psll_d;
9407       break;
9408     case Intrinsic::x86_sse2_pslli_q:
9409       NewIntNo = Intrinsic::x86_sse2_psll_q;
9410       break;
9411     case Intrinsic::x86_sse2_psrli_w:
9412       NewIntNo = Intrinsic::x86_sse2_psrl_w;
9413       break;
9414     case Intrinsic::x86_sse2_psrli_d:
9415       NewIntNo = Intrinsic::x86_sse2_psrl_d;
9416       break;
9417     case Intrinsic::x86_sse2_psrli_q:
9418       NewIntNo = Intrinsic::x86_sse2_psrl_q;
9419       break;
9420     case Intrinsic::x86_sse2_psrai_w:
9421       NewIntNo = Intrinsic::x86_sse2_psra_w;
9422       break;
9423     case Intrinsic::x86_sse2_psrai_d:
9424       NewIntNo = Intrinsic::x86_sse2_psra_d;
9425       break;
9426     case Intrinsic::x86_avx2_pslli_w:
9427       NewIntNo = Intrinsic::x86_avx2_psll_w;
9428       break;
9429     case Intrinsic::x86_avx2_pslli_d:
9430       NewIntNo = Intrinsic::x86_avx2_psll_d;
9431       break;
9432     case Intrinsic::x86_avx2_pslli_q:
9433       NewIntNo = Intrinsic::x86_avx2_psll_q;
9434       break;
9435     case Intrinsic::x86_avx2_psrli_w:
9436       NewIntNo = Intrinsic::x86_avx2_psrl_w;
9437       break;
9438     case Intrinsic::x86_avx2_psrli_d:
9439       NewIntNo = Intrinsic::x86_avx2_psrl_d;
9440       break;
9441     case Intrinsic::x86_avx2_psrli_q:
9442       NewIntNo = Intrinsic::x86_avx2_psrl_q;
9443       break;
9444     case Intrinsic::x86_avx2_psrai_w:
9445       NewIntNo = Intrinsic::x86_avx2_psra_w;
9446       break;
9447     case Intrinsic::x86_avx2_psrai_d:
9448       NewIntNo = Intrinsic::x86_avx2_psra_d;
9449       break;
9450     default: {
9451       ShAmtVT = MVT::v2i32;
9452       switch (IntNo) {
9453       case Intrinsic::x86_mmx_pslli_w:
9454         NewIntNo = Intrinsic::x86_mmx_psll_w;
9455         break;
9456       case Intrinsic::x86_mmx_pslli_d:
9457         NewIntNo = Intrinsic::x86_mmx_psll_d;
9458         break;
9459       case Intrinsic::x86_mmx_pslli_q:
9460         NewIntNo = Intrinsic::x86_mmx_psll_q;
9461         break;
9462       case Intrinsic::x86_mmx_psrli_w:
9463         NewIntNo = Intrinsic::x86_mmx_psrl_w;
9464         break;
9465       case Intrinsic::x86_mmx_psrli_d:
9466         NewIntNo = Intrinsic::x86_mmx_psrl_d;
9467         break;
9468       case Intrinsic::x86_mmx_psrli_q:
9469         NewIntNo = Intrinsic::x86_mmx_psrl_q;
9470         break;
9471       case Intrinsic::x86_mmx_psrai_w:
9472         NewIntNo = Intrinsic::x86_mmx_psra_w;
9473         break;
9474       case Intrinsic::x86_mmx_psrai_d:
9475         NewIntNo = Intrinsic::x86_mmx_psra_d;
9476         break;
9477       default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9478       }
9479       break;
9480     }
9481     }
9482
9483     // The vector shift intrinsics with scalars uses 32b shift amounts but
9484     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
9485     // to be zero.
9486     SDValue ShOps[4];
9487     ShOps[0] = ShAmt;
9488     ShOps[1] = DAG.getConstant(0, MVT::i32);
9489     if (ShAmtVT == MVT::v4i32) {
9490       ShOps[2] = DAG.getUNDEF(MVT::i32);
9491       ShOps[3] = DAG.getUNDEF(MVT::i32);
9492       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
9493     } else {
9494       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
9495 // FIXME this must be lowered to get rid of the invalid type.
9496     }
9497
9498     EVT VT = Op.getValueType();
9499     ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
9500     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9501                        DAG.getConstant(NewIntNo, MVT::i32),
9502                        Op.getOperand(1), ShAmt);
9503   }
9504   }
9505 }
9506
9507 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
9508                                            SelectionDAG &DAG) const {
9509   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9510   MFI->setReturnAddressIsTaken(true);
9511
9512   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9513   DebugLoc dl = Op.getDebugLoc();
9514
9515   if (Depth > 0) {
9516     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
9517     SDValue Offset =
9518       DAG.getConstant(TD->getPointerSize(),
9519                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
9520     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9521                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
9522                                    FrameAddr, Offset),
9523                        MachinePointerInfo(), false, false, false, 0);
9524   }
9525
9526   // Just load the return address.
9527   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
9528   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9529                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
9530 }
9531
9532 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
9533   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9534   MFI->setFrameAddressIsTaken(true);
9535
9536   EVT VT = Op.getValueType();
9537   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
9538   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9539   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
9540   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
9541   while (Depth--)
9542     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
9543                             MachinePointerInfo(),
9544                             false, false, false, 0);
9545   return FrameAddr;
9546 }
9547
9548 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
9549                                                      SelectionDAG &DAG) const {
9550   return DAG.getIntPtrConstant(2*TD->getPointerSize());
9551 }
9552
9553 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
9554   MachineFunction &MF = DAG.getMachineFunction();
9555   SDValue Chain     = Op.getOperand(0);
9556   SDValue Offset    = Op.getOperand(1);
9557   SDValue Handler   = Op.getOperand(2);
9558   DebugLoc dl       = Op.getDebugLoc();
9559
9560   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
9561                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
9562                                      getPointerTy());
9563   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
9564
9565   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
9566                                   DAG.getIntPtrConstant(TD->getPointerSize()));
9567   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
9568   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
9569                        false, false, 0);
9570   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
9571   MF.getRegInfo().addLiveOut(StoreAddrReg);
9572
9573   return DAG.getNode(X86ISD::EH_RETURN, dl,
9574                      MVT::Other,
9575                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
9576 }
9577
9578 SDValue X86TargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
9579                                                   SelectionDAG &DAG) const {
9580   return Op.getOperand(0);
9581 }
9582
9583 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
9584                                                 SelectionDAG &DAG) const {
9585   SDValue Root = Op.getOperand(0);
9586   SDValue Trmp = Op.getOperand(1); // trampoline
9587   SDValue FPtr = Op.getOperand(2); // nested function
9588   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
9589   DebugLoc dl  = Op.getDebugLoc();
9590
9591   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9592
9593   if (Subtarget->is64Bit()) {
9594     SDValue OutChains[6];
9595
9596     // Large code-model.
9597     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
9598     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
9599
9600     const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10);
9601     const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11);
9602
9603     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
9604
9605     // Load the pointer to the nested function into R11.
9606     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
9607     SDValue Addr = Trmp;
9608     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9609                                 Addr, MachinePointerInfo(TrmpAddr),
9610                                 false, false, 0);
9611
9612     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9613                        DAG.getConstant(2, MVT::i64));
9614     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
9615                                 MachinePointerInfo(TrmpAddr, 2),
9616                                 false, false, 2);
9617
9618     // Load the 'nest' parameter value into R10.
9619     // R10 is specified in X86CallingConv.td
9620     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
9621     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9622                        DAG.getConstant(10, MVT::i64));
9623     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9624                                 Addr, MachinePointerInfo(TrmpAddr, 10),
9625                                 false, false, 0);
9626
9627     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9628                        DAG.getConstant(12, MVT::i64));
9629     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
9630                                 MachinePointerInfo(TrmpAddr, 12),
9631                                 false, false, 2);
9632
9633     // Jump to the nested function.
9634     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
9635     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9636                        DAG.getConstant(20, MVT::i64));
9637     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9638                                 Addr, MachinePointerInfo(TrmpAddr, 20),
9639                                 false, false, 0);
9640
9641     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
9642     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9643                        DAG.getConstant(22, MVT::i64));
9644     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
9645                                 MachinePointerInfo(TrmpAddr, 22),
9646                                 false, false, 0);
9647
9648     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
9649   } else {
9650     const Function *Func =
9651       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
9652     CallingConv::ID CC = Func->getCallingConv();
9653     unsigned NestReg;
9654
9655     switch (CC) {
9656     default:
9657       llvm_unreachable("Unsupported calling convention");
9658     case CallingConv::C:
9659     case CallingConv::X86_StdCall: {
9660       // Pass 'nest' parameter in ECX.
9661       // Must be kept in sync with X86CallingConv.td
9662       NestReg = X86::ECX;
9663
9664       // Check that ECX wasn't needed by an 'inreg' parameter.
9665       FunctionType *FTy = Func->getFunctionType();
9666       const AttrListPtr &Attrs = Func->getAttributes();
9667
9668       if (!Attrs.isEmpty() && !Func->isVarArg()) {
9669         unsigned InRegCount = 0;
9670         unsigned Idx = 1;
9671
9672         for (FunctionType::param_iterator I = FTy->param_begin(),
9673              E = FTy->param_end(); I != E; ++I, ++Idx)
9674           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
9675             // FIXME: should only count parameters that are lowered to integers.
9676             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
9677
9678         if (InRegCount > 2) {
9679           report_fatal_error("Nest register in use - reduce number of inreg"
9680                              " parameters!");
9681         }
9682       }
9683       break;
9684     }
9685     case CallingConv::X86_FastCall:
9686     case CallingConv::X86_ThisCall:
9687     case CallingConv::Fast:
9688       // Pass 'nest' parameter in EAX.
9689       // Must be kept in sync with X86CallingConv.td
9690       NestReg = X86::EAX;
9691       break;
9692     }
9693
9694     SDValue OutChains[4];
9695     SDValue Addr, Disp;
9696
9697     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9698                        DAG.getConstant(10, MVT::i32));
9699     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
9700
9701     // This is storing the opcode for MOV32ri.
9702     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
9703     const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg);
9704     OutChains[0] = DAG.getStore(Root, dl,
9705                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
9706                                 Trmp, MachinePointerInfo(TrmpAddr),
9707                                 false, false, 0);
9708
9709     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9710                        DAG.getConstant(1, MVT::i32));
9711     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
9712                                 MachinePointerInfo(TrmpAddr, 1),
9713                                 false, false, 1);
9714
9715     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
9716     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9717                        DAG.getConstant(5, MVT::i32));
9718     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
9719                                 MachinePointerInfo(TrmpAddr, 5),
9720                                 false, false, 1);
9721
9722     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9723                        DAG.getConstant(6, MVT::i32));
9724     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
9725                                 MachinePointerInfo(TrmpAddr, 6),
9726                                 false, false, 1);
9727
9728     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
9729   }
9730 }
9731
9732 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
9733                                             SelectionDAG &DAG) const {
9734   /*
9735    The rounding mode is in bits 11:10 of FPSR, and has the following
9736    settings:
9737      00 Round to nearest
9738      01 Round to -inf
9739      10 Round to +inf
9740      11 Round to 0
9741
9742   FLT_ROUNDS, on the other hand, expects the following:
9743     -1 Undefined
9744      0 Round to 0
9745      1 Round to nearest
9746      2 Round to +inf
9747      3 Round to -inf
9748
9749   To perform the conversion, we do:
9750     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
9751   */
9752
9753   MachineFunction &MF = DAG.getMachineFunction();
9754   const TargetMachine &TM = MF.getTarget();
9755   const TargetFrameLowering &TFI = *TM.getFrameLowering();
9756   unsigned StackAlignment = TFI.getStackAlignment();
9757   EVT VT = Op.getValueType();
9758   DebugLoc DL = Op.getDebugLoc();
9759
9760   // Save FP Control Word to stack slot
9761   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
9762   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9763
9764
9765   MachineMemOperand *MMO =
9766    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9767                            MachineMemOperand::MOStore, 2, 2);
9768
9769   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
9770   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
9771                                           DAG.getVTList(MVT::Other),
9772                                           Ops, 2, MVT::i16, MMO);
9773
9774   // Load FP Control Word from stack slot
9775   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
9776                             MachinePointerInfo(), false, false, false, 0);
9777
9778   // Transform as necessary
9779   SDValue CWD1 =
9780     DAG.getNode(ISD::SRL, DL, MVT::i16,
9781                 DAG.getNode(ISD::AND, DL, MVT::i16,
9782                             CWD, DAG.getConstant(0x800, MVT::i16)),
9783                 DAG.getConstant(11, MVT::i8));
9784   SDValue CWD2 =
9785     DAG.getNode(ISD::SRL, DL, MVT::i16,
9786                 DAG.getNode(ISD::AND, DL, MVT::i16,
9787                             CWD, DAG.getConstant(0x400, MVT::i16)),
9788                 DAG.getConstant(9, MVT::i8));
9789
9790   SDValue RetVal =
9791     DAG.getNode(ISD::AND, DL, MVT::i16,
9792                 DAG.getNode(ISD::ADD, DL, MVT::i16,
9793                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
9794                             DAG.getConstant(1, MVT::i16)),
9795                 DAG.getConstant(3, MVT::i16));
9796
9797
9798   return DAG.getNode((VT.getSizeInBits() < 16 ?
9799                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
9800 }
9801
9802 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
9803   EVT VT = Op.getValueType();
9804   EVT OpVT = VT;
9805   unsigned NumBits = VT.getSizeInBits();
9806   DebugLoc dl = Op.getDebugLoc();
9807
9808   Op = Op.getOperand(0);
9809   if (VT == MVT::i8) {
9810     // Zero extend to i32 since there is not an i8 bsr.
9811     OpVT = MVT::i32;
9812     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
9813   }
9814
9815   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
9816   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
9817   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
9818
9819   // If src is zero (i.e. bsr sets ZF), returns NumBits.
9820   SDValue Ops[] = {
9821     Op,
9822     DAG.getConstant(NumBits+NumBits-1, OpVT),
9823     DAG.getConstant(X86::COND_E, MVT::i8),
9824     Op.getValue(1)
9825   };
9826   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
9827
9828   // Finally xor with NumBits-1.
9829   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
9830
9831   if (VT == MVT::i8)
9832     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
9833   return Op;
9834 }
9835
9836 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
9837   EVT VT = Op.getValueType();
9838   EVT OpVT = VT;
9839   unsigned NumBits = VT.getSizeInBits();
9840   DebugLoc dl = Op.getDebugLoc();
9841
9842   Op = Op.getOperand(0);
9843   if (VT == MVT::i8) {
9844     OpVT = MVT::i32;
9845     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
9846   }
9847
9848   // Issue a bsf (scan bits forward) which also sets EFLAGS.
9849   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
9850   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
9851
9852   // If src is zero (i.e. bsf sets ZF), returns NumBits.
9853   SDValue Ops[] = {
9854     Op,
9855     DAG.getConstant(NumBits, OpVT),
9856     DAG.getConstant(X86::COND_E, MVT::i8),
9857     Op.getValue(1)
9858   };
9859   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
9860
9861   if (VT == MVT::i8)
9862     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
9863   return Op;
9864 }
9865
9866 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
9867 // ones, and then concatenate the result back.
9868 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
9869   EVT VT = Op.getValueType();
9870
9871   assert(VT.getSizeInBits() == 256 && VT.isInteger() &&
9872          "Unsupported value type for operation");
9873
9874   int NumElems = VT.getVectorNumElements();
9875   DebugLoc dl = Op.getDebugLoc();
9876   SDValue Idx0 = DAG.getConstant(0, MVT::i32);
9877   SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
9878
9879   // Extract the LHS vectors
9880   SDValue LHS = Op.getOperand(0);
9881   SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
9882   SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
9883
9884   // Extract the RHS vectors
9885   SDValue RHS = Op.getOperand(1);
9886   SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl);
9887   SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl);
9888
9889   MVT EltVT = VT.getVectorElementType().getSimpleVT();
9890   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9891
9892   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9893                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
9894                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
9895 }
9896
9897 SDValue X86TargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const {
9898   assert(Op.getValueType().getSizeInBits() == 256 &&
9899          Op.getValueType().isInteger() &&
9900          "Only handle AVX 256-bit vector integer operation");
9901   return Lower256IntArith(Op, DAG);
9902 }
9903
9904 SDValue X86TargetLowering::LowerSUB(SDValue Op, SelectionDAG &DAG) const {
9905   assert(Op.getValueType().getSizeInBits() == 256 &&
9906          Op.getValueType().isInteger() &&
9907          "Only handle AVX 256-bit vector integer operation");
9908   return Lower256IntArith(Op, DAG);
9909 }
9910
9911 SDValue X86TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
9912   EVT VT = Op.getValueType();
9913
9914   // Decompose 256-bit ops into smaller 128-bit ops.
9915   if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2())
9916     return Lower256IntArith(Op, DAG);
9917
9918   DebugLoc dl = Op.getDebugLoc();
9919
9920   SDValue A = Op.getOperand(0);
9921   SDValue B = Op.getOperand(1);
9922
9923   if (VT == MVT::v4i64) {
9924     assert(Subtarget->hasAVX2() && "Lowering v4i64 multiply requires AVX2");
9925
9926     //  ulong2 Ahi = __builtin_ia32_psrlqi256( a, 32);
9927     //  ulong2 Bhi = __builtin_ia32_psrlqi256( b, 32);
9928     //  ulong2 AloBlo = __builtin_ia32_pmuludq256( a, b );
9929     //  ulong2 AloBhi = __builtin_ia32_pmuludq256( a, Bhi );
9930     //  ulong2 AhiBlo = __builtin_ia32_pmuludq256( Ahi, b );
9931     //
9932     //  AloBhi = __builtin_ia32_psllqi256( AloBhi, 32 );
9933     //  AhiBlo = __builtin_ia32_psllqi256( AhiBlo, 32 );
9934     //  return AloBlo + AloBhi + AhiBlo;
9935
9936     SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9937                          DAG.getConstant(Intrinsic::x86_avx2_psrli_q, MVT::i32),
9938                          A, DAG.getConstant(32, MVT::i32));
9939     SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9940                          DAG.getConstant(Intrinsic::x86_avx2_psrli_q, MVT::i32),
9941                          B, DAG.getConstant(32, MVT::i32));
9942     SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9943                          DAG.getConstant(Intrinsic::x86_avx2_pmulu_dq, MVT::i32),
9944                          A, B);
9945     SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9946                          DAG.getConstant(Intrinsic::x86_avx2_pmulu_dq, MVT::i32),
9947                          A, Bhi);
9948     SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9949                          DAG.getConstant(Intrinsic::x86_avx2_pmulu_dq, MVT::i32),
9950                          Ahi, B);
9951     AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9952                          DAG.getConstant(Intrinsic::x86_avx2_pslli_q, MVT::i32),
9953                          AloBhi, DAG.getConstant(32, MVT::i32));
9954     AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9955                          DAG.getConstant(Intrinsic::x86_avx2_pslli_q, MVT::i32),
9956                          AhiBlo, DAG.getConstant(32, MVT::i32));
9957     SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
9958     Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
9959     return Res;
9960   }
9961
9962   assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
9963
9964   //  ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
9965   //  ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
9966   //  ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
9967   //  ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
9968   //  ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
9969   //
9970   //  AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
9971   //  AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
9972   //  return AloBlo + AloBhi + AhiBlo;
9973
9974   SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9975                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9976                        A, DAG.getConstant(32, MVT::i32));
9977   SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9978                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9979                        B, DAG.getConstant(32, MVT::i32));
9980   SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9981                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
9982                        A, B);
9983   SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9984                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
9985                        A, Bhi);
9986   SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9987                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
9988                        Ahi, B);
9989   AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9990                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9991                        AloBhi, DAG.getConstant(32, MVT::i32));
9992   AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9993                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9994                        AhiBlo, DAG.getConstant(32, MVT::i32));
9995   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
9996   Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
9997   return Res;
9998 }
9999
10000 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
10001
10002   EVT VT = Op.getValueType();
10003   DebugLoc dl = Op.getDebugLoc();
10004   SDValue R = Op.getOperand(0);
10005   SDValue Amt = Op.getOperand(1);
10006   LLVMContext *Context = DAG.getContext();
10007
10008   if (!Subtarget->hasXMMInt())
10009     return SDValue();
10010
10011   // Optimize shl/srl/sra with constant shift amount.
10012   if (isSplatVector(Amt.getNode())) {
10013     SDValue SclrAmt = Amt->getOperand(0);
10014     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
10015       uint64_t ShiftAmt = C->getZExtValue();
10016
10017       if (VT == MVT::v16i8 && Op.getOpcode() == ISD::SHL) {
10018         // Make a large shift.
10019         SDValue SHL =
10020           DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10021                       DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10022                       R, DAG.getConstant(ShiftAmt, MVT::i32));
10023         // Zero out the rightmost bits.
10024         SmallVector<SDValue, 16> V(16, DAG.getConstant(uint8_t(-1U << ShiftAmt),
10025                                                        MVT::i8));
10026         return DAG.getNode(ISD::AND, dl, VT, SHL,
10027                            DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10028       }
10029
10030       if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SHL)
10031        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10032                      DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
10033                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10034
10035       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SHL)
10036        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10037                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
10038                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10039
10040       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SHL)
10041        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10042                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10043                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10044
10045       if (VT == MVT::v16i8 && Op.getOpcode() == ISD::SRL) {
10046         // Make a large shift.
10047         SDValue SRL =
10048           DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10049                       DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
10050                       R, DAG.getConstant(ShiftAmt, MVT::i32));
10051         // Zero out the leftmost bits.
10052         SmallVector<SDValue, 16> V(16, DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10053                                                        MVT::i8));
10054         return DAG.getNode(ISD::AND, dl, VT, SRL,
10055                            DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10056       }
10057
10058       if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SRL)
10059        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10060                      DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
10061                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10062
10063       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRL)
10064        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10065                      DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
10066                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10067
10068       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRL)
10069        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10070                      DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
10071                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10072
10073       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRA)
10074        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10075                      DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
10076                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10077
10078       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRA)
10079        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10080                      DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
10081                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10082
10083       if (VT == MVT::v16i8 && Op.getOpcode() == ISD::SRA) {
10084         if (ShiftAmt == 7) {
10085           // R s>> 7  ===  R s< 0
10086           SDValue Zeros = getZeroVector(VT, true /* HasXMMInt */, DAG, dl);
10087           return DAG.getNode(X86ISD::PCMPGTB, dl, VT, Zeros, R);
10088         }
10089
10090         // R s>> a === ((R u>> a) ^ m) - m
10091         SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10092         SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
10093                                                        MVT::i8));
10094         SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
10095         Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10096         Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10097         return Res;
10098       }
10099
10100       if (Subtarget->hasAVX2() && VT == MVT::v32i8) {
10101         if (Op.getOpcode() == ISD::SHL) {
10102           // Make a large shift.
10103           SDValue SHL =
10104             DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10105                         DAG.getConstant(Intrinsic::x86_avx2_pslli_w, MVT::i32),
10106                         R, DAG.getConstant(ShiftAmt, MVT::i32));
10107           // Zero out the rightmost bits.
10108           SmallVector<SDValue, 32> V(32, DAG.getConstant(uint8_t(-1U << ShiftAmt),
10109                                                          MVT::i8));
10110           return DAG.getNode(ISD::AND, dl, VT, SHL,
10111                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10112         }
10113         if (Op.getOpcode() == ISD::SRL) {
10114           // Make a large shift.
10115           SDValue SRL =
10116             DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10117                         DAG.getConstant(Intrinsic::x86_avx2_psrli_w, MVT::i32),
10118                         R, DAG.getConstant(ShiftAmt, MVT::i32));
10119           // Zero out the leftmost bits.
10120           SmallVector<SDValue, 32> V(32, DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10121                                                          MVT::i8));
10122           return DAG.getNode(ISD::AND, dl, VT, SRL,
10123                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10124         }
10125         if (Op.getOpcode() == ISD::SRA) {
10126           if (ShiftAmt == 7) {
10127             // R s>> 7  ===  R s< 0
10128             SDValue Zeros = getZeroVector(VT, true /* HasXMMInt */, DAG, dl);
10129             return DAG.getNode(X86ISD::PCMPGTB, dl, VT, Zeros, R);
10130           }
10131
10132           // R s>> a === ((R u>> a) ^ m) - m
10133           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10134           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
10135                                                          MVT::i8));
10136           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
10137           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10138           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10139           return Res;
10140         }
10141       }
10142     }
10143   }
10144
10145   // Lower SHL with variable shift amount.
10146   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
10147     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10148                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
10149                      Op.getOperand(1), DAG.getConstant(23, MVT::i32));
10150
10151     ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
10152
10153     std::vector<Constant*> CV(4, CI);
10154     Constant *C = ConstantVector::get(CV);
10155     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10156     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10157                                  MachinePointerInfo::getConstantPool(),
10158                                  false, false, false, 16);
10159
10160     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
10161     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
10162     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
10163     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
10164   }
10165   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
10166     assert((Subtarget->hasSSE2() || Subtarget->hasAVX()) &&
10167             "Need SSE2 for pslli/pcmpeq.");
10168
10169     // a = a << 5;
10170     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10171                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10172                      Op.getOperand(1), DAG.getConstant(5, MVT::i32));
10173
10174     // Turn 'a' into a mask suitable for VSELECT
10175     SDValue VSelM = DAG.getConstant(0x80, VT);
10176     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10177     OpVSel = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10178                         DAG.getConstant(Intrinsic::x86_sse2_pcmpeq_b, MVT::i32),
10179                         OpVSel, VSelM);
10180
10181     SDValue CM1 = DAG.getConstant(0x0f, VT);
10182     SDValue CM2 = DAG.getConstant(0x3f, VT);
10183
10184     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
10185     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
10186     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10187                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
10188                     DAG.getConstant(4, MVT::i32));
10189     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10190
10191     // a += a
10192     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10193     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10194     OpVSel = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10195                         DAG.getConstant(Intrinsic::x86_sse2_pcmpeq_b, MVT::i32),
10196                         OpVSel, VSelM);
10197
10198     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
10199     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
10200     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10201                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
10202                     DAG.getConstant(2, MVT::i32));
10203     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10204
10205     // a += a
10206     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10207     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10208     OpVSel = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10209                         DAG.getConstant(Intrinsic::x86_sse2_pcmpeq_b, MVT::i32),
10210                         OpVSel, VSelM);
10211
10212     // return VSELECT(r, r+r, a);
10213     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
10214                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
10215     return R;
10216   }
10217
10218   // Decompose 256-bit shifts into smaller 128-bit shifts.
10219   if (VT.getSizeInBits() == 256) {
10220     int NumElems = VT.getVectorNumElements();
10221     MVT EltVT = VT.getVectorElementType().getSimpleVT();
10222     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10223
10224     // Extract the two vectors
10225     SDValue V1 = Extract128BitVector(R, DAG.getConstant(0, MVT::i32), DAG, dl);
10226     SDValue V2 = Extract128BitVector(R, DAG.getConstant(NumElems/2, MVT::i32),
10227                                      DAG, dl);
10228
10229     // Recreate the shift amount vectors
10230     SDValue Amt1, Amt2;
10231     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
10232       // Constant shift amount
10233       SmallVector<SDValue, 4> Amt1Csts;
10234       SmallVector<SDValue, 4> Amt2Csts;
10235       for (int i = 0; i < NumElems/2; ++i)
10236         Amt1Csts.push_back(Amt->getOperand(i));
10237       for (int i = NumElems/2; i < NumElems; ++i)
10238         Amt2Csts.push_back(Amt->getOperand(i));
10239
10240       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10241                                  &Amt1Csts[0], NumElems/2);
10242       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10243                                  &Amt2Csts[0], NumElems/2);
10244     } else {
10245       // Variable shift amount
10246       Amt1 = Extract128BitVector(Amt, DAG.getConstant(0, MVT::i32), DAG, dl);
10247       Amt2 = Extract128BitVector(Amt, DAG.getConstant(NumElems/2, MVT::i32),
10248                                  DAG, dl);
10249     }
10250
10251     // Issue new vector shifts for the smaller types
10252     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
10253     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
10254
10255     // Concatenate the result back
10256     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
10257   }
10258
10259   return SDValue();
10260 }
10261
10262 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
10263   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
10264   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
10265   // looks for this combo and may remove the "setcc" instruction if the "setcc"
10266   // has only one use.
10267   SDNode *N = Op.getNode();
10268   SDValue LHS = N->getOperand(0);
10269   SDValue RHS = N->getOperand(1);
10270   unsigned BaseOp = 0;
10271   unsigned Cond = 0;
10272   DebugLoc DL = Op.getDebugLoc();
10273   switch (Op.getOpcode()) {
10274   default: llvm_unreachable("Unknown ovf instruction!");
10275   case ISD::SADDO:
10276     // A subtract of one will be selected as a INC. Note that INC doesn't
10277     // set CF, so we can't do this for UADDO.
10278     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10279       if (C->isOne()) {
10280         BaseOp = X86ISD::INC;
10281         Cond = X86::COND_O;
10282         break;
10283       }
10284     BaseOp = X86ISD::ADD;
10285     Cond = X86::COND_O;
10286     break;
10287   case ISD::UADDO:
10288     BaseOp = X86ISD::ADD;
10289     Cond = X86::COND_B;
10290     break;
10291   case ISD::SSUBO:
10292     // A subtract of one will be selected as a DEC. Note that DEC doesn't
10293     // set CF, so we can't do this for USUBO.
10294     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10295       if (C->isOne()) {
10296         BaseOp = X86ISD::DEC;
10297         Cond = X86::COND_O;
10298         break;
10299       }
10300     BaseOp = X86ISD::SUB;
10301     Cond = X86::COND_O;
10302     break;
10303   case ISD::USUBO:
10304     BaseOp = X86ISD::SUB;
10305     Cond = X86::COND_B;
10306     break;
10307   case ISD::SMULO:
10308     BaseOp = X86ISD::SMUL;
10309     Cond = X86::COND_O;
10310     break;
10311   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
10312     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
10313                                  MVT::i32);
10314     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
10315
10316     SDValue SetCC =
10317       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10318                   DAG.getConstant(X86::COND_O, MVT::i32),
10319                   SDValue(Sum.getNode(), 2));
10320
10321     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10322   }
10323   }
10324
10325   // Also sets EFLAGS.
10326   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
10327   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
10328
10329   SDValue SetCC =
10330     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
10331                 DAG.getConstant(Cond, MVT::i32),
10332                 SDValue(Sum.getNode(), 1));
10333
10334   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10335 }
10336
10337 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op, SelectionDAG &DAG) const{
10338   DebugLoc dl = Op.getDebugLoc();
10339   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
10340   EVT VT = Op.getValueType();
10341
10342   if (Subtarget->hasXMMInt() && VT.isVector()) {
10343     unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
10344                         ExtraVT.getScalarType().getSizeInBits();
10345     SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
10346
10347     unsigned SHLIntrinsicsID = 0;
10348     unsigned SRAIntrinsicsID = 0;
10349     switch (VT.getSimpleVT().SimpleTy) {
10350       default:
10351         return SDValue();
10352       case MVT::v4i32:
10353         SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_d;
10354         SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_d;
10355         break;
10356       case MVT::v8i16:
10357         SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_w;
10358         SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_w;
10359         break;
10360       case MVT::v8i32:
10361       case MVT::v16i16:
10362         if (!Subtarget->hasAVX())
10363           return SDValue();
10364         if (!Subtarget->hasAVX2()) {
10365           // needs to be split
10366           int NumElems = VT.getVectorNumElements();
10367           SDValue Idx0 = DAG.getConstant(0, MVT::i32);
10368           SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
10369
10370           // Extract the LHS vectors
10371           SDValue LHS = Op.getOperand(0);
10372           SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
10373           SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
10374
10375           MVT EltVT = VT.getVectorElementType().getSimpleVT();
10376           EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10377
10378           EVT ExtraEltVT = ExtraVT.getVectorElementType();
10379           int ExtraNumElems = ExtraVT.getVectorNumElements();
10380           ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
10381                                      ExtraNumElems/2);
10382           SDValue Extra = DAG.getValueType(ExtraVT);
10383
10384           LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
10385           LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
10386
10387           return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);;
10388         }
10389         if (VT == MVT::v8i32) {
10390           SHLIntrinsicsID = Intrinsic::x86_avx2_pslli_d;
10391           SRAIntrinsicsID = Intrinsic::x86_avx2_psrai_d;
10392         } else {
10393           SHLIntrinsicsID = Intrinsic::x86_avx2_pslli_w;
10394           SRAIntrinsicsID = Intrinsic::x86_avx2_psrai_w;
10395         }
10396     }
10397
10398     SDValue Tmp1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10399                          DAG.getConstant(SHLIntrinsicsID, MVT::i32),
10400                          Op.getOperand(0), ShAmt);
10401
10402     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10403                        DAG.getConstant(SRAIntrinsicsID, MVT::i32),
10404                        Tmp1, ShAmt);
10405   }
10406
10407   return SDValue();
10408 }
10409
10410
10411 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
10412   DebugLoc dl = Op.getDebugLoc();
10413
10414   // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
10415   // There isn't any reason to disable it if the target processor supports it.
10416   if (!Subtarget->hasXMMInt() && !Subtarget->is64Bit()) {
10417     SDValue Chain = Op.getOperand(0);
10418     SDValue Zero = DAG.getConstant(0, MVT::i32);
10419     SDValue Ops[] = {
10420       DAG.getRegister(X86::ESP, MVT::i32), // Base
10421       DAG.getTargetConstant(1, MVT::i8),   // Scale
10422       DAG.getRegister(0, MVT::i32),        // Index
10423       DAG.getTargetConstant(0, MVT::i32),  // Disp
10424       DAG.getRegister(0, MVT::i32),        // Segment.
10425       Zero,
10426       Chain
10427     };
10428     SDNode *Res =
10429       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10430                           array_lengthof(Ops));
10431     return SDValue(Res, 0);
10432   }
10433
10434   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
10435   if (!isDev)
10436     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10437
10438   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10439   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
10440   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
10441   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
10442
10443   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
10444   if (!Op1 && !Op2 && !Op3 && Op4)
10445     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
10446
10447   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
10448   if (Op1 && !Op2 && !Op3 && !Op4)
10449     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
10450
10451   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
10452   //           (MFENCE)>;
10453   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10454 }
10455
10456 SDValue X86TargetLowering::LowerATOMIC_FENCE(SDValue Op,
10457                                              SelectionDAG &DAG) const {
10458   DebugLoc dl = Op.getDebugLoc();
10459   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
10460     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
10461   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
10462     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
10463
10464   // The only fence that needs an instruction is a sequentially-consistent
10465   // cross-thread fence.
10466   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
10467     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
10468     // no-sse2). There isn't any reason to disable it if the target processor
10469     // supports it.
10470     if (Subtarget->hasXMMInt() || Subtarget->is64Bit())
10471       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10472
10473     SDValue Chain = Op.getOperand(0);
10474     SDValue Zero = DAG.getConstant(0, MVT::i32);
10475     SDValue Ops[] = {
10476       DAG.getRegister(X86::ESP, MVT::i32), // Base
10477       DAG.getTargetConstant(1, MVT::i8),   // Scale
10478       DAG.getRegister(0, MVT::i32),        // Index
10479       DAG.getTargetConstant(0, MVT::i32),  // Disp
10480       DAG.getRegister(0, MVT::i32),        // Segment.
10481       Zero,
10482       Chain
10483     };
10484     SDNode *Res =
10485       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10486                          array_lengthof(Ops));
10487     return SDValue(Res, 0);
10488   }
10489
10490   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
10491   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10492 }
10493
10494
10495 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
10496   EVT T = Op.getValueType();
10497   DebugLoc DL = Op.getDebugLoc();
10498   unsigned Reg = 0;
10499   unsigned size = 0;
10500   switch(T.getSimpleVT().SimpleTy) {
10501   default:
10502     assert(false && "Invalid value type!");
10503   case MVT::i8:  Reg = X86::AL;  size = 1; break;
10504   case MVT::i16: Reg = X86::AX;  size = 2; break;
10505   case MVT::i32: Reg = X86::EAX; size = 4; break;
10506   case MVT::i64:
10507     assert(Subtarget->is64Bit() && "Node not type legal!");
10508     Reg = X86::RAX; size = 8;
10509     break;
10510   }
10511   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
10512                                     Op.getOperand(2), SDValue());
10513   SDValue Ops[] = { cpIn.getValue(0),
10514                     Op.getOperand(1),
10515                     Op.getOperand(3),
10516                     DAG.getTargetConstant(size, MVT::i8),
10517                     cpIn.getValue(1) };
10518   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10519   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
10520   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
10521                                            Ops, 5, T, MMO);
10522   SDValue cpOut =
10523     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
10524   return cpOut;
10525 }
10526
10527 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
10528                                                  SelectionDAG &DAG) const {
10529   assert(Subtarget->is64Bit() && "Result not type legalized?");
10530   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10531   SDValue TheChain = Op.getOperand(0);
10532   DebugLoc dl = Op.getDebugLoc();
10533   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10534   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
10535   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
10536                                    rax.getValue(2));
10537   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
10538                             DAG.getConstant(32, MVT::i8));
10539   SDValue Ops[] = {
10540     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
10541     rdx.getValue(1)
10542   };
10543   return DAG.getMergeValues(Ops, 2, dl);
10544 }
10545
10546 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
10547                                             SelectionDAG &DAG) const {
10548   EVT SrcVT = Op.getOperand(0).getValueType();
10549   EVT DstVT = Op.getValueType();
10550   assert(Subtarget->is64Bit() && !Subtarget->hasXMMInt() &&
10551          Subtarget->hasMMX() && "Unexpected custom BITCAST");
10552   assert((DstVT == MVT::i64 ||
10553           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
10554          "Unexpected custom BITCAST");
10555   // i64 <=> MMX conversions are Legal.
10556   if (SrcVT==MVT::i64 && DstVT.isVector())
10557     return Op;
10558   if (DstVT==MVT::i64 && SrcVT.isVector())
10559     return Op;
10560   // MMX <=> MMX conversions are Legal.
10561   if (SrcVT.isVector() && DstVT.isVector())
10562     return Op;
10563   // All other conversions need to be expanded.
10564   return SDValue();
10565 }
10566
10567 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
10568   SDNode *Node = Op.getNode();
10569   DebugLoc dl = Node->getDebugLoc();
10570   EVT T = Node->getValueType(0);
10571   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
10572                               DAG.getConstant(0, T), Node->getOperand(2));
10573   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
10574                        cast<AtomicSDNode>(Node)->getMemoryVT(),
10575                        Node->getOperand(0),
10576                        Node->getOperand(1), negOp,
10577                        cast<AtomicSDNode>(Node)->getSrcValue(),
10578                        cast<AtomicSDNode>(Node)->getAlignment(),
10579                        cast<AtomicSDNode>(Node)->getOrdering(),
10580                        cast<AtomicSDNode>(Node)->getSynchScope());
10581 }
10582
10583 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
10584   SDNode *Node = Op.getNode();
10585   DebugLoc dl = Node->getDebugLoc();
10586   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10587
10588   // Convert seq_cst store -> xchg
10589   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
10590   // FIXME: On 32-bit, store -> fist or movq would be more efficient
10591   //        (The only way to get a 16-byte store is cmpxchg16b)
10592   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
10593   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
10594       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
10595     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
10596                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
10597                                  Node->getOperand(0),
10598                                  Node->getOperand(1), Node->getOperand(2),
10599                                  cast<AtomicSDNode>(Node)->getMemOperand(),
10600                                  cast<AtomicSDNode>(Node)->getOrdering(),
10601                                  cast<AtomicSDNode>(Node)->getSynchScope());
10602     return Swap.getValue(1);
10603   }
10604   // Other atomic stores have a simple pattern.
10605   return Op;
10606 }
10607
10608 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
10609   EVT VT = Op.getNode()->getValueType(0);
10610
10611   // Let legalize expand this if it isn't a legal type yet.
10612   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10613     return SDValue();
10614
10615   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10616
10617   unsigned Opc;
10618   bool ExtraOp = false;
10619   switch (Op.getOpcode()) {
10620   default: assert(0 && "Invalid code");
10621   case ISD::ADDC: Opc = X86ISD::ADD; break;
10622   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
10623   case ISD::SUBC: Opc = X86ISD::SUB; break;
10624   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
10625   }
10626
10627   if (!ExtraOp)
10628     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10629                        Op.getOperand(1));
10630   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10631                      Op.getOperand(1), Op.getOperand(2));
10632 }
10633
10634 /// LowerOperation - Provide custom lowering hooks for some operations.
10635 ///
10636 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10637   switch (Op.getOpcode()) {
10638   default: llvm_unreachable("Should not custom lower this!");
10639   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
10640   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op,DAG);
10641   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op,DAG);
10642   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
10643   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
10644   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
10645   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
10646   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
10647   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
10648   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
10649   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
10650   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op, DAG);
10651   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, DAG);
10652   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
10653   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
10654   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
10655   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
10656   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
10657   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
10658   case ISD::SHL_PARTS:
10659   case ISD::SRA_PARTS:
10660   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
10661   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
10662   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
10663   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
10664   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
10665   case ISD::FABS:               return LowerFABS(Op, DAG);
10666   case ISD::FNEG:               return LowerFNEG(Op, DAG);
10667   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
10668   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
10669   case ISD::SETCC:              return LowerSETCC(Op, DAG);
10670   case ISD::SELECT:             return LowerSELECT(Op, DAG);
10671   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
10672   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
10673   case ISD::VASTART:            return LowerVASTART(Op, DAG);
10674   case ISD::VAARG:              return LowerVAARG(Op, DAG);
10675   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
10676   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10677   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
10678   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
10679   case ISD::FRAME_TO_ARGS_OFFSET:
10680                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
10681   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10682   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
10683   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
10684   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
10685   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
10686   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
10687   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
10688   case ISD::MUL:                return LowerMUL(Op, DAG);
10689   case ISD::SRA:
10690   case ISD::SRL:
10691   case ISD::SHL:                return LowerShift(Op, DAG);
10692   case ISD::SADDO:
10693   case ISD::UADDO:
10694   case ISD::SSUBO:
10695   case ISD::USUBO:
10696   case ISD::SMULO:
10697   case ISD::UMULO:              return LowerXALUO(Op, DAG);
10698   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
10699   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
10700   case ISD::ADDC:
10701   case ISD::ADDE:
10702   case ISD::SUBC:
10703   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
10704   case ISD::ADD:                return LowerADD(Op, DAG);
10705   case ISD::SUB:                return LowerSUB(Op, DAG);
10706   }
10707 }
10708
10709 static void ReplaceATOMIC_LOAD(SDNode *Node,
10710                                   SmallVectorImpl<SDValue> &Results,
10711                                   SelectionDAG &DAG) {
10712   DebugLoc dl = Node->getDebugLoc();
10713   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10714
10715   // Convert wide load -> cmpxchg8b/cmpxchg16b
10716   // FIXME: On 32-bit, load -> fild or movq would be more efficient
10717   //        (The only way to get a 16-byte load is cmpxchg16b)
10718   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
10719   SDValue Zero = DAG.getConstant(0, VT);
10720   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
10721                                Node->getOperand(0),
10722                                Node->getOperand(1), Zero, Zero,
10723                                cast<AtomicSDNode>(Node)->getMemOperand(),
10724                                cast<AtomicSDNode>(Node)->getOrdering(),
10725                                cast<AtomicSDNode>(Node)->getSynchScope());
10726   Results.push_back(Swap.getValue(0));
10727   Results.push_back(Swap.getValue(1));
10728 }
10729
10730 void X86TargetLowering::
10731 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
10732                         SelectionDAG &DAG, unsigned NewOp) const {
10733   DebugLoc dl = Node->getDebugLoc();
10734   assert (Node->getValueType(0) == MVT::i64 &&
10735           "Only know how to expand i64 atomics");
10736
10737   SDValue Chain = Node->getOperand(0);
10738   SDValue In1 = Node->getOperand(1);
10739   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10740                              Node->getOperand(2), DAG.getIntPtrConstant(0));
10741   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10742                              Node->getOperand(2), DAG.getIntPtrConstant(1));
10743   SDValue Ops[] = { Chain, In1, In2L, In2H };
10744   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
10745   SDValue Result =
10746     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
10747                             cast<MemSDNode>(Node)->getMemOperand());
10748   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
10749   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
10750   Results.push_back(Result.getValue(2));
10751 }
10752
10753 /// ReplaceNodeResults - Replace a node with an illegal result type
10754 /// with a new node built out of custom code.
10755 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
10756                                            SmallVectorImpl<SDValue>&Results,
10757                                            SelectionDAG &DAG) const {
10758   DebugLoc dl = N->getDebugLoc();
10759   switch (N->getOpcode()) {
10760   default:
10761     assert(false && "Do not know how to custom type legalize this operation!");
10762     return;
10763   case ISD::SIGN_EXTEND_INREG:
10764   case ISD::ADDC:
10765   case ISD::ADDE:
10766   case ISD::SUBC:
10767   case ISD::SUBE:
10768     // We don't want to expand or promote these.
10769     return;
10770   case ISD::FP_TO_SINT: {
10771     std::pair<SDValue,SDValue> Vals =
10772         FP_TO_INTHelper(SDValue(N, 0), DAG, true);
10773     SDValue FIST = Vals.first, StackSlot = Vals.second;
10774     if (FIST.getNode() != 0) {
10775       EVT VT = N->getValueType(0);
10776       // Return a load from the stack slot.
10777       Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
10778                                     MachinePointerInfo(), 
10779                                     false, false, false, 0));
10780     }
10781     return;
10782   }
10783   case ISD::READCYCLECOUNTER: {
10784     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10785     SDValue TheChain = N->getOperand(0);
10786     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10787     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
10788                                      rd.getValue(1));
10789     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
10790                                      eax.getValue(2));
10791     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
10792     SDValue Ops[] = { eax, edx };
10793     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
10794     Results.push_back(edx.getValue(1));
10795     return;
10796   }
10797   case ISD::ATOMIC_CMP_SWAP: {
10798     EVT T = N->getValueType(0);
10799     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
10800     bool Regs64bit = T == MVT::i128;
10801     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
10802     SDValue cpInL, cpInH;
10803     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
10804                         DAG.getConstant(0, HalfT));
10805     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
10806                         DAG.getConstant(1, HalfT));
10807     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
10808                              Regs64bit ? X86::RAX : X86::EAX,
10809                              cpInL, SDValue());
10810     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
10811                              Regs64bit ? X86::RDX : X86::EDX,
10812                              cpInH, cpInL.getValue(1));
10813     SDValue swapInL, swapInH;
10814     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
10815                           DAG.getConstant(0, HalfT));
10816     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
10817                           DAG.getConstant(1, HalfT));
10818     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
10819                                Regs64bit ? X86::RBX : X86::EBX,
10820                                swapInL, cpInH.getValue(1));
10821     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
10822                                Regs64bit ? X86::RCX : X86::ECX, 
10823                                swapInH, swapInL.getValue(1));
10824     SDValue Ops[] = { swapInH.getValue(0),
10825                       N->getOperand(1),
10826                       swapInH.getValue(1) };
10827     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10828     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
10829     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
10830                                   X86ISD::LCMPXCHG8_DAG;
10831     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
10832                                              Ops, 3, T, MMO);
10833     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
10834                                         Regs64bit ? X86::RAX : X86::EAX,
10835                                         HalfT, Result.getValue(1));
10836     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
10837                                         Regs64bit ? X86::RDX : X86::EDX,
10838                                         HalfT, cpOutL.getValue(2));
10839     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
10840     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
10841     Results.push_back(cpOutH.getValue(1));
10842     return;
10843   }
10844   case ISD::ATOMIC_LOAD_ADD:
10845     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
10846     return;
10847   case ISD::ATOMIC_LOAD_AND:
10848     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
10849     return;
10850   case ISD::ATOMIC_LOAD_NAND:
10851     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
10852     return;
10853   case ISD::ATOMIC_LOAD_OR:
10854     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
10855     return;
10856   case ISD::ATOMIC_LOAD_SUB:
10857     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
10858     return;
10859   case ISD::ATOMIC_LOAD_XOR:
10860     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
10861     return;
10862   case ISD::ATOMIC_SWAP:
10863     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
10864     return;
10865   case ISD::ATOMIC_LOAD:
10866     ReplaceATOMIC_LOAD(N, Results, DAG);
10867   }
10868 }
10869
10870 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
10871   switch (Opcode) {
10872   default: return NULL;
10873   case X86ISD::BSF:                return "X86ISD::BSF";
10874   case X86ISD::BSR:                return "X86ISD::BSR";
10875   case X86ISD::SHLD:               return "X86ISD::SHLD";
10876   case X86ISD::SHRD:               return "X86ISD::SHRD";
10877   case X86ISD::FAND:               return "X86ISD::FAND";
10878   case X86ISD::FOR:                return "X86ISD::FOR";
10879   case X86ISD::FXOR:               return "X86ISD::FXOR";
10880   case X86ISD::FSRL:               return "X86ISD::FSRL";
10881   case X86ISD::FILD:               return "X86ISD::FILD";
10882   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
10883   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
10884   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
10885   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
10886   case X86ISD::FLD:                return "X86ISD::FLD";
10887   case X86ISD::FST:                return "X86ISD::FST";
10888   case X86ISD::CALL:               return "X86ISD::CALL";
10889   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
10890   case X86ISD::BT:                 return "X86ISD::BT";
10891   case X86ISD::CMP:                return "X86ISD::CMP";
10892   case X86ISD::COMI:               return "X86ISD::COMI";
10893   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
10894   case X86ISD::SETCC:              return "X86ISD::SETCC";
10895   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
10896   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
10897   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
10898   case X86ISD::CMOV:               return "X86ISD::CMOV";
10899   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
10900   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
10901   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
10902   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
10903   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
10904   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
10905   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
10906   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
10907   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
10908   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
10909   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
10910   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
10911   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
10912   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
10913   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
10914   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
10915   case X86ISD::HADD:               return "X86ISD::HADD";
10916   case X86ISD::HSUB:               return "X86ISD::HSUB";
10917   case X86ISD::FHADD:              return "X86ISD::FHADD";
10918   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
10919   case X86ISD::FMAX:               return "X86ISD::FMAX";
10920   case X86ISD::FMIN:               return "X86ISD::FMIN";
10921   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
10922   case X86ISD::FRCP:               return "X86ISD::FRCP";
10923   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
10924   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
10925   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
10926   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
10927   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
10928   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
10929   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
10930   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
10931   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
10932   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
10933   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
10934   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
10935   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
10936   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
10937   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
10938   case X86ISD::VSHL:               return "X86ISD::VSHL";
10939   case X86ISD::VSRL:               return "X86ISD::VSRL";
10940   case X86ISD::CMPPD:              return "X86ISD::CMPPD";
10941   case X86ISD::CMPPS:              return "X86ISD::CMPPS";
10942   case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
10943   case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
10944   case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
10945   case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
10946   case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
10947   case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
10948   case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
10949   case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
10950   case X86ISD::ADD:                return "X86ISD::ADD";
10951   case X86ISD::SUB:                return "X86ISD::SUB";
10952   case X86ISD::ADC:                return "X86ISD::ADC";
10953   case X86ISD::SBB:                return "X86ISD::SBB";
10954   case X86ISD::SMUL:               return "X86ISD::SMUL";
10955   case X86ISD::UMUL:               return "X86ISD::UMUL";
10956   case X86ISD::INC:                return "X86ISD::INC";
10957   case X86ISD::DEC:                return "X86ISD::DEC";
10958   case X86ISD::OR:                 return "X86ISD::OR";
10959   case X86ISD::XOR:                return "X86ISD::XOR";
10960   case X86ISD::AND:                return "X86ISD::AND";
10961   case X86ISD::ANDN:               return "X86ISD::ANDN";
10962   case X86ISD::BLSI:               return "X86ISD::BLSI";
10963   case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
10964   case X86ISD::BLSR:               return "X86ISD::BLSR";
10965   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
10966   case X86ISD::PTEST:              return "X86ISD::PTEST";
10967   case X86ISD::TESTP:              return "X86ISD::TESTP";
10968   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
10969   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
10970   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
10971   case X86ISD::PSHUFHW_LD:         return "X86ISD::PSHUFHW_LD";
10972   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
10973   case X86ISD::PSHUFLW_LD:         return "X86ISD::PSHUFLW_LD";
10974   case X86ISD::SHUFPS:             return "X86ISD::SHUFPS";
10975   case X86ISD::SHUFPD:             return "X86ISD::SHUFPD";
10976   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
10977   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
10978   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
10979   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
10980   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
10981   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
10982   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
10983   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
10984   case X86ISD::MOVSHDUP_LD:        return "X86ISD::MOVSHDUP_LD";
10985   case X86ISD::MOVSLDUP_LD:        return "X86ISD::MOVSLDUP_LD";
10986   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
10987   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
10988   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
10989   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
10990   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
10991   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
10992   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
10993   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
10994   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
10995   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
10996   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
10997   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
10998   }
10999 }
11000
11001 // isLegalAddressingMode - Return true if the addressing mode represented
11002 // by AM is legal for this target, for a load/store of the specified type.
11003 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
11004                                               Type *Ty) const {
11005   // X86 supports extremely general addressing modes.
11006   CodeModel::Model M = getTargetMachine().getCodeModel();
11007   Reloc::Model R = getTargetMachine().getRelocationModel();
11008
11009   // X86 allows a sign-extended 32-bit immediate field as a displacement.
11010   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
11011     return false;
11012
11013   if (AM.BaseGV) {
11014     unsigned GVFlags =
11015       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
11016
11017     // If a reference to this global requires an extra load, we can't fold it.
11018     if (isGlobalStubReference(GVFlags))
11019       return false;
11020
11021     // If BaseGV requires a register for the PIC base, we cannot also have a
11022     // BaseReg specified.
11023     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
11024       return false;
11025
11026     // If lower 4G is not available, then we must use rip-relative addressing.
11027     if ((M != CodeModel::Small || R != Reloc::Static) &&
11028         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
11029       return false;
11030   }
11031
11032   switch (AM.Scale) {
11033   case 0:
11034   case 1:
11035   case 2:
11036   case 4:
11037   case 8:
11038     // These scales always work.
11039     break;
11040   case 3:
11041   case 5:
11042   case 9:
11043     // These scales are formed with basereg+scalereg.  Only accept if there is
11044     // no basereg yet.
11045     if (AM.HasBaseReg)
11046       return false;
11047     break;
11048   default:  // Other stuff never works.
11049     return false;
11050   }
11051
11052   return true;
11053 }
11054
11055
11056 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11057   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11058     return false;
11059   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11060   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11061   if (NumBits1 <= NumBits2)
11062     return false;
11063   return true;
11064 }
11065
11066 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11067   if (!VT1.isInteger() || !VT2.isInteger())
11068     return false;
11069   unsigned NumBits1 = VT1.getSizeInBits();
11070   unsigned NumBits2 = VT2.getSizeInBits();
11071   if (NumBits1 <= NumBits2)
11072     return false;
11073   return true;
11074 }
11075
11076 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
11077   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11078   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
11079 }
11080
11081 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
11082   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11083   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
11084 }
11085
11086 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
11087   // i16 instructions are longer (0x66 prefix) and potentially slower.
11088   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
11089 }
11090
11091 /// isShuffleMaskLegal - Targets can use this to indicate that they only
11092 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
11093 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
11094 /// are assumed to be legal.
11095 bool
11096 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
11097                                       EVT VT) const {
11098   // Very little shuffling can be done for 64-bit vectors right now.
11099   if (VT.getSizeInBits() == 64)
11100     return false;
11101
11102   // FIXME: pshufb, blends, shifts.
11103   return (VT.getVectorNumElements() == 2 ||
11104           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
11105           isMOVLMask(M, VT) ||
11106           isSHUFPMask(M, VT) ||
11107           isPSHUFDMask(M, VT) ||
11108           isPSHUFHWMask(M, VT) ||
11109           isPSHUFLWMask(M, VT) ||
11110           isPALIGNRMask(M, VT, Subtarget->hasSSSE3orAVX()) ||
11111           isUNPCKLMask(M, VT, Subtarget->hasAVX2()) ||
11112           isUNPCKHMask(M, VT, Subtarget->hasAVX2()) ||
11113           isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasAVX2()) ||
11114           isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasAVX2()));
11115 }
11116
11117 bool
11118 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
11119                                           EVT VT) const {
11120   unsigned NumElts = VT.getVectorNumElements();
11121   // FIXME: This collection of masks seems suspect.
11122   if (NumElts == 2)
11123     return true;
11124   if (NumElts == 4 && VT.getSizeInBits() == 128) {
11125     return (isMOVLMask(Mask, VT)  ||
11126             isCommutedMOVLMask(Mask, VT, true) ||
11127             isSHUFPMask(Mask, VT) ||
11128             isSHUFPMask(Mask, VT, /* Commuted */ true));
11129   }
11130   return false;
11131 }
11132
11133 //===----------------------------------------------------------------------===//
11134 //                           X86 Scheduler Hooks
11135 //===----------------------------------------------------------------------===//
11136
11137 // private utility function
11138 MachineBasicBlock *
11139 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
11140                                                        MachineBasicBlock *MBB,
11141                                                        unsigned regOpc,
11142                                                        unsigned immOpc,
11143                                                        unsigned LoadOpc,
11144                                                        unsigned CXchgOpc,
11145                                                        unsigned notOpc,
11146                                                        unsigned EAXreg,
11147                                                        TargetRegisterClass *RC,
11148                                                        bool invSrc) const {
11149   // For the atomic bitwise operator, we generate
11150   //   thisMBB:
11151   //   newMBB:
11152   //     ld  t1 = [bitinstr.addr]
11153   //     op  t2 = t1, [bitinstr.val]
11154   //     mov EAX = t1
11155   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
11156   //     bz  newMBB
11157   //     fallthrough -->nextMBB
11158   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11159   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11160   MachineFunction::iterator MBBIter = MBB;
11161   ++MBBIter;
11162
11163   /// First build the CFG
11164   MachineFunction *F = MBB->getParent();
11165   MachineBasicBlock *thisMBB = MBB;
11166   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11167   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11168   F->insert(MBBIter, newMBB);
11169   F->insert(MBBIter, nextMBB);
11170
11171   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11172   nextMBB->splice(nextMBB->begin(), thisMBB,
11173                   llvm::next(MachineBasicBlock::iterator(bInstr)),
11174                   thisMBB->end());
11175   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11176
11177   // Update thisMBB to fall through to newMBB
11178   thisMBB->addSuccessor(newMBB);
11179
11180   // newMBB jumps to itself and fall through to nextMBB
11181   newMBB->addSuccessor(nextMBB);
11182   newMBB->addSuccessor(newMBB);
11183
11184   // Insert instructions into newMBB based on incoming instruction
11185   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11186          "unexpected number of operands");
11187   DebugLoc dl = bInstr->getDebugLoc();
11188   MachineOperand& destOper = bInstr->getOperand(0);
11189   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11190   int numArgs = bInstr->getNumOperands() - 1;
11191   for (int i=0; i < numArgs; ++i)
11192     argOpers[i] = &bInstr->getOperand(i+1);
11193
11194   // x86 address has 4 operands: base, index, scale, and displacement
11195   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11196   int valArgIndx = lastAddrIndx + 1;
11197
11198   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11199   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
11200   for (int i=0; i <= lastAddrIndx; ++i)
11201     (*MIB).addOperand(*argOpers[i]);
11202
11203   unsigned tt = F->getRegInfo().createVirtualRegister(RC);
11204   if (invSrc) {
11205     MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
11206   }
11207   else
11208     tt = t1;
11209
11210   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11211   assert((argOpers[valArgIndx]->isReg() ||
11212           argOpers[valArgIndx]->isImm()) &&
11213          "invalid operand");
11214   if (argOpers[valArgIndx]->isReg())
11215     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
11216   else
11217     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
11218   MIB.addReg(tt);
11219   (*MIB).addOperand(*argOpers[valArgIndx]);
11220
11221   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
11222   MIB.addReg(t1);
11223
11224   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
11225   for (int i=0; i <= lastAddrIndx; ++i)
11226     (*MIB).addOperand(*argOpers[i]);
11227   MIB.addReg(t2);
11228   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11229   (*MIB).setMemRefs(bInstr->memoperands_begin(),
11230                     bInstr->memoperands_end());
11231
11232   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11233   MIB.addReg(EAXreg);
11234
11235   // insert branch
11236   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11237
11238   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
11239   return nextMBB;
11240 }
11241
11242 // private utility function:  64 bit atomics on 32 bit host.
11243 MachineBasicBlock *
11244 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
11245                                                        MachineBasicBlock *MBB,
11246                                                        unsigned regOpcL,
11247                                                        unsigned regOpcH,
11248                                                        unsigned immOpcL,
11249                                                        unsigned immOpcH,
11250                                                        bool invSrc) const {
11251   // For the atomic bitwise operator, we generate
11252   //   thisMBB (instructions are in pairs, except cmpxchg8b)
11253   //     ld t1,t2 = [bitinstr.addr]
11254   //   newMBB:
11255   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
11256   //     op  t5, t6 <- out1, out2, [bitinstr.val]
11257   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
11258   //     mov ECX, EBX <- t5, t6
11259   //     mov EAX, EDX <- t1, t2
11260   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
11261   //     mov t3, t4 <- EAX, EDX
11262   //     bz  newMBB
11263   //     result in out1, out2
11264   //     fallthrough -->nextMBB
11265
11266   const TargetRegisterClass *RC = X86::GR32RegisterClass;
11267   const unsigned LoadOpc = X86::MOV32rm;
11268   const unsigned NotOpc = X86::NOT32r;
11269   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11270   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11271   MachineFunction::iterator MBBIter = MBB;
11272   ++MBBIter;
11273
11274   /// First build the CFG
11275   MachineFunction *F = MBB->getParent();
11276   MachineBasicBlock *thisMBB = MBB;
11277   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11278   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11279   F->insert(MBBIter, newMBB);
11280   F->insert(MBBIter, nextMBB);
11281
11282   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11283   nextMBB->splice(nextMBB->begin(), thisMBB,
11284                   llvm::next(MachineBasicBlock::iterator(bInstr)),
11285                   thisMBB->end());
11286   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11287
11288   // Update thisMBB to fall through to newMBB
11289   thisMBB->addSuccessor(newMBB);
11290
11291   // newMBB jumps to itself and fall through to nextMBB
11292   newMBB->addSuccessor(nextMBB);
11293   newMBB->addSuccessor(newMBB);
11294
11295   DebugLoc dl = bInstr->getDebugLoc();
11296   // Insert instructions into newMBB based on incoming instruction
11297   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
11298   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
11299          "unexpected number of operands");
11300   MachineOperand& dest1Oper = bInstr->getOperand(0);
11301   MachineOperand& dest2Oper = bInstr->getOperand(1);
11302   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11303   for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
11304     argOpers[i] = &bInstr->getOperand(i+2);
11305
11306     // We use some of the operands multiple times, so conservatively just
11307     // clear any kill flags that might be present.
11308     if (argOpers[i]->isReg() && argOpers[i]->isUse())
11309       argOpers[i]->setIsKill(false);
11310   }
11311
11312   // x86 address has 5 operands: base, index, scale, displacement, and segment.
11313   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11314
11315   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11316   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
11317   for (int i=0; i <= lastAddrIndx; ++i)
11318     (*MIB).addOperand(*argOpers[i]);
11319   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11320   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
11321   // add 4 to displacement.
11322   for (int i=0; i <= lastAddrIndx-2; ++i)
11323     (*MIB).addOperand(*argOpers[i]);
11324   MachineOperand newOp3 = *(argOpers[3]);
11325   if (newOp3.isImm())
11326     newOp3.setImm(newOp3.getImm()+4);
11327   else
11328     newOp3.setOffset(newOp3.getOffset()+4);
11329   (*MIB).addOperand(newOp3);
11330   (*MIB).addOperand(*argOpers[lastAddrIndx]);
11331
11332   // t3/4 are defined later, at the bottom of the loop
11333   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11334   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
11335   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
11336     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
11337   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
11338     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
11339
11340   // The subsequent operations should be using the destination registers of
11341   //the PHI instructions.
11342   if (invSrc) {
11343     t1 = F->getRegInfo().createVirtualRegister(RC);
11344     t2 = F->getRegInfo().createVirtualRegister(RC);
11345     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
11346     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
11347   } else {
11348     t1 = dest1Oper.getReg();
11349     t2 = dest2Oper.getReg();
11350   }
11351
11352   int valArgIndx = lastAddrIndx + 1;
11353   assert((argOpers[valArgIndx]->isReg() ||
11354           argOpers[valArgIndx]->isImm()) &&
11355          "invalid operand");
11356   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
11357   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
11358   if (argOpers[valArgIndx]->isReg())
11359     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
11360   else
11361     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
11362   if (regOpcL != X86::MOV32rr)
11363     MIB.addReg(t1);
11364   (*MIB).addOperand(*argOpers[valArgIndx]);
11365   assert(argOpers[valArgIndx + 1]->isReg() ==
11366          argOpers[valArgIndx]->isReg());
11367   assert(argOpers[valArgIndx + 1]->isImm() ==
11368          argOpers[valArgIndx]->isImm());
11369   if (argOpers[valArgIndx + 1]->isReg())
11370     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
11371   else
11372     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
11373   if (regOpcH != X86::MOV32rr)
11374     MIB.addReg(t2);
11375   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
11376
11377   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11378   MIB.addReg(t1);
11379   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
11380   MIB.addReg(t2);
11381
11382   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
11383   MIB.addReg(t5);
11384   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
11385   MIB.addReg(t6);
11386
11387   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
11388   for (int i=0; i <= lastAddrIndx; ++i)
11389     (*MIB).addOperand(*argOpers[i]);
11390
11391   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11392   (*MIB).setMemRefs(bInstr->memoperands_begin(),
11393                     bInstr->memoperands_end());
11394
11395   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
11396   MIB.addReg(X86::EAX);
11397   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
11398   MIB.addReg(X86::EDX);
11399
11400   // insert branch
11401   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11402
11403   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
11404   return nextMBB;
11405 }
11406
11407 // private utility function
11408 MachineBasicBlock *
11409 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
11410                                                       MachineBasicBlock *MBB,
11411                                                       unsigned cmovOpc) const {
11412   // For the atomic min/max operator, we generate
11413   //   thisMBB:
11414   //   newMBB:
11415   //     ld t1 = [min/max.addr]
11416   //     mov t2 = [min/max.val]
11417   //     cmp  t1, t2
11418   //     cmov[cond] t2 = t1
11419   //     mov EAX = t1
11420   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
11421   //     bz   newMBB
11422   //     fallthrough -->nextMBB
11423   //
11424   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11425   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11426   MachineFunction::iterator MBBIter = MBB;
11427   ++MBBIter;
11428
11429   /// First build the CFG
11430   MachineFunction *F = MBB->getParent();
11431   MachineBasicBlock *thisMBB = MBB;
11432   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11433   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11434   F->insert(MBBIter, newMBB);
11435   F->insert(MBBIter, nextMBB);
11436
11437   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11438   nextMBB->splice(nextMBB->begin(), thisMBB,
11439                   llvm::next(MachineBasicBlock::iterator(mInstr)),
11440                   thisMBB->end());
11441   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11442
11443   // Update thisMBB to fall through to newMBB
11444   thisMBB->addSuccessor(newMBB);
11445
11446   // newMBB jumps to newMBB and fall through to nextMBB
11447   newMBB->addSuccessor(nextMBB);
11448   newMBB->addSuccessor(newMBB);
11449
11450   DebugLoc dl = mInstr->getDebugLoc();
11451   // Insert instructions into newMBB based on incoming instruction
11452   assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11453          "unexpected number of operands");
11454   MachineOperand& destOper = mInstr->getOperand(0);
11455   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11456   int numArgs = mInstr->getNumOperands() - 1;
11457   for (int i=0; i < numArgs; ++i)
11458     argOpers[i] = &mInstr->getOperand(i+1);
11459
11460   // x86 address has 4 operands: base, index, scale, and displacement
11461   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11462   int valArgIndx = lastAddrIndx + 1;
11463
11464   unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11465   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
11466   for (int i=0; i <= lastAddrIndx; ++i)
11467     (*MIB).addOperand(*argOpers[i]);
11468
11469   // We only support register and immediate values
11470   assert((argOpers[valArgIndx]->isReg() ||
11471           argOpers[valArgIndx]->isImm()) &&
11472          "invalid operand");
11473
11474   unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11475   if (argOpers[valArgIndx]->isReg())
11476     MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
11477   else
11478     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
11479   (*MIB).addOperand(*argOpers[valArgIndx]);
11480
11481   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11482   MIB.addReg(t1);
11483
11484   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
11485   MIB.addReg(t1);
11486   MIB.addReg(t2);
11487
11488   // Generate movc
11489   unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11490   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
11491   MIB.addReg(t2);
11492   MIB.addReg(t1);
11493
11494   // Cmp and exchange if none has modified the memory location
11495   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
11496   for (int i=0; i <= lastAddrIndx; ++i)
11497     (*MIB).addOperand(*argOpers[i]);
11498   MIB.addReg(t3);
11499   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11500   (*MIB).setMemRefs(mInstr->memoperands_begin(),
11501                     mInstr->memoperands_end());
11502
11503   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11504   MIB.addReg(X86::EAX);
11505
11506   // insert branch
11507   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11508
11509   mInstr->eraseFromParent();   // The pseudo instruction is gone now.
11510   return nextMBB;
11511 }
11512
11513 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
11514 // or XMM0_V32I8 in AVX all of this code can be replaced with that
11515 // in the .td file.
11516 MachineBasicBlock *
11517 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
11518                             unsigned numArgs, bool memArg) const {
11519   assert(Subtarget->hasSSE42orAVX() &&
11520          "Target must have SSE4.2 or AVX features enabled");
11521
11522   DebugLoc dl = MI->getDebugLoc();
11523   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11524   unsigned Opc;
11525   if (!Subtarget->hasAVX()) {
11526     if (memArg)
11527       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
11528     else
11529       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
11530   } else {
11531     if (memArg)
11532       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
11533     else
11534       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
11535   }
11536
11537   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
11538   for (unsigned i = 0; i < numArgs; ++i) {
11539     MachineOperand &Op = MI->getOperand(i+1);
11540     if (!(Op.isReg() && Op.isImplicit()))
11541       MIB.addOperand(Op);
11542   }
11543   BuildMI(*BB, MI, dl,
11544     TII->get(Subtarget->hasAVX() ? X86::VMOVAPSrr : X86::MOVAPSrr),
11545              MI->getOperand(0).getReg())
11546     .addReg(X86::XMM0);
11547
11548   MI->eraseFromParent();
11549   return BB;
11550 }
11551
11552 MachineBasicBlock *
11553 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
11554   DebugLoc dl = MI->getDebugLoc();
11555   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11556
11557   // Address into RAX/EAX, other two args into ECX, EDX.
11558   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
11559   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11560   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
11561   for (int i = 0; i < X86::AddrNumOperands; ++i)
11562     MIB.addOperand(MI->getOperand(i));
11563
11564   unsigned ValOps = X86::AddrNumOperands;
11565   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11566     .addReg(MI->getOperand(ValOps).getReg());
11567   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
11568     .addReg(MI->getOperand(ValOps+1).getReg());
11569
11570   // The instruction doesn't actually take any operands though.
11571   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
11572
11573   MI->eraseFromParent(); // The pseudo is gone now.
11574   return BB;
11575 }
11576
11577 MachineBasicBlock *
11578 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
11579   DebugLoc dl = MI->getDebugLoc();
11580   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11581
11582   // First arg in ECX, the second in EAX.
11583   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11584     .addReg(MI->getOperand(0).getReg());
11585   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
11586     .addReg(MI->getOperand(1).getReg());
11587
11588   // The instruction doesn't actually take any operands though.
11589   BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
11590
11591   MI->eraseFromParent(); // The pseudo is gone now.
11592   return BB;
11593 }
11594
11595 MachineBasicBlock *
11596 X86TargetLowering::EmitVAARG64WithCustomInserter(
11597                    MachineInstr *MI,
11598                    MachineBasicBlock *MBB) const {
11599   // Emit va_arg instruction on X86-64.
11600
11601   // Operands to this pseudo-instruction:
11602   // 0  ) Output        : destination address (reg)
11603   // 1-5) Input         : va_list address (addr, i64mem)
11604   // 6  ) ArgSize       : Size (in bytes) of vararg type
11605   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
11606   // 8  ) Align         : Alignment of type
11607   // 9  ) EFLAGS (implicit-def)
11608
11609   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
11610   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
11611
11612   unsigned DestReg = MI->getOperand(0).getReg();
11613   MachineOperand &Base = MI->getOperand(1);
11614   MachineOperand &Scale = MI->getOperand(2);
11615   MachineOperand &Index = MI->getOperand(3);
11616   MachineOperand &Disp = MI->getOperand(4);
11617   MachineOperand &Segment = MI->getOperand(5);
11618   unsigned ArgSize = MI->getOperand(6).getImm();
11619   unsigned ArgMode = MI->getOperand(7).getImm();
11620   unsigned Align = MI->getOperand(8).getImm();
11621
11622   // Memory Reference
11623   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
11624   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
11625   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
11626
11627   // Machine Information
11628   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11629   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
11630   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
11631   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
11632   DebugLoc DL = MI->getDebugLoc();
11633
11634   // struct va_list {
11635   //   i32   gp_offset
11636   //   i32   fp_offset
11637   //   i64   overflow_area (address)
11638   //   i64   reg_save_area (address)
11639   // }
11640   // sizeof(va_list) = 24
11641   // alignment(va_list) = 8
11642
11643   unsigned TotalNumIntRegs = 6;
11644   unsigned TotalNumXMMRegs = 8;
11645   bool UseGPOffset = (ArgMode == 1);
11646   bool UseFPOffset = (ArgMode == 2);
11647   unsigned MaxOffset = TotalNumIntRegs * 8 +
11648                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
11649
11650   /* Align ArgSize to a multiple of 8 */
11651   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
11652   bool NeedsAlign = (Align > 8);
11653
11654   MachineBasicBlock *thisMBB = MBB;
11655   MachineBasicBlock *overflowMBB;
11656   MachineBasicBlock *offsetMBB;
11657   MachineBasicBlock *endMBB;
11658
11659   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
11660   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
11661   unsigned OffsetReg = 0;
11662
11663   if (!UseGPOffset && !UseFPOffset) {
11664     // If we only pull from the overflow region, we don't create a branch.
11665     // We don't need to alter control flow.
11666     OffsetDestReg = 0; // unused
11667     OverflowDestReg = DestReg;
11668
11669     offsetMBB = NULL;
11670     overflowMBB = thisMBB;
11671     endMBB = thisMBB;
11672   } else {
11673     // First emit code to check if gp_offset (or fp_offset) is below the bound.
11674     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
11675     // If not, pull from overflow_area. (branch to overflowMBB)
11676     //
11677     //       thisMBB
11678     //         |     .
11679     //         |        .
11680     //     offsetMBB   overflowMBB
11681     //         |        .
11682     //         |     .
11683     //        endMBB
11684
11685     // Registers for the PHI in endMBB
11686     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
11687     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
11688
11689     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11690     MachineFunction *MF = MBB->getParent();
11691     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11692     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11693     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11694
11695     MachineFunction::iterator MBBIter = MBB;
11696     ++MBBIter;
11697
11698     // Insert the new basic blocks
11699     MF->insert(MBBIter, offsetMBB);
11700     MF->insert(MBBIter, overflowMBB);
11701     MF->insert(MBBIter, endMBB);
11702
11703     // Transfer the remainder of MBB and its successor edges to endMBB.
11704     endMBB->splice(endMBB->begin(), thisMBB,
11705                     llvm::next(MachineBasicBlock::iterator(MI)),
11706                     thisMBB->end());
11707     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11708
11709     // Make offsetMBB and overflowMBB successors of thisMBB
11710     thisMBB->addSuccessor(offsetMBB);
11711     thisMBB->addSuccessor(overflowMBB);
11712
11713     // endMBB is a successor of both offsetMBB and overflowMBB
11714     offsetMBB->addSuccessor(endMBB);
11715     overflowMBB->addSuccessor(endMBB);
11716
11717     // Load the offset value into a register
11718     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
11719     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
11720       .addOperand(Base)
11721       .addOperand(Scale)
11722       .addOperand(Index)
11723       .addDisp(Disp, UseFPOffset ? 4 : 0)
11724       .addOperand(Segment)
11725       .setMemRefs(MMOBegin, MMOEnd);
11726
11727     // Check if there is enough room left to pull this argument.
11728     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
11729       .addReg(OffsetReg)
11730       .addImm(MaxOffset + 8 - ArgSizeA8);
11731
11732     // Branch to "overflowMBB" if offset >= max
11733     // Fall through to "offsetMBB" otherwise
11734     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
11735       .addMBB(overflowMBB);
11736   }
11737
11738   // In offsetMBB, emit code to use the reg_save_area.
11739   if (offsetMBB) {
11740     assert(OffsetReg != 0);
11741
11742     // Read the reg_save_area address.
11743     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
11744     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
11745       .addOperand(Base)
11746       .addOperand(Scale)
11747       .addOperand(Index)
11748       .addDisp(Disp, 16)
11749       .addOperand(Segment)
11750       .setMemRefs(MMOBegin, MMOEnd);
11751
11752     // Zero-extend the offset
11753     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
11754       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
11755         .addImm(0)
11756         .addReg(OffsetReg)
11757         .addImm(X86::sub_32bit);
11758
11759     // Add the offset to the reg_save_area to get the final address.
11760     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
11761       .addReg(OffsetReg64)
11762       .addReg(RegSaveReg);
11763
11764     // Compute the offset for the next argument
11765     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
11766     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
11767       .addReg(OffsetReg)
11768       .addImm(UseFPOffset ? 16 : 8);
11769
11770     // Store it back into the va_list.
11771     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
11772       .addOperand(Base)
11773       .addOperand(Scale)
11774       .addOperand(Index)
11775       .addDisp(Disp, UseFPOffset ? 4 : 0)
11776       .addOperand(Segment)
11777       .addReg(NextOffsetReg)
11778       .setMemRefs(MMOBegin, MMOEnd);
11779
11780     // Jump to endMBB
11781     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
11782       .addMBB(endMBB);
11783   }
11784
11785   //
11786   // Emit code to use overflow area
11787   //
11788
11789   // Load the overflow_area address into a register.
11790   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
11791   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
11792     .addOperand(Base)
11793     .addOperand(Scale)
11794     .addOperand(Index)
11795     .addDisp(Disp, 8)
11796     .addOperand(Segment)
11797     .setMemRefs(MMOBegin, MMOEnd);
11798
11799   // If we need to align it, do so. Otherwise, just copy the address
11800   // to OverflowDestReg.
11801   if (NeedsAlign) {
11802     // Align the overflow address
11803     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
11804     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
11805
11806     // aligned_addr = (addr + (align-1)) & ~(align-1)
11807     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
11808       .addReg(OverflowAddrReg)
11809       .addImm(Align-1);
11810
11811     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
11812       .addReg(TmpReg)
11813       .addImm(~(uint64_t)(Align-1));
11814   } else {
11815     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
11816       .addReg(OverflowAddrReg);
11817   }
11818
11819   // Compute the next overflow address after this argument.
11820   // (the overflow address should be kept 8-byte aligned)
11821   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
11822   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
11823     .addReg(OverflowDestReg)
11824     .addImm(ArgSizeA8);
11825
11826   // Store the new overflow address.
11827   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
11828     .addOperand(Base)
11829     .addOperand(Scale)
11830     .addOperand(Index)
11831     .addDisp(Disp, 8)
11832     .addOperand(Segment)
11833     .addReg(NextAddrReg)
11834     .setMemRefs(MMOBegin, MMOEnd);
11835
11836   // If we branched, emit the PHI to the front of endMBB.
11837   if (offsetMBB) {
11838     BuildMI(*endMBB, endMBB->begin(), DL,
11839             TII->get(X86::PHI), DestReg)
11840       .addReg(OffsetDestReg).addMBB(offsetMBB)
11841       .addReg(OverflowDestReg).addMBB(overflowMBB);
11842   }
11843
11844   // Erase the pseudo instruction
11845   MI->eraseFromParent();
11846
11847   return endMBB;
11848 }
11849
11850 MachineBasicBlock *
11851 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
11852                                                  MachineInstr *MI,
11853                                                  MachineBasicBlock *MBB) const {
11854   // Emit code to save XMM registers to the stack. The ABI says that the
11855   // number of registers to save is given in %al, so it's theoretically
11856   // possible to do an indirect jump trick to avoid saving all of them,
11857   // however this code takes a simpler approach and just executes all
11858   // of the stores if %al is non-zero. It's less code, and it's probably
11859   // easier on the hardware branch predictor, and stores aren't all that
11860   // expensive anyway.
11861
11862   // Create the new basic blocks. One block contains all the XMM stores,
11863   // and one block is the final destination regardless of whether any
11864   // stores were performed.
11865   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11866   MachineFunction *F = MBB->getParent();
11867   MachineFunction::iterator MBBIter = MBB;
11868   ++MBBIter;
11869   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
11870   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
11871   F->insert(MBBIter, XMMSaveMBB);
11872   F->insert(MBBIter, EndMBB);
11873
11874   // Transfer the remainder of MBB and its successor edges to EndMBB.
11875   EndMBB->splice(EndMBB->begin(), MBB,
11876                  llvm::next(MachineBasicBlock::iterator(MI)),
11877                  MBB->end());
11878   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
11879
11880   // The original block will now fall through to the XMM save block.
11881   MBB->addSuccessor(XMMSaveMBB);
11882   // The XMMSaveMBB will fall through to the end block.
11883   XMMSaveMBB->addSuccessor(EndMBB);
11884
11885   // Now add the instructions.
11886   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11887   DebugLoc DL = MI->getDebugLoc();
11888
11889   unsigned CountReg = MI->getOperand(0).getReg();
11890   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
11891   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
11892
11893   if (!Subtarget->isTargetWin64()) {
11894     // If %al is 0, branch around the XMM save block.
11895     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
11896     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
11897     MBB->addSuccessor(EndMBB);
11898   }
11899
11900   unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
11901   // In the XMM save block, save all the XMM argument registers.
11902   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
11903     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
11904     MachineMemOperand *MMO =
11905       F->getMachineMemOperand(
11906           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
11907         MachineMemOperand::MOStore,
11908         /*Size=*/16, /*Align=*/16);
11909     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
11910       .addFrameIndex(RegSaveFrameIndex)
11911       .addImm(/*Scale=*/1)
11912       .addReg(/*IndexReg=*/0)
11913       .addImm(/*Disp=*/Offset)
11914       .addReg(/*Segment=*/0)
11915       .addReg(MI->getOperand(i).getReg())
11916       .addMemOperand(MMO);
11917   }
11918
11919   MI->eraseFromParent();   // The pseudo instruction is gone now.
11920
11921   return EndMBB;
11922 }
11923
11924 MachineBasicBlock *
11925 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
11926                                      MachineBasicBlock *BB) const {
11927   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11928   DebugLoc DL = MI->getDebugLoc();
11929
11930   // To "insert" a SELECT_CC instruction, we actually have to insert the
11931   // diamond control-flow pattern.  The incoming instruction knows the
11932   // destination vreg to set, the condition code register to branch on, the
11933   // true/false values to select between, and a branch opcode to use.
11934   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11935   MachineFunction::iterator It = BB;
11936   ++It;
11937
11938   //  thisMBB:
11939   //  ...
11940   //   TrueVal = ...
11941   //   cmpTY ccX, r1, r2
11942   //   bCC copy1MBB
11943   //   fallthrough --> copy0MBB
11944   MachineBasicBlock *thisMBB = BB;
11945   MachineFunction *F = BB->getParent();
11946   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
11947   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11948   F->insert(It, copy0MBB);
11949   F->insert(It, sinkMBB);
11950
11951   // If the EFLAGS register isn't dead in the terminator, then claim that it's
11952   // live into the sink and copy blocks.
11953   if (!MI->killsRegister(X86::EFLAGS)) {
11954     copy0MBB->addLiveIn(X86::EFLAGS);
11955     sinkMBB->addLiveIn(X86::EFLAGS);
11956   }
11957
11958   // Transfer the remainder of BB and its successor edges to sinkMBB.
11959   sinkMBB->splice(sinkMBB->begin(), BB,
11960                   llvm::next(MachineBasicBlock::iterator(MI)),
11961                   BB->end());
11962   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11963
11964   // Add the true and fallthrough blocks as its successors.
11965   BB->addSuccessor(copy0MBB);
11966   BB->addSuccessor(sinkMBB);
11967
11968   // Create the conditional branch instruction.
11969   unsigned Opc =
11970     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
11971   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
11972
11973   //  copy0MBB:
11974   //   %FalseValue = ...
11975   //   # fallthrough to sinkMBB
11976   copy0MBB->addSuccessor(sinkMBB);
11977
11978   //  sinkMBB:
11979   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
11980   //  ...
11981   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
11982           TII->get(X86::PHI), MI->getOperand(0).getReg())
11983     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
11984     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
11985
11986   MI->eraseFromParent();   // The pseudo instruction is gone now.
11987   return sinkMBB;
11988 }
11989
11990 MachineBasicBlock *
11991 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
11992                                         bool Is64Bit) const {
11993   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11994   DebugLoc DL = MI->getDebugLoc();
11995   MachineFunction *MF = BB->getParent();
11996   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11997
11998   assert(getTargetMachine().Options.EnableSegmentedStacks);
11999
12000   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
12001   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
12002
12003   // BB:
12004   //  ... [Till the alloca]
12005   // If stacklet is not large enough, jump to mallocMBB
12006   //
12007   // bumpMBB:
12008   //  Allocate by subtracting from RSP
12009   //  Jump to continueMBB
12010   //
12011   // mallocMBB:
12012   //  Allocate by call to runtime
12013   //
12014   // continueMBB:
12015   //  ...
12016   //  [rest of original BB]
12017   //
12018
12019   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12020   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12021   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12022
12023   MachineRegisterInfo &MRI = MF->getRegInfo();
12024   const TargetRegisterClass *AddrRegClass =
12025     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
12026
12027   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12028     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12029     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
12030     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
12031     sizeVReg = MI->getOperand(1).getReg(),
12032     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
12033
12034   MachineFunction::iterator MBBIter = BB;
12035   ++MBBIter;
12036
12037   MF->insert(MBBIter, bumpMBB);
12038   MF->insert(MBBIter, mallocMBB);
12039   MF->insert(MBBIter, continueMBB);
12040
12041   continueMBB->splice(continueMBB->begin(), BB, llvm::next
12042                       (MachineBasicBlock::iterator(MI)), BB->end());
12043   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
12044
12045   // Add code to the main basic block to check if the stack limit has been hit,
12046   // and if so, jump to mallocMBB otherwise to bumpMBB.
12047   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
12048   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
12049     .addReg(tmpSPVReg).addReg(sizeVReg);
12050   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
12051     .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg)
12052     .addReg(SPLimitVReg);
12053   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
12054
12055   // bumpMBB simply decreases the stack pointer, since we know the current
12056   // stacklet has enough space.
12057   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
12058     .addReg(SPLimitVReg);
12059   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
12060     .addReg(SPLimitVReg);
12061   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12062
12063   // Calls into a routine in libgcc to allocate more space from the heap.
12064   if (Is64Bit) {
12065     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
12066       .addReg(sizeVReg);
12067     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
12068     .addExternalSymbol("__morestack_allocate_stack_space").addReg(X86::RDI);
12069   } else {
12070     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
12071       .addImm(12);
12072     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
12073     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
12074       .addExternalSymbol("__morestack_allocate_stack_space");
12075   }
12076
12077   if (!Is64Bit)
12078     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
12079       .addImm(16);
12080
12081   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
12082     .addReg(Is64Bit ? X86::RAX : X86::EAX);
12083   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12084
12085   // Set up the CFG correctly.
12086   BB->addSuccessor(bumpMBB);
12087   BB->addSuccessor(mallocMBB);
12088   mallocMBB->addSuccessor(continueMBB);
12089   bumpMBB->addSuccessor(continueMBB);
12090
12091   // Take care of the PHI nodes.
12092   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
12093           MI->getOperand(0).getReg())
12094     .addReg(mallocPtrVReg).addMBB(mallocMBB)
12095     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
12096
12097   // Delete the original pseudo instruction.
12098   MI->eraseFromParent();
12099
12100   // And we're done.
12101   return continueMBB;
12102 }
12103
12104 MachineBasicBlock *
12105 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
12106                                           MachineBasicBlock *BB) const {
12107   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12108   DebugLoc DL = MI->getDebugLoc();
12109
12110   assert(!Subtarget->isTargetEnvMacho());
12111
12112   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
12113   // non-trivial part is impdef of ESP.
12114
12115   if (Subtarget->isTargetWin64()) {
12116     if (Subtarget->isTargetCygMing()) {
12117       // ___chkstk(Mingw64):
12118       // Clobbers R10, R11, RAX and EFLAGS.
12119       // Updates RSP.
12120       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12121         .addExternalSymbol("___chkstk")
12122         .addReg(X86::RAX, RegState::Implicit)
12123         .addReg(X86::RSP, RegState::Implicit)
12124         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
12125         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
12126         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12127     } else {
12128       // __chkstk(MSVCRT): does not update stack pointer.
12129       // Clobbers R10, R11 and EFLAGS.
12130       // FIXME: RAX(allocated size) might be reused and not killed.
12131       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12132         .addExternalSymbol("__chkstk")
12133         .addReg(X86::RAX, RegState::Implicit)
12134         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12135       // RAX has the offset to subtracted from RSP.
12136       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
12137         .addReg(X86::RSP)
12138         .addReg(X86::RAX);
12139     }
12140   } else {
12141     const char *StackProbeSymbol =
12142       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
12143
12144     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
12145       .addExternalSymbol(StackProbeSymbol)
12146       .addReg(X86::EAX, RegState::Implicit)
12147       .addReg(X86::ESP, RegState::Implicit)
12148       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
12149       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
12150       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12151   }
12152
12153   MI->eraseFromParent();   // The pseudo instruction is gone now.
12154   return BB;
12155 }
12156
12157 MachineBasicBlock *
12158 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
12159                                       MachineBasicBlock *BB) const {
12160   // This is pretty easy.  We're taking the value that we received from
12161   // our load from the relocation, sticking it in either RDI (x86-64)
12162   // or EAX and doing an indirect call.  The return value will then
12163   // be in the normal return register.
12164   const X86InstrInfo *TII
12165     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
12166   DebugLoc DL = MI->getDebugLoc();
12167   MachineFunction *F = BB->getParent();
12168
12169   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
12170   assert(MI->getOperand(3).isGlobal() && "This should be a global");
12171
12172   if (Subtarget->is64Bit()) {
12173     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12174                                       TII->get(X86::MOV64rm), X86::RDI)
12175     .addReg(X86::RIP)
12176     .addImm(0).addReg(0)
12177     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12178                       MI->getOperand(3).getTargetFlags())
12179     .addReg(0);
12180     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
12181     addDirectMem(MIB, X86::RDI);
12182   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
12183     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12184                                       TII->get(X86::MOV32rm), X86::EAX)
12185     .addReg(0)
12186     .addImm(0).addReg(0)
12187     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12188                       MI->getOperand(3).getTargetFlags())
12189     .addReg(0);
12190     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12191     addDirectMem(MIB, X86::EAX);
12192   } else {
12193     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12194                                       TII->get(X86::MOV32rm), X86::EAX)
12195     .addReg(TII->getGlobalBaseReg(F))
12196     .addImm(0).addReg(0)
12197     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12198                       MI->getOperand(3).getTargetFlags())
12199     .addReg(0);
12200     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12201     addDirectMem(MIB, X86::EAX);
12202   }
12203
12204   MI->eraseFromParent(); // The pseudo instruction is gone now.
12205   return BB;
12206 }
12207
12208 MachineBasicBlock *
12209 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
12210                                                MachineBasicBlock *BB) const {
12211   switch (MI->getOpcode()) {
12212   default: assert(0 && "Unexpected instr type to insert");
12213   case X86::TAILJMPd64:
12214   case X86::TAILJMPr64:
12215   case X86::TAILJMPm64:
12216     assert(0 && "TAILJMP64 would not be touched here.");
12217   case X86::TCRETURNdi64:
12218   case X86::TCRETURNri64:
12219   case X86::TCRETURNmi64:
12220     // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset.
12221     // On AMD64, additional defs should be added before register allocation.
12222     if (!Subtarget->isTargetWin64()) {
12223       MI->addRegisterDefined(X86::RSI);
12224       MI->addRegisterDefined(X86::RDI);
12225       MI->addRegisterDefined(X86::XMM6);
12226       MI->addRegisterDefined(X86::XMM7);
12227       MI->addRegisterDefined(X86::XMM8);
12228       MI->addRegisterDefined(X86::XMM9);
12229       MI->addRegisterDefined(X86::XMM10);
12230       MI->addRegisterDefined(X86::XMM11);
12231       MI->addRegisterDefined(X86::XMM12);
12232       MI->addRegisterDefined(X86::XMM13);
12233       MI->addRegisterDefined(X86::XMM14);
12234       MI->addRegisterDefined(X86::XMM15);
12235     }
12236     return BB;
12237   case X86::WIN_ALLOCA:
12238     return EmitLoweredWinAlloca(MI, BB);
12239   case X86::SEG_ALLOCA_32:
12240     return EmitLoweredSegAlloca(MI, BB, false);
12241   case X86::SEG_ALLOCA_64:
12242     return EmitLoweredSegAlloca(MI, BB, true);
12243   case X86::TLSCall_32:
12244   case X86::TLSCall_64:
12245     return EmitLoweredTLSCall(MI, BB);
12246   case X86::CMOV_GR8:
12247   case X86::CMOV_FR32:
12248   case X86::CMOV_FR64:
12249   case X86::CMOV_V4F32:
12250   case X86::CMOV_V2F64:
12251   case X86::CMOV_V2I64:
12252   case X86::CMOV_V8F32:
12253   case X86::CMOV_V4F64:
12254   case X86::CMOV_V4I64:
12255   case X86::CMOV_GR16:
12256   case X86::CMOV_GR32:
12257   case X86::CMOV_RFP32:
12258   case X86::CMOV_RFP64:
12259   case X86::CMOV_RFP80:
12260     return EmitLoweredSelect(MI, BB);
12261
12262   case X86::FP32_TO_INT16_IN_MEM:
12263   case X86::FP32_TO_INT32_IN_MEM:
12264   case X86::FP32_TO_INT64_IN_MEM:
12265   case X86::FP64_TO_INT16_IN_MEM:
12266   case X86::FP64_TO_INT32_IN_MEM:
12267   case X86::FP64_TO_INT64_IN_MEM:
12268   case X86::FP80_TO_INT16_IN_MEM:
12269   case X86::FP80_TO_INT32_IN_MEM:
12270   case X86::FP80_TO_INT64_IN_MEM: {
12271     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12272     DebugLoc DL = MI->getDebugLoc();
12273
12274     // Change the floating point control register to use "round towards zero"
12275     // mode when truncating to an integer value.
12276     MachineFunction *F = BB->getParent();
12277     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
12278     addFrameReference(BuildMI(*BB, MI, DL,
12279                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
12280
12281     // Load the old value of the high byte of the control word...
12282     unsigned OldCW =
12283       F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
12284     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
12285                       CWFrameIdx);
12286
12287     // Set the high part to be round to zero...
12288     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
12289       .addImm(0xC7F);
12290
12291     // Reload the modified control word now...
12292     addFrameReference(BuildMI(*BB, MI, DL,
12293                               TII->get(X86::FLDCW16m)), CWFrameIdx);
12294
12295     // Restore the memory image of control word to original value
12296     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
12297       .addReg(OldCW);
12298
12299     // Get the X86 opcode to use.
12300     unsigned Opc;
12301     switch (MI->getOpcode()) {
12302     default: llvm_unreachable("illegal opcode!");
12303     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
12304     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
12305     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
12306     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
12307     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
12308     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
12309     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
12310     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
12311     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
12312     }
12313
12314     X86AddressMode AM;
12315     MachineOperand &Op = MI->getOperand(0);
12316     if (Op.isReg()) {
12317       AM.BaseType = X86AddressMode::RegBase;
12318       AM.Base.Reg = Op.getReg();
12319     } else {
12320       AM.BaseType = X86AddressMode::FrameIndexBase;
12321       AM.Base.FrameIndex = Op.getIndex();
12322     }
12323     Op = MI->getOperand(1);
12324     if (Op.isImm())
12325       AM.Scale = Op.getImm();
12326     Op = MI->getOperand(2);
12327     if (Op.isImm())
12328       AM.IndexReg = Op.getImm();
12329     Op = MI->getOperand(3);
12330     if (Op.isGlobal()) {
12331       AM.GV = Op.getGlobal();
12332     } else {
12333       AM.Disp = Op.getImm();
12334     }
12335     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
12336                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
12337
12338     // Reload the original control word now.
12339     addFrameReference(BuildMI(*BB, MI, DL,
12340                               TII->get(X86::FLDCW16m)), CWFrameIdx);
12341
12342     MI->eraseFromParent();   // The pseudo instruction is gone now.
12343     return BB;
12344   }
12345     // String/text processing lowering.
12346   case X86::PCMPISTRM128REG:
12347   case X86::VPCMPISTRM128REG:
12348     return EmitPCMP(MI, BB, 3, false /* in-mem */);
12349   case X86::PCMPISTRM128MEM:
12350   case X86::VPCMPISTRM128MEM:
12351     return EmitPCMP(MI, BB, 3, true /* in-mem */);
12352   case X86::PCMPESTRM128REG:
12353   case X86::VPCMPESTRM128REG:
12354     return EmitPCMP(MI, BB, 5, false /* in mem */);
12355   case X86::PCMPESTRM128MEM:
12356   case X86::VPCMPESTRM128MEM:
12357     return EmitPCMP(MI, BB, 5, true /* in mem */);
12358
12359     // Thread synchronization.
12360   case X86::MONITOR:
12361     return EmitMonitor(MI, BB);
12362   case X86::MWAIT:
12363     return EmitMwait(MI, BB);
12364
12365     // Atomic Lowering.
12366   case X86::ATOMAND32:
12367     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12368                                                X86::AND32ri, X86::MOV32rm,
12369                                                X86::LCMPXCHG32,
12370                                                X86::NOT32r, X86::EAX,
12371                                                X86::GR32RegisterClass);
12372   case X86::ATOMOR32:
12373     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
12374                                                X86::OR32ri, X86::MOV32rm,
12375                                                X86::LCMPXCHG32,
12376                                                X86::NOT32r, X86::EAX,
12377                                                X86::GR32RegisterClass);
12378   case X86::ATOMXOR32:
12379     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
12380                                                X86::XOR32ri, X86::MOV32rm,
12381                                                X86::LCMPXCHG32,
12382                                                X86::NOT32r, X86::EAX,
12383                                                X86::GR32RegisterClass);
12384   case X86::ATOMNAND32:
12385     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12386                                                X86::AND32ri, X86::MOV32rm,
12387                                                X86::LCMPXCHG32,
12388                                                X86::NOT32r, X86::EAX,
12389                                                X86::GR32RegisterClass, true);
12390   case X86::ATOMMIN32:
12391     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
12392   case X86::ATOMMAX32:
12393     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
12394   case X86::ATOMUMIN32:
12395     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
12396   case X86::ATOMUMAX32:
12397     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
12398
12399   case X86::ATOMAND16:
12400     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12401                                                X86::AND16ri, X86::MOV16rm,
12402                                                X86::LCMPXCHG16,
12403                                                X86::NOT16r, X86::AX,
12404                                                X86::GR16RegisterClass);
12405   case X86::ATOMOR16:
12406     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
12407                                                X86::OR16ri, X86::MOV16rm,
12408                                                X86::LCMPXCHG16,
12409                                                X86::NOT16r, X86::AX,
12410                                                X86::GR16RegisterClass);
12411   case X86::ATOMXOR16:
12412     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
12413                                                X86::XOR16ri, X86::MOV16rm,
12414                                                X86::LCMPXCHG16,
12415                                                X86::NOT16r, X86::AX,
12416                                                X86::GR16RegisterClass);
12417   case X86::ATOMNAND16:
12418     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12419                                                X86::AND16ri, X86::MOV16rm,
12420                                                X86::LCMPXCHG16,
12421                                                X86::NOT16r, X86::AX,
12422                                                X86::GR16RegisterClass, true);
12423   case X86::ATOMMIN16:
12424     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
12425   case X86::ATOMMAX16:
12426     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
12427   case X86::ATOMUMIN16:
12428     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
12429   case X86::ATOMUMAX16:
12430     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
12431
12432   case X86::ATOMAND8:
12433     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12434                                                X86::AND8ri, X86::MOV8rm,
12435                                                X86::LCMPXCHG8,
12436                                                X86::NOT8r, X86::AL,
12437                                                X86::GR8RegisterClass);
12438   case X86::ATOMOR8:
12439     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
12440                                                X86::OR8ri, X86::MOV8rm,
12441                                                X86::LCMPXCHG8,
12442                                                X86::NOT8r, X86::AL,
12443                                                X86::GR8RegisterClass);
12444   case X86::ATOMXOR8:
12445     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
12446                                                X86::XOR8ri, X86::MOV8rm,
12447                                                X86::LCMPXCHG8,
12448                                                X86::NOT8r, X86::AL,
12449                                                X86::GR8RegisterClass);
12450   case X86::ATOMNAND8:
12451     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12452                                                X86::AND8ri, X86::MOV8rm,
12453                                                X86::LCMPXCHG8,
12454                                                X86::NOT8r, X86::AL,
12455                                                X86::GR8RegisterClass, true);
12456   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
12457   // This group is for 64-bit host.
12458   case X86::ATOMAND64:
12459     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12460                                                X86::AND64ri32, X86::MOV64rm,
12461                                                X86::LCMPXCHG64,
12462                                                X86::NOT64r, X86::RAX,
12463                                                X86::GR64RegisterClass);
12464   case X86::ATOMOR64:
12465     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
12466                                                X86::OR64ri32, X86::MOV64rm,
12467                                                X86::LCMPXCHG64,
12468                                                X86::NOT64r, X86::RAX,
12469                                                X86::GR64RegisterClass);
12470   case X86::ATOMXOR64:
12471     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
12472                                                X86::XOR64ri32, X86::MOV64rm,
12473                                                X86::LCMPXCHG64,
12474                                                X86::NOT64r, X86::RAX,
12475                                                X86::GR64RegisterClass);
12476   case X86::ATOMNAND64:
12477     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12478                                                X86::AND64ri32, X86::MOV64rm,
12479                                                X86::LCMPXCHG64,
12480                                                X86::NOT64r, X86::RAX,
12481                                                X86::GR64RegisterClass, true);
12482   case X86::ATOMMIN64:
12483     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
12484   case X86::ATOMMAX64:
12485     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
12486   case X86::ATOMUMIN64:
12487     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
12488   case X86::ATOMUMAX64:
12489     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
12490
12491   // This group does 64-bit operations on a 32-bit host.
12492   case X86::ATOMAND6432:
12493     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12494                                                X86::AND32rr, X86::AND32rr,
12495                                                X86::AND32ri, X86::AND32ri,
12496                                                false);
12497   case X86::ATOMOR6432:
12498     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12499                                                X86::OR32rr, X86::OR32rr,
12500                                                X86::OR32ri, X86::OR32ri,
12501                                                false);
12502   case X86::ATOMXOR6432:
12503     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12504                                                X86::XOR32rr, X86::XOR32rr,
12505                                                X86::XOR32ri, X86::XOR32ri,
12506                                                false);
12507   case X86::ATOMNAND6432:
12508     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12509                                                X86::AND32rr, X86::AND32rr,
12510                                                X86::AND32ri, X86::AND32ri,
12511                                                true);
12512   case X86::ATOMADD6432:
12513     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12514                                                X86::ADD32rr, X86::ADC32rr,
12515                                                X86::ADD32ri, X86::ADC32ri,
12516                                                false);
12517   case X86::ATOMSUB6432:
12518     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12519                                                X86::SUB32rr, X86::SBB32rr,
12520                                                X86::SUB32ri, X86::SBB32ri,
12521                                                false);
12522   case X86::ATOMSWAP6432:
12523     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12524                                                X86::MOV32rr, X86::MOV32rr,
12525                                                X86::MOV32ri, X86::MOV32ri,
12526                                                false);
12527   case X86::VASTART_SAVE_XMM_REGS:
12528     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
12529
12530   case X86::VAARG_64:
12531     return EmitVAARG64WithCustomInserter(MI, BB);
12532   }
12533 }
12534
12535 //===----------------------------------------------------------------------===//
12536 //                           X86 Optimization Hooks
12537 //===----------------------------------------------------------------------===//
12538
12539 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
12540                                                        const APInt &Mask,
12541                                                        APInt &KnownZero,
12542                                                        APInt &KnownOne,
12543                                                        const SelectionDAG &DAG,
12544                                                        unsigned Depth) const {
12545   unsigned Opc = Op.getOpcode();
12546   assert((Opc >= ISD::BUILTIN_OP_END ||
12547           Opc == ISD::INTRINSIC_WO_CHAIN ||
12548           Opc == ISD::INTRINSIC_W_CHAIN ||
12549           Opc == ISD::INTRINSIC_VOID) &&
12550          "Should use MaskedValueIsZero if you don't know whether Op"
12551          " is a target node!");
12552
12553   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
12554   switch (Opc) {
12555   default: break;
12556   case X86ISD::ADD:
12557   case X86ISD::SUB:
12558   case X86ISD::ADC:
12559   case X86ISD::SBB:
12560   case X86ISD::SMUL:
12561   case X86ISD::UMUL:
12562   case X86ISD::INC:
12563   case X86ISD::DEC:
12564   case X86ISD::OR:
12565   case X86ISD::XOR:
12566   case X86ISD::AND:
12567     // These nodes' second result is a boolean.
12568     if (Op.getResNo() == 0)
12569       break;
12570     // Fallthrough
12571   case X86ISD::SETCC:
12572     KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
12573                                        Mask.getBitWidth() - 1);
12574     break;
12575   case ISD::INTRINSIC_WO_CHAIN: {
12576     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12577     unsigned NumLoBits = 0;
12578     switch (IntId) {
12579     default: break;
12580     case Intrinsic::x86_sse_movmsk_ps:
12581     case Intrinsic::x86_avx_movmsk_ps_256:
12582     case Intrinsic::x86_sse2_movmsk_pd:
12583     case Intrinsic::x86_avx_movmsk_pd_256:
12584     case Intrinsic::x86_mmx_pmovmskb:
12585     case Intrinsic::x86_sse2_pmovmskb_128: {
12586       // High bits of movmskp{s|d}, pmovmskb are known zero.
12587       switch (IntId) {
12588         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
12589         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
12590         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
12591         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
12592         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
12593         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
12594       }
12595       KnownZero = APInt::getHighBitsSet(Mask.getBitWidth(),
12596                                         Mask.getBitWidth() - NumLoBits);
12597       break;
12598     }
12599     }
12600     break;
12601   }
12602   }
12603 }
12604
12605 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
12606                                                          unsigned Depth) const {
12607   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
12608   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
12609     return Op.getValueType().getScalarType().getSizeInBits();
12610
12611   // Fallback case.
12612   return 1;
12613 }
12614
12615 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
12616 /// node is a GlobalAddress + offset.
12617 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
12618                                        const GlobalValue* &GA,
12619                                        int64_t &Offset) const {
12620   if (N->getOpcode() == X86ISD::Wrapper) {
12621     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
12622       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
12623       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
12624       return true;
12625     }
12626   }
12627   return TargetLowering::isGAPlusOffset(N, GA, Offset);
12628 }
12629
12630 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
12631 /// same as extracting the high 128-bit part of 256-bit vector and then
12632 /// inserting the result into the low part of a new 256-bit vector
12633 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
12634   EVT VT = SVOp->getValueType(0);
12635   int NumElems = VT.getVectorNumElements();
12636
12637   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
12638   for (int i = 0, j = NumElems/2; i < NumElems/2; ++i, ++j)
12639     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12640         SVOp->getMaskElt(j) >= 0)
12641       return false;
12642
12643   return true;
12644 }
12645
12646 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
12647 /// same as extracting the low 128-bit part of 256-bit vector and then
12648 /// inserting the result into the high part of a new 256-bit vector
12649 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
12650   EVT VT = SVOp->getValueType(0);
12651   int NumElems = VT.getVectorNumElements();
12652
12653   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
12654   for (int i = NumElems/2, j = 0; i < NumElems; ++i, ++j)
12655     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12656         SVOp->getMaskElt(j) >= 0)
12657       return false;
12658
12659   return true;
12660 }
12661
12662 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
12663 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
12664                                         TargetLowering::DAGCombinerInfo &DCI) {
12665   DebugLoc dl = N->getDebugLoc();
12666   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
12667   SDValue V1 = SVOp->getOperand(0);
12668   SDValue V2 = SVOp->getOperand(1);
12669   EVT VT = SVOp->getValueType(0);
12670   int NumElems = VT.getVectorNumElements();
12671
12672   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
12673       V2.getOpcode() == ISD::CONCAT_VECTORS) {
12674     //
12675     //                   0,0,0,...
12676     //                      |
12677     //    V      UNDEF    BUILD_VECTOR    UNDEF
12678     //     \      /           \           /
12679     //  CONCAT_VECTOR         CONCAT_VECTOR
12680     //         \                  /
12681     //          \                /
12682     //          RESULT: V + zero extended
12683     //
12684     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
12685         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
12686         V1.getOperand(1).getOpcode() != ISD::UNDEF)
12687       return SDValue();
12688
12689     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
12690       return SDValue();
12691
12692     // To match the shuffle mask, the first half of the mask should
12693     // be exactly the first vector, and all the rest a splat with the
12694     // first element of the second one.
12695     for (int i = 0; i < NumElems/2; ++i)
12696       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
12697           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
12698         return SDValue();
12699
12700     // Emit a zeroed vector and insert the desired subvector on its
12701     // first half.
12702     SDValue Zeros = getZeroVector(VT, true /* HasXMMInt */, DAG, dl);
12703     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0),
12704                          DAG.getConstant(0, MVT::i32), DAG, dl);
12705     return DCI.CombineTo(N, InsV);
12706   }
12707
12708   //===--------------------------------------------------------------------===//
12709   // Combine some shuffles into subvector extracts and inserts:
12710   //
12711
12712   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
12713   if (isShuffleHigh128VectorInsertLow(SVOp)) {
12714     SDValue V = Extract128BitVector(V1, DAG.getConstant(NumElems/2, MVT::i32),
12715                                     DAG, dl);
12716     SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT),
12717                                       V, DAG.getConstant(0, MVT::i32), DAG, dl);
12718     return DCI.CombineTo(N, InsV);
12719   }
12720
12721   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
12722   if (isShuffleLow128VectorInsertHigh(SVOp)) {
12723     SDValue V = Extract128BitVector(V1, DAG.getConstant(0, MVT::i32), DAG, dl);
12724     SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT),
12725                              V, DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
12726     return DCI.CombineTo(N, InsV);
12727   }
12728
12729   return SDValue();
12730 }
12731
12732 /// PerformShuffleCombine - Performs several different shuffle combines.
12733 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
12734                                      TargetLowering::DAGCombinerInfo &DCI,
12735                                      const X86Subtarget *Subtarget) {
12736   DebugLoc dl = N->getDebugLoc();
12737   EVT VT = N->getValueType(0);
12738
12739   // Don't create instructions with illegal types after legalize types has run.
12740   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12741   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
12742     return SDValue();
12743
12744   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
12745   if (Subtarget->hasAVX() && VT.getSizeInBits() == 256 &&
12746       N->getOpcode() == ISD::VECTOR_SHUFFLE)
12747     return PerformShuffleCombine256(N, DAG, DCI);
12748
12749   // Only handle 128 wide vector from here on.
12750   if (VT.getSizeInBits() != 128)
12751     return SDValue();
12752
12753   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
12754   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
12755   // consecutive, non-overlapping, and in the right order.
12756   SmallVector<SDValue, 16> Elts;
12757   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
12758     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
12759
12760   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
12761 }
12762
12763 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
12764 /// generation and convert it from being a bunch of shuffles and extracts
12765 /// to a simple store and scalar loads to extract the elements.
12766 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
12767                                                 const TargetLowering &TLI) {
12768   SDValue InputVector = N->getOperand(0);
12769
12770   // Only operate on vectors of 4 elements, where the alternative shuffling
12771   // gets to be more expensive.
12772   if (InputVector.getValueType() != MVT::v4i32)
12773     return SDValue();
12774
12775   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
12776   // single use which is a sign-extend or zero-extend, and all elements are
12777   // used.
12778   SmallVector<SDNode *, 4> Uses;
12779   unsigned ExtractedElements = 0;
12780   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
12781        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
12782     if (UI.getUse().getResNo() != InputVector.getResNo())
12783       return SDValue();
12784
12785     SDNode *Extract = *UI;
12786     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12787       return SDValue();
12788
12789     if (Extract->getValueType(0) != MVT::i32)
12790       return SDValue();
12791     if (!Extract->hasOneUse())
12792       return SDValue();
12793     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
12794         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
12795       return SDValue();
12796     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
12797       return SDValue();
12798
12799     // Record which element was extracted.
12800     ExtractedElements |=
12801       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
12802
12803     Uses.push_back(Extract);
12804   }
12805
12806   // If not all the elements were used, this may not be worthwhile.
12807   if (ExtractedElements != 15)
12808     return SDValue();
12809
12810   // Ok, we've now decided to do the transformation.
12811   DebugLoc dl = InputVector.getDebugLoc();
12812
12813   // Store the value to a temporary stack slot.
12814   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
12815   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
12816                             MachinePointerInfo(), false, false, 0);
12817
12818   // Replace each use (extract) with a load of the appropriate element.
12819   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
12820        UE = Uses.end(); UI != UE; ++UI) {
12821     SDNode *Extract = *UI;
12822
12823     // cOMpute the element's address.
12824     SDValue Idx = Extract->getOperand(1);
12825     unsigned EltSize =
12826         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
12827     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
12828     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
12829
12830     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
12831                                      StackPtr, OffsetVal);
12832
12833     // Load the scalar.
12834     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
12835                                      ScalarAddr, MachinePointerInfo(),
12836                                      false, false, false, 0);
12837
12838     // Replace the exact with the load.
12839     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
12840   }
12841
12842   // The replacement was made in place; don't return anything.
12843   return SDValue();
12844 }
12845
12846 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
12847 /// nodes.
12848 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
12849                                     const X86Subtarget *Subtarget) {
12850   DebugLoc DL = N->getDebugLoc();
12851   SDValue Cond = N->getOperand(0);
12852   // Get the LHS/RHS of the select.
12853   SDValue LHS = N->getOperand(1);
12854   SDValue RHS = N->getOperand(2);
12855   EVT VT = LHS.getValueType();
12856
12857   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
12858   // instructions match the semantics of the common C idiom x<y?x:y but not
12859   // x<=y?x:y, because of how they handle negative zero (which can be
12860   // ignored in unsafe-math mode).
12861   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
12862       VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
12863       (Subtarget->hasXMMInt() ||
12864        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
12865     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
12866
12867     unsigned Opcode = 0;
12868     // Check for x CC y ? x : y.
12869     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
12870         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
12871       switch (CC) {
12872       default: break;
12873       case ISD::SETULT:
12874         // Converting this to a min would handle NaNs incorrectly, and swapping
12875         // the operands would cause it to handle comparisons between positive
12876         // and negative zero incorrectly.
12877         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
12878           if (!DAG.getTarget().Options.UnsafeFPMath &&
12879               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
12880             break;
12881           std::swap(LHS, RHS);
12882         }
12883         Opcode = X86ISD::FMIN;
12884         break;
12885       case ISD::SETOLE:
12886         // Converting this to a min would handle comparisons between positive
12887         // and negative zero incorrectly.
12888         if (!DAG.getTarget().Options.UnsafeFPMath &&
12889             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
12890           break;
12891         Opcode = X86ISD::FMIN;
12892         break;
12893       case ISD::SETULE:
12894         // Converting this to a min would handle both negative zeros and NaNs
12895         // incorrectly, but we can swap the operands to fix both.
12896         std::swap(LHS, RHS);
12897       case ISD::SETOLT:
12898       case ISD::SETLT:
12899       case ISD::SETLE:
12900         Opcode = X86ISD::FMIN;
12901         break;
12902
12903       case ISD::SETOGE:
12904         // Converting this to a max would handle comparisons between positive
12905         // and negative zero incorrectly.
12906         if (!DAG.getTarget().Options.UnsafeFPMath &&
12907             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
12908           break;
12909         Opcode = X86ISD::FMAX;
12910         break;
12911       case ISD::SETUGT:
12912         // Converting this to a max would handle NaNs incorrectly, and swapping
12913         // the operands would cause it to handle comparisons between positive
12914         // and negative zero incorrectly.
12915         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
12916           if (!DAG.getTarget().Options.UnsafeFPMath &&
12917               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
12918             break;
12919           std::swap(LHS, RHS);
12920         }
12921         Opcode = X86ISD::FMAX;
12922         break;
12923       case ISD::SETUGE:
12924         // Converting this to a max would handle both negative zeros and NaNs
12925         // incorrectly, but we can swap the operands to fix both.
12926         std::swap(LHS, RHS);
12927       case ISD::SETOGT:
12928       case ISD::SETGT:
12929       case ISD::SETGE:
12930         Opcode = X86ISD::FMAX;
12931         break;
12932       }
12933     // Check for x CC y ? y : x -- a min/max with reversed arms.
12934     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
12935                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
12936       switch (CC) {
12937       default: break;
12938       case ISD::SETOGE:
12939         // Converting this to a min would handle comparisons between positive
12940         // and negative zero incorrectly, and swapping the operands would
12941         // cause it to handle NaNs incorrectly.
12942         if (!DAG.getTarget().Options.UnsafeFPMath &&
12943             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
12944           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
12945             break;
12946           std::swap(LHS, RHS);
12947         }
12948         Opcode = X86ISD::FMIN;
12949         break;
12950       case ISD::SETUGT:
12951         // Converting this to a min would handle NaNs incorrectly.
12952         if (!DAG.getTarget().Options.UnsafeFPMath &&
12953             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
12954           break;
12955         Opcode = X86ISD::FMIN;
12956         break;
12957       case ISD::SETUGE:
12958         // Converting this to a min would handle both negative zeros and NaNs
12959         // incorrectly, but we can swap the operands to fix both.
12960         std::swap(LHS, RHS);
12961       case ISD::SETOGT:
12962       case ISD::SETGT:
12963       case ISD::SETGE:
12964         Opcode = X86ISD::FMIN;
12965         break;
12966
12967       case ISD::SETULT:
12968         // Converting this to a max would handle NaNs incorrectly.
12969         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
12970           break;
12971         Opcode = X86ISD::FMAX;
12972         break;
12973       case ISD::SETOLE:
12974         // Converting this to a max would handle comparisons between positive
12975         // and negative zero incorrectly, and swapping the operands would
12976         // cause it to handle NaNs incorrectly.
12977         if (!DAG.getTarget().Options.UnsafeFPMath &&
12978             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
12979           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
12980             break;
12981           std::swap(LHS, RHS);
12982         }
12983         Opcode = X86ISD::FMAX;
12984         break;
12985       case ISD::SETULE:
12986         // Converting this to a max would handle both negative zeros and NaNs
12987         // incorrectly, but we can swap the operands to fix both.
12988         std::swap(LHS, RHS);
12989       case ISD::SETOLT:
12990       case ISD::SETLT:
12991       case ISD::SETLE:
12992         Opcode = X86ISD::FMAX;
12993         break;
12994       }
12995     }
12996
12997     if (Opcode)
12998       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
12999   }
13000
13001   // If this is a select between two integer constants, try to do some
13002   // optimizations.
13003   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
13004     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
13005       // Don't do this for crazy integer types.
13006       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
13007         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
13008         // so that TrueC (the true value) is larger than FalseC.
13009         bool NeedsCondInvert = false;
13010
13011         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
13012             // Efficiently invertible.
13013             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
13014              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
13015               isa<ConstantSDNode>(Cond.getOperand(1))))) {
13016           NeedsCondInvert = true;
13017           std::swap(TrueC, FalseC);
13018         }
13019
13020         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
13021         if (FalseC->getAPIntValue() == 0 &&
13022             TrueC->getAPIntValue().isPowerOf2()) {
13023           if (NeedsCondInvert) // Invert the condition if needed.
13024             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13025                                DAG.getConstant(1, Cond.getValueType()));
13026
13027           // Zero extend the condition if needed.
13028           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
13029
13030           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13031           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
13032                              DAG.getConstant(ShAmt, MVT::i8));
13033         }
13034
13035         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
13036         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13037           if (NeedsCondInvert) // Invert the condition if needed.
13038             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13039                                DAG.getConstant(1, Cond.getValueType()));
13040
13041           // Zero extend the condition if needed.
13042           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13043                              FalseC->getValueType(0), Cond);
13044           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13045                              SDValue(FalseC, 0));
13046         }
13047
13048         // Optimize cases that will turn into an LEA instruction.  This requires
13049         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13050         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13051           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13052           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13053
13054           bool isFastMultiplier = false;
13055           if (Diff < 10) {
13056             switch ((unsigned char)Diff) {
13057               default: break;
13058               case 1:  // result = add base, cond
13059               case 2:  // result = lea base(    , cond*2)
13060               case 3:  // result = lea base(cond, cond*2)
13061               case 4:  // result = lea base(    , cond*4)
13062               case 5:  // result = lea base(cond, cond*4)
13063               case 8:  // result = lea base(    , cond*8)
13064               case 9:  // result = lea base(cond, cond*8)
13065                 isFastMultiplier = true;
13066                 break;
13067             }
13068           }
13069
13070           if (isFastMultiplier) {
13071             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13072             if (NeedsCondInvert) // Invert the condition if needed.
13073               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13074                                  DAG.getConstant(1, Cond.getValueType()));
13075
13076             // Zero extend the condition if needed.
13077             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13078                                Cond);
13079             // Scale the condition by the difference.
13080             if (Diff != 1)
13081               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13082                                  DAG.getConstant(Diff, Cond.getValueType()));
13083
13084             // Add the base if non-zero.
13085             if (FalseC->getAPIntValue() != 0)
13086               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13087                                  SDValue(FalseC, 0));
13088             return Cond;
13089           }
13090         }
13091       }
13092   }
13093
13094   return SDValue();
13095 }
13096
13097 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
13098 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
13099                                   TargetLowering::DAGCombinerInfo &DCI) {
13100   DebugLoc DL = N->getDebugLoc();
13101
13102   // If the flag operand isn't dead, don't touch this CMOV.
13103   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
13104     return SDValue();
13105
13106   SDValue FalseOp = N->getOperand(0);
13107   SDValue TrueOp = N->getOperand(1);
13108   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
13109   SDValue Cond = N->getOperand(3);
13110   if (CC == X86::COND_E || CC == X86::COND_NE) {
13111     switch (Cond.getOpcode()) {
13112     default: break;
13113     case X86ISD::BSR:
13114     case X86ISD::BSF:
13115       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
13116       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
13117         return (CC == X86::COND_E) ? FalseOp : TrueOp;
13118     }
13119   }
13120
13121   // If this is a select between two integer constants, try to do some
13122   // optimizations.  Note that the operands are ordered the opposite of SELECT
13123   // operands.
13124   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
13125     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
13126       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
13127       // larger than FalseC (the false value).
13128       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
13129         CC = X86::GetOppositeBranchCondition(CC);
13130         std::swap(TrueC, FalseC);
13131       }
13132
13133       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
13134       // This is efficient for any integer data type (including i8/i16) and
13135       // shift amount.
13136       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
13137         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13138                            DAG.getConstant(CC, MVT::i8), Cond);
13139
13140         // Zero extend the condition if needed.
13141         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
13142
13143         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13144         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
13145                            DAG.getConstant(ShAmt, MVT::i8));
13146         if (N->getNumValues() == 2)  // Dead flag value?
13147           return DCI.CombineTo(N, Cond, SDValue());
13148         return Cond;
13149       }
13150
13151       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
13152       // for any integer data type, including i8/i16.
13153       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13154         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13155                            DAG.getConstant(CC, MVT::i8), Cond);
13156
13157         // Zero extend the condition if needed.
13158         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13159                            FalseC->getValueType(0), Cond);
13160         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13161                            SDValue(FalseC, 0));
13162
13163         if (N->getNumValues() == 2)  // Dead flag value?
13164           return DCI.CombineTo(N, Cond, SDValue());
13165         return Cond;
13166       }
13167
13168       // Optimize cases that will turn into an LEA instruction.  This requires
13169       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13170       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13171         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13172         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13173
13174         bool isFastMultiplier = false;
13175         if (Diff < 10) {
13176           switch ((unsigned char)Diff) {
13177           default: break;
13178           case 1:  // result = add base, cond
13179           case 2:  // result = lea base(    , cond*2)
13180           case 3:  // result = lea base(cond, cond*2)
13181           case 4:  // result = lea base(    , cond*4)
13182           case 5:  // result = lea base(cond, cond*4)
13183           case 8:  // result = lea base(    , cond*8)
13184           case 9:  // result = lea base(cond, cond*8)
13185             isFastMultiplier = true;
13186             break;
13187           }
13188         }
13189
13190         if (isFastMultiplier) {
13191           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13192           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13193                              DAG.getConstant(CC, MVT::i8), Cond);
13194           // Zero extend the condition if needed.
13195           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13196                              Cond);
13197           // Scale the condition by the difference.
13198           if (Diff != 1)
13199             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13200                                DAG.getConstant(Diff, Cond.getValueType()));
13201
13202           // Add the base if non-zero.
13203           if (FalseC->getAPIntValue() != 0)
13204             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13205                                SDValue(FalseC, 0));
13206           if (N->getNumValues() == 2)  // Dead flag value?
13207             return DCI.CombineTo(N, Cond, SDValue());
13208           return Cond;
13209         }
13210       }
13211     }
13212   }
13213   return SDValue();
13214 }
13215
13216
13217 /// PerformMulCombine - Optimize a single multiply with constant into two
13218 /// in order to implement it with two cheaper instructions, e.g.
13219 /// LEA + SHL, LEA + LEA.
13220 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
13221                                  TargetLowering::DAGCombinerInfo &DCI) {
13222   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
13223     return SDValue();
13224
13225   EVT VT = N->getValueType(0);
13226   if (VT != MVT::i64)
13227     return SDValue();
13228
13229   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
13230   if (!C)
13231     return SDValue();
13232   uint64_t MulAmt = C->getZExtValue();
13233   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
13234     return SDValue();
13235
13236   uint64_t MulAmt1 = 0;
13237   uint64_t MulAmt2 = 0;
13238   if ((MulAmt % 9) == 0) {
13239     MulAmt1 = 9;
13240     MulAmt2 = MulAmt / 9;
13241   } else if ((MulAmt % 5) == 0) {
13242     MulAmt1 = 5;
13243     MulAmt2 = MulAmt / 5;
13244   } else if ((MulAmt % 3) == 0) {
13245     MulAmt1 = 3;
13246     MulAmt2 = MulAmt / 3;
13247   }
13248   if (MulAmt2 &&
13249       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
13250     DebugLoc DL = N->getDebugLoc();
13251
13252     if (isPowerOf2_64(MulAmt2) &&
13253         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
13254       // If second multiplifer is pow2, issue it first. We want the multiply by
13255       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
13256       // is an add.
13257       std::swap(MulAmt1, MulAmt2);
13258
13259     SDValue NewMul;
13260     if (isPowerOf2_64(MulAmt1))
13261       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
13262                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
13263     else
13264       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
13265                            DAG.getConstant(MulAmt1, VT));
13266
13267     if (isPowerOf2_64(MulAmt2))
13268       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
13269                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
13270     else
13271       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
13272                            DAG.getConstant(MulAmt2, VT));
13273
13274     // Do not add new nodes to DAG combiner worklist.
13275     DCI.CombineTo(N, NewMul, false);
13276   }
13277   return SDValue();
13278 }
13279
13280 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
13281   SDValue N0 = N->getOperand(0);
13282   SDValue N1 = N->getOperand(1);
13283   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
13284   EVT VT = N0.getValueType();
13285
13286   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
13287   // since the result of setcc_c is all zero's or all ones.
13288   if (VT.isInteger() && !VT.isVector() &&
13289       N1C && N0.getOpcode() == ISD::AND &&
13290       N0.getOperand(1).getOpcode() == ISD::Constant) {
13291     SDValue N00 = N0.getOperand(0);
13292     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
13293         ((N00.getOpcode() == ISD::ANY_EXTEND ||
13294           N00.getOpcode() == ISD::ZERO_EXTEND) &&
13295          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
13296       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
13297       APInt ShAmt = N1C->getAPIntValue();
13298       Mask = Mask.shl(ShAmt);
13299       if (Mask != 0)
13300         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
13301                            N00, DAG.getConstant(Mask, VT));
13302     }
13303   }
13304
13305
13306   // Hardware support for vector shifts is sparse which makes us scalarize the
13307   // vector operations in many cases. Also, on sandybridge ADD is faster than
13308   // shl.
13309   // (shl V, 1) -> add V,V
13310   if (isSplatVector(N1.getNode())) {
13311     assert(N0.getValueType().isVector() && "Invalid vector shift type");
13312     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
13313     // We shift all of the values by one. In many cases we do not have
13314     // hardware support for this operation. This is better expressed as an ADD
13315     // of two values.
13316     if (N1C && (1 == N1C->getZExtValue())) {
13317       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
13318     }
13319   }
13320
13321   return SDValue();
13322 }
13323
13324 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
13325 ///                       when possible.
13326 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
13327                                    const X86Subtarget *Subtarget) {
13328   EVT VT = N->getValueType(0);
13329   if (N->getOpcode() == ISD::SHL) {
13330     SDValue V = PerformSHLCombine(N, DAG);
13331     if (V.getNode()) return V;
13332   }
13333
13334   // On X86 with SSE2 support, we can transform this to a vector shift if
13335   // all elements are shifted by the same amount.  We can't do this in legalize
13336   // because the a constant vector is typically transformed to a constant pool
13337   // so we have no knowledge of the shift amount.
13338   if (!Subtarget->hasXMMInt())
13339     return SDValue();
13340
13341   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
13342       (!Subtarget->hasAVX2() ||
13343        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
13344     return SDValue();
13345
13346   SDValue ShAmtOp = N->getOperand(1);
13347   EVT EltVT = VT.getVectorElementType();
13348   DebugLoc DL = N->getDebugLoc();
13349   SDValue BaseShAmt = SDValue();
13350   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
13351     unsigned NumElts = VT.getVectorNumElements();
13352     unsigned i = 0;
13353     for (; i != NumElts; ++i) {
13354       SDValue Arg = ShAmtOp.getOperand(i);
13355       if (Arg.getOpcode() == ISD::UNDEF) continue;
13356       BaseShAmt = Arg;
13357       break;
13358     }
13359     for (; i != NumElts; ++i) {
13360       SDValue Arg = ShAmtOp.getOperand(i);
13361       if (Arg.getOpcode() == ISD::UNDEF) continue;
13362       if (Arg != BaseShAmt) {
13363         return SDValue();
13364       }
13365     }
13366   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
13367              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
13368     SDValue InVec = ShAmtOp.getOperand(0);
13369     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13370       unsigned NumElts = InVec.getValueType().getVectorNumElements();
13371       unsigned i = 0;
13372       for (; i != NumElts; ++i) {
13373         SDValue Arg = InVec.getOperand(i);
13374         if (Arg.getOpcode() == ISD::UNDEF) continue;
13375         BaseShAmt = Arg;
13376         break;
13377       }
13378     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13379        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13380          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
13381          if (C->getZExtValue() == SplatIdx)
13382            BaseShAmt = InVec.getOperand(1);
13383        }
13384     }
13385     if (BaseShAmt.getNode() == 0)
13386       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
13387                               DAG.getIntPtrConstant(0));
13388   } else
13389     return SDValue();
13390
13391   // The shift amount is an i32.
13392   if (EltVT.bitsGT(MVT::i32))
13393     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
13394   else if (EltVT.bitsLT(MVT::i32))
13395     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
13396
13397   // The shift amount is identical so we can do a vector shift.
13398   SDValue  ValOp = N->getOperand(0);
13399   switch (N->getOpcode()) {
13400   default:
13401     llvm_unreachable("Unknown shift opcode!");
13402     break;
13403   case ISD::SHL:
13404     if (VT == MVT::v2i64)
13405       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13406                          DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
13407                          ValOp, BaseShAmt);
13408     if (VT == MVT::v4i32)
13409       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13410                          DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
13411                          ValOp, BaseShAmt);
13412     if (VT == MVT::v8i16)
13413       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13414                          DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
13415                          ValOp, BaseShAmt);
13416     if (VT == MVT::v4i64)
13417       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13418                          DAG.getConstant(Intrinsic::x86_avx2_pslli_q, MVT::i32),
13419                          ValOp, BaseShAmt);
13420     if (VT == MVT::v8i32)
13421       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13422                          DAG.getConstant(Intrinsic::x86_avx2_pslli_d, MVT::i32),
13423                          ValOp, BaseShAmt);
13424     if (VT == MVT::v16i16)
13425       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13426                          DAG.getConstant(Intrinsic::x86_avx2_pslli_w, MVT::i32),
13427                          ValOp, BaseShAmt);
13428     break;
13429   case ISD::SRA:
13430     if (VT == MVT::v4i32)
13431       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13432                          DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
13433                          ValOp, BaseShAmt);
13434     if (VT == MVT::v8i16)
13435       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13436                          DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
13437                          ValOp, BaseShAmt);
13438     if (VT == MVT::v8i32)
13439       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13440                          DAG.getConstant(Intrinsic::x86_avx2_psrai_d, MVT::i32),
13441                          ValOp, BaseShAmt);
13442     if (VT == MVT::v16i16)
13443       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13444                          DAG.getConstant(Intrinsic::x86_avx2_psrai_w, MVT::i32),
13445                          ValOp, BaseShAmt);
13446     break;
13447   case ISD::SRL:
13448     if (VT == MVT::v2i64)
13449       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13450                          DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
13451                          ValOp, BaseShAmt);
13452     if (VT == MVT::v4i32)
13453       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13454                          DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
13455                          ValOp, BaseShAmt);
13456     if (VT ==  MVT::v8i16)
13457       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13458                          DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
13459                          ValOp, BaseShAmt);
13460     if (VT == MVT::v4i64)
13461       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13462                          DAG.getConstant(Intrinsic::x86_avx2_psrli_q, MVT::i32),
13463                          ValOp, BaseShAmt);
13464     if (VT == MVT::v8i32)
13465       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13466                          DAG.getConstant(Intrinsic::x86_avx2_psrli_d, MVT::i32),
13467                          ValOp, BaseShAmt);
13468     if (VT ==  MVT::v16i16)
13469       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13470                          DAG.getConstant(Intrinsic::x86_avx2_psrli_w, MVT::i32),
13471                          ValOp, BaseShAmt);
13472     break;
13473   }
13474   return SDValue();
13475 }
13476
13477
13478 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
13479 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
13480 // and friends.  Likewise for OR -> CMPNEQSS.
13481 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
13482                             TargetLowering::DAGCombinerInfo &DCI,
13483                             const X86Subtarget *Subtarget) {
13484   unsigned opcode;
13485
13486   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
13487   // we're requiring SSE2 for both.
13488   if (Subtarget->hasXMMInt() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
13489     SDValue N0 = N->getOperand(0);
13490     SDValue N1 = N->getOperand(1);
13491     SDValue CMP0 = N0->getOperand(1);
13492     SDValue CMP1 = N1->getOperand(1);
13493     DebugLoc DL = N->getDebugLoc();
13494
13495     // The SETCCs should both refer to the same CMP.
13496     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
13497       return SDValue();
13498
13499     SDValue CMP00 = CMP0->getOperand(0);
13500     SDValue CMP01 = CMP0->getOperand(1);
13501     EVT     VT    = CMP00.getValueType();
13502
13503     if (VT == MVT::f32 || VT == MVT::f64) {
13504       bool ExpectingFlags = false;
13505       // Check for any users that want flags:
13506       for (SDNode::use_iterator UI = N->use_begin(),
13507              UE = N->use_end();
13508            !ExpectingFlags && UI != UE; ++UI)
13509         switch (UI->getOpcode()) {
13510         default:
13511         case ISD::BR_CC:
13512         case ISD::BRCOND:
13513         case ISD::SELECT:
13514           ExpectingFlags = true;
13515           break;
13516         case ISD::CopyToReg:
13517         case ISD::SIGN_EXTEND:
13518         case ISD::ZERO_EXTEND:
13519         case ISD::ANY_EXTEND:
13520           break;
13521         }
13522
13523       if (!ExpectingFlags) {
13524         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
13525         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
13526
13527         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
13528           X86::CondCode tmp = cc0;
13529           cc0 = cc1;
13530           cc1 = tmp;
13531         }
13532
13533         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
13534             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
13535           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
13536           X86ISD::NodeType NTOperator = is64BitFP ?
13537             X86ISD::FSETCCsd : X86ISD::FSETCCss;
13538           // FIXME: need symbolic constants for these magic numbers.
13539           // See X86ATTInstPrinter.cpp:printSSECC().
13540           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
13541           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
13542                                               DAG.getConstant(x86cc, MVT::i8));
13543           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
13544                                               OnesOrZeroesF);
13545           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
13546                                       DAG.getConstant(1, MVT::i32));
13547           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
13548           return OneBitOfTruth;
13549         }
13550       }
13551     }
13552   }
13553   return SDValue();
13554 }
13555
13556 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
13557 /// so it can be folded inside ANDNP.
13558 static bool CanFoldXORWithAllOnes(const SDNode *N) {
13559   EVT VT = N->getValueType(0);
13560
13561   // Match direct AllOnes for 128 and 256-bit vectors
13562   if (ISD::isBuildVectorAllOnes(N))
13563     return true;
13564
13565   // Look through a bit convert.
13566   if (N->getOpcode() == ISD::BITCAST)
13567     N = N->getOperand(0).getNode();
13568
13569   // Sometimes the operand may come from a insert_subvector building a 256-bit
13570   // allones vector
13571   if (VT.getSizeInBits() == 256 &&
13572       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
13573     SDValue V1 = N->getOperand(0);
13574     SDValue V2 = N->getOperand(1);
13575
13576     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
13577         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
13578         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
13579         ISD::isBuildVectorAllOnes(V2.getNode()))
13580       return true;
13581   }
13582
13583   return false;
13584 }
13585
13586 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
13587                                  TargetLowering::DAGCombinerInfo &DCI,
13588                                  const X86Subtarget *Subtarget) {
13589   if (DCI.isBeforeLegalizeOps())
13590     return SDValue();
13591
13592   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
13593   if (R.getNode())
13594     return R;
13595
13596   EVT VT = N->getValueType(0);
13597
13598   // Create ANDN, BLSI, and BLSR instructions
13599   // BLSI is X & (-X)
13600   // BLSR is X & (X-1)
13601   if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
13602     SDValue N0 = N->getOperand(0);
13603     SDValue N1 = N->getOperand(1);
13604     DebugLoc DL = N->getDebugLoc();
13605
13606     // Check LHS for not
13607     if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1)))
13608       return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1);
13609     // Check RHS for not
13610     if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1)))
13611       return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
13612
13613     // Check LHS for neg
13614     if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
13615         isZero(N0.getOperand(0)))
13616       return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
13617
13618     // Check RHS for neg
13619     if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
13620         isZero(N1.getOperand(0)))
13621       return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
13622
13623     // Check LHS for X-1
13624     if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
13625         isAllOnes(N0.getOperand(1)))
13626       return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
13627
13628     // Check RHS for X-1
13629     if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
13630         isAllOnes(N1.getOperand(1)))
13631       return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
13632
13633     return SDValue();
13634   }
13635
13636   // Want to form ANDNP nodes:
13637   // 1) In the hopes of then easily combining them with OR and AND nodes
13638   //    to form PBLEND/PSIGN.
13639   // 2) To match ANDN packed intrinsics
13640   if (VT != MVT::v2i64 && VT != MVT::v4i64)
13641     return SDValue();
13642
13643   SDValue N0 = N->getOperand(0);
13644   SDValue N1 = N->getOperand(1);
13645   DebugLoc DL = N->getDebugLoc();
13646
13647   // Check LHS for vnot
13648   if (N0.getOpcode() == ISD::XOR &&
13649       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
13650       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
13651     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
13652
13653   // Check RHS for vnot
13654   if (N1.getOpcode() == ISD::XOR &&
13655       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
13656       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
13657     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
13658
13659   return SDValue();
13660 }
13661
13662 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
13663                                 TargetLowering::DAGCombinerInfo &DCI,
13664                                 const X86Subtarget *Subtarget) {
13665   if (DCI.isBeforeLegalizeOps())
13666     return SDValue();
13667
13668   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
13669   if (R.getNode())
13670     return R;
13671
13672   EVT VT = N->getValueType(0);
13673
13674   SDValue N0 = N->getOperand(0);
13675   SDValue N1 = N->getOperand(1);
13676
13677   // look for psign/blend
13678   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
13679     if (!Subtarget->hasSSSE3orAVX() ||
13680         (VT == MVT::v4i64 && !Subtarget->hasAVX2()))
13681       return SDValue();
13682
13683     // Canonicalize pandn to RHS
13684     if (N0.getOpcode() == X86ISD::ANDNP)
13685       std::swap(N0, N1);
13686     // or (and (m, x), (pandn m, y))
13687     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
13688       SDValue Mask = N1.getOperand(0);
13689       SDValue X    = N1.getOperand(1);
13690       SDValue Y;
13691       if (N0.getOperand(0) == Mask)
13692         Y = N0.getOperand(1);
13693       if (N0.getOperand(1) == Mask)
13694         Y = N0.getOperand(0);
13695
13696       // Check to see if the mask appeared in both the AND and ANDNP and
13697       if (!Y.getNode())
13698         return SDValue();
13699
13700       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
13701       if (Mask.getOpcode() != ISD::BITCAST ||
13702           X.getOpcode() != ISD::BITCAST ||
13703           Y.getOpcode() != ISD::BITCAST)
13704         return SDValue();
13705
13706       // Look through mask bitcast.
13707       Mask = Mask.getOperand(0);
13708       EVT MaskVT = Mask.getValueType();
13709
13710       // Validate that the Mask operand is a vector sra node.  The sra node
13711       // will be an intrinsic.
13712       if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
13713         return SDValue();
13714
13715       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
13716       // there is no psrai.b
13717       switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
13718       case Intrinsic::x86_sse2_psrai_w:
13719       case Intrinsic::x86_sse2_psrai_d:
13720       case Intrinsic::x86_avx2_psrai_w:
13721       case Intrinsic::x86_avx2_psrai_d:
13722         break;
13723       default: return SDValue();
13724       }
13725
13726       // Check that the SRA is all signbits.
13727       SDValue SraC = Mask.getOperand(2);
13728       unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
13729       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
13730       if ((SraAmt + 1) != EltBits)
13731         return SDValue();
13732
13733       DebugLoc DL = N->getDebugLoc();
13734
13735       // Now we know we at least have a plendvb with the mask val.  See if
13736       // we can form a psignb/w/d.
13737       // psign = x.type == y.type == mask.type && y = sub(0, x);
13738       X = X.getOperand(0);
13739       Y = Y.getOperand(0);
13740       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
13741           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
13742           X.getValueType() == MaskVT && X.getValueType() == Y.getValueType() &&
13743           (EltBits == 8 || EltBits == 16 || EltBits == 32)) {
13744         SDValue Sign = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X,
13745                                    Mask.getOperand(1));
13746         return DAG.getNode(ISD::BITCAST, DL, VT, Sign);
13747       }
13748       // PBLENDVB only available on SSE 4.1
13749       if (!Subtarget->hasSSE41orAVX())
13750         return SDValue();
13751
13752       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
13753
13754       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
13755       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
13756       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
13757       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
13758       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
13759     }
13760   }
13761
13762   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
13763     return SDValue();
13764
13765   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
13766   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
13767     std::swap(N0, N1);
13768   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
13769     return SDValue();
13770   if (!N0.hasOneUse() || !N1.hasOneUse())
13771     return SDValue();
13772
13773   SDValue ShAmt0 = N0.getOperand(1);
13774   if (ShAmt0.getValueType() != MVT::i8)
13775     return SDValue();
13776   SDValue ShAmt1 = N1.getOperand(1);
13777   if (ShAmt1.getValueType() != MVT::i8)
13778     return SDValue();
13779   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
13780     ShAmt0 = ShAmt0.getOperand(0);
13781   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
13782     ShAmt1 = ShAmt1.getOperand(0);
13783
13784   DebugLoc DL = N->getDebugLoc();
13785   unsigned Opc = X86ISD::SHLD;
13786   SDValue Op0 = N0.getOperand(0);
13787   SDValue Op1 = N1.getOperand(0);
13788   if (ShAmt0.getOpcode() == ISD::SUB) {
13789     Opc = X86ISD::SHRD;
13790     std::swap(Op0, Op1);
13791     std::swap(ShAmt0, ShAmt1);
13792   }
13793
13794   unsigned Bits = VT.getSizeInBits();
13795   if (ShAmt1.getOpcode() == ISD::SUB) {
13796     SDValue Sum = ShAmt1.getOperand(0);
13797     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
13798       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
13799       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
13800         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
13801       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
13802         return DAG.getNode(Opc, DL, VT,
13803                            Op0, Op1,
13804                            DAG.getNode(ISD::TRUNCATE, DL,
13805                                        MVT::i8, ShAmt0));
13806     }
13807   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
13808     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
13809     if (ShAmt0C &&
13810         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
13811       return DAG.getNode(Opc, DL, VT,
13812                          N0.getOperand(0), N1.getOperand(0),
13813                          DAG.getNode(ISD::TRUNCATE, DL,
13814                                        MVT::i8, ShAmt0));
13815   }
13816
13817   return SDValue();
13818 }
13819
13820 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
13821                                  TargetLowering::DAGCombinerInfo &DCI,
13822                                  const X86Subtarget *Subtarget) {
13823   if (DCI.isBeforeLegalizeOps())
13824     return SDValue();
13825
13826   EVT VT = N->getValueType(0);
13827
13828   if (VT != MVT::i32 && VT != MVT::i64)
13829     return SDValue();
13830
13831   // Create BLSMSK instructions by finding X ^ (X-1)
13832   SDValue N0 = N->getOperand(0);
13833   SDValue N1 = N->getOperand(1);
13834   DebugLoc DL = N->getDebugLoc();
13835
13836   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
13837       isAllOnes(N0.getOperand(1)))
13838     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
13839
13840   if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
13841       isAllOnes(N1.getOperand(1)))
13842     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
13843
13844   return SDValue();
13845 }
13846
13847 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
13848 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
13849                                    const X86Subtarget *Subtarget) {
13850   LoadSDNode *Ld = cast<LoadSDNode>(N);
13851   EVT RegVT = Ld->getValueType(0);
13852   EVT MemVT = Ld->getMemoryVT();
13853   DebugLoc dl = Ld->getDebugLoc();
13854   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13855
13856   ISD::LoadExtType Ext = Ld->getExtensionType();
13857
13858   // If this is a vector EXT Load then attempt to optimize it using a
13859   // shuffle. We need SSE4 for the shuffles.
13860   // TODO: It is possible to support ZExt by zeroing the undef values
13861   // during the shuffle phase or after the shuffle.
13862   if (RegVT.isVector() && Ext == ISD::EXTLOAD && Subtarget->hasSSE41()) {
13863     assert(MemVT != RegVT && "Cannot extend to the same type");
13864     assert(MemVT.isVector() && "Must load a vector from memory");
13865
13866     unsigned NumElems = RegVT.getVectorNumElements();
13867     unsigned RegSz = RegVT.getSizeInBits();
13868     unsigned MemSz = MemVT.getSizeInBits();
13869     assert(RegSz > MemSz && "Register size must be greater than the mem size");
13870     // All sizes must be a power of two
13871     if (!isPowerOf2_32(RegSz * MemSz * NumElems)) return SDValue();
13872
13873     // Attempt to load the original value using a single load op.
13874     // Find a scalar type which is equal to the loaded word size.
13875     MVT SclrLoadTy = MVT::i8;
13876     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
13877          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
13878       MVT Tp = (MVT::SimpleValueType)tp;
13879       if (TLI.isTypeLegal(Tp) &&  Tp.getSizeInBits() == MemSz) {
13880         SclrLoadTy = Tp;
13881         break;
13882       }
13883     }
13884
13885     // Proceed if a load word is found.
13886     if (SclrLoadTy.getSizeInBits() != MemSz) return SDValue();
13887
13888     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
13889       RegSz/SclrLoadTy.getSizeInBits());
13890
13891     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
13892                                   RegSz/MemVT.getScalarType().getSizeInBits());
13893     // Can't shuffle using an illegal type.
13894     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
13895
13896     // Perform a single load.
13897     SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
13898                                   Ld->getBasePtr(),
13899                                   Ld->getPointerInfo(), Ld->isVolatile(),
13900                                   Ld->isNonTemporal(), Ld->isInvariant(),
13901                                   Ld->getAlignment());
13902
13903     // Insert the word loaded into a vector.
13904     SDValue ScalarInVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
13905       LoadUnitVecVT, ScalarLoad);
13906
13907     // Bitcast the loaded value to a vector of the original element type, in
13908     // the size of the target vector type.
13909     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, ScalarInVector);
13910     unsigned SizeRatio = RegSz/MemSz;
13911
13912     // Redistribute the loaded elements into the different locations.
13913     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13914     for (unsigned i = 0; i < NumElems; i++) ShuffleVec[i*SizeRatio] = i;
13915
13916     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
13917                                 DAG.getUNDEF(SlicedVec.getValueType()),
13918                                 ShuffleVec.data());
13919
13920     // Bitcast to the requested type.
13921     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13922     // Replace the original load with the new sequence
13923     // and return the new chain.
13924     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Shuff);
13925     return SDValue(ScalarLoad.getNode(), 1);
13926   }
13927
13928   return SDValue();
13929 }
13930
13931 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
13932 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
13933                                    const X86Subtarget *Subtarget) {
13934   StoreSDNode *St = cast<StoreSDNode>(N);
13935   EVT VT = St->getValue().getValueType();
13936   EVT StVT = St->getMemoryVT();
13937   DebugLoc dl = St->getDebugLoc();
13938   SDValue StoredVal = St->getOperand(1);
13939   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13940
13941   // If we are saving a concatenation of two XMM registers, perform two stores.
13942   // This is better in Sandy Bridge cause one 256-bit mem op is done via two
13943   // 128-bit ones. If in the future the cost becomes only one memory access the
13944   // first version would be better.
13945   if (VT.getSizeInBits() == 256 &&
13946     StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
13947     StoredVal.getNumOperands() == 2) {
13948
13949     SDValue Value0 = StoredVal.getOperand(0);
13950     SDValue Value1 = StoredVal.getOperand(1);
13951
13952     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
13953     SDValue Ptr0 = St->getBasePtr();
13954     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
13955
13956     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
13957                                 St->getPointerInfo(), St->isVolatile(),
13958                                 St->isNonTemporal(), St->getAlignment());
13959     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
13960                                 St->getPointerInfo(), St->isVolatile(),
13961                                 St->isNonTemporal(), St->getAlignment());
13962     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
13963   }
13964
13965   // Optimize trunc store (of multiple scalars) to shuffle and store.
13966   // First, pack all of the elements in one place. Next, store to memory
13967   // in fewer chunks.
13968   if (St->isTruncatingStore() && VT.isVector()) {
13969     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13970     unsigned NumElems = VT.getVectorNumElements();
13971     assert(StVT != VT && "Cannot truncate to the same type");
13972     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
13973     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
13974
13975     // From, To sizes and ElemCount must be pow of two
13976     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
13977     // We are going to use the original vector elt for storing.
13978     // Accumulated smaller vector elements must be a multiple of the store size.
13979     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
13980
13981     unsigned SizeRatio  = FromSz / ToSz;
13982
13983     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
13984
13985     // Create a type on which we perform the shuffle
13986     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
13987             StVT.getScalarType(), NumElems*SizeRatio);
13988
13989     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
13990
13991     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
13992     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13993     for (unsigned i = 0; i < NumElems; i++ ) ShuffleVec[i] = i * SizeRatio;
13994
13995     // Can't shuffle using an illegal type
13996     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
13997
13998     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
13999                                 DAG.getUNDEF(WideVec.getValueType()),
14000                                 ShuffleVec.data());
14001     // At this point all of the data is stored at the bottom of the
14002     // register. We now need to save it to mem.
14003
14004     // Find the largest store unit
14005     MVT StoreType = MVT::i8;
14006     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
14007          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
14008       MVT Tp = (MVT::SimpleValueType)tp;
14009       if (TLI.isTypeLegal(Tp) && StoreType.getSizeInBits() < NumElems * ToSz)
14010         StoreType = Tp;
14011     }
14012
14013     // Bitcast the original vector into a vector of store-size units
14014     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
14015             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
14016     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
14017     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
14018     SmallVector<SDValue, 8> Chains;
14019     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
14020                                         TLI.getPointerTy());
14021     SDValue Ptr = St->getBasePtr();
14022
14023     // Perform one or more big stores into memory.
14024     for (unsigned i = 0; i < (ToSz*NumElems)/StoreType.getSizeInBits() ; i++) {
14025       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
14026                                    StoreType, ShuffWide,
14027                                    DAG.getIntPtrConstant(i));
14028       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
14029                                 St->getPointerInfo(), St->isVolatile(),
14030                                 St->isNonTemporal(), St->getAlignment());
14031       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14032       Chains.push_back(Ch);
14033     }
14034
14035     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
14036                                Chains.size());
14037   }
14038
14039
14040   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
14041   // the FP state in cases where an emms may be missing.
14042   // A preferable solution to the general problem is to figure out the right
14043   // places to insert EMMS.  This qualifies as a quick hack.
14044
14045   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
14046   if (VT.getSizeInBits() != 64)
14047     return SDValue();
14048
14049   const Function *F = DAG.getMachineFunction().getFunction();
14050   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
14051   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
14052                      && Subtarget->hasXMMInt();
14053   if ((VT.isVector() ||
14054        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
14055       isa<LoadSDNode>(St->getValue()) &&
14056       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
14057       St->getChain().hasOneUse() && !St->isVolatile()) {
14058     SDNode* LdVal = St->getValue().getNode();
14059     LoadSDNode *Ld = 0;
14060     int TokenFactorIndex = -1;
14061     SmallVector<SDValue, 8> Ops;
14062     SDNode* ChainVal = St->getChain().getNode();
14063     // Must be a store of a load.  We currently handle two cases:  the load
14064     // is a direct child, and it's under an intervening TokenFactor.  It is
14065     // possible to dig deeper under nested TokenFactors.
14066     if (ChainVal == LdVal)
14067       Ld = cast<LoadSDNode>(St->getChain());
14068     else if (St->getValue().hasOneUse() &&
14069              ChainVal->getOpcode() == ISD::TokenFactor) {
14070       for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
14071         if (ChainVal->getOperand(i).getNode() == LdVal) {
14072           TokenFactorIndex = i;
14073           Ld = cast<LoadSDNode>(St->getValue());
14074         } else
14075           Ops.push_back(ChainVal->getOperand(i));
14076       }
14077     }
14078
14079     if (!Ld || !ISD::isNormalLoad(Ld))
14080       return SDValue();
14081
14082     // If this is not the MMX case, i.e. we are just turning i64 load/store
14083     // into f64 load/store, avoid the transformation if there are multiple
14084     // uses of the loaded value.
14085     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
14086       return SDValue();
14087
14088     DebugLoc LdDL = Ld->getDebugLoc();
14089     DebugLoc StDL = N->getDebugLoc();
14090     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
14091     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
14092     // pair instead.
14093     if (Subtarget->is64Bit() || F64IsLegal) {
14094       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
14095       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
14096                                   Ld->getPointerInfo(), Ld->isVolatile(),
14097                                   Ld->isNonTemporal(), Ld->isInvariant(),
14098                                   Ld->getAlignment());
14099       SDValue NewChain = NewLd.getValue(1);
14100       if (TokenFactorIndex != -1) {
14101         Ops.push_back(NewChain);
14102         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14103                                Ops.size());
14104       }
14105       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
14106                           St->getPointerInfo(),
14107                           St->isVolatile(), St->isNonTemporal(),
14108                           St->getAlignment());
14109     }
14110
14111     // Otherwise, lower to two pairs of 32-bit loads / stores.
14112     SDValue LoAddr = Ld->getBasePtr();
14113     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
14114                                  DAG.getConstant(4, MVT::i32));
14115
14116     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
14117                                Ld->getPointerInfo(),
14118                                Ld->isVolatile(), Ld->isNonTemporal(),
14119                                Ld->isInvariant(), Ld->getAlignment());
14120     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
14121                                Ld->getPointerInfo().getWithOffset(4),
14122                                Ld->isVolatile(), Ld->isNonTemporal(),
14123                                Ld->isInvariant(),
14124                                MinAlign(Ld->getAlignment(), 4));
14125
14126     SDValue NewChain = LoLd.getValue(1);
14127     if (TokenFactorIndex != -1) {
14128       Ops.push_back(LoLd);
14129       Ops.push_back(HiLd);
14130       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14131                              Ops.size());
14132     }
14133
14134     LoAddr = St->getBasePtr();
14135     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
14136                          DAG.getConstant(4, MVT::i32));
14137
14138     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
14139                                 St->getPointerInfo(),
14140                                 St->isVolatile(), St->isNonTemporal(),
14141                                 St->getAlignment());
14142     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
14143                                 St->getPointerInfo().getWithOffset(4),
14144                                 St->isVolatile(),
14145                                 St->isNonTemporal(),
14146                                 MinAlign(St->getAlignment(), 4));
14147     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
14148   }
14149   return SDValue();
14150 }
14151
14152 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
14153 /// and return the operands for the horizontal operation in LHS and RHS.  A
14154 /// horizontal operation performs the binary operation on successive elements
14155 /// of its first operand, then on successive elements of its second operand,
14156 /// returning the resulting values in a vector.  For example, if
14157 ///   A = < float a0, float a1, float a2, float a3 >
14158 /// and
14159 ///   B = < float b0, float b1, float b2, float b3 >
14160 /// then the result of doing a horizontal operation on A and B is
14161 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
14162 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
14163 /// A horizontal-op B, for some already available A and B, and if so then LHS is
14164 /// set to A, RHS to B, and the routine returns 'true'.
14165 /// Note that the binary operation should have the property that if one of the
14166 /// operands is UNDEF then the result is UNDEF.
14167 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
14168   // Look for the following pattern: if
14169   //   A = < float a0, float a1, float a2, float a3 >
14170   //   B = < float b0, float b1, float b2, float b3 >
14171   // and
14172   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
14173   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
14174   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
14175   // which is A horizontal-op B.
14176
14177   // At least one of the operands should be a vector shuffle.
14178   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
14179       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
14180     return false;
14181
14182   EVT VT = LHS.getValueType();
14183
14184   assert((VT.is128BitVector() || VT.is256BitVector()) &&
14185          "Unsupported vector type for horizontal add/sub");
14186
14187   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
14188   // operate independently on 128-bit lanes.
14189   unsigned NumElts = VT.getVectorNumElements();
14190   unsigned NumLanes = VT.getSizeInBits()/128;
14191   unsigned NumLaneElts = NumElts / NumLanes;
14192   assert((NumLaneElts % 2 == 0) &&
14193          "Vector type should have an even number of elements in each lane");
14194   unsigned HalfLaneElts = NumLaneElts/2;
14195
14196   // View LHS in the form
14197   //   LHS = VECTOR_SHUFFLE A, B, LMask
14198   // If LHS is not a shuffle then pretend it is the shuffle
14199   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
14200   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
14201   // type VT.
14202   SDValue A, B;
14203   SmallVector<int, 16> LMask(NumElts);
14204   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
14205     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
14206       A = LHS.getOperand(0);
14207     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
14208       B = LHS.getOperand(1);
14209     cast<ShuffleVectorSDNode>(LHS.getNode())->getMask(LMask);
14210   } else {
14211     if (LHS.getOpcode() != ISD::UNDEF)
14212       A = LHS;
14213     for (unsigned i = 0; i != NumElts; ++i)
14214       LMask[i] = i;
14215   }
14216
14217   // Likewise, view RHS in the form
14218   //   RHS = VECTOR_SHUFFLE C, D, RMask
14219   SDValue C, D;
14220   SmallVector<int, 16> RMask(NumElts);
14221   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
14222     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
14223       C = RHS.getOperand(0);
14224     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
14225       D = RHS.getOperand(1);
14226     cast<ShuffleVectorSDNode>(RHS.getNode())->getMask(RMask);
14227   } else {
14228     if (RHS.getOpcode() != ISD::UNDEF)
14229       C = RHS;
14230     for (unsigned i = 0; i != NumElts; ++i)
14231       RMask[i] = i;
14232   }
14233
14234   // Check that the shuffles are both shuffling the same vectors.
14235   if (!(A == C && B == D) && !(A == D && B == C))
14236     return false;
14237
14238   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
14239   if (!A.getNode() && !B.getNode())
14240     return false;
14241
14242   // If A and B occur in reverse order in RHS, then "swap" them (which means
14243   // rewriting the mask).
14244   if (A != C)
14245     CommuteVectorShuffleMask(RMask, NumElts);
14246
14247   // At this point LHS and RHS are equivalent to
14248   //   LHS = VECTOR_SHUFFLE A, B, LMask
14249   //   RHS = VECTOR_SHUFFLE A, B, RMask
14250   // Check that the masks correspond to performing a horizontal operation.
14251   for (unsigned i = 0; i != NumElts; ++i) {
14252     int LIdx = LMask[i], RIdx = RMask[i];
14253
14254     // Ignore any UNDEF components.
14255     if (LIdx < 0 || RIdx < 0 ||
14256         (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
14257         (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
14258       continue;
14259
14260     // Check that successive elements are being operated on.  If not, this is
14261     // not a horizontal operation.
14262     unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
14263     unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
14264     int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
14265     if (!(LIdx == Index && RIdx == Index + 1) &&
14266         !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
14267       return false;
14268   }
14269
14270   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
14271   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
14272   return true;
14273 }
14274
14275 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
14276 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
14277                                   const X86Subtarget *Subtarget) {
14278   EVT VT = N->getValueType(0);
14279   SDValue LHS = N->getOperand(0);
14280   SDValue RHS = N->getOperand(1);
14281
14282   // Try to synthesize horizontal adds from adds of shuffles.
14283   if (((Subtarget->hasSSE3orAVX() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
14284        (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
14285       isHorizontalBinOp(LHS, RHS, true))
14286     return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
14287   return SDValue();
14288 }
14289
14290 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
14291 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
14292                                   const X86Subtarget *Subtarget) {
14293   EVT VT = N->getValueType(0);
14294   SDValue LHS = N->getOperand(0);
14295   SDValue RHS = N->getOperand(1);
14296
14297   // Try to synthesize horizontal subs from subs of shuffles.
14298   if (((Subtarget->hasSSE3orAVX() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
14299        (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
14300       isHorizontalBinOp(LHS, RHS, false))
14301     return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
14302   return SDValue();
14303 }
14304
14305 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
14306 /// X86ISD::FXOR nodes.
14307 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
14308   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
14309   // F[X]OR(0.0, x) -> x
14310   // F[X]OR(x, 0.0) -> x
14311   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
14312     if (C->getValueAPF().isPosZero())
14313       return N->getOperand(1);
14314   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
14315     if (C->getValueAPF().isPosZero())
14316       return N->getOperand(0);
14317   return SDValue();
14318 }
14319
14320 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
14321 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
14322   // FAND(0.0, x) -> 0.0
14323   // FAND(x, 0.0) -> 0.0
14324   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
14325     if (C->getValueAPF().isPosZero())
14326       return N->getOperand(0);
14327   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
14328     if (C->getValueAPF().isPosZero())
14329       return N->getOperand(1);
14330   return SDValue();
14331 }
14332
14333 static SDValue PerformBTCombine(SDNode *N,
14334                                 SelectionDAG &DAG,
14335                                 TargetLowering::DAGCombinerInfo &DCI) {
14336   // BT ignores high bits in the bit index operand.
14337   SDValue Op1 = N->getOperand(1);
14338   if (Op1.hasOneUse()) {
14339     unsigned BitWidth = Op1.getValueSizeInBits();
14340     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
14341     APInt KnownZero, KnownOne;
14342     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
14343                                           !DCI.isBeforeLegalizeOps());
14344     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14345     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
14346         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
14347       DCI.CommitTargetLoweringOpt(TLO);
14348   }
14349   return SDValue();
14350 }
14351
14352 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
14353   SDValue Op = N->getOperand(0);
14354   if (Op.getOpcode() == ISD::BITCAST)
14355     Op = Op.getOperand(0);
14356   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
14357   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
14358       VT.getVectorElementType().getSizeInBits() ==
14359       OpVT.getVectorElementType().getSizeInBits()) {
14360     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
14361   }
14362   return SDValue();
14363 }
14364
14365 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
14366   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
14367   //           (and (i32 x86isd::setcc_carry), 1)
14368   // This eliminates the zext. This transformation is necessary because
14369   // ISD::SETCC is always legalized to i8.
14370   DebugLoc dl = N->getDebugLoc();
14371   SDValue N0 = N->getOperand(0);
14372   EVT VT = N->getValueType(0);
14373   if (N0.getOpcode() == ISD::AND &&
14374       N0.hasOneUse() &&
14375       N0.getOperand(0).hasOneUse()) {
14376     SDValue N00 = N0.getOperand(0);
14377     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
14378       return SDValue();
14379     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
14380     if (!C || C->getZExtValue() != 1)
14381       return SDValue();
14382     return DAG.getNode(ISD::AND, dl, VT,
14383                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
14384                                    N00.getOperand(0), N00.getOperand(1)),
14385                        DAG.getConstant(1, VT));
14386   }
14387
14388   return SDValue();
14389 }
14390
14391 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
14392 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
14393   unsigned X86CC = N->getConstantOperandVal(0);
14394   SDValue EFLAG = N->getOperand(1);
14395   DebugLoc DL = N->getDebugLoc();
14396
14397   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
14398   // a zext and produces an all-ones bit which is more useful than 0/1 in some
14399   // cases.
14400   if (X86CC == X86::COND_B)
14401     return DAG.getNode(ISD::AND, DL, MVT::i8,
14402                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
14403                                    DAG.getConstant(X86CC, MVT::i8), EFLAG),
14404                        DAG.getConstant(1, MVT::i8));
14405
14406   return SDValue();
14407 }
14408
14409 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
14410                                         const X86TargetLowering *XTLI) {
14411   SDValue Op0 = N->getOperand(0);
14412   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
14413   // a 32-bit target where SSE doesn't support i64->FP operations.
14414   if (Op0.getOpcode() == ISD::LOAD) {
14415     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
14416     EVT VT = Ld->getValueType(0);
14417     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
14418         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
14419         !XTLI->getSubtarget()->is64Bit() &&
14420         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14421       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
14422                                           Ld->getChain(), Op0, DAG);
14423       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
14424       return FILDChain;
14425     }
14426   }
14427   return SDValue();
14428 }
14429
14430 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
14431 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
14432                                  X86TargetLowering::DAGCombinerInfo &DCI) {
14433   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
14434   // the result is either zero or one (depending on the input carry bit).
14435   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
14436   if (X86::isZeroNode(N->getOperand(0)) &&
14437       X86::isZeroNode(N->getOperand(1)) &&
14438       // We don't have a good way to replace an EFLAGS use, so only do this when
14439       // dead right now.
14440       SDValue(N, 1).use_empty()) {
14441     DebugLoc DL = N->getDebugLoc();
14442     EVT VT = N->getValueType(0);
14443     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
14444     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
14445                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
14446                                            DAG.getConstant(X86::COND_B,MVT::i8),
14447                                            N->getOperand(2)),
14448                                DAG.getConstant(1, VT));
14449     return DCI.CombineTo(N, Res1, CarryOut);
14450   }
14451
14452   return SDValue();
14453 }
14454
14455 // fold (add Y, (sete  X, 0)) -> adc  0, Y
14456 //      (add Y, (setne X, 0)) -> sbb -1, Y
14457 //      (sub (sete  X, 0), Y) -> sbb  0, Y
14458 //      (sub (setne X, 0), Y) -> adc -1, Y
14459 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
14460   DebugLoc DL = N->getDebugLoc();
14461
14462   // Look through ZExts.
14463   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
14464   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
14465     return SDValue();
14466
14467   SDValue SetCC = Ext.getOperand(0);
14468   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
14469     return SDValue();
14470
14471   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
14472   if (CC != X86::COND_E && CC != X86::COND_NE)
14473     return SDValue();
14474
14475   SDValue Cmp = SetCC.getOperand(1);
14476   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
14477       !X86::isZeroNode(Cmp.getOperand(1)) ||
14478       !Cmp.getOperand(0).getValueType().isInteger())
14479     return SDValue();
14480
14481   SDValue CmpOp0 = Cmp.getOperand(0);
14482   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
14483                                DAG.getConstant(1, CmpOp0.getValueType()));
14484
14485   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
14486   if (CC == X86::COND_NE)
14487     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
14488                        DL, OtherVal.getValueType(), OtherVal,
14489                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
14490   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
14491                      DL, OtherVal.getValueType(), OtherVal,
14492                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
14493 }
14494
14495 /// PerformADDCombine - Do target-specific dag combines on integer adds.
14496 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
14497                                  const X86Subtarget *Subtarget) {
14498   EVT VT = N->getValueType(0);
14499   SDValue Op0 = N->getOperand(0);
14500   SDValue Op1 = N->getOperand(1);
14501
14502   // Try to synthesize horizontal adds from adds of shuffles.
14503   if (((Subtarget->hasSSSE3orAVX() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
14504        (Subtarget->hasAVX2() && (VT == MVT::v16i16 || MVT::v8i32))) &&
14505       isHorizontalBinOp(Op0, Op1, true))
14506     return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
14507
14508   return OptimizeConditionalInDecrement(N, DAG);
14509 }
14510
14511 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
14512                                  const X86Subtarget *Subtarget) {
14513   SDValue Op0 = N->getOperand(0);
14514   SDValue Op1 = N->getOperand(1);
14515
14516   // X86 can't encode an immediate LHS of a sub. See if we can push the
14517   // negation into a preceding instruction.
14518   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
14519     // If the RHS of the sub is a XOR with one use and a constant, invert the
14520     // immediate. Then add one to the LHS of the sub so we can turn
14521     // X-Y -> X+~Y+1, saving one register.
14522     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
14523         isa<ConstantSDNode>(Op1.getOperand(1))) {
14524       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
14525       EVT VT = Op0.getValueType();
14526       SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
14527                                    Op1.getOperand(0),
14528                                    DAG.getConstant(~XorC, VT));
14529       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
14530                          DAG.getConstant(C->getAPIntValue()+1, VT));
14531     }
14532   }
14533
14534   // Try to synthesize horizontal adds from adds of shuffles.
14535   EVT VT = N->getValueType(0);
14536   if (((Subtarget->hasSSSE3orAVX() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
14537        (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
14538       isHorizontalBinOp(Op0, Op1, true))
14539     return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
14540
14541   return OptimizeConditionalInDecrement(N, DAG);
14542 }
14543
14544 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
14545                                              DAGCombinerInfo &DCI) const {
14546   SelectionDAG &DAG = DCI.DAG;
14547   switch (N->getOpcode()) {
14548   default: break;
14549   case ISD::EXTRACT_VECTOR_ELT:
14550     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
14551   case ISD::VSELECT:
14552   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
14553   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
14554   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
14555   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
14556   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
14557   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
14558   case ISD::SHL:
14559   case ISD::SRA:
14560   case ISD::SRL:            return PerformShiftCombine(N, DAG, Subtarget);
14561   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
14562   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
14563   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
14564   case ISD::LOAD:           return PerformLOADCombine(N, DAG, Subtarget);
14565   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
14566   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
14567   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
14568   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
14569   case X86ISD::FXOR:
14570   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
14571   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
14572   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
14573   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
14574   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG);
14575   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG);
14576   case X86ISD::SHUFPS:      // Handle all target specific shuffles
14577   case X86ISD::SHUFPD:
14578   case X86ISD::PALIGN:
14579   case X86ISD::UNPCKH:
14580   case X86ISD::UNPCKL:
14581   case X86ISD::MOVHLPS:
14582   case X86ISD::MOVLHPS:
14583   case X86ISD::PSHUFD:
14584   case X86ISD::PSHUFHW:
14585   case X86ISD::PSHUFLW:
14586   case X86ISD::MOVSS:
14587   case X86ISD::MOVSD:
14588   case X86ISD::VPERMILP:
14589   case X86ISD::VPERM2X128:
14590   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
14591   }
14592
14593   return SDValue();
14594 }
14595
14596 /// isTypeDesirableForOp - Return true if the target has native support for
14597 /// the specified value type and it is 'desirable' to use the type for the
14598 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
14599 /// instruction encodings are longer and some i16 instructions are slow.
14600 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
14601   if (!isTypeLegal(VT))
14602     return false;
14603   if (VT != MVT::i16)
14604     return true;
14605
14606   switch (Opc) {
14607   default:
14608     return true;
14609   case ISD::LOAD:
14610   case ISD::SIGN_EXTEND:
14611   case ISD::ZERO_EXTEND:
14612   case ISD::ANY_EXTEND:
14613   case ISD::SHL:
14614   case ISD::SRL:
14615   case ISD::SUB:
14616   case ISD::ADD:
14617   case ISD::MUL:
14618   case ISD::AND:
14619   case ISD::OR:
14620   case ISD::XOR:
14621     return false;
14622   }
14623 }
14624
14625 /// IsDesirableToPromoteOp - This method query the target whether it is
14626 /// beneficial for dag combiner to promote the specified node. If true, it
14627 /// should return the desired promotion type by reference.
14628 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
14629   EVT VT = Op.getValueType();
14630   if (VT != MVT::i16)
14631     return false;
14632
14633   bool Promote = false;
14634   bool Commute = false;
14635   switch (Op.getOpcode()) {
14636   default: break;
14637   case ISD::LOAD: {
14638     LoadSDNode *LD = cast<LoadSDNode>(Op);
14639     // If the non-extending load has a single use and it's not live out, then it
14640     // might be folded.
14641     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
14642                                                      Op.hasOneUse()*/) {
14643       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
14644              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
14645         // The only case where we'd want to promote LOAD (rather then it being
14646         // promoted as an operand is when it's only use is liveout.
14647         if (UI->getOpcode() != ISD::CopyToReg)
14648           return false;
14649       }
14650     }
14651     Promote = true;
14652     break;
14653   }
14654   case ISD::SIGN_EXTEND:
14655   case ISD::ZERO_EXTEND:
14656   case ISD::ANY_EXTEND:
14657     Promote = true;
14658     break;
14659   case ISD::SHL:
14660   case ISD::SRL: {
14661     SDValue N0 = Op.getOperand(0);
14662     // Look out for (store (shl (load), x)).
14663     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
14664       return false;
14665     Promote = true;
14666     break;
14667   }
14668   case ISD::ADD:
14669   case ISD::MUL:
14670   case ISD::AND:
14671   case ISD::OR:
14672   case ISD::XOR:
14673     Commute = true;
14674     // fallthrough
14675   case ISD::SUB: {
14676     SDValue N0 = Op.getOperand(0);
14677     SDValue N1 = Op.getOperand(1);
14678     if (!Commute && MayFoldLoad(N1))
14679       return false;
14680     // Avoid disabling potential load folding opportunities.
14681     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
14682       return false;
14683     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
14684       return false;
14685     Promote = true;
14686   }
14687   }
14688
14689   PVT = MVT::i32;
14690   return Promote;
14691 }
14692
14693 //===----------------------------------------------------------------------===//
14694 //                           X86 Inline Assembly Support
14695 //===----------------------------------------------------------------------===//
14696
14697 namespace {
14698   // Helper to match a string separated by whitespace.
14699   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
14700     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
14701
14702     for (unsigned i = 0, e = args.size(); i != e; ++i) {
14703       StringRef piece(*args[i]);
14704       if (!s.startswith(piece)) // Check if the piece matches.
14705         return false;
14706
14707       s = s.substr(piece.size());
14708       StringRef::size_type pos = s.find_first_not_of(" \t");
14709       if (pos == 0) // We matched a prefix.
14710         return false;
14711
14712       s = s.substr(pos);
14713     }
14714
14715     return s.empty();
14716   }
14717   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
14718 }
14719
14720 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
14721   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
14722
14723   std::string AsmStr = IA->getAsmString();
14724
14725   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14726   if (!Ty || Ty->getBitWidth() % 16 != 0)
14727     return false;
14728
14729   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
14730   SmallVector<StringRef, 4> AsmPieces;
14731   SplitString(AsmStr, AsmPieces, ";\n");
14732
14733   switch (AsmPieces.size()) {
14734   default: return false;
14735   case 1:
14736     // FIXME: this should verify that we are targeting a 486 or better.  If not,
14737     // we will turn this bswap into something that will be lowered to logical
14738     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
14739     // lower so don't worry about this.
14740     // bswap $0
14741     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
14742         matchAsm(AsmPieces[0], "bswapl", "$0") ||
14743         matchAsm(AsmPieces[0], "bswapq", "$0") ||
14744         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
14745         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
14746         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
14747       // No need to check constraints, nothing other than the equivalent of
14748       // "=r,0" would be valid here.
14749       return IntrinsicLowering::LowerToByteSwap(CI);
14750     }
14751
14752     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
14753     if (CI->getType()->isIntegerTy(16) &&
14754         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
14755         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
14756          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
14757       AsmPieces.clear();
14758       const std::string &ConstraintsStr = IA->getConstraintString();
14759       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
14760       std::sort(AsmPieces.begin(), AsmPieces.end());
14761       if (AsmPieces.size() == 4 &&
14762           AsmPieces[0] == "~{cc}" &&
14763           AsmPieces[1] == "~{dirflag}" &&
14764           AsmPieces[2] == "~{flags}" &&
14765           AsmPieces[3] == "~{fpsr}")
14766       return IntrinsicLowering::LowerToByteSwap(CI);
14767     }
14768     break;
14769   case 3:
14770     if (CI->getType()->isIntegerTy(32) &&
14771         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
14772         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
14773         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
14774         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
14775       AsmPieces.clear();
14776       const std::string &ConstraintsStr = IA->getConstraintString();
14777       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
14778       std::sort(AsmPieces.begin(), AsmPieces.end());
14779       if (AsmPieces.size() == 4 &&
14780           AsmPieces[0] == "~{cc}" &&
14781           AsmPieces[1] == "~{dirflag}" &&
14782           AsmPieces[2] == "~{flags}" &&
14783           AsmPieces[3] == "~{fpsr}")
14784         return IntrinsicLowering::LowerToByteSwap(CI);
14785     }
14786
14787     if (CI->getType()->isIntegerTy(64)) {
14788       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
14789       if (Constraints.size() >= 2 &&
14790           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
14791           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
14792         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
14793         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
14794             matchAsm(AsmPieces[1], "bswap", "%edx") &&
14795             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
14796           return IntrinsicLowering::LowerToByteSwap(CI);
14797       }
14798     }
14799     break;
14800   }
14801   return false;
14802 }
14803
14804
14805
14806 /// getConstraintType - Given a constraint letter, return the type of
14807 /// constraint it is for this target.
14808 X86TargetLowering::ConstraintType
14809 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
14810   if (Constraint.size() == 1) {
14811     switch (Constraint[0]) {
14812     case 'R':
14813     case 'q':
14814     case 'Q':
14815     case 'f':
14816     case 't':
14817     case 'u':
14818     case 'y':
14819     case 'x':
14820     case 'Y':
14821     case 'l':
14822       return C_RegisterClass;
14823     case 'a':
14824     case 'b':
14825     case 'c':
14826     case 'd':
14827     case 'S':
14828     case 'D':
14829     case 'A':
14830       return C_Register;
14831     case 'I':
14832     case 'J':
14833     case 'K':
14834     case 'L':
14835     case 'M':
14836     case 'N':
14837     case 'G':
14838     case 'C':
14839     case 'e':
14840     case 'Z':
14841       return C_Other;
14842     default:
14843       break;
14844     }
14845   }
14846   return TargetLowering::getConstraintType(Constraint);
14847 }
14848
14849 /// Examine constraint type and operand type and determine a weight value.
14850 /// This object must already have been set up with the operand type
14851 /// and the current alternative constraint selected.
14852 TargetLowering::ConstraintWeight
14853   X86TargetLowering::getSingleConstraintMatchWeight(
14854     AsmOperandInfo &info, const char *constraint) const {
14855   ConstraintWeight weight = CW_Invalid;
14856   Value *CallOperandVal = info.CallOperandVal;
14857     // If we don't have a value, we can't do a match,
14858     // but allow it at the lowest weight.
14859   if (CallOperandVal == NULL)
14860     return CW_Default;
14861   Type *type = CallOperandVal->getType();
14862   // Look at the constraint type.
14863   switch (*constraint) {
14864   default:
14865     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
14866   case 'R':
14867   case 'q':
14868   case 'Q':
14869   case 'a':
14870   case 'b':
14871   case 'c':
14872   case 'd':
14873   case 'S':
14874   case 'D':
14875   case 'A':
14876     if (CallOperandVal->getType()->isIntegerTy())
14877       weight = CW_SpecificReg;
14878     break;
14879   case 'f':
14880   case 't':
14881   case 'u':
14882       if (type->isFloatingPointTy())
14883         weight = CW_SpecificReg;
14884       break;
14885   case 'y':
14886       if (type->isX86_MMXTy() && Subtarget->hasMMX())
14887         weight = CW_SpecificReg;
14888       break;
14889   case 'x':
14890   case 'Y':
14891     if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
14892       weight = CW_Register;
14893     break;
14894   case 'I':
14895     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
14896       if (C->getZExtValue() <= 31)
14897         weight = CW_Constant;
14898     }
14899     break;
14900   case 'J':
14901     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14902       if (C->getZExtValue() <= 63)
14903         weight = CW_Constant;
14904     }
14905     break;
14906   case 'K':
14907     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14908       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
14909         weight = CW_Constant;
14910     }
14911     break;
14912   case 'L':
14913     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14914       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
14915         weight = CW_Constant;
14916     }
14917     break;
14918   case 'M':
14919     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14920       if (C->getZExtValue() <= 3)
14921         weight = CW_Constant;
14922     }
14923     break;
14924   case 'N':
14925     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14926       if (C->getZExtValue() <= 0xff)
14927         weight = CW_Constant;
14928     }
14929     break;
14930   case 'G':
14931   case 'C':
14932     if (dyn_cast<ConstantFP>(CallOperandVal)) {
14933       weight = CW_Constant;
14934     }
14935     break;
14936   case 'e':
14937     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14938       if ((C->getSExtValue() >= -0x80000000LL) &&
14939           (C->getSExtValue() <= 0x7fffffffLL))
14940         weight = CW_Constant;
14941     }
14942     break;
14943   case 'Z':
14944     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14945       if (C->getZExtValue() <= 0xffffffff)
14946         weight = CW_Constant;
14947     }
14948     break;
14949   }
14950   return weight;
14951 }
14952
14953 /// LowerXConstraint - try to replace an X constraint, which matches anything,
14954 /// with another that has more specific requirements based on the type of the
14955 /// corresponding operand.
14956 const char *X86TargetLowering::
14957 LowerXConstraint(EVT ConstraintVT) const {
14958   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
14959   // 'f' like normal targets.
14960   if (ConstraintVT.isFloatingPoint()) {
14961     if (Subtarget->hasXMMInt())
14962       return "Y";
14963     if (Subtarget->hasXMM())
14964       return "x";
14965   }
14966
14967   return TargetLowering::LowerXConstraint(ConstraintVT);
14968 }
14969
14970 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
14971 /// vector.  If it is invalid, don't add anything to Ops.
14972 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
14973                                                      std::string &Constraint,
14974                                                      std::vector<SDValue>&Ops,
14975                                                      SelectionDAG &DAG) const {
14976   SDValue Result(0, 0);
14977
14978   // Only support length 1 constraints for now.
14979   if (Constraint.length() > 1) return;
14980
14981   char ConstraintLetter = Constraint[0];
14982   switch (ConstraintLetter) {
14983   default: break;
14984   case 'I':
14985     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14986       if (C->getZExtValue() <= 31) {
14987         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
14988         break;
14989       }
14990     }
14991     return;
14992   case 'J':
14993     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14994       if (C->getZExtValue() <= 63) {
14995         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
14996         break;
14997       }
14998     }
14999     return;
15000   case 'K':
15001     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15002       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
15003         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15004         break;
15005       }
15006     }
15007     return;
15008   case 'N':
15009     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15010       if (C->getZExtValue() <= 255) {
15011         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15012         break;
15013       }
15014     }
15015     return;
15016   case 'e': {
15017     // 32-bit signed value
15018     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15019       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
15020                                            C->getSExtValue())) {
15021         // Widen to 64 bits here to get it sign extended.
15022         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
15023         break;
15024       }
15025     // FIXME gcc accepts some relocatable values here too, but only in certain
15026     // memory models; it's complicated.
15027     }
15028     return;
15029   }
15030   case 'Z': {
15031     // 32-bit unsigned value
15032     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15033       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
15034                                            C->getZExtValue())) {
15035         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15036         break;
15037       }
15038     }
15039     // FIXME gcc accepts some relocatable values here too, but only in certain
15040     // memory models; it's complicated.
15041     return;
15042   }
15043   case 'i': {
15044     // Literal immediates are always ok.
15045     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
15046       // Widen to 64 bits here to get it sign extended.
15047       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
15048       break;
15049     }
15050
15051     // In any sort of PIC mode addresses need to be computed at runtime by
15052     // adding in a register or some sort of table lookup.  These can't
15053     // be used as immediates.
15054     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
15055       return;
15056
15057     // If we are in non-pic codegen mode, we allow the address of a global (with
15058     // an optional displacement) to be used with 'i'.
15059     GlobalAddressSDNode *GA = 0;
15060     int64_t Offset = 0;
15061
15062     // Match either (GA), (GA+C), (GA+C1+C2), etc.
15063     while (1) {
15064       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
15065         Offset += GA->getOffset();
15066         break;
15067       } else if (Op.getOpcode() == ISD::ADD) {
15068         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
15069           Offset += C->getZExtValue();
15070           Op = Op.getOperand(0);
15071           continue;
15072         }
15073       } else if (Op.getOpcode() == ISD::SUB) {
15074         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
15075           Offset += -C->getZExtValue();
15076           Op = Op.getOperand(0);
15077           continue;
15078         }
15079       }
15080
15081       // Otherwise, this isn't something we can handle, reject it.
15082       return;
15083     }
15084
15085     const GlobalValue *GV = GA->getGlobal();
15086     // If we require an extra load to get this address, as in PIC mode, we
15087     // can't accept it.
15088     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
15089                                                         getTargetMachine())))
15090       return;
15091
15092     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
15093                                         GA->getValueType(0), Offset);
15094     break;
15095   }
15096   }
15097
15098   if (Result.getNode()) {
15099     Ops.push_back(Result);
15100     return;
15101   }
15102   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
15103 }
15104
15105 std::pair<unsigned, const TargetRegisterClass*>
15106 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
15107                                                 EVT VT) const {
15108   // First, see if this is a constraint that directly corresponds to an LLVM
15109   // register class.
15110   if (Constraint.size() == 1) {
15111     // GCC Constraint Letters
15112     switch (Constraint[0]) {
15113     default: break;
15114       // TODO: Slight differences here in allocation order and leaving
15115       // RIP in the class. Do they matter any more here than they do
15116       // in the normal allocation?
15117     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
15118       if (Subtarget->is64Bit()) {
15119         if (VT == MVT::i32 || VT == MVT::f32)
15120           return std::make_pair(0U, X86::GR32RegisterClass);
15121         else if (VT == MVT::i16)
15122           return std::make_pair(0U, X86::GR16RegisterClass);
15123         else if (VT == MVT::i8 || VT == MVT::i1)
15124           return std::make_pair(0U, X86::GR8RegisterClass);
15125         else if (VT == MVT::i64 || VT == MVT::f64)
15126           return std::make_pair(0U, X86::GR64RegisterClass);
15127         break;
15128       }
15129       // 32-bit fallthrough
15130     case 'Q':   // Q_REGS
15131       if (VT == MVT::i32 || VT == MVT::f32)
15132         return std::make_pair(0U, X86::GR32_ABCDRegisterClass);
15133       else if (VT == MVT::i16)
15134         return std::make_pair(0U, X86::GR16_ABCDRegisterClass);
15135       else if (VT == MVT::i8 || VT == MVT::i1)
15136         return std::make_pair(0U, X86::GR8_ABCD_LRegisterClass);
15137       else if (VT == MVT::i64)
15138         return std::make_pair(0U, X86::GR64_ABCDRegisterClass);
15139       break;
15140     case 'r':   // GENERAL_REGS
15141     case 'l':   // INDEX_REGS
15142       if (VT == MVT::i8 || VT == MVT::i1)
15143         return std::make_pair(0U, X86::GR8RegisterClass);
15144       if (VT == MVT::i16)
15145         return std::make_pair(0U, X86::GR16RegisterClass);
15146       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
15147         return std::make_pair(0U, X86::GR32RegisterClass);
15148       return std::make_pair(0U, X86::GR64RegisterClass);
15149     case 'R':   // LEGACY_REGS
15150       if (VT == MVT::i8 || VT == MVT::i1)
15151         return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
15152       if (VT == MVT::i16)
15153         return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
15154       if (VT == MVT::i32 || !Subtarget->is64Bit())
15155         return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
15156       return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
15157     case 'f':  // FP Stack registers.
15158       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
15159       // value to the correct fpstack register class.
15160       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
15161         return std::make_pair(0U, X86::RFP32RegisterClass);
15162       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
15163         return std::make_pair(0U, X86::RFP64RegisterClass);
15164       return std::make_pair(0U, X86::RFP80RegisterClass);
15165     case 'y':   // MMX_REGS if MMX allowed.
15166       if (!Subtarget->hasMMX()) break;
15167       return std::make_pair(0U, X86::VR64RegisterClass);
15168     case 'Y':   // SSE_REGS if SSE2 allowed
15169       if (!Subtarget->hasXMMInt()) break;
15170       // FALL THROUGH.
15171     case 'x':   // SSE_REGS if SSE1 allowed
15172       if (!Subtarget->hasXMM()) break;
15173
15174       switch (VT.getSimpleVT().SimpleTy) {
15175       default: break;
15176       // Scalar SSE types.
15177       case MVT::f32:
15178       case MVT::i32:
15179         return std::make_pair(0U, X86::FR32RegisterClass);
15180       case MVT::f64:
15181       case MVT::i64:
15182         return std::make_pair(0U, X86::FR64RegisterClass);
15183       // Vector types.
15184       case MVT::v16i8:
15185       case MVT::v8i16:
15186       case MVT::v4i32:
15187       case MVT::v2i64:
15188       case MVT::v4f32:
15189       case MVT::v2f64:
15190         return std::make_pair(0U, X86::VR128RegisterClass);
15191       }
15192       break;
15193     }
15194   }
15195
15196   // Use the default implementation in TargetLowering to convert the register
15197   // constraint into a member of a register class.
15198   std::pair<unsigned, const TargetRegisterClass*> Res;
15199   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
15200
15201   // Not found as a standard register?
15202   if (Res.second == 0) {
15203     // Map st(0) -> st(7) -> ST0
15204     if (Constraint.size() == 7 && Constraint[0] == '{' &&
15205         tolower(Constraint[1]) == 's' &&
15206         tolower(Constraint[2]) == 't' &&
15207         Constraint[3] == '(' &&
15208         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
15209         Constraint[5] == ')' &&
15210         Constraint[6] == '}') {
15211
15212       Res.first = X86::ST0+Constraint[4]-'0';
15213       Res.second = X86::RFP80RegisterClass;
15214       return Res;
15215     }
15216
15217     // GCC allows "st(0)" to be called just plain "st".
15218     if (StringRef("{st}").equals_lower(Constraint)) {
15219       Res.first = X86::ST0;
15220       Res.second = X86::RFP80RegisterClass;
15221       return Res;
15222     }
15223
15224     // flags -> EFLAGS
15225     if (StringRef("{flags}").equals_lower(Constraint)) {
15226       Res.first = X86::EFLAGS;
15227       Res.second = X86::CCRRegisterClass;
15228       return Res;
15229     }
15230
15231     // 'A' means EAX + EDX.
15232     if (Constraint == "A") {
15233       Res.first = X86::EAX;
15234       Res.second = X86::GR32_ADRegisterClass;
15235       return Res;
15236     }
15237     return Res;
15238   }
15239
15240   // Otherwise, check to see if this is a register class of the wrong value
15241   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
15242   // turn into {ax},{dx}.
15243   if (Res.second->hasType(VT))
15244     return Res;   // Correct type already, nothing to do.
15245
15246   // All of the single-register GCC register classes map their values onto
15247   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
15248   // really want an 8-bit or 32-bit register, map to the appropriate register
15249   // class and return the appropriate register.
15250   if (Res.second == X86::GR16RegisterClass) {
15251     if (VT == MVT::i8) {
15252       unsigned DestReg = 0;
15253       switch (Res.first) {
15254       default: break;
15255       case X86::AX: DestReg = X86::AL; break;
15256       case X86::DX: DestReg = X86::DL; break;
15257       case X86::CX: DestReg = X86::CL; break;
15258       case X86::BX: DestReg = X86::BL; break;
15259       }
15260       if (DestReg) {
15261         Res.first = DestReg;
15262         Res.second = X86::GR8RegisterClass;
15263       }
15264     } else if (VT == MVT::i32) {
15265       unsigned DestReg = 0;
15266       switch (Res.first) {
15267       default: break;
15268       case X86::AX: DestReg = X86::EAX; break;
15269       case X86::DX: DestReg = X86::EDX; break;
15270       case X86::CX: DestReg = X86::ECX; break;
15271       case X86::BX: DestReg = X86::EBX; break;
15272       case X86::SI: DestReg = X86::ESI; break;
15273       case X86::DI: DestReg = X86::EDI; break;
15274       case X86::BP: DestReg = X86::EBP; break;
15275       case X86::SP: DestReg = X86::ESP; break;
15276       }
15277       if (DestReg) {
15278         Res.first = DestReg;
15279         Res.second = X86::GR32RegisterClass;
15280       }
15281     } else if (VT == MVT::i64) {
15282       unsigned DestReg = 0;
15283       switch (Res.first) {
15284       default: break;
15285       case X86::AX: DestReg = X86::RAX; break;
15286       case X86::DX: DestReg = X86::RDX; break;
15287       case X86::CX: DestReg = X86::RCX; break;
15288       case X86::BX: DestReg = X86::RBX; break;
15289       case X86::SI: DestReg = X86::RSI; break;
15290       case X86::DI: DestReg = X86::RDI; break;
15291       case X86::BP: DestReg = X86::RBP; break;
15292       case X86::SP: DestReg = X86::RSP; break;
15293       }
15294       if (DestReg) {
15295         Res.first = DestReg;
15296         Res.second = X86::GR64RegisterClass;
15297       }
15298     }
15299   } else if (Res.second == X86::FR32RegisterClass ||
15300              Res.second == X86::FR64RegisterClass ||
15301              Res.second == X86::VR128RegisterClass) {
15302     // Handle references to XMM physical registers that got mapped into the
15303     // wrong class.  This can happen with constraints like {xmm0} where the
15304     // target independent register mapper will just pick the first match it can
15305     // find, ignoring the required type.
15306     if (VT == MVT::f32)
15307       Res.second = X86::FR32RegisterClass;
15308     else if (VT == MVT::f64)
15309       Res.second = X86::FR64RegisterClass;
15310     else if (X86::VR128RegisterClass->hasType(VT))
15311       Res.second = X86::VR128RegisterClass;
15312   }
15313
15314   return Res;
15315 }