Avoid replacing the value of a directly stored load with the stored value if the...
[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/CodeGen/PseudoSourceValue.h"
39 #include "llvm/MC/MCAsmInfo.h"
40 #include "llvm/MC/MCContext.h"
41 #include "llvm/MC/MCExpr.h"
42 #include "llvm/MC/MCSymbol.h"
43 #include "llvm/ADT/BitVector.h"
44 #include "llvm/ADT/SmallSet.h"
45 #include "llvm/ADT/Statistic.h"
46 #include "llvm/ADT/StringExtras.h"
47 #include "llvm/ADT/VectorExtras.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/Dwarf.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/MathExtras.h"
52 #include "llvm/Support/raw_ostream.h"
53 using namespace llvm;
54 using namespace dwarf;
55
56 STATISTIC(NumTailCalls, "Number of tail calls");
57
58 // Forward declarations.
59 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
60                        SDValue V2);
61
62 static SDValue Insert128BitVector(SDValue Result,
63                                   SDValue Vec,
64                                   SDValue Idx,
65                                   SelectionDAG &DAG,
66                                   DebugLoc dl);
67
68 static SDValue Extract128BitVector(SDValue Vec,
69                                    SDValue Idx,
70                                    SelectionDAG &DAG,
71                                    DebugLoc dl);
72
73 static SDValue ConcatVectors(SDValue Lower, SDValue Upper, SelectionDAG &DAG);
74
75
76 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
77 /// sets things up to match to an AVX VEXTRACTF128 instruction or a
78 /// simple subregister reference.  Idx is an index in the 128 bits we
79 /// want.  It need not be aligned to a 128-bit bounday.  That makes
80 /// lowering EXTRACT_VECTOR_ELT operations easier.
81 static SDValue Extract128BitVector(SDValue Vec,
82                                    SDValue Idx,
83                                    SelectionDAG &DAG,
84                                    DebugLoc dl) {
85   EVT VT = Vec.getValueType();
86   assert(VT.getSizeInBits() == 256 && "Unexpected vector size!");
87
88   EVT ElVT = VT.getVectorElementType();
89
90   int Factor = VT.getSizeInBits() / 128;
91
92   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(),
93                                   ElVT,
94                                   VT.getVectorNumElements() / Factor);
95
96   // Extract from UNDEF is UNDEF.
97   if (Vec.getOpcode() == ISD::UNDEF)
98     return DAG.getNode(ISD::UNDEF, dl, ResultVT);
99
100   if (isa<ConstantSDNode>(Idx)) {
101     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
102
103     // Extract the relevant 128 bits.  Generate an EXTRACT_SUBVECTOR
104     // we can match to VEXTRACTF128.
105     unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
106
107     // This is the index of the first element of the 128-bit chunk
108     // we want.
109     unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
110                                  * ElemsPerChunk);
111
112     SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
113
114     SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
115                                  VecIdx);
116
117     return Result;
118   }
119
120   return SDValue();
121 }
122
123 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
124 /// sets things up to match to an AVX VINSERTF128 instruction or a
125 /// simple superregister reference.  Idx is an index in the 128 bits
126 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
127 /// lowering INSERT_VECTOR_ELT operations easier.
128 static SDValue Insert128BitVector(SDValue Result,
129                                   SDValue Vec,
130                                   SDValue Idx,
131                                   SelectionDAG &DAG,
132                                   DebugLoc dl) {
133   if (isa<ConstantSDNode>(Idx)) {
134     EVT VT = Vec.getValueType();
135     assert(VT.getSizeInBits() == 128 && "Unexpected vector size!");
136
137     EVT ElVT = VT.getVectorElementType();
138
139     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
140
141     EVT ResultVT = Result.getValueType();
142
143     // Insert the relevant 128 bits.
144     unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
145
146     // This is the index of the first element of the 128-bit chunk
147     // we want.
148     unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
149                                  * ElemsPerChunk);
150
151     SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
152
153     Result = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
154                          VecIdx);
155     return Result;
156   }
157
158   return SDValue();
159 }
160
161 /// Given two vectors, concat them.
162 static SDValue ConcatVectors(SDValue Lower, SDValue Upper, SelectionDAG &DAG) {
163   DebugLoc dl = Lower.getDebugLoc();
164
165   assert(Lower.getValueType() == Upper.getValueType() && "Mismatched vectors!");
166
167   EVT VT = EVT::getVectorVT(*DAG.getContext(),
168                             Lower.getValueType().getVectorElementType(),
169                             Lower.getValueType().getVectorNumElements() * 2);
170
171   // TODO: Generalize to arbitrary vector length (this assumes 256-bit vectors).
172   assert(VT.getSizeInBits() == 256 && "Unsupported vector concat!");
173
174   // Insert the upper subvector.
175   SDValue Vec = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), Upper,
176                                    DAG.getConstant(
177                                      // This is half the length of the result
178                                      // vector.  Start inserting the upper 128
179                                      // bits here.
180                                      Lower.getValueType().getVectorNumElements(),
181                                      MVT::i32),
182                                    DAG, dl);
183
184   // Insert the lower subvector.
185   Vec = Insert128BitVector(Vec, Lower, DAG.getConstant(0, MVT::i32), DAG, dl);
186   return Vec;
187 }
188
189 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
190   const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
191   bool is64Bit = Subtarget->is64Bit();
192
193   if (Subtarget->isTargetEnvMacho()) {
194     if (is64Bit)
195       return new X8664_MachoTargetObjectFile();
196     return new TargetLoweringObjectFileMachO();
197   }
198
199   if (Subtarget->isTargetELF()) {
200     if (is64Bit)
201       return new X8664_ELFTargetObjectFile(TM);
202     return new X8632_ELFTargetObjectFile(TM);
203   }
204   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
205     return new TargetLoweringObjectFileCOFF();
206   llvm_unreachable("unknown subtarget type");
207 }
208
209 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
210   : TargetLowering(TM, createTLOF(TM)) {
211   Subtarget = &TM.getSubtarget<X86Subtarget>();
212   X86ScalarSSEf64 = Subtarget->hasXMMInt();
213   X86ScalarSSEf32 = Subtarget->hasXMM();
214   X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
215
216   RegInfo = TM.getRegisterInfo();
217   TD = getTargetData();
218
219   // Set up the TargetLowering object.
220   static MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
221
222   // X86 is weird, it always uses i8 for shift amounts and setcc results.
223   setBooleanContents(ZeroOrOneBooleanContent);
224   setSchedulingPreference(Sched::ILP);
225   setStackPointerRegisterToSaveRestore(X86StackPtr);
226
227   if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
228     // Setup Windows compiler runtime calls.
229     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
230     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
231     setLibcallName(RTLIB::FPTOUINT_F64_I64, "_ftol2");
232     setLibcallName(RTLIB::FPTOUINT_F32_I64, "_ftol2");
233     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
234     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
235     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::C);
236     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::C);
237   }
238
239   if (Subtarget->isTargetDarwin()) {
240     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
241     setUseUnderscoreSetJmp(false);
242     setUseUnderscoreLongJmp(false);
243   } else if (Subtarget->isTargetMingw()) {
244     // MS runtime is weird: it exports _setjmp, but longjmp!
245     setUseUnderscoreSetJmp(true);
246     setUseUnderscoreLongJmp(false);
247   } else {
248     setUseUnderscoreSetJmp(true);
249     setUseUnderscoreLongJmp(true);
250   }
251
252   // Set up the register classes.
253   addRegisterClass(MVT::i8, X86::GR8RegisterClass);
254   addRegisterClass(MVT::i16, X86::GR16RegisterClass);
255   addRegisterClass(MVT::i32, X86::GR32RegisterClass);
256   if (Subtarget->is64Bit())
257     addRegisterClass(MVT::i64, X86::GR64RegisterClass);
258
259   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
260
261   // We don't accept any truncstore of integer registers.
262   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
263   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
264   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
265   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
266   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
267   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
268
269   // SETOEQ and SETUNE require checking two conditions.
270   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
271   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
272   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
273   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
274   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
275   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
276
277   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
278   // operation.
279   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
280   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
281   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
282
283   if (Subtarget->is64Bit()) {
284     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
285     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Expand);
286   } else if (!UseSoftFloat) {
287     // We have an algorithm for SSE2->double, and we turn this into a
288     // 64-bit FILD followed by conditional FADD for other targets.
289     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
290     // We have an algorithm for SSE2, and we turn this into a 64-bit
291     // FILD for other targets.
292     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
293   }
294
295   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
296   // this operation.
297   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
298   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
299
300   if (!UseSoftFloat) {
301     // SSE has no i16 to fp conversion, only i32
302     if (X86ScalarSSEf32) {
303       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
304       // f32 and f64 cases are Legal, f80 case is not
305       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
306     } else {
307       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
308       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
309     }
310   } else {
311     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
312     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
313   }
314
315   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
316   // are Legal, f80 is custom lowered.
317   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
318   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
319
320   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
321   // this operation.
322   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
323   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
324
325   if (X86ScalarSSEf32) {
326     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
327     // f32 and f64 cases are Legal, f80 case is not
328     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
329   } else {
330     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
331     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
332   }
333
334   // Handle FP_TO_UINT by promoting the destination to a larger signed
335   // conversion.
336   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
337   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
338   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
339
340   if (Subtarget->is64Bit()) {
341     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
342     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
343   } else if (!UseSoftFloat) {
344     if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
345       // Expand FP_TO_UINT into a select.
346       // FIXME: We would like to use a Custom expander here eventually to do
347       // the optimal thing for SSE vs. the default expansion in the legalizer.
348       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
349     else
350       // With SSE3 we can use fisttpll to convert to a signed i64; without
351       // SSE, we're stuck with a fistpll.
352       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
353   }
354
355   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
356   if (!X86ScalarSSEf64) {
357     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
358     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
359     if (Subtarget->is64Bit()) {
360       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
361       // Without SSE, i64->f64 goes through memory.
362       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
363     }
364   }
365
366   // Scalar integer divide and remainder are lowered to use operations that
367   // produce two results, to match the available instructions. This exposes
368   // the two-result form to trivial CSE, which is able to combine x/y and x%y
369   // into a single instruction.
370   //
371   // Scalar integer multiply-high is also lowered to use two-result
372   // operations, to match the available instructions. However, plain multiply
373   // (low) operations are left as Legal, as there are single-result
374   // instructions for this in x86. Using the two-result multiply instructions
375   // when both high and low results are needed must be arranged by dagcombine.
376   for (unsigned i = 0, e = 4; i != e; ++i) {
377     MVT VT = IntVTs[i];
378     setOperationAction(ISD::MULHS, VT, Expand);
379     setOperationAction(ISD::MULHU, VT, Expand);
380     setOperationAction(ISD::SDIV, VT, Expand);
381     setOperationAction(ISD::UDIV, VT, Expand);
382     setOperationAction(ISD::SREM, VT, Expand);
383     setOperationAction(ISD::UREM, VT, Expand);
384
385     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
386     setOperationAction(ISD::ADDC, VT, Custom);
387     setOperationAction(ISD::ADDE, VT, Custom);
388     setOperationAction(ISD::SUBC, VT, Custom);
389     setOperationAction(ISD::SUBE, VT, Custom);
390   }
391
392   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
393   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
394   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
395   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
396   if (Subtarget->is64Bit())
397     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
398   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
399   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
400   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
401   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
402   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
403   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
404   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
405   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
406
407   setOperationAction(ISD::CTTZ             , MVT::i8   , Custom);
408   setOperationAction(ISD::CTLZ             , MVT::i8   , Custom);
409   setOperationAction(ISD::CTTZ             , MVT::i16  , Custom);
410   setOperationAction(ISD::CTLZ             , MVT::i16  , Custom);
411   setOperationAction(ISD::CTTZ             , MVT::i32  , Custom);
412   setOperationAction(ISD::CTLZ             , MVT::i32  , Custom);
413   if (Subtarget->is64Bit()) {
414     setOperationAction(ISD::CTTZ           , MVT::i64  , Custom);
415     setOperationAction(ISD::CTLZ           , MVT::i64  , Custom);
416   }
417
418   if (Subtarget->hasPOPCNT()) {
419     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
420   } else {
421     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
422     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
423     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
424     if (Subtarget->is64Bit())
425       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
426   }
427
428   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
429   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
430
431   // These should be promoted to a larger select which is supported.
432   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
433   // X86 wants to expand cmov itself.
434   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
435   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
436   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
437   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
438   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
439   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
440   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
441   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
442   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
443   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
444   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
445   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
446   if (Subtarget->is64Bit()) {
447     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
448     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
449   }
450   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
451
452   // Darwin ABI issue.
453   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
454   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
455   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
456   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
457   if (Subtarget->is64Bit())
458     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
459   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
460   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
461   if (Subtarget->is64Bit()) {
462     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
463     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
464     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
465     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
466     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
467   }
468   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
469   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
470   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
471   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
472   if (Subtarget->is64Bit()) {
473     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
474     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
475     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
476   }
477
478   if (Subtarget->hasXMM())
479     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
480
481   // We may not have a libcall for MEMBARRIER so we should lower this.
482   setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
483
484   // On X86 and X86-64, atomic operations are lowered to locked instructions.
485   // Locked instructions, in turn, have implicit fence semantics (all memory
486   // operations are flushed before issuing the locked instruction, and they
487   // are not buffered), so we can fold away the common pattern of
488   // fence-atomic-fence.
489   setShouldFoldAtomicFences(true);
490
491   // Expand certain atomics
492   for (unsigned i = 0, e = 4; i != e; ++i) {
493     MVT VT = IntVTs[i];
494     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
495     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
496   }
497
498   if (!Subtarget->is64Bit()) {
499     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
500     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
501     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
502     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
503     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
504     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
505     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
506   }
507
508   // FIXME - use subtarget debug flags
509   if (!Subtarget->isTargetDarwin() &&
510       !Subtarget->isTargetELF() &&
511       !Subtarget->isTargetCygMing()) {
512     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
513   }
514
515   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
516   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
517   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
518   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
519   if (Subtarget->is64Bit()) {
520     setExceptionPointerRegister(X86::RAX);
521     setExceptionSelectorRegister(X86::RDX);
522   } else {
523     setExceptionPointerRegister(X86::EAX);
524     setExceptionSelectorRegister(X86::EDX);
525   }
526   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
527   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
528
529   setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
530
531   setOperationAction(ISD::TRAP, MVT::Other, Legal);
532
533   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
534   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
535   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
536   if (Subtarget->is64Bit()) {
537     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
538     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
539   } else {
540     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
541     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
542   }
543
544   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
545   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
546   if (Subtarget->is64Bit())
547     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
548   if (Subtarget->isTargetCygMing() || Subtarget->isTargetWindows())
549     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
550   else
551     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
552
553   if (!UseSoftFloat && X86ScalarSSEf64) {
554     // f32 and f64 use SSE.
555     // Set up the FP register classes.
556     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
557     addRegisterClass(MVT::f64, X86::FR64RegisterClass);
558
559     // Use ANDPD to simulate FABS.
560     setOperationAction(ISD::FABS , MVT::f64, Custom);
561     setOperationAction(ISD::FABS , MVT::f32, Custom);
562
563     // Use XORP to simulate FNEG.
564     setOperationAction(ISD::FNEG , MVT::f64, Custom);
565     setOperationAction(ISD::FNEG , MVT::f32, Custom);
566
567     // Use ANDPD and ORPD to simulate FCOPYSIGN.
568     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
569     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
570
571     // We don't support sin/cos/fmod
572     setOperationAction(ISD::FSIN , MVT::f64, Expand);
573     setOperationAction(ISD::FCOS , MVT::f64, Expand);
574     setOperationAction(ISD::FSIN , MVT::f32, Expand);
575     setOperationAction(ISD::FCOS , MVT::f32, Expand);
576
577     // Expand FP immediates into loads from the stack, except for the special
578     // cases we handle.
579     addLegalFPImmediate(APFloat(+0.0)); // xorpd
580     addLegalFPImmediate(APFloat(+0.0f)); // xorps
581   } else if (!UseSoftFloat && X86ScalarSSEf32) {
582     // Use SSE for f32, x87 for f64.
583     // Set up the FP register classes.
584     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
585     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
586
587     // Use ANDPS to simulate FABS.
588     setOperationAction(ISD::FABS , MVT::f32, Custom);
589
590     // Use XORP to simulate FNEG.
591     setOperationAction(ISD::FNEG , MVT::f32, Custom);
592
593     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
594
595     // Use ANDPS and ORPS to simulate FCOPYSIGN.
596     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
597     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
598
599     // We don't support sin/cos/fmod
600     setOperationAction(ISD::FSIN , MVT::f32, Expand);
601     setOperationAction(ISD::FCOS , MVT::f32, Expand);
602
603     // Special cases we handle for FP constants.
604     addLegalFPImmediate(APFloat(+0.0f)); // xorps
605     addLegalFPImmediate(APFloat(+0.0)); // FLD0
606     addLegalFPImmediate(APFloat(+1.0)); // FLD1
607     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
608     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
609
610     if (!UnsafeFPMath) {
611       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
612       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
613     }
614   } else if (!UseSoftFloat) {
615     // f32 and f64 in x87.
616     // Set up the FP register classes.
617     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
618     addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
619
620     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
621     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
622     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
623     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
624
625     if (!UnsafeFPMath) {
626       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
627       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
628     }
629     addLegalFPImmediate(APFloat(+0.0)); // FLD0
630     addLegalFPImmediate(APFloat(+1.0)); // FLD1
631     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
632     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
633     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
634     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
635     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
636     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
637   }
638
639   // Long double always uses X87.
640   if (!UseSoftFloat) {
641     addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
642     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
643     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
644     {
645       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
646       addLegalFPImmediate(TmpFlt);  // FLD0
647       TmpFlt.changeSign();
648       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
649
650       bool ignored;
651       APFloat TmpFlt2(+1.0);
652       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
653                       &ignored);
654       addLegalFPImmediate(TmpFlt2);  // FLD1
655       TmpFlt2.changeSign();
656       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
657     }
658
659     if (!UnsafeFPMath) {
660       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
661       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
662     }
663   }
664
665   // Always use a library call for pow.
666   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
667   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
668   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
669
670   setOperationAction(ISD::FLOG, MVT::f80, Expand);
671   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
672   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
673   setOperationAction(ISD::FEXP, MVT::f80, Expand);
674   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
675
676   // First set operation action for all vector types to either promote
677   // (for widening) or expand (for scalarization). Then we will selectively
678   // turn on ones that can be effectively codegen'd.
679   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
680        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
681     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
682     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
683     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
684     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
685     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
686     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
687     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
688     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
689     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
690     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
691     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
692     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
693     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
694     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
695     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
696     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
697     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
698     setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
699     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
700     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
701     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
702     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
703     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
704     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
705     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
706     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
707     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
708     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
709     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
710     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
711     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
712     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
713     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
714     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
715     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
716     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
717     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
718     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
719     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
720     setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
721     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
722     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
723     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
724     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
725     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
726     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
727     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
728     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
729     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
730     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
731     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
732     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
733     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
734     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
735     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
736          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
737       setTruncStoreAction((MVT::SimpleValueType)VT,
738                           (MVT::SimpleValueType)InnerVT, Expand);
739     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
740     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
741     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
742   }
743
744   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
745   // with -msoft-float, disable use of MMX as well.
746   if (!UseSoftFloat && Subtarget->hasMMX()) {
747     addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass);
748     // No operations on x86mmx supported, everything uses intrinsics.
749   }
750
751   // MMX-sized vectors (other than x86mmx) are expected to be expanded
752   // into smaller operations.
753   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
754   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
755   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
756   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
757   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
758   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
759   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
760   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
761   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
762   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
763   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
764   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
765   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
766   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
767   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
768   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
769   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
770   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
771   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
772   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
773   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
774   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
775   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
776   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
777   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
778   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
779   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
780   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
781   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
782
783   if (!UseSoftFloat && Subtarget->hasXMM()) {
784     addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
785
786     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
787     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
788     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
789     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
790     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
791     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
792     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
793     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
794     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
795     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
796     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
797     setOperationAction(ISD::VSETCC,             MVT::v4f32, Custom);
798   }
799
800   if (!UseSoftFloat && Subtarget->hasXMMInt()) {
801     addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
802
803     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
804     // registers cannot be used even for integer operations.
805     addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
806     addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
807     addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
808     addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
809
810     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
811     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
812     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
813     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
814     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
815     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
816     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
817     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
818     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
819     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
820     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
821     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
822     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
823     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
824     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
825     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
826
827     setOperationAction(ISD::VSETCC,             MVT::v2f64, Custom);
828     setOperationAction(ISD::VSETCC,             MVT::v16i8, Custom);
829     setOperationAction(ISD::VSETCC,             MVT::v8i16, Custom);
830     setOperationAction(ISD::VSETCC,             MVT::v4i32, Custom);
831
832     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
833     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
834     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
835     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
836     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
837
838     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2f64, Custom);
839     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2i64, Custom);
840     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i8, Custom);
841     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i16, Custom);
842     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i32, Custom);
843
844     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
845     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
846       EVT VT = (MVT::SimpleValueType)i;
847       // Do not attempt to custom lower non-power-of-2 vectors
848       if (!isPowerOf2_32(VT.getVectorNumElements()))
849         continue;
850       // Do not attempt to custom lower non-128-bit vectors
851       if (!VT.is128BitVector())
852         continue;
853       setOperationAction(ISD::BUILD_VECTOR,
854                          VT.getSimpleVT().SimpleTy, Custom);
855       setOperationAction(ISD::VECTOR_SHUFFLE,
856                          VT.getSimpleVT().SimpleTy, Custom);
857       setOperationAction(ISD::EXTRACT_VECTOR_ELT,
858                          VT.getSimpleVT().SimpleTy, Custom);
859     }
860
861     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
862     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
863     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
864     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
865     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
866     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
867
868     if (Subtarget->is64Bit()) {
869       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
870       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
871     }
872
873     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
874     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
875       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
876       EVT VT = SVT;
877
878       // Do not attempt to promote non-128-bit vectors
879       if (!VT.is128BitVector())
880         continue;
881
882       setOperationAction(ISD::AND,    SVT, Promote);
883       AddPromotedToType (ISD::AND,    SVT, MVT::v2i64);
884       setOperationAction(ISD::OR,     SVT, Promote);
885       AddPromotedToType (ISD::OR,     SVT, MVT::v2i64);
886       setOperationAction(ISD::XOR,    SVT, Promote);
887       AddPromotedToType (ISD::XOR,    SVT, MVT::v2i64);
888       setOperationAction(ISD::LOAD,   SVT, Promote);
889       AddPromotedToType (ISD::LOAD,   SVT, MVT::v2i64);
890       setOperationAction(ISD::SELECT, SVT, Promote);
891       AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
892     }
893
894     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
895
896     // Custom lower v2i64 and v2f64 selects.
897     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
898     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
899     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
900     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
901
902     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
903     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
904   }
905
906   if (Subtarget->hasSSE41()) {
907     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
908     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
909     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
910     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
911     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
912     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
913     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
914     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
915     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
916     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
917
918     // FIXME: Do we need to handle scalar-to-vector here?
919     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
920
921     // Can turn SHL into an integer multiply.
922     setOperationAction(ISD::SHL,                MVT::v4i32, Custom);
923     setOperationAction(ISD::SHL,                MVT::v16i8, Custom);
924
925     // i8 and i16 vectors are custom , because the source register and source
926     // source memory operand types are not the same width.  f32 vectors are
927     // custom since the immediate controlling the insert encodes additional
928     // information.
929     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
930     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
931     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
932     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
933
934     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
935     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
936     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
937     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
938
939     if (Subtarget->is64Bit()) {
940       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Legal);
941       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
942     }
943   }
944
945   if (Subtarget->hasSSE42())
946     setOperationAction(ISD::VSETCC,             MVT::v2i64, Custom);
947
948   if (!UseSoftFloat && Subtarget->hasAVX()) {
949     addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
950     addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
951     addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
952     addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
953     addRegisterClass(MVT::v32i8, X86::VR256RegisterClass);
954
955     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
956     setOperationAction(ISD::LOAD,               MVT::v8i32, Legal);
957     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
958     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
959
960     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
961     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
962     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
963     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
964     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
965     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
966
967     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
968     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
969     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
970     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
971     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
972     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
973
974     // Custom lower build_vector, vector_shuffle, scalar_to_vector,
975     // insert_vector_elt extract_subvector and extract_vector_elt for
976     // 256-bit types.
977     for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
978          i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE;
979          ++i) {
980       MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
981       // Do not attempt to custom lower non-256-bit vectors
982       if (!isPowerOf2_32(MVT(VT).getVectorNumElements())
983           || (MVT(VT).getSizeInBits() < 256))
984         continue;
985       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
986       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
987       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
988       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
989       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
990     }
991     // Custom-lower insert_subvector and extract_subvector based on
992     // the result type.
993     for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
994          i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE;
995          ++i) {
996       MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
997       // Do not attempt to custom lower non-256-bit vectors
998       if (!isPowerOf2_32(MVT(VT).getVectorNumElements()))
999         continue;
1000
1001       if (MVT(VT).getSizeInBits() == 128) {
1002         setOperationAction(ISD::EXTRACT_SUBVECTOR,  VT, Custom);
1003       }
1004       else if (MVT(VT).getSizeInBits() == 256) {
1005         setOperationAction(ISD::INSERT_SUBVECTOR,  VT, Custom);
1006       }
1007     }
1008
1009     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1010     // Don't promote loads because we need them for VPERM vector index versions.
1011
1012     for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1013          VT != (unsigned)MVT::LAST_VECTOR_VALUETYPE;
1014          VT++) {
1015       if (!isPowerOf2_32(MVT((MVT::SimpleValueType)VT).getVectorNumElements())
1016           || (MVT((MVT::SimpleValueType)VT).getSizeInBits() < 256))
1017         continue;
1018       setOperationAction(ISD::AND,    (MVT::SimpleValueType)VT, Promote);
1019       AddPromotedToType (ISD::AND,    (MVT::SimpleValueType)VT, MVT::v4i64);
1020       setOperationAction(ISD::OR,     (MVT::SimpleValueType)VT, Promote);
1021       AddPromotedToType (ISD::OR,     (MVT::SimpleValueType)VT, MVT::v4i64);
1022       setOperationAction(ISD::XOR,    (MVT::SimpleValueType)VT, Promote);
1023       AddPromotedToType (ISD::XOR,    (MVT::SimpleValueType)VT, MVT::v4i64);
1024       //setOperationAction(ISD::LOAD,   (MVT::SimpleValueType)VT, Promote);
1025       //AddPromotedToType (ISD::LOAD,   (MVT::SimpleValueType)VT, MVT::v4i64);
1026       setOperationAction(ISD::SELECT, (MVT::SimpleValueType)VT, Promote);
1027       AddPromotedToType (ISD::SELECT, (MVT::SimpleValueType)VT, MVT::v4i64);
1028     }
1029   }
1030
1031   // We want to custom lower some of our intrinsics.
1032   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1033
1034
1035   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1036   // handle type legalization for these operations here.
1037   //
1038   // FIXME: We really should do custom legalization for addition and
1039   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1040   // than generic legalization for 64-bit multiplication-with-overflow, though.
1041   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1042     // Add/Sub/Mul with overflow operations are custom lowered.
1043     MVT VT = IntVTs[i];
1044     setOperationAction(ISD::SADDO, VT, Custom);
1045     setOperationAction(ISD::UADDO, VT, Custom);
1046     setOperationAction(ISD::SSUBO, VT, Custom);
1047     setOperationAction(ISD::USUBO, VT, Custom);
1048     setOperationAction(ISD::SMULO, VT, Custom);
1049     setOperationAction(ISD::UMULO, VT, Custom);
1050   }
1051
1052   // There are no 8-bit 3-address imul/mul instructions
1053   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1054   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1055
1056   if (!Subtarget->is64Bit()) {
1057     // These libcalls are not available in 32-bit.
1058     setLibcallName(RTLIB::SHL_I128, 0);
1059     setLibcallName(RTLIB::SRL_I128, 0);
1060     setLibcallName(RTLIB::SRA_I128, 0);
1061   }
1062
1063   // We have target-specific dag combine patterns for the following nodes:
1064   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1065   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1066   setTargetDAGCombine(ISD::BUILD_VECTOR);
1067   setTargetDAGCombine(ISD::SELECT);
1068   setTargetDAGCombine(ISD::SHL);
1069   setTargetDAGCombine(ISD::SRA);
1070   setTargetDAGCombine(ISD::SRL);
1071   setTargetDAGCombine(ISD::OR);
1072   setTargetDAGCombine(ISD::AND);
1073   setTargetDAGCombine(ISD::ADD);
1074   setTargetDAGCombine(ISD::SUB);
1075   setTargetDAGCombine(ISD::STORE);
1076   setTargetDAGCombine(ISD::ZERO_EXTEND);
1077   if (Subtarget->is64Bit())
1078     setTargetDAGCombine(ISD::MUL);
1079
1080   computeRegisterProperties();
1081
1082   // On Darwin, -Os means optimize for size without hurting performance,
1083   // do not reduce the limit.
1084   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1085   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1086   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1087   maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1088   maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1089   maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1090   setPrefLoopAlignment(16);
1091   benefitFromCodePlacementOpt = true;
1092 }
1093
1094
1095 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
1096   return MVT::i8;
1097 }
1098
1099
1100 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1101 /// the desired ByVal argument alignment.
1102 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
1103   if (MaxAlign == 16)
1104     return;
1105   if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1106     if (VTy->getBitWidth() == 128)
1107       MaxAlign = 16;
1108   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1109     unsigned EltAlign = 0;
1110     getMaxByValAlign(ATy->getElementType(), EltAlign);
1111     if (EltAlign > MaxAlign)
1112       MaxAlign = EltAlign;
1113   } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1114     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1115       unsigned EltAlign = 0;
1116       getMaxByValAlign(STy->getElementType(i), EltAlign);
1117       if (EltAlign > MaxAlign)
1118         MaxAlign = EltAlign;
1119       if (MaxAlign == 16)
1120         break;
1121     }
1122   }
1123   return;
1124 }
1125
1126 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1127 /// function arguments in the caller parameter area. For X86, aggregates
1128 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1129 /// are at 4-byte boundaries.
1130 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1131   if (Subtarget->is64Bit()) {
1132     // Max of 8 and alignment of type.
1133     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1134     if (TyAlign > 8)
1135       return TyAlign;
1136     return 8;
1137   }
1138
1139   unsigned Align = 4;
1140   if (Subtarget->hasXMM())
1141     getMaxByValAlign(Ty, Align);
1142   return Align;
1143 }
1144
1145 /// getOptimalMemOpType - Returns the target specific optimal type for load
1146 /// and store operations as a result of memset, memcpy, and memmove
1147 /// lowering. If DstAlign is zero that means it's safe to destination
1148 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1149 /// means there isn't a need to check it against alignment requirement,
1150 /// probably because the source does not need to be loaded. If
1151 /// 'NonScalarIntSafe' is true, that means it's safe to return a
1152 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1153 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1154 /// constant so it does not need to be loaded.
1155 /// It returns EVT::Other if the type should be determined using generic
1156 /// target-independent logic.
1157 EVT
1158 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1159                                        unsigned DstAlign, unsigned SrcAlign,
1160                                        bool NonScalarIntSafe,
1161                                        bool MemcpyStrSrc,
1162                                        MachineFunction &MF) const {
1163   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1164   // linux.  This is because the stack realignment code can't handle certain
1165   // cases like PR2962.  This should be removed when PR2962 is fixed.
1166   const Function *F = MF.getFunction();
1167   if (NonScalarIntSafe &&
1168       !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1169     if (Size >= 16 &&
1170         (Subtarget->isUnalignedMemAccessFast() ||
1171          ((DstAlign == 0 || DstAlign >= 16) &&
1172           (SrcAlign == 0 || SrcAlign >= 16))) &&
1173         Subtarget->getStackAlignment() >= 16) {
1174       if (Subtarget->hasSSE2())
1175         return MVT::v4i32;
1176       if (Subtarget->hasSSE1())
1177         return MVT::v4f32;
1178     } else if (!MemcpyStrSrc && Size >= 8 &&
1179                !Subtarget->is64Bit() &&
1180                Subtarget->getStackAlignment() >= 8 &&
1181                Subtarget->hasXMMInt()) {
1182       // Do not use f64 to lower memcpy if source is string constant. It's
1183       // better to use i32 to avoid the loads.
1184       return MVT::f64;
1185     }
1186   }
1187   if (Subtarget->is64Bit() && Size >= 8)
1188     return MVT::i64;
1189   return MVT::i32;
1190 }
1191
1192 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1193 /// current function.  The returned value is a member of the
1194 /// MachineJumpTableInfo::JTEntryKind enum.
1195 unsigned X86TargetLowering::getJumpTableEncoding() const {
1196   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1197   // symbol.
1198   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1199       Subtarget->isPICStyleGOT())
1200     return MachineJumpTableInfo::EK_Custom32;
1201
1202   // Otherwise, use the normal jump table encoding heuristics.
1203   return TargetLowering::getJumpTableEncoding();
1204 }
1205
1206 const MCExpr *
1207 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1208                                              const MachineBasicBlock *MBB,
1209                                              unsigned uid,MCContext &Ctx) const{
1210   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1211          Subtarget->isPICStyleGOT());
1212   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1213   // entries.
1214   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1215                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1216 }
1217
1218 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1219 /// jumptable.
1220 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1221                                                     SelectionDAG &DAG) const {
1222   if (!Subtarget->is64Bit())
1223     // This doesn't have DebugLoc associated with it, but is not really the
1224     // same as a Register.
1225     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1226   return Table;
1227 }
1228
1229 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1230 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1231 /// MCExpr.
1232 const MCExpr *X86TargetLowering::
1233 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1234                              MCContext &Ctx) const {
1235   // X86-64 uses RIP relative addressing based on the jump table label.
1236   if (Subtarget->isPICStyleRIPRel())
1237     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1238
1239   // Otherwise, the reference is relative to the PIC base.
1240   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1241 }
1242
1243 /// getFunctionAlignment - Return the Log2 alignment of this function.
1244 unsigned X86TargetLowering::getFunctionAlignment(const Function *F) const {
1245   return F->hasFnAttr(Attribute::OptimizeForSize) ? 0 : 4;
1246 }
1247
1248 // FIXME: Why this routine is here? Move to RegInfo!
1249 std::pair<const TargetRegisterClass*, uint8_t>
1250 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1251   const TargetRegisterClass *RRC = 0;
1252   uint8_t Cost = 1;
1253   switch (VT.getSimpleVT().SimpleTy) {
1254   default:
1255     return TargetLowering::findRepresentativeClass(VT);
1256   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1257     RRC = (Subtarget->is64Bit()
1258            ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1259     break;
1260   case MVT::x86mmx:
1261     RRC = X86::VR64RegisterClass;
1262     break;
1263   case MVT::f32: case MVT::f64:
1264   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1265   case MVT::v4f32: case MVT::v2f64:
1266   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1267   case MVT::v4f64:
1268     RRC = X86::VR128RegisterClass;
1269     break;
1270   }
1271   return std::make_pair(RRC, Cost);
1272 }
1273
1274 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1275                                                unsigned &Offset) const {
1276   if (!Subtarget->isTargetLinux())
1277     return false;
1278
1279   if (Subtarget->is64Bit()) {
1280     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1281     Offset = 0x28;
1282     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1283       AddressSpace = 256;
1284     else
1285       AddressSpace = 257;
1286   } else {
1287     // %gs:0x14 on i386
1288     Offset = 0x14;
1289     AddressSpace = 256;
1290   }
1291   return true;
1292 }
1293
1294
1295 //===----------------------------------------------------------------------===//
1296 //               Return Value Calling Convention Implementation
1297 //===----------------------------------------------------------------------===//
1298
1299 #include "X86GenCallingConv.inc"
1300
1301 bool
1302 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv, bool isVarArg,
1303                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1304                         LLVMContext &Context) const {
1305   SmallVector<CCValAssign, 16> RVLocs;
1306   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1307                  RVLocs, Context);
1308   return CCInfo.CheckReturn(Outs, RetCC_X86);
1309 }
1310
1311 SDValue
1312 X86TargetLowering::LowerReturn(SDValue Chain,
1313                                CallingConv::ID CallConv, bool isVarArg,
1314                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1315                                const SmallVectorImpl<SDValue> &OutVals,
1316                                DebugLoc dl, SelectionDAG &DAG) const {
1317   MachineFunction &MF = DAG.getMachineFunction();
1318   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1319
1320   SmallVector<CCValAssign, 16> RVLocs;
1321   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1322                  RVLocs, *DAG.getContext());
1323   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1324
1325   // Add the regs to the liveout set for the function.
1326   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1327   for (unsigned i = 0; i != RVLocs.size(); ++i)
1328     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1329       MRI.addLiveOut(RVLocs[i].getLocReg());
1330
1331   SDValue Flag;
1332
1333   SmallVector<SDValue, 6> RetOps;
1334   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1335   // Operand #1 = Bytes To Pop
1336   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1337                    MVT::i16));
1338
1339   // Copy the result values into the output registers.
1340   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1341     CCValAssign &VA = RVLocs[i];
1342     assert(VA.isRegLoc() && "Can only return in registers!");
1343     SDValue ValToCopy = OutVals[i];
1344     EVT ValVT = ValToCopy.getValueType();
1345
1346     // If this is x86-64, and we disabled SSE, we can't return FP values,
1347     // or SSE or MMX vectors.
1348     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1349          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1350           (Subtarget->is64Bit() && !Subtarget->hasXMM())) {
1351       report_fatal_error("SSE register return with SSE disabled");
1352     }
1353     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1354     // llvm-gcc has never done it right and no one has noticed, so this
1355     // should be OK for now.
1356     if (ValVT == MVT::f64 &&
1357         (Subtarget->is64Bit() && !Subtarget->hasXMMInt()))
1358       report_fatal_error("SSE2 register return with SSE2 disabled");
1359
1360     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1361     // the RET instruction and handled by the FP Stackifier.
1362     if (VA.getLocReg() == X86::ST0 ||
1363         VA.getLocReg() == X86::ST1) {
1364       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1365       // change the value to the FP stack register class.
1366       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1367         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1368       RetOps.push_back(ValToCopy);
1369       // Don't emit a copytoreg.
1370       continue;
1371     }
1372
1373     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1374     // which is returned in RAX / RDX.
1375     if (Subtarget->is64Bit()) {
1376       if (ValVT == MVT::x86mmx) {
1377         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1378           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1379           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1380                                   ValToCopy);
1381           // If we don't have SSE2 available, convert to v4f32 so the generated
1382           // register is legal.
1383           if (!Subtarget->hasSSE2())
1384             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1385         }
1386       }
1387     }
1388
1389     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1390     Flag = Chain.getValue(1);
1391   }
1392
1393   // The x86-64 ABI for returning structs by value requires that we copy
1394   // the sret argument into %rax for the return. We saved the argument into
1395   // a virtual register in the entry block, so now we copy the value out
1396   // and into %rax.
1397   if (Subtarget->is64Bit() &&
1398       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1399     MachineFunction &MF = DAG.getMachineFunction();
1400     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1401     unsigned Reg = FuncInfo->getSRetReturnReg();
1402     assert(Reg &&
1403            "SRetReturnReg should have been set in LowerFormalArguments().");
1404     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1405
1406     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1407     Flag = Chain.getValue(1);
1408
1409     // RAX now acts like a return value.
1410     MRI.addLiveOut(X86::RAX);
1411   }
1412
1413   RetOps[0] = Chain;  // Update chain.
1414
1415   // Add the flag if we have it.
1416   if (Flag.getNode())
1417     RetOps.push_back(Flag);
1418
1419   return DAG.getNode(X86ISD::RET_FLAG, dl,
1420                      MVT::Other, &RetOps[0], RetOps.size());
1421 }
1422
1423 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1424   if (N->getNumValues() != 1)
1425     return false;
1426   if (!N->hasNUsesOfValue(1, 0))
1427     return false;
1428
1429   SDNode *Copy = *N->use_begin();
1430   if (Copy->getOpcode() != ISD::CopyToReg &&
1431       Copy->getOpcode() != ISD::FP_EXTEND)
1432     return false;
1433
1434   bool HasRet = false;
1435   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1436        UI != UE; ++UI) {
1437     if (UI->getOpcode() != X86ISD::RET_FLAG)
1438       return false;
1439     HasRet = true;
1440   }
1441
1442   return HasRet;
1443 }
1444
1445 /// LowerCallResult - Lower the result values of a call into the
1446 /// appropriate copies out of appropriate physical registers.
1447 ///
1448 SDValue
1449 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1450                                    CallingConv::ID CallConv, bool isVarArg,
1451                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1452                                    DebugLoc dl, SelectionDAG &DAG,
1453                                    SmallVectorImpl<SDValue> &InVals) const {
1454
1455   // Assign locations to each value returned by this call.
1456   SmallVector<CCValAssign, 16> RVLocs;
1457   bool Is64Bit = Subtarget->is64Bit();
1458   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1459                  RVLocs, *DAG.getContext());
1460   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1461
1462   // Copy all of the result registers out of their specified physreg.
1463   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1464     CCValAssign &VA = RVLocs[i];
1465     EVT CopyVT = VA.getValVT();
1466
1467     // If this is x86-64, and we disabled SSE, we can't return FP values
1468     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1469         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) {
1470       report_fatal_error("SSE register return with SSE disabled");
1471     }
1472
1473     SDValue Val;
1474
1475     // If this is a call to a function that returns an fp value on the floating
1476     // point stack, we must guarantee the the value is popped from the stack, so
1477     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1478     // if the return value is not used. We use the FpGET_ST0 instructions
1479     // instead.
1480     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1481       // If we prefer to use the value in xmm registers, copy it out as f80 and
1482       // use a truncate to move it from fp stack reg to xmm reg.
1483       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1484       bool isST0 = VA.getLocReg() == X86::ST0;
1485       unsigned Opc = 0;
1486       if (CopyVT == MVT::f32) Opc = isST0 ? X86::FpGET_ST0_32:X86::FpGET_ST1_32;
1487       if (CopyVT == MVT::f64) Opc = isST0 ? X86::FpGET_ST0_64:X86::FpGET_ST1_64;
1488       if (CopyVT == MVT::f80) Opc = isST0 ? X86::FpGET_ST0_80:X86::FpGET_ST1_80;
1489       SDValue Ops[] = { Chain, InFlag };
1490       Chain = SDValue(DAG.getMachineNode(Opc, dl, CopyVT, MVT::Other, MVT::Glue,
1491                                          Ops, 2), 1);
1492       Val = Chain.getValue(0);
1493
1494       // Round the f80 to the right size, which also moves it to the appropriate
1495       // xmm register.
1496       if (CopyVT != VA.getValVT())
1497         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1498                           // This truncation won't change the value.
1499                           DAG.getIntPtrConstant(1));
1500     } else if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1501       // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1502       if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1503         Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1504                                    MVT::v2i64, InFlag).getValue(1);
1505         Val = Chain.getValue(0);
1506         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1507                           Val, DAG.getConstant(0, MVT::i64));
1508       } else {
1509         Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1510                                    MVT::i64, InFlag).getValue(1);
1511         Val = Chain.getValue(0);
1512       }
1513       Val = DAG.getNode(ISD::BITCAST, dl, CopyVT, Val);
1514     } else {
1515       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1516                                  CopyVT, InFlag).getValue(1);
1517       Val = Chain.getValue(0);
1518     }
1519     InFlag = Chain.getValue(2);
1520     InVals.push_back(Val);
1521   }
1522
1523   return Chain;
1524 }
1525
1526
1527 //===----------------------------------------------------------------------===//
1528 //                C & StdCall & Fast Calling Convention implementation
1529 //===----------------------------------------------------------------------===//
1530 //  StdCall calling convention seems to be standard for many Windows' API
1531 //  routines and around. It differs from C calling convention just a little:
1532 //  callee should clean up the stack, not caller. Symbols should be also
1533 //  decorated in some fancy way :) It doesn't support any vector arguments.
1534 //  For info on fast calling convention see Fast Calling Convention (tail call)
1535 //  implementation LowerX86_32FastCCCallTo.
1536
1537 /// CallIsStructReturn - Determines whether a call uses struct return
1538 /// semantics.
1539 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1540   if (Outs.empty())
1541     return false;
1542
1543   return Outs[0].Flags.isSRet();
1544 }
1545
1546 /// ArgsAreStructReturn - Determines whether a function uses struct
1547 /// return semantics.
1548 static bool
1549 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1550   if (Ins.empty())
1551     return false;
1552
1553   return Ins[0].Flags.isSRet();
1554 }
1555
1556 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1557 /// by "Src" to address "Dst" with size and alignment information specified by
1558 /// the specific parameter attribute. The copy will be passed as a byval
1559 /// function parameter.
1560 static SDValue
1561 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1562                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1563                           DebugLoc dl) {
1564   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1565
1566   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1567                        /*isVolatile*/false, /*AlwaysInline=*/true,
1568                        MachinePointerInfo(), MachinePointerInfo());
1569 }
1570
1571 /// IsTailCallConvention - Return true if the calling convention is one that
1572 /// supports tail call optimization.
1573 static bool IsTailCallConvention(CallingConv::ID CC) {
1574   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1575 }
1576
1577 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1578 /// a tailcall target by changing its ABI.
1579 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1580   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1581 }
1582
1583 SDValue
1584 X86TargetLowering::LowerMemArgument(SDValue Chain,
1585                                     CallingConv::ID CallConv,
1586                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1587                                     DebugLoc dl, SelectionDAG &DAG,
1588                                     const CCValAssign &VA,
1589                                     MachineFrameInfo *MFI,
1590                                     unsigned i) const {
1591   // Create the nodes corresponding to a load from this parameter slot.
1592   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1593   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1594   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1595   EVT ValVT;
1596
1597   // If value is passed by pointer we have address passed instead of the value
1598   // itself.
1599   if (VA.getLocInfo() == CCValAssign::Indirect)
1600     ValVT = VA.getLocVT();
1601   else
1602     ValVT = VA.getValVT();
1603
1604   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1605   // changed with more analysis.
1606   // In case of tail call optimization mark all arguments mutable. Since they
1607   // could be overwritten by lowering of arguments in case of a tail call.
1608   if (Flags.isByVal()) {
1609     int FI = MFI->CreateFixedObject(Flags.getByValSize(),
1610                                     VA.getLocMemOffset(), isImmutable);
1611     return DAG.getFrameIndex(FI, getPointerTy());
1612   } else {
1613     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1614                                     VA.getLocMemOffset(), isImmutable);
1615     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1616     return DAG.getLoad(ValVT, dl, Chain, FIN,
1617                        MachinePointerInfo::getFixedStack(FI),
1618                        false, false, 0);
1619   }
1620 }
1621
1622 SDValue
1623 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1624                                         CallingConv::ID CallConv,
1625                                         bool isVarArg,
1626                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1627                                         DebugLoc dl,
1628                                         SelectionDAG &DAG,
1629                                         SmallVectorImpl<SDValue> &InVals)
1630                                           const {
1631   MachineFunction &MF = DAG.getMachineFunction();
1632   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1633
1634   const Function* Fn = MF.getFunction();
1635   if (Fn->hasExternalLinkage() &&
1636       Subtarget->isTargetCygMing() &&
1637       Fn->getName() == "main")
1638     FuncInfo->setForceFramePointer(true);
1639
1640   MachineFrameInfo *MFI = MF.getFrameInfo();
1641   bool Is64Bit = Subtarget->is64Bit();
1642   bool IsWin64 = Subtarget->isTargetWin64();
1643
1644   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1645          "Var args not supported with calling convention fastcc or ghc");
1646
1647   // Assign locations to all of the incoming arguments.
1648   SmallVector<CCValAssign, 16> ArgLocs;
1649   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1650                  ArgLocs, *DAG.getContext());
1651
1652   // Allocate shadow area for Win64
1653   if (IsWin64) {
1654     CCInfo.AllocateStack(32, 8);
1655   }
1656
1657   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1658
1659   unsigned LastVal = ~0U;
1660   SDValue ArgValue;
1661   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1662     CCValAssign &VA = ArgLocs[i];
1663     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1664     // places.
1665     assert(VA.getValNo() != LastVal &&
1666            "Don't support value assigned to multiple locs yet");
1667     LastVal = VA.getValNo();
1668
1669     if (VA.isRegLoc()) {
1670       EVT RegVT = VA.getLocVT();
1671       TargetRegisterClass *RC = NULL;
1672       if (RegVT == MVT::i32)
1673         RC = X86::GR32RegisterClass;
1674       else if (Is64Bit && RegVT == MVT::i64)
1675         RC = X86::GR64RegisterClass;
1676       else if (RegVT == MVT::f32)
1677         RC = X86::FR32RegisterClass;
1678       else if (RegVT == MVT::f64)
1679         RC = X86::FR64RegisterClass;
1680       else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1681         RC = X86::VR256RegisterClass;
1682       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1683         RC = X86::VR128RegisterClass;
1684       else if (RegVT == MVT::x86mmx)
1685         RC = X86::VR64RegisterClass;
1686       else
1687         llvm_unreachable("Unknown argument type!");
1688
1689       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1690       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1691
1692       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1693       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1694       // right size.
1695       if (VA.getLocInfo() == CCValAssign::SExt)
1696         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1697                                DAG.getValueType(VA.getValVT()));
1698       else if (VA.getLocInfo() == CCValAssign::ZExt)
1699         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1700                                DAG.getValueType(VA.getValVT()));
1701       else if (VA.getLocInfo() == CCValAssign::BCvt)
1702         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1703
1704       if (VA.isExtInLoc()) {
1705         // Handle MMX values passed in XMM regs.
1706         if (RegVT.isVector()) {
1707           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1708                                  ArgValue);
1709         } else
1710           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1711       }
1712     } else {
1713       assert(VA.isMemLoc());
1714       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1715     }
1716
1717     // If value is passed via pointer - do a load.
1718     if (VA.getLocInfo() == CCValAssign::Indirect)
1719       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1720                              MachinePointerInfo(), false, false, 0);
1721
1722     InVals.push_back(ArgValue);
1723   }
1724
1725   // The x86-64 ABI for returning structs by value requires that we copy
1726   // the sret argument into %rax for the return. Save the argument into
1727   // a virtual register so that we can access it from the return points.
1728   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1729     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1730     unsigned Reg = FuncInfo->getSRetReturnReg();
1731     if (!Reg) {
1732       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1733       FuncInfo->setSRetReturnReg(Reg);
1734     }
1735     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1736     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1737   }
1738
1739   unsigned StackSize = CCInfo.getNextStackOffset();
1740   // Align stack specially for tail calls.
1741   if (FuncIsMadeTailCallSafe(CallConv))
1742     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1743
1744   // If the function takes variable number of arguments, make a frame index for
1745   // the start of the first vararg value... for expansion of llvm.va_start.
1746   if (isVarArg) {
1747     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1748                     CallConv != CallingConv::X86_ThisCall)) {
1749       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1750     }
1751     if (Is64Bit) {
1752       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1753
1754       // FIXME: We should really autogenerate these arrays
1755       static const unsigned GPR64ArgRegsWin64[] = {
1756         X86::RCX, X86::RDX, X86::R8,  X86::R9
1757       };
1758       static const unsigned GPR64ArgRegs64Bit[] = {
1759         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1760       };
1761       static const unsigned XMMArgRegs64Bit[] = {
1762         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1763         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1764       };
1765       const unsigned *GPR64ArgRegs;
1766       unsigned NumXMMRegs = 0;
1767
1768       if (IsWin64) {
1769         // The XMM registers which might contain var arg parameters are shadowed
1770         // in their paired GPR.  So we only need to save the GPR to their home
1771         // slots.
1772         TotalNumIntRegs = 4;
1773         GPR64ArgRegs = GPR64ArgRegsWin64;
1774       } else {
1775         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1776         GPR64ArgRegs = GPR64ArgRegs64Bit;
1777
1778         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1779       }
1780       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1781                                                        TotalNumIntRegs);
1782
1783       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1784       assert(!(NumXMMRegs && !Subtarget->hasXMM()) &&
1785              "SSE register cannot be used when SSE is disabled!");
1786       assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1787              "SSE register cannot be used when SSE is disabled!");
1788       if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasXMM())
1789         // Kernel mode asks for SSE to be disabled, so don't push them
1790         // on the stack.
1791         TotalNumXMMRegs = 0;
1792
1793       if (IsWin64) {
1794         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1795         // Get to the caller-allocated home save location.  Add 8 to account
1796         // for the return address.
1797         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1798         FuncInfo->setRegSaveFrameIndex(
1799           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1800         // Fixup to set vararg frame on shadow area (4 x i64).
1801         if (NumIntRegs < 4)
1802           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1803       } else {
1804         // For X86-64, if there are vararg parameters that are passed via
1805         // registers, then we must store them to their spots on the stack so they
1806         // may be loaded by deferencing the result of va_next.
1807         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1808         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1809         FuncInfo->setRegSaveFrameIndex(
1810           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1811                                false));
1812       }
1813
1814       // Store the integer parameter registers.
1815       SmallVector<SDValue, 8> MemOps;
1816       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1817                                         getPointerTy());
1818       unsigned Offset = FuncInfo->getVarArgsGPOffset();
1819       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1820         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1821                                   DAG.getIntPtrConstant(Offset));
1822         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1823                                      X86::GR64RegisterClass);
1824         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1825         SDValue Store =
1826           DAG.getStore(Val.getValue(1), dl, Val, FIN,
1827                        MachinePointerInfo::getFixedStack(
1828                          FuncInfo->getRegSaveFrameIndex(), Offset),
1829                        false, false, 0);
1830         MemOps.push_back(Store);
1831         Offset += 8;
1832       }
1833
1834       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1835         // Now store the XMM (fp + vector) parameter registers.
1836         SmallVector<SDValue, 11> SaveXMMOps;
1837         SaveXMMOps.push_back(Chain);
1838
1839         unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1840         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1841         SaveXMMOps.push_back(ALVal);
1842
1843         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1844                                FuncInfo->getRegSaveFrameIndex()));
1845         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1846                                FuncInfo->getVarArgsFPOffset()));
1847
1848         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1849           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
1850                                        X86::VR128RegisterClass);
1851           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1852           SaveXMMOps.push_back(Val);
1853         }
1854         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1855                                      MVT::Other,
1856                                      &SaveXMMOps[0], SaveXMMOps.size()));
1857       }
1858
1859       if (!MemOps.empty())
1860         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1861                             &MemOps[0], MemOps.size());
1862     }
1863   }
1864
1865   // Some CCs need callee pop.
1866   if (Subtarget->IsCalleePop(isVarArg, CallConv)) {
1867     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1868   } else {
1869     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1870     // If this is an sret function, the return should pop the hidden pointer.
1871     if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1872       FuncInfo->setBytesToPopOnReturn(4);
1873   }
1874
1875   if (!Is64Bit) {
1876     // RegSaveFrameIndex is X86-64 only.
1877     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1878     if (CallConv == CallingConv::X86_FastCall ||
1879         CallConv == CallingConv::X86_ThisCall)
1880       // fastcc functions can't have varargs.
1881       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1882   }
1883
1884   return Chain;
1885 }
1886
1887 SDValue
1888 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1889                                     SDValue StackPtr, SDValue Arg,
1890                                     DebugLoc dl, SelectionDAG &DAG,
1891                                     const CCValAssign &VA,
1892                                     ISD::ArgFlagsTy Flags) const {
1893   unsigned LocMemOffset = VA.getLocMemOffset();
1894   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1895   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1896   if (Flags.isByVal())
1897     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1898
1899   return DAG.getStore(Chain, dl, Arg, PtrOff,
1900                       MachinePointerInfo::getStack(LocMemOffset),
1901                       false, false, 0);
1902 }
1903
1904 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1905 /// optimization is performed and it is required.
1906 SDValue
1907 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1908                                            SDValue &OutRetAddr, SDValue Chain,
1909                                            bool IsTailCall, bool Is64Bit,
1910                                            int FPDiff, DebugLoc dl) const {
1911   // Adjust the Return address stack slot.
1912   EVT VT = getPointerTy();
1913   OutRetAddr = getReturnAddressFrameIndex(DAG);
1914
1915   // Load the "old" Return address.
1916   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
1917                            false, false, 0);
1918   return SDValue(OutRetAddr.getNode(), 1);
1919 }
1920
1921 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1922 /// optimization is performed and it is required (FPDiff!=0).
1923 static SDValue
1924 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1925                          SDValue Chain, SDValue RetAddrFrIdx,
1926                          bool Is64Bit, int FPDiff, DebugLoc dl) {
1927   // Store the return address to the appropriate stack slot.
1928   if (!FPDiff) return Chain;
1929   // Calculate the new stack slot for the return address.
1930   int SlotSize = Is64Bit ? 8 : 4;
1931   int NewReturnAddrFI =
1932     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
1933   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1934   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1935   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1936                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
1937                        false, false, 0);
1938   return Chain;
1939 }
1940
1941 SDValue
1942 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1943                              CallingConv::ID CallConv, bool isVarArg,
1944                              bool &isTailCall,
1945                              const SmallVectorImpl<ISD::OutputArg> &Outs,
1946                              const SmallVectorImpl<SDValue> &OutVals,
1947                              const SmallVectorImpl<ISD::InputArg> &Ins,
1948                              DebugLoc dl, SelectionDAG &DAG,
1949                              SmallVectorImpl<SDValue> &InVals) const {
1950   MachineFunction &MF = DAG.getMachineFunction();
1951   bool Is64Bit        = Subtarget->is64Bit();
1952   bool IsWin64        = Subtarget->isTargetWin64();
1953   bool IsStructRet    = CallIsStructReturn(Outs);
1954   bool IsSibcall      = false;
1955
1956   if (isTailCall) {
1957     // Check if it's really possible to do a tail call.
1958     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1959                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1960                                                    Outs, OutVals, Ins, DAG);
1961
1962     // Sibcalls are automatically detected tailcalls which do not require
1963     // ABI changes.
1964     if (!GuaranteedTailCallOpt && isTailCall)
1965       IsSibcall = true;
1966
1967     if (isTailCall)
1968       ++NumTailCalls;
1969   }
1970
1971   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1972          "Var args not supported with calling convention fastcc or ghc");
1973
1974   // Analyze operands of the call, assigning locations to each operand.
1975   SmallVector<CCValAssign, 16> ArgLocs;
1976   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1977                  ArgLocs, *DAG.getContext());
1978
1979   // Allocate shadow area for Win64
1980   if (IsWin64) {
1981     CCInfo.AllocateStack(32, 8);
1982   }
1983
1984   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
1985
1986   // Get a count of how many bytes are to be pushed on the stack.
1987   unsigned NumBytes = CCInfo.getNextStackOffset();
1988   if (IsSibcall)
1989     // This is a sibcall. The memory operands are available in caller's
1990     // own caller's stack.
1991     NumBytes = 0;
1992   else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
1993     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1994
1995   int FPDiff = 0;
1996   if (isTailCall && !IsSibcall) {
1997     // Lower arguments at fp - stackoffset + fpdiff.
1998     unsigned NumBytesCallerPushed =
1999       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2000     FPDiff = NumBytesCallerPushed - NumBytes;
2001
2002     // Set the delta of movement of the returnaddr stackslot.
2003     // But only set if delta is greater than previous delta.
2004     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2005       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2006   }
2007
2008   if (!IsSibcall)
2009     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2010
2011   SDValue RetAddrFrIdx;
2012   // Load return adress for tail calls.
2013   if (isTailCall && FPDiff)
2014     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2015                                     Is64Bit, FPDiff, dl);
2016
2017   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2018   SmallVector<SDValue, 8> MemOpChains;
2019   SDValue StackPtr;
2020
2021   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2022   // of tail call optimization arguments are handle later.
2023   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2024     CCValAssign &VA = ArgLocs[i];
2025     EVT RegVT = VA.getLocVT();
2026     SDValue Arg = OutVals[i];
2027     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2028     bool isByVal = Flags.isByVal();
2029
2030     // Promote the value if needed.
2031     switch (VA.getLocInfo()) {
2032     default: llvm_unreachable("Unknown loc info!");
2033     case CCValAssign::Full: break;
2034     case CCValAssign::SExt:
2035       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2036       break;
2037     case CCValAssign::ZExt:
2038       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2039       break;
2040     case CCValAssign::AExt:
2041       if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2042         // Special case: passing MMX values in XMM registers.
2043         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2044         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2045         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2046       } else
2047         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2048       break;
2049     case CCValAssign::BCvt:
2050       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2051       break;
2052     case CCValAssign::Indirect: {
2053       // Store the argument.
2054       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2055       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2056       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2057                            MachinePointerInfo::getFixedStack(FI),
2058                            false, false, 0);
2059       Arg = SpillSlot;
2060       break;
2061     }
2062     }
2063
2064     if (VA.isRegLoc()) {
2065       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2066       if (isVarArg && IsWin64) {
2067         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2068         // shadow reg if callee is a varargs function.
2069         unsigned ShadowReg = 0;
2070         switch (VA.getLocReg()) {
2071         case X86::XMM0: ShadowReg = X86::RCX; break;
2072         case X86::XMM1: ShadowReg = X86::RDX; break;
2073         case X86::XMM2: ShadowReg = X86::R8; break;
2074         case X86::XMM3: ShadowReg = X86::R9; break;
2075         }
2076         if (ShadowReg)
2077           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2078       }
2079     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2080       assert(VA.isMemLoc());
2081       if (StackPtr.getNode() == 0)
2082         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2083       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2084                                              dl, DAG, VA, Flags));
2085     }
2086   }
2087
2088   if (!MemOpChains.empty())
2089     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2090                         &MemOpChains[0], MemOpChains.size());
2091
2092   // Build a sequence of copy-to-reg nodes chained together with token chain
2093   // and flag operands which copy the outgoing args into registers.
2094   SDValue InFlag;
2095   // Tail call byval lowering might overwrite argument registers so in case of
2096   // tail call optimization the copies to registers are lowered later.
2097   if (!isTailCall)
2098     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2099       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2100                                RegsToPass[i].second, InFlag);
2101       InFlag = Chain.getValue(1);
2102     }
2103
2104   if (Subtarget->isPICStyleGOT()) {
2105     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2106     // GOT pointer.
2107     if (!isTailCall) {
2108       Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2109                                DAG.getNode(X86ISD::GlobalBaseReg,
2110                                            DebugLoc(), getPointerTy()),
2111                                InFlag);
2112       InFlag = Chain.getValue(1);
2113     } else {
2114       // If we are tail calling and generating PIC/GOT style code load the
2115       // address of the callee into ECX. The value in ecx is used as target of
2116       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2117       // for tail calls on PIC/GOT architectures. Normally we would just put the
2118       // address of GOT into ebx and then call target@PLT. But for tail calls
2119       // ebx would be restored (since ebx is callee saved) before jumping to the
2120       // target@PLT.
2121
2122       // Note: The actual moving to ECX is done further down.
2123       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2124       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2125           !G->getGlobal()->hasProtectedVisibility())
2126         Callee = LowerGlobalAddress(Callee, DAG);
2127       else if (isa<ExternalSymbolSDNode>(Callee))
2128         Callee = LowerExternalSymbol(Callee, DAG);
2129     }
2130   }
2131
2132   if (Is64Bit && isVarArg && !IsWin64) {
2133     // From AMD64 ABI document:
2134     // For calls that may call functions that use varargs or stdargs
2135     // (prototype-less calls or calls to functions containing ellipsis (...) in
2136     // the declaration) %al is used as hidden argument to specify the number
2137     // of SSE registers used. The contents of %al do not need to match exactly
2138     // the number of registers, but must be an ubound on the number of SSE
2139     // registers used and is in the range 0 - 8 inclusive.
2140
2141     // Count the number of XMM registers allocated.
2142     static const unsigned XMMArgRegs[] = {
2143       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2144       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2145     };
2146     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2147     assert((Subtarget->hasXMM() || !NumXMMRegs)
2148            && "SSE registers cannot be used when SSE is disabled");
2149
2150     Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2151                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2152     InFlag = Chain.getValue(1);
2153   }
2154
2155
2156   // For tail calls lower the arguments to the 'real' stack slot.
2157   if (isTailCall) {
2158     // Force all the incoming stack arguments to be loaded from the stack
2159     // before any new outgoing arguments are stored to the stack, because the
2160     // outgoing stack slots may alias the incoming argument stack slots, and
2161     // the alias isn't otherwise explicit. This is slightly more conservative
2162     // than necessary, because it means that each store effectively depends
2163     // on every argument instead of just those arguments it would clobber.
2164     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2165
2166     SmallVector<SDValue, 8> MemOpChains2;
2167     SDValue FIN;
2168     int FI = 0;
2169     // Do not flag preceeding copytoreg stuff together with the following stuff.
2170     InFlag = SDValue();
2171     if (GuaranteedTailCallOpt) {
2172       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2173         CCValAssign &VA = ArgLocs[i];
2174         if (VA.isRegLoc())
2175           continue;
2176         assert(VA.isMemLoc());
2177         SDValue Arg = OutVals[i];
2178         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2179         // Create frame index.
2180         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2181         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2182         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2183         FIN = DAG.getFrameIndex(FI, getPointerTy());
2184
2185         if (Flags.isByVal()) {
2186           // Copy relative to framepointer.
2187           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2188           if (StackPtr.getNode() == 0)
2189             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2190                                           getPointerTy());
2191           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2192
2193           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2194                                                            ArgChain,
2195                                                            Flags, DAG, dl));
2196         } else {
2197           // Store relative to framepointer.
2198           MemOpChains2.push_back(
2199             DAG.getStore(ArgChain, dl, Arg, FIN,
2200                          MachinePointerInfo::getFixedStack(FI),
2201                          false, false, 0));
2202         }
2203       }
2204     }
2205
2206     if (!MemOpChains2.empty())
2207       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2208                           &MemOpChains2[0], MemOpChains2.size());
2209
2210     // Copy arguments to their registers.
2211     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2212       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2213                                RegsToPass[i].second, InFlag);
2214       InFlag = Chain.getValue(1);
2215     }
2216     InFlag =SDValue();
2217
2218     // Store the return address to the appropriate stack slot.
2219     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2220                                      FPDiff, dl);
2221   }
2222
2223   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2224     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2225     // In the 64-bit large code model, we have to make all calls
2226     // through a register, since the call instruction's 32-bit
2227     // pc-relative offset may not be large enough to hold the whole
2228     // address.
2229   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2230     // If the callee is a GlobalAddress node (quite common, every direct call
2231     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2232     // it.
2233
2234     // We should use extra load for direct calls to dllimported functions in
2235     // non-JIT mode.
2236     const GlobalValue *GV = G->getGlobal();
2237     if (!GV->hasDLLImportLinkage()) {
2238       unsigned char OpFlags = 0;
2239
2240       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2241       // external symbols most go through the PLT in PIC mode.  If the symbol
2242       // has hidden or protected visibility, or if it is static or local, then
2243       // we don't need to use the PLT - we can directly call it.
2244       if (Subtarget->isTargetELF() &&
2245           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2246           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2247         OpFlags = X86II::MO_PLT;
2248       } else if (Subtarget->isPICStyleStubAny() &&
2249                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2250                  Subtarget->getDarwinVers() < 9) {
2251         // PC-relative references to external symbols should go through $stub,
2252         // unless we're building with the leopard linker or later, which
2253         // automatically synthesizes these stubs.
2254         OpFlags = X86II::MO_DARWIN_STUB;
2255       }
2256
2257       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2258                                           G->getOffset(), OpFlags);
2259     }
2260   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2261     unsigned char OpFlags = 0;
2262
2263     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2264     // external symbols should go through the PLT.
2265     if (Subtarget->isTargetELF() &&
2266         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2267       OpFlags = X86II::MO_PLT;
2268     } else if (Subtarget->isPICStyleStubAny() &&
2269                Subtarget->getDarwinVers() < 9) {
2270       // PC-relative references to external symbols should go through $stub,
2271       // unless we're building with the leopard linker or later, which
2272       // automatically synthesizes these stubs.
2273       OpFlags = X86II::MO_DARWIN_STUB;
2274     }
2275
2276     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2277                                          OpFlags);
2278   }
2279
2280   // Returns a chain & a flag for retval copy to use.
2281   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2282   SmallVector<SDValue, 8> Ops;
2283
2284   if (!IsSibcall && isTailCall) {
2285     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2286                            DAG.getIntPtrConstant(0, true), InFlag);
2287     InFlag = Chain.getValue(1);
2288   }
2289
2290   Ops.push_back(Chain);
2291   Ops.push_back(Callee);
2292
2293   if (isTailCall)
2294     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2295
2296   // Add argument registers to the end of the list so that they are known live
2297   // into the call.
2298   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2299     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2300                                   RegsToPass[i].second.getValueType()));
2301
2302   // Add an implicit use GOT pointer in EBX.
2303   if (!isTailCall && Subtarget->isPICStyleGOT())
2304     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2305
2306   // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2307   if (Is64Bit && isVarArg && !IsWin64)
2308     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2309
2310   if (InFlag.getNode())
2311     Ops.push_back(InFlag);
2312
2313   if (isTailCall) {
2314     // We used to do:
2315     //// If this is the first return lowered for this function, add the regs
2316     //// to the liveout set for the function.
2317     // This isn't right, although it's probably harmless on x86; liveouts
2318     // should be computed from returns not tail calls.  Consider a void
2319     // function making a tail call to a function returning int.
2320     return DAG.getNode(X86ISD::TC_RETURN, dl,
2321                        NodeTys, &Ops[0], Ops.size());
2322   }
2323
2324   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2325   InFlag = Chain.getValue(1);
2326
2327   // Create the CALLSEQ_END node.
2328   unsigned NumBytesForCalleeToPush;
2329   if (Subtarget->IsCalleePop(isVarArg, CallConv))
2330     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2331   else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2332     // If this is a call to a struct-return function, the callee
2333     // pops the hidden struct pointer, so we have to push it back.
2334     // This is common for Darwin/X86, Linux & Mingw32 targets.
2335     NumBytesForCalleeToPush = 4;
2336   else
2337     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2338
2339   // Returns a flag for retval copy to use.
2340   if (!IsSibcall) {
2341     Chain = DAG.getCALLSEQ_END(Chain,
2342                                DAG.getIntPtrConstant(NumBytes, true),
2343                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2344                                                      true),
2345                                InFlag);
2346     InFlag = Chain.getValue(1);
2347   }
2348
2349   // Handle result values, copying them out of physregs into vregs that we
2350   // return.
2351   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2352                          Ins, dl, DAG, InVals);
2353 }
2354
2355
2356 //===----------------------------------------------------------------------===//
2357 //                Fast Calling Convention (tail call) implementation
2358 //===----------------------------------------------------------------------===//
2359
2360 //  Like std call, callee cleans arguments, convention except that ECX is
2361 //  reserved for storing the tail called function address. Only 2 registers are
2362 //  free for argument passing (inreg). Tail call optimization is performed
2363 //  provided:
2364 //                * tailcallopt is enabled
2365 //                * caller/callee are fastcc
2366 //  On X86_64 architecture with GOT-style position independent code only local
2367 //  (within module) calls are supported at the moment.
2368 //  To keep the stack aligned according to platform abi the function
2369 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2370 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2371 //  If a tail called function callee has more arguments than the caller the
2372 //  caller needs to make sure that there is room to move the RETADDR to. This is
2373 //  achieved by reserving an area the size of the argument delta right after the
2374 //  original REtADDR, but before the saved framepointer or the spilled registers
2375 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2376 //  stack layout:
2377 //    arg1
2378 //    arg2
2379 //    RETADDR
2380 //    [ new RETADDR
2381 //      move area ]
2382 //    (possible EBP)
2383 //    ESI
2384 //    EDI
2385 //    local1 ..
2386
2387 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2388 /// for a 16 byte align requirement.
2389 unsigned
2390 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2391                                                SelectionDAG& DAG) const {
2392   MachineFunction &MF = DAG.getMachineFunction();
2393   const TargetMachine &TM = MF.getTarget();
2394   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2395   unsigned StackAlignment = TFI.getStackAlignment();
2396   uint64_t AlignMask = StackAlignment - 1;
2397   int64_t Offset = StackSize;
2398   uint64_t SlotSize = TD->getPointerSize();
2399   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2400     // Number smaller than 12 so just add the difference.
2401     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2402   } else {
2403     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2404     Offset = ((~AlignMask) & Offset) + StackAlignment +
2405       (StackAlignment-SlotSize);
2406   }
2407   return Offset;
2408 }
2409
2410 /// MatchingStackOffset - Return true if the given stack call argument is
2411 /// already available in the same position (relatively) of the caller's
2412 /// incoming argument stack.
2413 static
2414 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2415                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2416                          const X86InstrInfo *TII) {
2417   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2418   int FI = INT_MAX;
2419   if (Arg.getOpcode() == ISD::CopyFromReg) {
2420     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2421     if (!TargetRegisterInfo::isVirtualRegister(VR))
2422       return false;
2423     MachineInstr *Def = MRI->getVRegDef(VR);
2424     if (!Def)
2425       return false;
2426     if (!Flags.isByVal()) {
2427       if (!TII->isLoadFromStackSlot(Def, FI))
2428         return false;
2429     } else {
2430       unsigned Opcode = Def->getOpcode();
2431       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2432           Def->getOperand(1).isFI()) {
2433         FI = Def->getOperand(1).getIndex();
2434         Bytes = Flags.getByValSize();
2435       } else
2436         return false;
2437     }
2438   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2439     if (Flags.isByVal())
2440       // ByVal argument is passed in as a pointer but it's now being
2441       // dereferenced. e.g.
2442       // define @foo(%struct.X* %A) {
2443       //   tail call @bar(%struct.X* byval %A)
2444       // }
2445       return false;
2446     SDValue Ptr = Ld->getBasePtr();
2447     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2448     if (!FINode)
2449       return false;
2450     FI = FINode->getIndex();
2451   } else
2452     return false;
2453
2454   assert(FI != INT_MAX);
2455   if (!MFI->isFixedObjectIndex(FI))
2456     return false;
2457   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2458 }
2459
2460 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2461 /// for tail call optimization. Targets which want to do tail call
2462 /// optimization should implement this function.
2463 bool
2464 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2465                                                      CallingConv::ID CalleeCC,
2466                                                      bool isVarArg,
2467                                                      bool isCalleeStructRet,
2468                                                      bool isCallerStructRet,
2469                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2470                                     const SmallVectorImpl<SDValue> &OutVals,
2471                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2472                                                      SelectionDAG& DAG) const {
2473   if (!IsTailCallConvention(CalleeCC) &&
2474       CalleeCC != CallingConv::C)
2475     return false;
2476
2477   // If -tailcallopt is specified, make fastcc functions tail-callable.
2478   const MachineFunction &MF = DAG.getMachineFunction();
2479   const Function *CallerF = DAG.getMachineFunction().getFunction();
2480   CallingConv::ID CallerCC = CallerF->getCallingConv();
2481   bool CCMatch = CallerCC == CalleeCC;
2482
2483   if (GuaranteedTailCallOpt) {
2484     if (IsTailCallConvention(CalleeCC) && CCMatch)
2485       return true;
2486     return false;
2487   }
2488
2489   // Look for obvious safe cases to perform tail call optimization that do not
2490   // require ABI changes. This is what gcc calls sibcall.
2491
2492   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2493   // emit a special epilogue.
2494   if (RegInfo->needsStackRealignment(MF))
2495     return false;
2496
2497   // Do not sibcall optimize vararg calls unless the call site is not passing
2498   // any arguments.
2499   if (isVarArg && !Outs.empty())
2500     return false;
2501
2502   // Also avoid sibcall optimization if either caller or callee uses struct
2503   // return semantics.
2504   if (isCalleeStructRet || isCallerStructRet)
2505     return false;
2506
2507   // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2508   // Therefore if it's not used by the call it is not safe to optimize this into
2509   // a sibcall.
2510   bool Unused = false;
2511   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2512     if (!Ins[i].Used) {
2513       Unused = true;
2514       break;
2515     }
2516   }
2517   if (Unused) {
2518     SmallVector<CCValAssign, 16> RVLocs;
2519     CCState CCInfo(CalleeCC, false, getTargetMachine(),
2520                    RVLocs, *DAG.getContext());
2521     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2522     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2523       CCValAssign &VA = RVLocs[i];
2524       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2525         return false;
2526     }
2527   }
2528
2529   // If the calling conventions do not match, then we'd better make sure the
2530   // results are returned in the same way as what the caller expects.
2531   if (!CCMatch) {
2532     SmallVector<CCValAssign, 16> RVLocs1;
2533     CCState CCInfo1(CalleeCC, false, getTargetMachine(),
2534                     RVLocs1, *DAG.getContext());
2535     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2536
2537     SmallVector<CCValAssign, 16> RVLocs2;
2538     CCState CCInfo2(CallerCC, false, getTargetMachine(),
2539                     RVLocs2, *DAG.getContext());
2540     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2541
2542     if (RVLocs1.size() != RVLocs2.size())
2543       return false;
2544     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2545       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2546         return false;
2547       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2548         return false;
2549       if (RVLocs1[i].isRegLoc()) {
2550         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2551           return false;
2552       } else {
2553         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2554           return false;
2555       }
2556     }
2557   }
2558
2559   // If the callee takes no arguments then go on to check the results of the
2560   // call.
2561   if (!Outs.empty()) {
2562     // Check if stack adjustment is needed. For now, do not do this if any
2563     // argument is passed on the stack.
2564     SmallVector<CCValAssign, 16> ArgLocs;
2565     CCState CCInfo(CalleeCC, isVarArg, getTargetMachine(),
2566                    ArgLocs, *DAG.getContext());
2567
2568     // Allocate shadow area for Win64
2569     if (Subtarget->isTargetWin64()) {
2570       CCInfo.AllocateStack(32, 8);
2571     }
2572
2573     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2574     if (CCInfo.getNextStackOffset()) {
2575       MachineFunction &MF = DAG.getMachineFunction();
2576       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2577         return false;
2578
2579       // Check if the arguments are already laid out in the right way as
2580       // the caller's fixed stack objects.
2581       MachineFrameInfo *MFI = MF.getFrameInfo();
2582       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2583       const X86InstrInfo *TII =
2584         ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2585       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2586         CCValAssign &VA = ArgLocs[i];
2587         SDValue Arg = OutVals[i];
2588         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2589         if (VA.getLocInfo() == CCValAssign::Indirect)
2590           return false;
2591         if (!VA.isRegLoc()) {
2592           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2593                                    MFI, MRI, TII))
2594             return false;
2595         }
2596       }
2597     }
2598
2599     // If the tailcall address may be in a register, then make sure it's
2600     // possible to register allocate for it. In 32-bit, the call address can
2601     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2602     // callee-saved registers are restored. These happen to be the same
2603     // registers used to pass 'inreg' arguments so watch out for those.
2604     if (!Subtarget->is64Bit() &&
2605         !isa<GlobalAddressSDNode>(Callee) &&
2606         !isa<ExternalSymbolSDNode>(Callee)) {
2607       unsigned NumInRegs = 0;
2608       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2609         CCValAssign &VA = ArgLocs[i];
2610         if (!VA.isRegLoc())
2611           continue;
2612         unsigned Reg = VA.getLocReg();
2613         switch (Reg) {
2614         default: break;
2615         case X86::EAX: case X86::EDX: case X86::ECX:
2616           if (++NumInRegs == 3)
2617             return false;
2618           break;
2619         }
2620       }
2621     }
2622   }
2623
2624   // An stdcall caller is expected to clean up its arguments; the callee
2625   // isn't going to do that.
2626   if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2627     return false;
2628
2629   return true;
2630 }
2631
2632 FastISel *
2633 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2634   return X86::createFastISel(funcInfo);
2635 }
2636
2637
2638 //===----------------------------------------------------------------------===//
2639 //                           Other Lowering Hooks
2640 //===----------------------------------------------------------------------===//
2641
2642 static bool MayFoldLoad(SDValue Op) {
2643   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2644 }
2645
2646 static bool MayFoldIntoStore(SDValue Op) {
2647   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2648 }
2649
2650 static bool isTargetShuffle(unsigned Opcode) {
2651   switch(Opcode) {
2652   default: return false;
2653   case X86ISD::PSHUFD:
2654   case X86ISD::PSHUFHW:
2655   case X86ISD::PSHUFLW:
2656   case X86ISD::SHUFPD:
2657   case X86ISD::PALIGN:
2658   case X86ISD::SHUFPS:
2659   case X86ISD::MOVLHPS:
2660   case X86ISD::MOVLHPD:
2661   case X86ISD::MOVHLPS:
2662   case X86ISD::MOVLPS:
2663   case X86ISD::MOVLPD:
2664   case X86ISD::MOVSHDUP:
2665   case X86ISD::MOVSLDUP:
2666   case X86ISD::MOVDDUP:
2667   case X86ISD::MOVSS:
2668   case X86ISD::MOVSD:
2669   case X86ISD::UNPCKLPS:
2670   case X86ISD::UNPCKLPD:
2671   case X86ISD::VUNPCKLPS:
2672   case X86ISD::VUNPCKLPD:
2673   case X86ISD::VUNPCKLPSY:
2674   case X86ISD::VUNPCKLPDY:
2675   case X86ISD::PUNPCKLWD:
2676   case X86ISD::PUNPCKLBW:
2677   case X86ISD::PUNPCKLDQ:
2678   case X86ISD::PUNPCKLQDQ:
2679   case X86ISD::UNPCKHPS:
2680   case X86ISD::UNPCKHPD:
2681   case X86ISD::PUNPCKHWD:
2682   case X86ISD::PUNPCKHBW:
2683   case X86ISD::PUNPCKHDQ:
2684   case X86ISD::PUNPCKHQDQ:
2685     return true;
2686   }
2687   return false;
2688 }
2689
2690 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2691                                                SDValue V1, SelectionDAG &DAG) {
2692   switch(Opc) {
2693   default: llvm_unreachable("Unknown x86 shuffle node");
2694   case X86ISD::MOVSHDUP:
2695   case X86ISD::MOVSLDUP:
2696   case X86ISD::MOVDDUP:
2697     return DAG.getNode(Opc, dl, VT, V1);
2698   }
2699
2700   return SDValue();
2701 }
2702
2703 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2704                           SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2705   switch(Opc) {
2706   default: llvm_unreachable("Unknown x86 shuffle node");
2707   case X86ISD::PSHUFD:
2708   case X86ISD::PSHUFHW:
2709   case X86ISD::PSHUFLW:
2710     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2711   }
2712
2713   return SDValue();
2714 }
2715
2716 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2717                SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2718   switch(Opc) {
2719   default: llvm_unreachable("Unknown x86 shuffle node");
2720   case X86ISD::PALIGN:
2721   case X86ISD::SHUFPD:
2722   case X86ISD::SHUFPS:
2723     return DAG.getNode(Opc, dl, VT, V1, V2,
2724                        DAG.getConstant(TargetMask, MVT::i8));
2725   }
2726   return SDValue();
2727 }
2728
2729 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2730                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
2731   switch(Opc) {
2732   default: llvm_unreachable("Unknown x86 shuffle node");
2733   case X86ISD::MOVLHPS:
2734   case X86ISD::MOVLHPD:
2735   case X86ISD::MOVHLPS:
2736   case X86ISD::MOVLPS:
2737   case X86ISD::MOVLPD:
2738   case X86ISD::MOVSS:
2739   case X86ISD::MOVSD:
2740   case X86ISD::UNPCKLPS:
2741   case X86ISD::UNPCKLPD:
2742   case X86ISD::VUNPCKLPS:
2743   case X86ISD::VUNPCKLPD:
2744   case X86ISD::VUNPCKLPSY:
2745   case X86ISD::VUNPCKLPDY:
2746   case X86ISD::PUNPCKLWD:
2747   case X86ISD::PUNPCKLBW:
2748   case X86ISD::PUNPCKLDQ:
2749   case X86ISD::PUNPCKLQDQ:
2750   case X86ISD::UNPCKHPS:
2751   case X86ISD::UNPCKHPD:
2752   case X86ISD::PUNPCKHWD:
2753   case X86ISD::PUNPCKHBW:
2754   case X86ISD::PUNPCKHDQ:
2755   case X86ISD::PUNPCKHQDQ:
2756     return DAG.getNode(Opc, dl, VT, V1, V2);
2757   }
2758   return SDValue();
2759 }
2760
2761 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2762   MachineFunction &MF = DAG.getMachineFunction();
2763   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2764   int ReturnAddrIndex = FuncInfo->getRAIndex();
2765
2766   if (ReturnAddrIndex == 0) {
2767     // Set up a frame object for the return address.
2768     uint64_t SlotSize = TD->getPointerSize();
2769     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2770                                                            false);
2771     FuncInfo->setRAIndex(ReturnAddrIndex);
2772   }
2773
2774   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2775 }
2776
2777
2778 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2779                                        bool hasSymbolicDisplacement) {
2780   // Offset should fit into 32 bit immediate field.
2781   if (!isInt<32>(Offset))
2782     return false;
2783
2784   // If we don't have a symbolic displacement - we don't have any extra
2785   // restrictions.
2786   if (!hasSymbolicDisplacement)
2787     return true;
2788
2789   // FIXME: Some tweaks might be needed for medium code model.
2790   if (M != CodeModel::Small && M != CodeModel::Kernel)
2791     return false;
2792
2793   // For small code model we assume that latest object is 16MB before end of 31
2794   // bits boundary. We may also accept pretty large negative constants knowing
2795   // that all objects are in the positive half of address space.
2796   if (M == CodeModel::Small && Offset < 16*1024*1024)
2797     return true;
2798
2799   // For kernel code model we know that all object resist in the negative half
2800   // of 32bits address space. We may not accept negative offsets, since they may
2801   // be just off and we may accept pretty large positive ones.
2802   if (M == CodeModel::Kernel && Offset > 0)
2803     return true;
2804
2805   return false;
2806 }
2807
2808 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2809 /// specific condition code, returning the condition code and the LHS/RHS of the
2810 /// comparison to make.
2811 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2812                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2813   if (!isFP) {
2814     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2815       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2816         // X > -1   -> X == 0, jump !sign.
2817         RHS = DAG.getConstant(0, RHS.getValueType());
2818         return X86::COND_NS;
2819       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2820         // X < 0   -> X == 0, jump on sign.
2821         return X86::COND_S;
2822       } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2823         // X < 1   -> X <= 0
2824         RHS = DAG.getConstant(0, RHS.getValueType());
2825         return X86::COND_LE;
2826       }
2827     }
2828
2829     switch (SetCCOpcode) {
2830     default: llvm_unreachable("Invalid integer condition!");
2831     case ISD::SETEQ:  return X86::COND_E;
2832     case ISD::SETGT:  return X86::COND_G;
2833     case ISD::SETGE:  return X86::COND_GE;
2834     case ISD::SETLT:  return X86::COND_L;
2835     case ISD::SETLE:  return X86::COND_LE;
2836     case ISD::SETNE:  return X86::COND_NE;
2837     case ISD::SETULT: return X86::COND_B;
2838     case ISD::SETUGT: return X86::COND_A;
2839     case ISD::SETULE: return X86::COND_BE;
2840     case ISD::SETUGE: return X86::COND_AE;
2841     }
2842   }
2843
2844   // First determine if it is required or is profitable to flip the operands.
2845
2846   // If LHS is a foldable load, but RHS is not, flip the condition.
2847   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
2848       !ISD::isNON_EXTLoad(RHS.getNode())) {
2849     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2850     std::swap(LHS, RHS);
2851   }
2852
2853   switch (SetCCOpcode) {
2854   default: break;
2855   case ISD::SETOLT:
2856   case ISD::SETOLE:
2857   case ISD::SETUGT:
2858   case ISD::SETUGE:
2859     std::swap(LHS, RHS);
2860     break;
2861   }
2862
2863   // On a floating point condition, the flags are set as follows:
2864   // ZF  PF  CF   op
2865   //  0 | 0 | 0 | X > Y
2866   //  0 | 0 | 1 | X < Y
2867   //  1 | 0 | 0 | X == Y
2868   //  1 | 1 | 1 | unordered
2869   switch (SetCCOpcode) {
2870   default: llvm_unreachable("Condcode should be pre-legalized away");
2871   case ISD::SETUEQ:
2872   case ISD::SETEQ:   return X86::COND_E;
2873   case ISD::SETOLT:              // flipped
2874   case ISD::SETOGT:
2875   case ISD::SETGT:   return X86::COND_A;
2876   case ISD::SETOLE:              // flipped
2877   case ISD::SETOGE:
2878   case ISD::SETGE:   return X86::COND_AE;
2879   case ISD::SETUGT:              // flipped
2880   case ISD::SETULT:
2881   case ISD::SETLT:   return X86::COND_B;
2882   case ISD::SETUGE:              // flipped
2883   case ISD::SETULE:
2884   case ISD::SETLE:   return X86::COND_BE;
2885   case ISD::SETONE:
2886   case ISD::SETNE:   return X86::COND_NE;
2887   case ISD::SETUO:   return X86::COND_P;
2888   case ISD::SETO:    return X86::COND_NP;
2889   case ISD::SETOEQ:
2890   case ISD::SETUNE:  return X86::COND_INVALID;
2891   }
2892 }
2893
2894 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2895 /// code. Current x86 isa includes the following FP cmov instructions:
2896 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2897 static bool hasFPCMov(unsigned X86CC) {
2898   switch (X86CC) {
2899   default:
2900     return false;
2901   case X86::COND_B:
2902   case X86::COND_BE:
2903   case X86::COND_E:
2904   case X86::COND_P:
2905   case X86::COND_A:
2906   case X86::COND_AE:
2907   case X86::COND_NE:
2908   case X86::COND_NP:
2909     return true;
2910   }
2911 }
2912
2913 /// isFPImmLegal - Returns true if the target can instruction select the
2914 /// specified FP immediate natively. If false, the legalizer will
2915 /// materialize the FP immediate as a load from a constant pool.
2916 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2917   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
2918     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
2919       return true;
2920   }
2921   return false;
2922 }
2923
2924 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2925 /// the specified range (L, H].
2926 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2927   return (Val < 0) || (Val >= Low && Val < Hi);
2928 }
2929
2930 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2931 /// specified value.
2932 static bool isUndefOrEqual(int Val, int CmpVal) {
2933   if (Val < 0 || Val == CmpVal)
2934     return true;
2935   return false;
2936 }
2937
2938 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2939 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
2940 /// the second operand.
2941 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2942   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
2943     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2944   if (VT == MVT::v2f64 || VT == MVT::v2i64)
2945     return (Mask[0] < 2 && Mask[1] < 2);
2946   return false;
2947 }
2948
2949 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2950   SmallVector<int, 8> M;
2951   N->getMask(M);
2952   return ::isPSHUFDMask(M, N->getValueType(0));
2953 }
2954
2955 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2956 /// is suitable for input to PSHUFHW.
2957 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2958   if (VT != MVT::v8i16)
2959     return false;
2960
2961   // Lower quadword copied in order or undef.
2962   for (int i = 0; i != 4; ++i)
2963     if (Mask[i] >= 0 && Mask[i] != i)
2964       return false;
2965
2966   // Upper quadword shuffled.
2967   for (int i = 4; i != 8; ++i)
2968     if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2969       return false;
2970
2971   return true;
2972 }
2973
2974 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2975   SmallVector<int, 8> M;
2976   N->getMask(M);
2977   return ::isPSHUFHWMask(M, N->getValueType(0));
2978 }
2979
2980 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
2981 /// is suitable for input to PSHUFLW.
2982 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2983   if (VT != MVT::v8i16)
2984     return false;
2985
2986   // Upper quadword copied in order.
2987   for (int i = 4; i != 8; ++i)
2988     if (Mask[i] >= 0 && Mask[i] != i)
2989       return false;
2990
2991   // Lower quadword shuffled.
2992   for (int i = 0; i != 4; ++i)
2993     if (Mask[i] >= 4)
2994       return false;
2995
2996   return true;
2997 }
2998
2999 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
3000   SmallVector<int, 8> M;
3001   N->getMask(M);
3002   return ::isPSHUFLWMask(M, N->getValueType(0));
3003 }
3004
3005 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3006 /// is suitable for input to PALIGNR.
3007 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
3008                           bool hasSSSE3) {
3009   int i, e = VT.getVectorNumElements();
3010
3011   // Do not handle v2i64 / v2f64 shuffles with palignr.
3012   if (e < 4 || !hasSSSE3)
3013     return false;
3014
3015   for (i = 0; i != e; ++i)
3016     if (Mask[i] >= 0)
3017       break;
3018
3019   // All undef, not a palignr.
3020   if (i == e)
3021     return false;
3022
3023   // Determine if it's ok to perform a palignr with only the LHS, since we
3024   // don't have access to the actual shuffle elements to see if RHS is undef.
3025   bool Unary = Mask[i] < (int)e;
3026   bool NeedsUnary = false;
3027
3028   int s = Mask[i] - i;
3029
3030   // Check the rest of the elements to see if they are consecutive.
3031   for (++i; i != e; ++i) {
3032     int m = Mask[i];
3033     if (m < 0)
3034       continue;
3035
3036     Unary = Unary && (m < (int)e);
3037     NeedsUnary = NeedsUnary || (m < s);
3038
3039     if (NeedsUnary && !Unary)
3040       return false;
3041     if (Unary && m != ((s+i) & (e-1)))
3042       return false;
3043     if (!Unary && m != (s+i))
3044       return false;
3045   }
3046   return true;
3047 }
3048
3049 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
3050   SmallVector<int, 8> M;
3051   N->getMask(M);
3052   return ::isPALIGNRMask(M, N->getValueType(0), true);
3053 }
3054
3055 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3056 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
3057 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3058   int NumElems = VT.getVectorNumElements();
3059   if (NumElems != 2 && NumElems != 4)
3060     return false;
3061
3062   int Half = NumElems / 2;
3063   for (int i = 0; i < Half; ++i)
3064     if (!isUndefOrInRange(Mask[i], 0, NumElems))
3065       return false;
3066   for (int i = Half; i < NumElems; ++i)
3067     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3068       return false;
3069
3070   return true;
3071 }
3072
3073 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
3074   SmallVector<int, 8> M;
3075   N->getMask(M);
3076   return ::isSHUFPMask(M, N->getValueType(0));
3077 }
3078
3079 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
3080 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
3081 /// half elements to come from vector 1 (which would equal the dest.) and
3082 /// the upper half to come from vector 2.
3083 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3084   int NumElems = VT.getVectorNumElements();
3085
3086   if (NumElems != 2 && NumElems != 4)
3087     return false;
3088
3089   int Half = NumElems / 2;
3090   for (int i = 0; i < Half; ++i)
3091     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3092       return false;
3093   for (int i = Half; i < NumElems; ++i)
3094     if (!isUndefOrInRange(Mask[i], 0, NumElems))
3095       return false;
3096   return true;
3097 }
3098
3099 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
3100   SmallVector<int, 8> M;
3101   N->getMask(M);
3102   return isCommutedSHUFPMask(M, N->getValueType(0));
3103 }
3104
3105 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3106 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3107 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3108   if (N->getValueType(0).getVectorNumElements() != 4)
3109     return false;
3110
3111   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3112   return isUndefOrEqual(N->getMaskElt(0), 6) &&
3113          isUndefOrEqual(N->getMaskElt(1), 7) &&
3114          isUndefOrEqual(N->getMaskElt(2), 2) &&
3115          isUndefOrEqual(N->getMaskElt(3), 3);
3116 }
3117
3118 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3119 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3120 /// <2, 3, 2, 3>
3121 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3122   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3123
3124   if (NumElems != 4)
3125     return false;
3126
3127   return isUndefOrEqual(N->getMaskElt(0), 2) &&
3128   isUndefOrEqual(N->getMaskElt(1), 3) &&
3129   isUndefOrEqual(N->getMaskElt(2), 2) &&
3130   isUndefOrEqual(N->getMaskElt(3), 3);
3131 }
3132
3133 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3134 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3135 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3136   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3137
3138   if (NumElems != 2 && NumElems != 4)
3139     return false;
3140
3141   for (unsigned i = 0; i < NumElems/2; ++i)
3142     if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3143       return false;
3144
3145   for (unsigned i = NumElems/2; i < NumElems; ++i)
3146     if (!isUndefOrEqual(N->getMaskElt(i), i))
3147       return false;
3148
3149   return true;
3150 }
3151
3152 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3153 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3154 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3155   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3156
3157   if ((NumElems != 2 && NumElems != 4)
3158       || N->getValueType(0).getSizeInBits() > 128)
3159     return false;
3160
3161   for (unsigned i = 0; i < NumElems/2; ++i)
3162     if (!isUndefOrEqual(N->getMaskElt(i), i))
3163       return false;
3164
3165   for (unsigned i = 0; i < NumElems/2; ++i)
3166     if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3167       return false;
3168
3169   return true;
3170 }
3171
3172 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3173 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3174 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3175                          bool V2IsSplat = false) {
3176   int NumElts = VT.getVectorNumElements();
3177   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3178     return false;
3179
3180   // Handle vector lengths > 128 bits.  Define a "section" as a set of
3181   // 128 bits.  AVX defines UNPCK* to operate independently on 128-bit
3182   // sections.
3183   unsigned NumSections = VT.getSizeInBits() / 128;
3184   if (NumSections == 0 ) NumSections = 1;  // Handle MMX
3185   unsigned NumSectionElts = NumElts / NumSections;
3186
3187   unsigned Start = 0;
3188   unsigned End = NumSectionElts;
3189   for (unsigned s = 0; s < NumSections; ++s) {
3190     for (unsigned i = Start, j = s * NumSectionElts;
3191          i != End;
3192          i += 2, ++j) {
3193       int BitI  = Mask[i];
3194       int BitI1 = Mask[i+1];
3195       if (!isUndefOrEqual(BitI, j))
3196         return false;
3197       if (V2IsSplat) {
3198         if (!isUndefOrEqual(BitI1, NumElts))
3199           return false;
3200       } else {
3201         if (!isUndefOrEqual(BitI1, j + NumElts))
3202           return false;
3203       }
3204     }
3205     // Process the next 128 bits.
3206     Start += NumSectionElts;
3207     End += NumSectionElts;
3208   }
3209
3210   return true;
3211 }
3212
3213 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3214   SmallVector<int, 8> M;
3215   N->getMask(M);
3216   return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
3217 }
3218
3219 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3220 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3221 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3222                          bool V2IsSplat = false) {
3223   int NumElts = VT.getVectorNumElements();
3224   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3225     return false;
3226
3227   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3228     int BitI  = Mask[i];
3229     int BitI1 = Mask[i+1];
3230     if (!isUndefOrEqual(BitI, j + NumElts/2))
3231       return false;
3232     if (V2IsSplat) {
3233       if (isUndefOrEqual(BitI1, NumElts))
3234         return false;
3235     } else {
3236       if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
3237         return false;
3238     }
3239   }
3240   return true;
3241 }
3242
3243 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3244   SmallVector<int, 8> M;
3245   N->getMask(M);
3246   return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
3247 }
3248
3249 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3250 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3251 /// <0, 0, 1, 1>
3252 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3253   int NumElems = VT.getVectorNumElements();
3254   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3255     return false;
3256
3257   // Handle vector lengths > 128 bits.  Define a "section" as a set of
3258   // 128 bits.  AVX defines UNPCK* to operate independently on 128-bit
3259   // sections.
3260   unsigned NumSections = VT.getSizeInBits() / 128;
3261   if (NumSections == 0 ) NumSections = 1;  // Handle MMX
3262   unsigned NumSectionElts = NumElems / NumSections;
3263
3264   for (unsigned s = 0; s < NumSections; ++s) {
3265     for (unsigned i = s * NumSectionElts, j = s * NumSectionElts;
3266          i != NumSectionElts * (s + 1);
3267          i += 2, ++j) {
3268       int BitI  = Mask[i];
3269       int BitI1 = Mask[i+1];
3270
3271       if (!isUndefOrEqual(BitI, j))
3272         return false;
3273       if (!isUndefOrEqual(BitI1, j))
3274         return false;
3275     }
3276   }
3277
3278   return true;
3279 }
3280
3281 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3282   SmallVector<int, 8> M;
3283   N->getMask(M);
3284   return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3285 }
3286
3287 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3288 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3289 /// <2, 2, 3, 3>
3290 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3291   int NumElems = VT.getVectorNumElements();
3292   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3293     return false;
3294
3295   for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3296     int BitI  = Mask[i];
3297     int BitI1 = Mask[i+1];
3298     if (!isUndefOrEqual(BitI, j))
3299       return false;
3300     if (!isUndefOrEqual(BitI1, j))
3301       return false;
3302   }
3303   return true;
3304 }
3305
3306 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3307   SmallVector<int, 8> M;
3308   N->getMask(M);
3309   return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3310 }
3311
3312 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3313 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3314 /// MOVSD, and MOVD, i.e. setting the lowest element.
3315 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3316   if (VT.getVectorElementType().getSizeInBits() < 32)
3317     return false;
3318
3319   int NumElts = VT.getVectorNumElements();
3320
3321   if (!isUndefOrEqual(Mask[0], NumElts))
3322     return false;
3323
3324   for (int i = 1; i < NumElts; ++i)
3325     if (!isUndefOrEqual(Mask[i], i))
3326       return false;
3327
3328   return true;
3329 }
3330
3331 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3332   SmallVector<int, 8> M;
3333   N->getMask(M);
3334   return ::isMOVLMask(M, N->getValueType(0));
3335 }
3336
3337 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3338 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3339 /// element of vector 2 and the other elements to come from vector 1 in order.
3340 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3341                                bool V2IsSplat = false, bool V2IsUndef = false) {
3342   int NumOps = VT.getVectorNumElements();
3343   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3344     return false;
3345
3346   if (!isUndefOrEqual(Mask[0], 0))
3347     return false;
3348
3349   for (int i = 1; i < NumOps; ++i)
3350     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3351           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3352           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3353       return false;
3354
3355   return true;
3356 }
3357
3358 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3359                            bool V2IsUndef = false) {
3360   SmallVector<int, 8> M;
3361   N->getMask(M);
3362   return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3363 }
3364
3365 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3366 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3367 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
3368   if (N->getValueType(0).getVectorNumElements() != 4)
3369     return false;
3370
3371   // Expect 1, 1, 3, 3
3372   for (unsigned i = 0; i < 2; ++i) {
3373     int Elt = N->getMaskElt(i);
3374     if (Elt >= 0 && Elt != 1)
3375       return false;
3376   }
3377
3378   bool HasHi = false;
3379   for (unsigned i = 2; i < 4; ++i) {
3380     int Elt = N->getMaskElt(i);
3381     if (Elt >= 0 && Elt != 3)
3382       return false;
3383     if (Elt == 3)
3384       HasHi = true;
3385   }
3386   // Don't use movshdup if it can be done with a shufps.
3387   // FIXME: verify that matching u, u, 3, 3 is what we want.
3388   return HasHi;
3389 }
3390
3391 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3392 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3393 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
3394   if (N->getValueType(0).getVectorNumElements() != 4)
3395     return false;
3396
3397   // Expect 0, 0, 2, 2
3398   for (unsigned i = 0; i < 2; ++i)
3399     if (N->getMaskElt(i) > 0)
3400       return false;
3401
3402   bool HasHi = false;
3403   for (unsigned i = 2; i < 4; ++i) {
3404     int Elt = N->getMaskElt(i);
3405     if (Elt >= 0 && Elt != 2)
3406       return false;
3407     if (Elt == 2)
3408       HasHi = true;
3409   }
3410   // Don't use movsldup if it can be done with a shufps.
3411   return HasHi;
3412 }
3413
3414 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3415 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3416 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3417   int e = N->getValueType(0).getVectorNumElements() / 2;
3418
3419   for (int i = 0; i < e; ++i)
3420     if (!isUndefOrEqual(N->getMaskElt(i), i))
3421       return false;
3422   for (int i = 0; i < e; ++i)
3423     if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3424       return false;
3425   return true;
3426 }
3427
3428 /// isVEXTRACTF128Index - Return true if the specified
3429 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3430 /// suitable for input to VEXTRACTF128.
3431 bool X86::isVEXTRACTF128Index(SDNode *N) {
3432   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3433     return false;
3434
3435   // The index should be aligned on a 128-bit boundary.
3436   uint64_t Index =
3437     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3438
3439   unsigned VL = N->getValueType(0).getVectorNumElements();
3440   unsigned VBits = N->getValueType(0).getSizeInBits();
3441   unsigned ElSize = VBits / VL;
3442   bool Result = (Index * ElSize) % 128 == 0;
3443
3444   return Result;
3445 }
3446
3447 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3448 /// operand specifies a subvector insert that is suitable for input to
3449 /// VINSERTF128.
3450 bool X86::isVINSERTF128Index(SDNode *N) {
3451   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3452     return false;
3453
3454   // The index should be aligned on a 128-bit boundary.
3455   uint64_t Index =
3456     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3457
3458   unsigned VL = N->getValueType(0).getVectorNumElements();
3459   unsigned VBits = N->getValueType(0).getSizeInBits();
3460   unsigned ElSize = VBits / VL;
3461   bool Result = (Index * ElSize) % 128 == 0;
3462
3463   return Result;
3464 }
3465
3466 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3467 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3468 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3469   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3470   int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3471
3472   unsigned Shift = (NumOperands == 4) ? 2 : 1;
3473   unsigned Mask = 0;
3474   for (int i = 0; i < NumOperands; ++i) {
3475     int Val = SVOp->getMaskElt(NumOperands-i-1);
3476     if (Val < 0) Val = 0;
3477     if (Val >= NumOperands) Val -= NumOperands;
3478     Mask |= Val;
3479     if (i != NumOperands - 1)
3480       Mask <<= Shift;
3481   }
3482   return Mask;
3483 }
3484
3485 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3486 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3487 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3488   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3489   unsigned Mask = 0;
3490   // 8 nodes, but we only care about the last 4.
3491   for (unsigned i = 7; i >= 4; --i) {
3492     int Val = SVOp->getMaskElt(i);
3493     if (Val >= 0)
3494       Mask |= (Val - 4);
3495     if (i != 4)
3496       Mask <<= 2;
3497   }
3498   return Mask;
3499 }
3500
3501 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3502 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3503 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3504   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3505   unsigned Mask = 0;
3506   // 8 nodes, but we only care about the first 4.
3507   for (int i = 3; i >= 0; --i) {
3508     int Val = SVOp->getMaskElt(i);
3509     if (Val >= 0)
3510       Mask |= Val;
3511     if (i != 0)
3512       Mask <<= 2;
3513   }
3514   return Mask;
3515 }
3516
3517 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3518 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3519 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3520   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3521   EVT VVT = N->getValueType(0);
3522   unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3523   int Val = 0;
3524
3525   unsigned i, e;
3526   for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3527     Val = SVOp->getMaskElt(i);
3528     if (Val >= 0)
3529       break;
3530   }
3531   return (Val - i) * EltSize;
3532 }
3533
3534 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
3535 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
3536 /// instructions.
3537 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
3538   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3539     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
3540
3541   uint64_t Index =
3542     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3543
3544   EVT VecVT = N->getOperand(0).getValueType();
3545   EVT ElVT = VecVT.getVectorElementType();
3546
3547   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3548
3549   return Index / NumElemsPerChunk;
3550 }
3551
3552 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
3553 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
3554 /// instructions.
3555 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
3556   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3557     llvm_unreachable("Illegal insert subvector for VINSERTF128");
3558
3559   uint64_t Index =
3560     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3561
3562   EVT VecVT = N->getValueType(0);
3563   EVT ElVT = VecVT.getVectorElementType();
3564
3565   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3566
3567   return Index / NumElemsPerChunk;
3568 }
3569
3570 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3571 /// constant +0.0.
3572 bool X86::isZeroNode(SDValue Elt) {
3573   return ((isa<ConstantSDNode>(Elt) &&
3574            cast<ConstantSDNode>(Elt)->isNullValue()) ||
3575           (isa<ConstantFPSDNode>(Elt) &&
3576            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3577 }
3578
3579 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3580 /// their permute mask.
3581 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3582                                     SelectionDAG &DAG) {
3583   EVT VT = SVOp->getValueType(0);
3584   unsigned NumElems = VT.getVectorNumElements();
3585   SmallVector<int, 8> MaskVec;
3586
3587   for (unsigned i = 0; i != NumElems; ++i) {
3588     int idx = SVOp->getMaskElt(i);
3589     if (idx < 0)
3590       MaskVec.push_back(idx);
3591     else if (idx < (int)NumElems)
3592       MaskVec.push_back(idx + NumElems);
3593     else
3594       MaskVec.push_back(idx - NumElems);
3595   }
3596   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3597                               SVOp->getOperand(0), &MaskVec[0]);
3598 }
3599
3600 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3601 /// the two vector operands have swapped position.
3602 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3603   unsigned NumElems = VT.getVectorNumElements();
3604   for (unsigned i = 0; i != NumElems; ++i) {
3605     int idx = Mask[i];
3606     if (idx < 0)
3607       continue;
3608     else if (idx < (int)NumElems)
3609       Mask[i] = idx + NumElems;
3610     else
3611       Mask[i] = idx - NumElems;
3612   }
3613 }
3614
3615 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3616 /// match movhlps. The lower half elements should come from upper half of
3617 /// V1 (and in order), and the upper half elements should come from the upper
3618 /// half of V2 (and in order).
3619 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3620   if (Op->getValueType(0).getVectorNumElements() != 4)
3621     return false;
3622   for (unsigned i = 0, e = 2; i != e; ++i)
3623     if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3624       return false;
3625   for (unsigned i = 2; i != 4; ++i)
3626     if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3627       return false;
3628   return true;
3629 }
3630
3631 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3632 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3633 /// required.
3634 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3635   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3636     return false;
3637   N = N->getOperand(0).getNode();
3638   if (!ISD::isNON_EXTLoad(N))
3639     return false;
3640   if (LD)
3641     *LD = cast<LoadSDNode>(N);
3642   return true;
3643 }
3644
3645 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3646 /// match movlp{s|d}. The lower half elements should come from lower half of
3647 /// V1 (and in order), and the upper half elements should come from the upper
3648 /// half of V2 (and in order). And since V1 will become the source of the
3649 /// MOVLP, it must be either a vector load or a scalar load to vector.
3650 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3651                                ShuffleVectorSDNode *Op) {
3652   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3653     return false;
3654   // Is V2 is a vector load, don't do this transformation. We will try to use
3655   // load folding shufps op.
3656   if (ISD::isNON_EXTLoad(V2))
3657     return false;
3658
3659   unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3660
3661   if (NumElems != 2 && NumElems != 4)
3662     return false;
3663   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3664     if (!isUndefOrEqual(Op->getMaskElt(i), i))
3665       return false;
3666   for (unsigned i = NumElems/2; i != NumElems; ++i)
3667     if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3668       return false;
3669   return true;
3670 }
3671
3672 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3673 /// all the same.
3674 static bool isSplatVector(SDNode *N) {
3675   if (N->getOpcode() != ISD::BUILD_VECTOR)
3676     return false;
3677
3678   SDValue SplatValue = N->getOperand(0);
3679   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3680     if (N->getOperand(i) != SplatValue)
3681       return false;
3682   return true;
3683 }
3684
3685 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3686 /// to an zero vector.
3687 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3688 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3689   SDValue V1 = N->getOperand(0);
3690   SDValue V2 = N->getOperand(1);
3691   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3692   for (unsigned i = 0; i != NumElems; ++i) {
3693     int Idx = N->getMaskElt(i);
3694     if (Idx >= (int)NumElems) {
3695       unsigned Opc = V2.getOpcode();
3696       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3697         continue;
3698       if (Opc != ISD::BUILD_VECTOR ||
3699           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3700         return false;
3701     } else if (Idx >= 0) {
3702       unsigned Opc = V1.getOpcode();
3703       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3704         continue;
3705       if (Opc != ISD::BUILD_VECTOR ||
3706           !X86::isZeroNode(V1.getOperand(Idx)))
3707         return false;
3708     }
3709   }
3710   return true;
3711 }
3712
3713 /// getZeroVector - Returns a vector of specified type with all zero elements.
3714 ///
3715 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3716                              DebugLoc dl) {
3717   assert(VT.isVector() && "Expected a vector type");
3718
3719   // Always build SSE zero vectors as <4 x i32> bitcasted
3720   // to their dest type. This ensures they get CSE'd.
3721   SDValue Vec;
3722   if (VT.getSizeInBits() == 128) {  // SSE
3723     if (HasSSE2) {  // SSE2
3724       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3725       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3726     } else { // SSE1
3727       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3728       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3729     }
3730   } else if (VT.getSizeInBits() == 256) { // AVX
3731     // 256-bit logic and arithmetic instructions in AVX are
3732     // all floating-point, no support for integer ops. Default
3733     // to emitting fp zeroed vectors then.
3734     SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3735     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3736     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
3737   }
3738   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3739 }
3740
3741 /// getOnesVector - Returns a vector of specified type with all bits set.
3742 ///
3743 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3744   assert(VT.isVector() && "Expected a vector type");
3745
3746   // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3747   // type.  This ensures they get CSE'd.
3748   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3749   SDValue Vec;
3750   Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3751   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3752 }
3753
3754
3755 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3756 /// that point to V2 points to its first element.
3757 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3758   EVT VT = SVOp->getValueType(0);
3759   unsigned NumElems = VT.getVectorNumElements();
3760
3761   bool Changed = false;
3762   SmallVector<int, 8> MaskVec;
3763   SVOp->getMask(MaskVec);
3764
3765   for (unsigned i = 0; i != NumElems; ++i) {
3766     if (MaskVec[i] > (int)NumElems) {
3767       MaskVec[i] = NumElems;
3768       Changed = true;
3769     }
3770   }
3771   if (Changed)
3772     return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3773                                 SVOp->getOperand(1), &MaskVec[0]);
3774   return SDValue(SVOp, 0);
3775 }
3776
3777 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3778 /// operation of specified width.
3779 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3780                        SDValue V2) {
3781   unsigned NumElems = VT.getVectorNumElements();
3782   SmallVector<int, 8> Mask;
3783   Mask.push_back(NumElems);
3784   for (unsigned i = 1; i != NumElems; ++i)
3785     Mask.push_back(i);
3786   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3787 }
3788
3789 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3790 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3791                           SDValue V2) {
3792   unsigned NumElems = VT.getVectorNumElements();
3793   SmallVector<int, 8> Mask;
3794   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3795     Mask.push_back(i);
3796     Mask.push_back(i + NumElems);
3797   }
3798   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3799 }
3800
3801 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3802 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3803                           SDValue V2) {
3804   unsigned NumElems = VT.getVectorNumElements();
3805   unsigned Half = NumElems/2;
3806   SmallVector<int, 8> Mask;
3807   for (unsigned i = 0; i != Half; ++i) {
3808     Mask.push_back(i + Half);
3809     Mask.push_back(i + NumElems + Half);
3810   }
3811   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3812 }
3813
3814 /// PromoteSplat - Promote a splat of v4i32, v8i16 or v16i8 to v4f32.
3815 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
3816   EVT PVT = MVT::v4f32;
3817   EVT VT = SV->getValueType(0);
3818   DebugLoc dl = SV->getDebugLoc();
3819   SDValue V1 = SV->getOperand(0);
3820   int NumElems = VT.getVectorNumElements();
3821   int EltNo = SV->getSplatIndex();
3822
3823   // unpack elements to the correct location
3824   while (NumElems > 4) {
3825     if (EltNo < NumElems/2) {
3826       V1 = getUnpackl(DAG, dl, VT, V1, V1);
3827     } else {
3828       V1 = getUnpackh(DAG, dl, VT, V1, V1);
3829       EltNo -= NumElems/2;
3830     }
3831     NumElems >>= 1;
3832   }
3833
3834   // Perform the splat.
3835   int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3836   V1 = DAG.getNode(ISD::BITCAST, dl, PVT, V1);
3837   V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3838   return DAG.getNode(ISD::BITCAST, dl, VT, V1);
3839 }
3840
3841 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3842 /// vector of zero or undef vector.  This produces a shuffle where the low
3843 /// element of V2 is swizzled into the zero/undef vector, landing at element
3844 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
3845 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3846                                              bool isZero, bool HasSSE2,
3847                                              SelectionDAG &DAG) {
3848   EVT VT = V2.getValueType();
3849   SDValue V1 = isZero
3850     ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3851   unsigned NumElems = VT.getVectorNumElements();
3852   SmallVector<int, 16> MaskVec;
3853   for (unsigned i = 0; i != NumElems; ++i)
3854     // If this is the insertion idx, put the low elt of V2 here.
3855     MaskVec.push_back(i == Idx ? NumElems : i);
3856   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3857 }
3858
3859 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
3860 /// element of the result of the vector shuffle.
3861 SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
3862                             unsigned Depth) {
3863   if (Depth == 6)
3864     return SDValue();  // Limit search depth.
3865
3866   SDValue V = SDValue(N, 0);
3867   EVT VT = V.getValueType();
3868   unsigned Opcode = V.getOpcode();
3869
3870   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
3871   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
3872     Index = SV->getMaskElt(Index);
3873
3874     if (Index < 0)
3875       return DAG.getUNDEF(VT.getVectorElementType());
3876
3877     int NumElems = VT.getVectorNumElements();
3878     SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
3879     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
3880   }
3881
3882   // Recurse into target specific vector shuffles to find scalars.
3883   if (isTargetShuffle(Opcode)) {
3884     int NumElems = VT.getVectorNumElements();
3885     SmallVector<unsigned, 16> ShuffleMask;
3886     SDValue ImmN;
3887
3888     switch(Opcode) {
3889     case X86ISD::SHUFPS:
3890     case X86ISD::SHUFPD:
3891       ImmN = N->getOperand(N->getNumOperands()-1);
3892       DecodeSHUFPSMask(NumElems,
3893                        cast<ConstantSDNode>(ImmN)->getZExtValue(),
3894                        ShuffleMask);
3895       break;
3896     case X86ISD::PUNPCKHBW:
3897     case X86ISD::PUNPCKHWD:
3898     case X86ISD::PUNPCKHDQ:
3899     case X86ISD::PUNPCKHQDQ:
3900       DecodePUNPCKHMask(NumElems, ShuffleMask);
3901       break;
3902     case X86ISD::UNPCKHPS:
3903     case X86ISD::UNPCKHPD:
3904       DecodeUNPCKHPMask(NumElems, ShuffleMask);
3905       break;
3906     case X86ISD::PUNPCKLBW:
3907     case X86ISD::PUNPCKLWD:
3908     case X86ISD::PUNPCKLDQ:
3909     case X86ISD::PUNPCKLQDQ:
3910       DecodePUNPCKLMask(VT, ShuffleMask);
3911       break;
3912     case X86ISD::UNPCKLPS:
3913     case X86ISD::UNPCKLPD:
3914     case X86ISD::VUNPCKLPS:
3915     case X86ISD::VUNPCKLPD:
3916     case X86ISD::VUNPCKLPSY:
3917     case X86ISD::VUNPCKLPDY:
3918       DecodeUNPCKLPMask(VT, ShuffleMask);
3919       break;
3920     case X86ISD::MOVHLPS:
3921       DecodeMOVHLPSMask(NumElems, ShuffleMask);
3922       break;
3923     case X86ISD::MOVLHPS:
3924       DecodeMOVLHPSMask(NumElems, ShuffleMask);
3925       break;
3926     case X86ISD::PSHUFD:
3927       ImmN = N->getOperand(N->getNumOperands()-1);
3928       DecodePSHUFMask(NumElems,
3929                       cast<ConstantSDNode>(ImmN)->getZExtValue(),
3930                       ShuffleMask);
3931       break;
3932     case X86ISD::PSHUFHW:
3933       ImmN = N->getOperand(N->getNumOperands()-1);
3934       DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
3935                         ShuffleMask);
3936       break;
3937     case X86ISD::PSHUFLW:
3938       ImmN = N->getOperand(N->getNumOperands()-1);
3939       DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
3940                         ShuffleMask);
3941       break;
3942     case X86ISD::MOVSS:
3943     case X86ISD::MOVSD: {
3944       // The index 0 always comes from the first element of the second source,
3945       // this is why MOVSS and MOVSD are used in the first place. The other
3946       // elements come from the other positions of the first source vector.
3947       unsigned OpNum = (Index == 0) ? 1 : 0;
3948       return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
3949                                  Depth+1);
3950     }
3951     default:
3952       assert("not implemented for target shuffle node");
3953       return SDValue();
3954     }
3955
3956     Index = ShuffleMask[Index];
3957     if (Index < 0)
3958       return DAG.getUNDEF(VT.getVectorElementType());
3959
3960     SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
3961     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
3962                                Depth+1);
3963   }
3964
3965   // Actual nodes that may contain scalar elements
3966   if (Opcode == ISD::BITCAST) {
3967     V = V.getOperand(0);
3968     EVT SrcVT = V.getValueType();
3969     unsigned NumElems = VT.getVectorNumElements();
3970
3971     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
3972       return SDValue();
3973   }
3974
3975   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
3976     return (Index == 0) ? V.getOperand(0)
3977                           : DAG.getUNDEF(VT.getVectorElementType());
3978
3979   if (V.getOpcode() == ISD::BUILD_VECTOR)
3980     return V.getOperand(Index);
3981
3982   return SDValue();
3983 }
3984
3985 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
3986 /// shuffle operation which come from a consecutively from a zero. The
3987 /// search can start in two diferent directions, from left or right.
3988 static
3989 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
3990                                   bool ZerosFromLeft, SelectionDAG &DAG) {
3991   int i = 0;
3992
3993   while (i < NumElems) {
3994     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
3995     SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
3996     if (!(Elt.getNode() &&
3997          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
3998       break;
3999     ++i;
4000   }
4001
4002   return i;
4003 }
4004
4005 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
4006 /// MaskE correspond consecutively to elements from one of the vector operands,
4007 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4008 static
4009 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
4010                               int OpIdx, int NumElems, unsigned &OpNum) {
4011   bool SeenV1 = false;
4012   bool SeenV2 = false;
4013
4014   for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
4015     int Idx = SVOp->getMaskElt(i);
4016     // Ignore undef indicies
4017     if (Idx < 0)
4018       continue;
4019
4020     if (Idx < NumElems)
4021       SeenV1 = true;
4022     else
4023       SeenV2 = true;
4024
4025     // Only accept consecutive elements from the same vector
4026     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4027       return false;
4028   }
4029
4030   OpNum = SeenV1 ? 0 : 1;
4031   return true;
4032 }
4033
4034 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4035 /// logical left shift of a vector.
4036 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4037                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4038   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4039   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4040               false /* check zeros from right */, DAG);
4041   unsigned OpSrc;
4042
4043   if (!NumZeros)
4044     return false;
4045
4046   // Considering the elements in the mask that are not consecutive zeros,
4047   // check if they consecutively come from only one of the source vectors.
4048   //
4049   //               V1 = {X, A, B, C}     0
4050   //                         \  \  \    /
4051   //   vector_shuffle V1, V2 <1, 2, 3, X>
4052   //
4053   if (!isShuffleMaskConsecutive(SVOp,
4054             0,                   // Mask Start Index
4055             NumElems-NumZeros-1, // Mask End Index
4056             NumZeros,            // Where to start looking in the src vector
4057             NumElems,            // Number of elements in vector
4058             OpSrc))              // Which source operand ?
4059     return false;
4060
4061   isLeft = false;
4062   ShAmt = NumZeros;
4063   ShVal = SVOp->getOperand(OpSrc);
4064   return true;
4065 }
4066
4067 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4068 /// logical left shift of a vector.
4069 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4070                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4071   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4072   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4073               true /* check zeros from left */, DAG);
4074   unsigned OpSrc;
4075
4076   if (!NumZeros)
4077     return false;
4078
4079   // Considering the elements in the mask that are not consecutive zeros,
4080   // check if they consecutively come from only one of the source vectors.
4081   //
4082   //                           0    { A, B, X, X } = V2
4083   //                          / \    /  /
4084   //   vector_shuffle V1, V2 <X, X, 4, 5>
4085   //
4086   if (!isShuffleMaskConsecutive(SVOp,
4087             NumZeros,     // Mask Start Index
4088             NumElems-1,   // Mask End Index
4089             0,            // Where to start looking in the src vector
4090             NumElems,     // Number of elements in vector
4091             OpSrc))       // Which source operand ?
4092     return false;
4093
4094   isLeft = true;
4095   ShAmt = NumZeros;
4096   ShVal = SVOp->getOperand(OpSrc);
4097   return true;
4098 }
4099
4100 /// isVectorShift - Returns true if the shuffle can be implemented as a
4101 /// logical left or right shift of a vector.
4102 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4103                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4104   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4105       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4106     return true;
4107
4108   return false;
4109 }
4110
4111 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4112 ///
4113 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4114                                        unsigned NumNonZero, unsigned NumZero,
4115                                        SelectionDAG &DAG,
4116                                        const TargetLowering &TLI) {
4117   if (NumNonZero > 8)
4118     return SDValue();
4119
4120   DebugLoc dl = Op.getDebugLoc();
4121   SDValue V(0, 0);
4122   bool First = true;
4123   for (unsigned i = 0; i < 16; ++i) {
4124     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4125     if (ThisIsNonZero && First) {
4126       if (NumZero)
4127         V = getZeroVector(MVT::v8i16, true, DAG, dl);
4128       else
4129         V = DAG.getUNDEF(MVT::v8i16);
4130       First = false;
4131     }
4132
4133     if ((i & 1) != 0) {
4134       SDValue ThisElt(0, 0), LastElt(0, 0);
4135       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4136       if (LastIsNonZero) {
4137         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4138                               MVT::i16, Op.getOperand(i-1));
4139       }
4140       if (ThisIsNonZero) {
4141         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4142         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4143                               ThisElt, DAG.getConstant(8, MVT::i8));
4144         if (LastIsNonZero)
4145           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4146       } else
4147         ThisElt = LastElt;
4148
4149       if (ThisElt.getNode())
4150         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4151                         DAG.getIntPtrConstant(i/2));
4152     }
4153   }
4154
4155   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4156 }
4157
4158 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4159 ///
4160 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4161                                      unsigned NumNonZero, unsigned NumZero,
4162                                      SelectionDAG &DAG,
4163                                      const TargetLowering &TLI) {
4164   if (NumNonZero > 4)
4165     return SDValue();
4166
4167   DebugLoc dl = Op.getDebugLoc();
4168   SDValue V(0, 0);
4169   bool First = true;
4170   for (unsigned i = 0; i < 8; ++i) {
4171     bool isNonZero = (NonZeros & (1 << i)) != 0;
4172     if (isNonZero) {
4173       if (First) {
4174         if (NumZero)
4175           V = getZeroVector(MVT::v8i16, true, DAG, dl);
4176         else
4177           V = DAG.getUNDEF(MVT::v8i16);
4178         First = false;
4179       }
4180       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4181                       MVT::v8i16, V, Op.getOperand(i),
4182                       DAG.getIntPtrConstant(i));
4183     }
4184   }
4185
4186   return V;
4187 }
4188
4189 /// getVShift - Return a vector logical shift node.
4190 ///
4191 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4192                          unsigned NumBits, SelectionDAG &DAG,
4193                          const TargetLowering &TLI, DebugLoc dl) {
4194   EVT ShVT = MVT::v2i64;
4195   unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
4196   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4197   return DAG.getNode(ISD::BITCAST, dl, VT,
4198                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4199                              DAG.getConstant(NumBits,
4200                                   TLI.getShiftAmountTy(SrcOp.getValueType()))));
4201 }
4202
4203 SDValue
4204 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4205                                           SelectionDAG &DAG) const {
4206
4207   // Check if the scalar load can be widened into a vector load. And if
4208   // the address is "base + cst" see if the cst can be "absorbed" into
4209   // the shuffle mask.
4210   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4211     SDValue Ptr = LD->getBasePtr();
4212     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4213       return SDValue();
4214     EVT PVT = LD->getValueType(0);
4215     if (PVT != MVT::i32 && PVT != MVT::f32)
4216       return SDValue();
4217
4218     int FI = -1;
4219     int64_t Offset = 0;
4220     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4221       FI = FINode->getIndex();
4222       Offset = 0;
4223     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4224                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4225       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4226       Offset = Ptr.getConstantOperandVal(1);
4227       Ptr = Ptr.getOperand(0);
4228     } else {
4229       return SDValue();
4230     }
4231
4232     SDValue Chain = LD->getChain();
4233     // Make sure the stack object alignment is at least 16.
4234     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4235     if (DAG.InferPtrAlignment(Ptr) < 16) {
4236       if (MFI->isFixedObjectIndex(FI)) {
4237         // Can't change the alignment. FIXME: It's possible to compute
4238         // the exact stack offset and reference FI + adjust offset instead.
4239         // If someone *really* cares about this. That's the way to implement it.
4240         return SDValue();
4241       } else {
4242         MFI->setObjectAlignment(FI, 16);
4243       }
4244     }
4245
4246     // (Offset % 16) must be multiple of 4. Then address is then
4247     // Ptr + (Offset & ~15).
4248     if (Offset < 0)
4249       return SDValue();
4250     if ((Offset % 16) & 3)
4251       return SDValue();
4252     int64_t StartOffset = Offset & ~15;
4253     if (StartOffset)
4254       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4255                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4256
4257     int EltNo = (Offset - StartOffset) >> 2;
4258     int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
4259     EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
4260     SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,
4261                              LD->getPointerInfo().getWithOffset(StartOffset),
4262                              false, false, 0);
4263     // Canonicalize it to a v4i32 shuffle.
4264     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
4265     return DAG.getNode(ISD::BITCAST, dl, VT,
4266                        DAG.getVectorShuffle(MVT::v4i32, dl, V1,
4267                                             DAG.getUNDEF(MVT::v4i32),&Mask[0]));
4268   }
4269
4270   return SDValue();
4271 }
4272
4273 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4274 /// vector of type 'VT', see if the elements can be replaced by a single large
4275 /// load which has the same value as a build_vector whose operands are 'elts'.
4276 ///
4277 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4278 ///
4279 /// FIXME: we'd also like to handle the case where the last elements are zero
4280 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4281 /// There's even a handy isZeroNode for that purpose.
4282 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4283                                         DebugLoc &DL, SelectionDAG &DAG) {
4284   EVT EltVT = VT.getVectorElementType();
4285   unsigned NumElems = Elts.size();
4286
4287   LoadSDNode *LDBase = NULL;
4288   unsigned LastLoadedElt = -1U;
4289
4290   // For each element in the initializer, see if we've found a load or an undef.
4291   // If we don't find an initial load element, or later load elements are
4292   // non-consecutive, bail out.
4293   for (unsigned i = 0; i < NumElems; ++i) {
4294     SDValue Elt = Elts[i];
4295
4296     if (!Elt.getNode() ||
4297         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4298       return SDValue();
4299     if (!LDBase) {
4300       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4301         return SDValue();
4302       LDBase = cast<LoadSDNode>(Elt.getNode());
4303       LastLoadedElt = i;
4304       continue;
4305     }
4306     if (Elt.getOpcode() == ISD::UNDEF)
4307       continue;
4308
4309     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4310     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4311       return SDValue();
4312     LastLoadedElt = i;
4313   }
4314
4315   // If we have found an entire vector of loads and undefs, then return a large
4316   // load of the entire vector width starting at the base pointer.  If we found
4317   // consecutive loads for the low half, generate a vzext_load node.
4318   if (LastLoadedElt == NumElems - 1) {
4319     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4320       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4321                          LDBase->getPointerInfo(),
4322                          LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
4323     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4324                        LDBase->getPointerInfo(),
4325                        LDBase->isVolatile(), LDBase->isNonTemporal(),
4326                        LDBase->getAlignment());
4327   } else if (NumElems == 4 && LastLoadedElt == 1) {
4328     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4329     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4330     SDValue ResNode = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys,
4331                                               Ops, 2, MVT::i32,
4332                                               LDBase->getMemOperand());
4333     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4334   }
4335   return SDValue();
4336 }
4337
4338 SDValue
4339 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
4340   DebugLoc dl = Op.getDebugLoc();
4341
4342   EVT VT = Op.getValueType();
4343   EVT ExtVT = VT.getVectorElementType();
4344
4345   unsigned NumElems = Op.getNumOperands();
4346
4347   // For AVX-length vectors, build the individual 128-bit pieces and
4348   // use shuffles to put them in place.
4349   if (VT.getSizeInBits() > 256 &&
4350       Subtarget->hasAVX() &&
4351       !ISD::isBuildVectorAllZeros(Op.getNode())) {
4352     SmallVector<SDValue, 8> V;
4353     V.resize(NumElems);
4354     for (unsigned i = 0; i < NumElems; ++i) {
4355       V[i] = Op.getOperand(i);
4356     }
4357
4358     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
4359
4360     // Build the lower subvector.
4361     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
4362     // Build the upper subvector.
4363     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
4364                                 NumElems/2);
4365
4366     return ConcatVectors(Lower, Upper, DAG);
4367   }
4368
4369   // All zero's are handled with pxor in SSE2 and above, xorps in SSE1.
4370   // All one's are handled with pcmpeqd. In AVX, zero's are handled with
4371   // vpxor in 128-bit and xor{pd,ps} in 256-bit, but no 256 version of pcmpeqd
4372   // is present, so AllOnes is ignored.
4373   if (ISD::isBuildVectorAllZeros(Op.getNode()) ||
4374       (Op.getValueType().getSizeInBits() != 256 &&
4375        ISD::isBuildVectorAllOnes(Op.getNode()))) {
4376     // Canonicalize this to <4 x i32> (SSE) to
4377     // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
4378     // eliminated on x86-32 hosts.
4379     if (Op.getValueType() == MVT::v4i32)
4380       return Op;
4381
4382     if (ISD::isBuildVectorAllOnes(Op.getNode()))
4383       return getOnesVector(Op.getValueType(), DAG, dl);
4384     return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
4385   }
4386
4387   unsigned EVTBits = ExtVT.getSizeInBits();
4388
4389   unsigned NumZero  = 0;
4390   unsigned NumNonZero = 0;
4391   unsigned NonZeros = 0;
4392   bool IsAllConstants = true;
4393   SmallSet<SDValue, 8> Values;
4394   for (unsigned i = 0; i < NumElems; ++i) {
4395     SDValue Elt = Op.getOperand(i);
4396     if (Elt.getOpcode() == ISD::UNDEF)
4397       continue;
4398     Values.insert(Elt);
4399     if (Elt.getOpcode() != ISD::Constant &&
4400         Elt.getOpcode() != ISD::ConstantFP)
4401       IsAllConstants = false;
4402     if (X86::isZeroNode(Elt))
4403       NumZero++;
4404     else {
4405       NonZeros |= (1 << i);
4406       NumNonZero++;
4407     }
4408   }
4409
4410   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
4411   if (NumNonZero == 0)
4412     return DAG.getUNDEF(VT);
4413
4414   // Special case for single non-zero, non-undef, element.
4415   if (NumNonZero == 1) {
4416     unsigned Idx = CountTrailingZeros_32(NonZeros);
4417     SDValue Item = Op.getOperand(Idx);
4418
4419     // If this is an insertion of an i64 value on x86-32, and if the top bits of
4420     // the value are obviously zero, truncate the value to i32 and do the
4421     // insertion that way.  Only do this if the value is non-constant or if the
4422     // value is a constant being inserted into element 0.  It is cheaper to do
4423     // a constant pool load than it is to do a movd + shuffle.
4424     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
4425         (!IsAllConstants || Idx == 0)) {
4426       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
4427         // Handle SSE only.
4428         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
4429         EVT VecVT = MVT::v4i32;
4430         unsigned VecElts = 4;
4431
4432         // Truncate the value (which may itself be a constant) to i32, and
4433         // convert it to a vector with movd (S2V+shuffle to zero extend).
4434         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
4435         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
4436         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4437                                            Subtarget->hasSSE2(), DAG);
4438
4439         // Now we have our 32-bit value zero extended in the low element of
4440         // a vector.  If Idx != 0, swizzle it into place.
4441         if (Idx != 0) {
4442           SmallVector<int, 4> Mask;
4443           Mask.push_back(Idx);
4444           for (unsigned i = 1; i != VecElts; ++i)
4445             Mask.push_back(i);
4446           Item = DAG.getVectorShuffle(VecVT, dl, Item,
4447                                       DAG.getUNDEF(Item.getValueType()),
4448                                       &Mask[0]);
4449         }
4450         return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
4451       }
4452     }
4453
4454     // If we have a constant or non-constant insertion into the low element of
4455     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
4456     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
4457     // depending on what the source datatype is.
4458     if (Idx == 0) {
4459       if (NumZero == 0) {
4460         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4461       } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
4462           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
4463         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4464         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
4465         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
4466                                            DAG);
4467       } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
4468         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
4469         assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
4470         EVT MiddleVT = MVT::v4i32;
4471         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
4472         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4473                                            Subtarget->hasSSE2(), DAG);
4474         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
4475       }
4476     }
4477
4478     // Is it a vector logical left shift?
4479     if (NumElems == 2 && Idx == 1 &&
4480         X86::isZeroNode(Op.getOperand(0)) &&
4481         !X86::isZeroNode(Op.getOperand(1))) {
4482       unsigned NumBits = VT.getSizeInBits();
4483       return getVShift(true, VT,
4484                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4485                                    VT, Op.getOperand(1)),
4486                        NumBits/2, DAG, *this, dl);
4487     }
4488
4489     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
4490       return SDValue();
4491
4492     // Otherwise, if this is a vector with i32 or f32 elements, and the element
4493     // is a non-constant being inserted into an element other than the low one,
4494     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
4495     // movd/movss) to move this into the low element, then shuffle it into
4496     // place.
4497     if (EVTBits == 32) {
4498       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4499
4500       // Turn it into a shuffle of zero and zero-extended scalar to vector.
4501       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
4502                                          Subtarget->hasSSE2(), DAG);
4503       SmallVector<int, 8> MaskVec;
4504       for (unsigned i = 0; i < NumElems; i++)
4505         MaskVec.push_back(i == Idx ? 0 : 1);
4506       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
4507     }
4508   }
4509
4510   // Splat is obviously ok. Let legalizer expand it to a shuffle.
4511   if (Values.size() == 1) {
4512     if (EVTBits == 32) {
4513       // Instead of a shuffle like this:
4514       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
4515       // Check if it's possible to issue this instead.
4516       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
4517       unsigned Idx = CountTrailingZeros_32(NonZeros);
4518       SDValue Item = Op.getOperand(Idx);
4519       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
4520         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
4521     }
4522     return SDValue();
4523   }
4524
4525   // A vector full of immediates; various special cases are already
4526   // handled, so this is best done with a single constant-pool load.
4527   if (IsAllConstants)
4528     return SDValue();
4529
4530   // Let legalizer expand 2-wide build_vectors.
4531   if (EVTBits == 64) {
4532     if (NumNonZero == 1) {
4533       // One half is zero or undef.
4534       unsigned Idx = CountTrailingZeros_32(NonZeros);
4535       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
4536                                  Op.getOperand(Idx));
4537       return getShuffleVectorZeroOrUndef(V2, Idx, true,
4538                                          Subtarget->hasSSE2(), DAG);
4539     }
4540     return SDValue();
4541   }
4542
4543   // If element VT is < 32 bits, convert it to inserts into a zero vector.
4544   if (EVTBits == 8 && NumElems == 16) {
4545     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
4546                                         *this);
4547     if (V.getNode()) return V;
4548   }
4549
4550   if (EVTBits == 16 && NumElems == 8) {
4551     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
4552                                       *this);
4553     if (V.getNode()) return V;
4554   }
4555
4556   // If element VT is == 32 bits, turn it into a number of shuffles.
4557   SmallVector<SDValue, 8> V;
4558   V.resize(NumElems);
4559   if (NumElems == 4 && NumZero > 0) {
4560     for (unsigned i = 0; i < 4; ++i) {
4561       bool isZero = !(NonZeros & (1 << i));
4562       if (isZero)
4563         V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4564       else
4565         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4566     }
4567
4568     for (unsigned i = 0; i < 2; ++i) {
4569       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
4570         default: break;
4571         case 0:
4572           V[i] = V[i*2];  // Must be a zero vector.
4573           break;
4574         case 1:
4575           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
4576           break;
4577         case 2:
4578           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
4579           break;
4580         case 3:
4581           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
4582           break;
4583       }
4584     }
4585
4586     SmallVector<int, 8> MaskVec;
4587     bool Reverse = (NonZeros & 0x3) == 2;
4588     for (unsigned i = 0; i < 2; ++i)
4589       MaskVec.push_back(Reverse ? 1-i : i);
4590     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
4591     for (unsigned i = 0; i < 2; ++i)
4592       MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
4593     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
4594   }
4595
4596   if (Values.size() > 1 && VT.getSizeInBits() == 128) {
4597     // Check for a build vector of consecutive loads.
4598     for (unsigned i = 0; i < NumElems; ++i)
4599       V[i] = Op.getOperand(i);
4600
4601     // Check for elements which are consecutive loads.
4602     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
4603     if (LD.getNode())
4604       return LD;
4605
4606     // For SSE 4.1, use insertps to put the high elements into the low element.
4607     if (getSubtarget()->hasSSE41()) {
4608       SDValue Result;
4609       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
4610         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
4611       else
4612         Result = DAG.getUNDEF(VT);
4613
4614       for (unsigned i = 1; i < NumElems; ++i) {
4615         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
4616         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
4617                              Op.getOperand(i), DAG.getIntPtrConstant(i));
4618       }
4619       return Result;
4620     }
4621
4622     // Otherwise, expand into a number of unpckl*, start by extending each of
4623     // our (non-undef) elements to the full vector width with the element in the
4624     // bottom slot of the vector (which generates no code for SSE).
4625     for (unsigned i = 0; i < NumElems; ++i) {
4626       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
4627         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4628       else
4629         V[i] = DAG.getUNDEF(VT);
4630     }
4631
4632     // Next, we iteratively mix elements, e.g. for v4f32:
4633     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
4634     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
4635     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
4636     unsigned EltStride = NumElems >> 1;
4637     while (EltStride != 0) {
4638       for (unsigned i = 0; i < EltStride; ++i) {
4639         // If V[i+EltStride] is undef and this is the first round of mixing,
4640         // then it is safe to just drop this shuffle: V[i] is already in the
4641         // right place, the one element (since it's the first round) being
4642         // inserted as undef can be dropped.  This isn't safe for successive
4643         // rounds because they will permute elements within both vectors.
4644         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
4645             EltStride == NumElems/2)
4646           continue;
4647
4648         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
4649       }
4650       EltStride >>= 1;
4651     }
4652     return V[0];
4653   }
4654   return SDValue();
4655 }
4656
4657 SDValue
4658 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
4659   // We support concatenate two MMX registers and place them in a MMX
4660   // register.  This is better than doing a stack convert.
4661   DebugLoc dl = Op.getDebugLoc();
4662   EVT ResVT = Op.getValueType();
4663   assert(Op.getNumOperands() == 2);
4664   assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
4665          ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
4666   int Mask[2];
4667   SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
4668   SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4669   InVec = Op.getOperand(1);
4670   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4671     unsigned NumElts = ResVT.getVectorNumElements();
4672     VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4673     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
4674                        InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
4675   } else {
4676     InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
4677     SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4678     Mask[0] = 0; Mask[1] = 2;
4679     VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
4680   }
4681   return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4682 }
4683
4684 // v8i16 shuffles - Prefer shuffles in the following order:
4685 // 1. [all]   pshuflw, pshufhw, optional move
4686 // 2. [ssse3] 1 x pshufb
4687 // 3. [ssse3] 2 x pshufb + 1 x por
4688 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
4689 SDValue
4690 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
4691                                             SelectionDAG &DAG) const {
4692   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4693   SDValue V1 = SVOp->getOperand(0);
4694   SDValue V2 = SVOp->getOperand(1);
4695   DebugLoc dl = SVOp->getDebugLoc();
4696   SmallVector<int, 8> MaskVals;
4697
4698   // Determine if more than 1 of the words in each of the low and high quadwords
4699   // of the result come from the same quadword of one of the two inputs.  Undef
4700   // mask values count as coming from any quadword, for better codegen.
4701   SmallVector<unsigned, 4> LoQuad(4);
4702   SmallVector<unsigned, 4> HiQuad(4);
4703   BitVector InputQuads(4);
4704   for (unsigned i = 0; i < 8; ++i) {
4705     SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
4706     int EltIdx = SVOp->getMaskElt(i);
4707     MaskVals.push_back(EltIdx);
4708     if (EltIdx < 0) {
4709       ++Quad[0];
4710       ++Quad[1];
4711       ++Quad[2];
4712       ++Quad[3];
4713       continue;
4714     }
4715     ++Quad[EltIdx / 4];
4716     InputQuads.set(EltIdx / 4);
4717   }
4718
4719   int BestLoQuad = -1;
4720   unsigned MaxQuad = 1;
4721   for (unsigned i = 0; i < 4; ++i) {
4722     if (LoQuad[i] > MaxQuad) {
4723       BestLoQuad = i;
4724       MaxQuad = LoQuad[i];
4725     }
4726   }
4727
4728   int BestHiQuad = -1;
4729   MaxQuad = 1;
4730   for (unsigned i = 0; i < 4; ++i) {
4731     if (HiQuad[i] > MaxQuad) {
4732       BestHiQuad = i;
4733       MaxQuad = HiQuad[i];
4734     }
4735   }
4736
4737   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
4738   // of the two input vectors, shuffle them into one input vector so only a
4739   // single pshufb instruction is necessary. If There are more than 2 input
4740   // quads, disable the next transformation since it does not help SSSE3.
4741   bool V1Used = InputQuads[0] || InputQuads[1];
4742   bool V2Used = InputQuads[2] || InputQuads[3];
4743   if (Subtarget->hasSSSE3()) {
4744     if (InputQuads.count() == 2 && V1Used && V2Used) {
4745       BestLoQuad = InputQuads.find_first();
4746       BestHiQuad = InputQuads.find_next(BestLoQuad);
4747     }
4748     if (InputQuads.count() > 2) {
4749       BestLoQuad = -1;
4750       BestHiQuad = -1;
4751     }
4752   }
4753
4754   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
4755   // the shuffle mask.  If a quad is scored as -1, that means that it contains
4756   // words from all 4 input quadwords.
4757   SDValue NewV;
4758   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
4759     SmallVector<int, 8> MaskV;
4760     MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
4761     MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
4762     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
4763                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
4764                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
4765     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
4766
4767     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
4768     // source words for the shuffle, to aid later transformations.
4769     bool AllWordsInNewV = true;
4770     bool InOrder[2] = { true, true };
4771     for (unsigned i = 0; i != 8; ++i) {
4772       int idx = MaskVals[i];
4773       if (idx != (int)i)
4774         InOrder[i/4] = false;
4775       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
4776         continue;
4777       AllWordsInNewV = false;
4778       break;
4779     }
4780
4781     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
4782     if (AllWordsInNewV) {
4783       for (int i = 0; i != 8; ++i) {
4784         int idx = MaskVals[i];
4785         if (idx < 0)
4786           continue;
4787         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
4788         if ((idx != i) && idx < 4)
4789           pshufhw = false;
4790         if ((idx != i) && idx > 3)
4791           pshuflw = false;
4792       }
4793       V1 = NewV;
4794       V2Used = false;
4795       BestLoQuad = 0;
4796       BestHiQuad = 1;
4797     }
4798
4799     // If we've eliminated the use of V2, and the new mask is a pshuflw or
4800     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
4801     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
4802       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
4803       unsigned TargetMask = 0;
4804       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
4805                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
4806       TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
4807                              X86::getShufflePSHUFLWImmediate(NewV.getNode());
4808       V1 = NewV.getOperand(0);
4809       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
4810     }
4811   }
4812
4813   // If we have SSSE3, and all words of the result are from 1 input vector,
4814   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
4815   // is present, fall back to case 4.
4816   if (Subtarget->hasSSSE3()) {
4817     SmallVector<SDValue,16> pshufbMask;
4818
4819     // If we have elements from both input vectors, set the high bit of the
4820     // shuffle mask element to zero out elements that come from V2 in the V1
4821     // mask, and elements that come from V1 in the V2 mask, so that the two
4822     // results can be OR'd together.
4823     bool TwoInputs = V1Used && V2Used;
4824     for (unsigned i = 0; i != 8; ++i) {
4825       int EltIdx = MaskVals[i] * 2;
4826       if (TwoInputs && (EltIdx >= 16)) {
4827         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4828         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4829         continue;
4830       }
4831       pshufbMask.push_back(DAG.getConstant(EltIdx,   MVT::i8));
4832       pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
4833     }
4834     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
4835     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4836                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4837                                  MVT::v16i8, &pshufbMask[0], 16));
4838     if (!TwoInputs)
4839       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4840
4841     // Calculate the shuffle mask for the second input, shuffle it, and
4842     // OR it with the first shuffled input.
4843     pshufbMask.clear();
4844     for (unsigned i = 0; i != 8; ++i) {
4845       int EltIdx = MaskVals[i] * 2;
4846       if (EltIdx < 16) {
4847         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4848         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4849         continue;
4850       }
4851       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4852       pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
4853     }
4854     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
4855     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4856                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4857                                  MVT::v16i8, &pshufbMask[0], 16));
4858     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4859     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4860   }
4861
4862   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
4863   // and update MaskVals with new element order.
4864   BitVector InOrder(8);
4865   if (BestLoQuad >= 0) {
4866     SmallVector<int, 8> MaskV;
4867     for (int i = 0; i != 4; ++i) {
4868       int idx = MaskVals[i];
4869       if (idx < 0) {
4870         MaskV.push_back(-1);
4871         InOrder.set(i);
4872       } else if ((idx / 4) == BestLoQuad) {
4873         MaskV.push_back(idx & 3);
4874         InOrder.set(i);
4875       } else {
4876         MaskV.push_back(-1);
4877       }
4878     }
4879     for (unsigned i = 4; i != 8; ++i)
4880       MaskV.push_back(i);
4881     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4882                                 &MaskV[0]);
4883
4884     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4885       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
4886                                NewV.getOperand(0),
4887                                X86::getShufflePSHUFLWImmediate(NewV.getNode()),
4888                                DAG);
4889   }
4890
4891   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
4892   // and update MaskVals with the new element order.
4893   if (BestHiQuad >= 0) {
4894     SmallVector<int, 8> MaskV;
4895     for (unsigned i = 0; i != 4; ++i)
4896       MaskV.push_back(i);
4897     for (unsigned i = 4; i != 8; ++i) {
4898       int idx = MaskVals[i];
4899       if (idx < 0) {
4900         MaskV.push_back(-1);
4901         InOrder.set(i);
4902       } else if ((idx / 4) == BestHiQuad) {
4903         MaskV.push_back((idx & 3) + 4);
4904         InOrder.set(i);
4905       } else {
4906         MaskV.push_back(-1);
4907       }
4908     }
4909     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4910                                 &MaskV[0]);
4911
4912     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4913       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
4914                               NewV.getOperand(0),
4915                               X86::getShufflePSHUFHWImmediate(NewV.getNode()),
4916                               DAG);
4917   }
4918
4919   // In case BestHi & BestLo were both -1, which means each quadword has a word
4920   // from each of the four input quadwords, calculate the InOrder bitvector now
4921   // before falling through to the insert/extract cleanup.
4922   if (BestLoQuad == -1 && BestHiQuad == -1) {
4923     NewV = V1;
4924     for (int i = 0; i != 8; ++i)
4925       if (MaskVals[i] < 0 || MaskVals[i] == i)
4926         InOrder.set(i);
4927   }
4928
4929   // The other elements are put in the right place using pextrw and pinsrw.
4930   for (unsigned i = 0; i != 8; ++i) {
4931     if (InOrder[i])
4932       continue;
4933     int EltIdx = MaskVals[i];
4934     if (EltIdx < 0)
4935       continue;
4936     SDValue ExtOp = (EltIdx < 8)
4937     ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
4938                   DAG.getIntPtrConstant(EltIdx))
4939     : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
4940                   DAG.getIntPtrConstant(EltIdx - 8));
4941     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
4942                        DAG.getIntPtrConstant(i));
4943   }
4944   return NewV;
4945 }
4946
4947 // v16i8 shuffles - Prefer shuffles in the following order:
4948 // 1. [ssse3] 1 x pshufb
4949 // 2. [ssse3] 2 x pshufb + 1 x por
4950 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
4951 static
4952 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
4953                                  SelectionDAG &DAG,
4954                                  const X86TargetLowering &TLI) {
4955   SDValue V1 = SVOp->getOperand(0);
4956   SDValue V2 = SVOp->getOperand(1);
4957   DebugLoc dl = SVOp->getDebugLoc();
4958   SmallVector<int, 16> MaskVals;
4959   SVOp->getMask(MaskVals);
4960
4961   // If we have SSSE3, case 1 is generated when all result bytes come from
4962   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
4963   // present, fall back to case 3.
4964   // FIXME: kill V2Only once shuffles are canonizalized by getNode.
4965   bool V1Only = true;
4966   bool V2Only = true;
4967   for (unsigned i = 0; i < 16; ++i) {
4968     int EltIdx = MaskVals[i];
4969     if (EltIdx < 0)
4970       continue;
4971     if (EltIdx < 16)
4972       V2Only = false;
4973     else
4974       V1Only = false;
4975   }
4976
4977   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
4978   if (TLI.getSubtarget()->hasSSSE3()) {
4979     SmallVector<SDValue,16> pshufbMask;
4980
4981     // If all result elements are from one input vector, then only translate
4982     // undef mask values to 0x80 (zero out result) in the pshufb mask.
4983     //
4984     // Otherwise, we have elements from both input vectors, and must zero out
4985     // elements that come from V2 in the first mask, and V1 in the second mask
4986     // so that we can OR them together.
4987     bool TwoInputs = !(V1Only || V2Only);
4988     for (unsigned i = 0; i != 16; ++i) {
4989       int EltIdx = MaskVals[i];
4990       if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
4991         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4992         continue;
4993       }
4994       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4995     }
4996     // If all the elements are from V2, assign it to V1 and return after
4997     // building the first pshufb.
4998     if (V2Only)
4999       V1 = V2;
5000     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5001                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5002                                  MVT::v16i8, &pshufbMask[0], 16));
5003     if (!TwoInputs)
5004       return V1;
5005
5006     // Calculate the shuffle mask for the second input, shuffle it, and
5007     // OR it with the first shuffled input.
5008     pshufbMask.clear();
5009     for (unsigned i = 0; i != 16; ++i) {
5010       int EltIdx = MaskVals[i];
5011       if (EltIdx < 16) {
5012         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5013         continue;
5014       }
5015       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5016     }
5017     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5018                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5019                                  MVT::v16i8, &pshufbMask[0], 16));
5020     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5021   }
5022
5023   // No SSSE3 - Calculate in place words and then fix all out of place words
5024   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
5025   // the 16 different words that comprise the two doublequadword input vectors.
5026   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5027   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5028   SDValue NewV = V2Only ? V2 : V1;
5029   for (int i = 0; i != 8; ++i) {
5030     int Elt0 = MaskVals[i*2];
5031     int Elt1 = MaskVals[i*2+1];
5032
5033     // This word of the result is all undef, skip it.
5034     if (Elt0 < 0 && Elt1 < 0)
5035       continue;
5036
5037     // This word of the result is already in the correct place, skip it.
5038     if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
5039       continue;
5040     if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
5041       continue;
5042
5043     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5044     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5045     SDValue InsElt;
5046
5047     // If Elt0 and Elt1 are defined, are consecutive, and can be load
5048     // using a single extract together, load it and store it.
5049     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5050       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5051                            DAG.getIntPtrConstant(Elt1 / 2));
5052       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5053                         DAG.getIntPtrConstant(i));
5054       continue;
5055     }
5056
5057     // If Elt1 is defined, extract it from the appropriate source.  If the
5058     // source byte is not also odd, shift the extracted word left 8 bits
5059     // otherwise clear the bottom 8 bits if we need to do an or.
5060     if (Elt1 >= 0) {
5061       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5062                            DAG.getIntPtrConstant(Elt1 / 2));
5063       if ((Elt1 & 1) == 0)
5064         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5065                              DAG.getConstant(8,
5066                                   TLI.getShiftAmountTy(InsElt.getValueType())));
5067       else if (Elt0 >= 0)
5068         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5069                              DAG.getConstant(0xFF00, MVT::i16));
5070     }
5071     // If Elt0 is defined, extract it from the appropriate source.  If the
5072     // source byte is not also even, shift the extracted word right 8 bits. If
5073     // Elt1 was also defined, OR the extracted values together before
5074     // inserting them in the result.
5075     if (Elt0 >= 0) {
5076       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5077                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5078       if ((Elt0 & 1) != 0)
5079         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5080                               DAG.getConstant(8,
5081                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
5082       else if (Elt1 >= 0)
5083         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5084                              DAG.getConstant(0x00FF, MVT::i16));
5085       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5086                          : InsElt0;
5087     }
5088     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5089                        DAG.getIntPtrConstant(i));
5090   }
5091   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5092 }
5093
5094 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5095 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5096 /// done when every pair / quad of shuffle mask elements point to elements in
5097 /// the right sequence. e.g.
5098 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5099 static
5100 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5101                                  SelectionDAG &DAG, DebugLoc dl) {
5102   EVT VT = SVOp->getValueType(0);
5103   SDValue V1 = SVOp->getOperand(0);
5104   SDValue V2 = SVOp->getOperand(1);
5105   unsigned NumElems = VT.getVectorNumElements();
5106   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
5107   EVT NewVT;
5108   switch (VT.getSimpleVT().SimpleTy) {
5109   default: assert(false && "Unexpected!");
5110   case MVT::v4f32: NewVT = MVT::v2f64; break;
5111   case MVT::v4i32: NewVT = MVT::v2i64; break;
5112   case MVT::v8i16: NewVT = MVT::v4i32; break;
5113   case MVT::v16i8: NewVT = MVT::v4i32; break;
5114   }
5115
5116   int Scale = NumElems / NewWidth;
5117   SmallVector<int, 8> MaskVec;
5118   for (unsigned i = 0; i < NumElems; i += Scale) {
5119     int StartIdx = -1;
5120     for (int j = 0; j < Scale; ++j) {
5121       int EltIdx = SVOp->getMaskElt(i+j);
5122       if (EltIdx < 0)
5123         continue;
5124       if (StartIdx == -1)
5125         StartIdx = EltIdx - (EltIdx % Scale);
5126       if (EltIdx != StartIdx + j)
5127         return SDValue();
5128     }
5129     if (StartIdx == -1)
5130       MaskVec.push_back(-1);
5131     else
5132       MaskVec.push_back(StartIdx / Scale);
5133   }
5134
5135   V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
5136   V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
5137   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5138 }
5139
5140 /// getVZextMovL - Return a zero-extending vector move low node.
5141 ///
5142 static SDValue getVZextMovL(EVT VT, EVT OpVT,
5143                             SDValue SrcOp, SelectionDAG &DAG,
5144                             const X86Subtarget *Subtarget, DebugLoc dl) {
5145   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
5146     LoadSDNode *LD = NULL;
5147     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
5148       LD = dyn_cast<LoadSDNode>(SrcOp);
5149     if (!LD) {
5150       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
5151       // instead.
5152       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
5153       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
5154           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5155           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
5156           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
5157         // PR2108
5158         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
5159         return DAG.getNode(ISD::BITCAST, dl, VT,
5160                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5161                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5162                                                    OpVT,
5163                                                    SrcOp.getOperand(0)
5164                                                           .getOperand(0))));
5165       }
5166     }
5167   }
5168
5169   return DAG.getNode(ISD::BITCAST, dl, VT,
5170                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5171                                  DAG.getNode(ISD::BITCAST, dl,
5172                                              OpVT, SrcOp)));
5173 }
5174
5175 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
5176 /// shuffles.
5177 static SDValue
5178 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5179   SDValue V1 = SVOp->getOperand(0);
5180   SDValue V2 = SVOp->getOperand(1);
5181   DebugLoc dl = SVOp->getDebugLoc();
5182   EVT VT = SVOp->getValueType(0);
5183
5184   SmallVector<std::pair<int, int>, 8> Locs;
5185   Locs.resize(4);
5186   SmallVector<int, 8> Mask1(4U, -1);
5187   SmallVector<int, 8> PermMask;
5188   SVOp->getMask(PermMask);
5189
5190   unsigned NumHi = 0;
5191   unsigned NumLo = 0;
5192   for (unsigned i = 0; i != 4; ++i) {
5193     int Idx = PermMask[i];
5194     if (Idx < 0) {
5195       Locs[i] = std::make_pair(-1, -1);
5196     } else {
5197       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
5198       if (Idx < 4) {
5199         Locs[i] = std::make_pair(0, NumLo);
5200         Mask1[NumLo] = Idx;
5201         NumLo++;
5202       } else {
5203         Locs[i] = std::make_pair(1, NumHi);
5204         if (2+NumHi < 4)
5205           Mask1[2+NumHi] = Idx;
5206         NumHi++;
5207       }
5208     }
5209   }
5210
5211   if (NumLo <= 2 && NumHi <= 2) {
5212     // If no more than two elements come from either vector. This can be
5213     // implemented with two shuffles. First shuffle gather the elements.
5214     // The second shuffle, which takes the first shuffle as both of its
5215     // vector operands, put the elements into the right order.
5216     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5217
5218     SmallVector<int, 8> Mask2(4U, -1);
5219
5220     for (unsigned i = 0; i != 4; ++i) {
5221       if (Locs[i].first == -1)
5222         continue;
5223       else {
5224         unsigned Idx = (i < 2) ? 0 : 4;
5225         Idx += Locs[i].first * 2 + Locs[i].second;
5226         Mask2[i] = Idx;
5227       }
5228     }
5229
5230     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
5231   } else if (NumLo == 3 || NumHi == 3) {
5232     // Otherwise, we must have three elements from one vector, call it X, and
5233     // one element from the other, call it Y.  First, use a shufps to build an
5234     // intermediate vector with the one element from Y and the element from X
5235     // that will be in the same half in the final destination (the indexes don't
5236     // matter). Then, use a shufps to build the final vector, taking the half
5237     // containing the element from Y from the intermediate, and the other half
5238     // from X.
5239     if (NumHi == 3) {
5240       // Normalize it so the 3 elements come from V1.
5241       CommuteVectorShuffleMask(PermMask, VT);
5242       std::swap(V1, V2);
5243     }
5244
5245     // Find the element from V2.
5246     unsigned HiIndex;
5247     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
5248       int Val = PermMask[HiIndex];
5249       if (Val < 0)
5250         continue;
5251       if (Val >= 4)
5252         break;
5253     }
5254
5255     Mask1[0] = PermMask[HiIndex];
5256     Mask1[1] = -1;
5257     Mask1[2] = PermMask[HiIndex^1];
5258     Mask1[3] = -1;
5259     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5260
5261     if (HiIndex >= 2) {
5262       Mask1[0] = PermMask[0];
5263       Mask1[1] = PermMask[1];
5264       Mask1[2] = HiIndex & 1 ? 6 : 4;
5265       Mask1[3] = HiIndex & 1 ? 4 : 6;
5266       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5267     } else {
5268       Mask1[0] = HiIndex & 1 ? 2 : 0;
5269       Mask1[1] = HiIndex & 1 ? 0 : 2;
5270       Mask1[2] = PermMask[2];
5271       Mask1[3] = PermMask[3];
5272       if (Mask1[2] >= 0)
5273         Mask1[2] += 4;
5274       if (Mask1[3] >= 0)
5275         Mask1[3] += 4;
5276       return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
5277     }
5278   }
5279
5280   // Break it into (shuffle shuffle_hi, shuffle_lo).
5281   Locs.clear();
5282   Locs.resize(4);
5283   SmallVector<int,8> LoMask(4U, -1);
5284   SmallVector<int,8> HiMask(4U, -1);
5285
5286   SmallVector<int,8> *MaskPtr = &LoMask;
5287   unsigned MaskIdx = 0;
5288   unsigned LoIdx = 0;
5289   unsigned HiIdx = 2;
5290   for (unsigned i = 0; i != 4; ++i) {
5291     if (i == 2) {
5292       MaskPtr = &HiMask;
5293       MaskIdx = 1;
5294       LoIdx = 0;
5295       HiIdx = 2;
5296     }
5297     int Idx = PermMask[i];
5298     if (Idx < 0) {
5299       Locs[i] = std::make_pair(-1, -1);
5300     } else if (Idx < 4) {
5301       Locs[i] = std::make_pair(MaskIdx, LoIdx);
5302       (*MaskPtr)[LoIdx] = Idx;
5303       LoIdx++;
5304     } else {
5305       Locs[i] = std::make_pair(MaskIdx, HiIdx);
5306       (*MaskPtr)[HiIdx] = Idx;
5307       HiIdx++;
5308     }
5309   }
5310
5311   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
5312   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
5313   SmallVector<int, 8> MaskOps;
5314   for (unsigned i = 0; i != 4; ++i) {
5315     if (Locs[i].first == -1) {
5316       MaskOps.push_back(-1);
5317     } else {
5318       unsigned Idx = Locs[i].first * 4 + Locs[i].second;
5319       MaskOps.push_back(Idx);
5320     }
5321   }
5322   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
5323 }
5324
5325 static bool MayFoldVectorLoad(SDValue V) {
5326   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5327     V = V.getOperand(0);
5328   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5329     V = V.getOperand(0);
5330   if (MayFoldLoad(V))
5331     return true;
5332   return false;
5333 }
5334
5335 // FIXME: the version above should always be used. Since there's
5336 // a bug where several vector shuffles can't be folded because the
5337 // DAG is not updated during lowering and a node claims to have two
5338 // uses while it only has one, use this version, and let isel match
5339 // another instruction if the load really happens to have more than
5340 // one use. Remove this version after this bug get fixed.
5341 // rdar://8434668, PR8156
5342 static bool RelaxedMayFoldVectorLoad(SDValue V) {
5343   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5344     V = V.getOperand(0);
5345   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5346     V = V.getOperand(0);
5347   if (ISD::isNormalLoad(V.getNode()))
5348     return true;
5349   return false;
5350 }
5351
5352 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
5353 /// a vector extract, and if both can be later optimized into a single load.
5354 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
5355 /// here because otherwise a target specific shuffle node is going to be
5356 /// emitted for this shuffle, and the optimization not done.
5357 /// FIXME: This is probably not the best approach, but fix the problem
5358 /// until the right path is decided.
5359 static
5360 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
5361                                          const TargetLowering &TLI) {
5362   EVT VT = V.getValueType();
5363   ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
5364
5365   // Be sure that the vector shuffle is present in a pattern like this:
5366   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
5367   if (!V.hasOneUse())
5368     return false;
5369
5370   SDNode *N = *V.getNode()->use_begin();
5371   if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5372     return false;
5373
5374   SDValue EltNo = N->getOperand(1);
5375   if (!isa<ConstantSDNode>(EltNo))
5376     return false;
5377
5378   // If the bit convert changed the number of elements, it is unsafe
5379   // to examine the mask.
5380   bool HasShuffleIntoBitcast = false;
5381   if (V.getOpcode() == ISD::BITCAST) {
5382     EVT SrcVT = V.getOperand(0).getValueType();
5383     if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
5384       return false;
5385     V = V.getOperand(0);
5386     HasShuffleIntoBitcast = true;
5387   }
5388
5389   // Select the input vector, guarding against out of range extract vector.
5390   unsigned NumElems = VT.getVectorNumElements();
5391   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5392   int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
5393   V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
5394
5395   // Skip one more bit_convert if necessary
5396   if (V.getOpcode() == ISD::BITCAST)
5397     V = V.getOperand(0);
5398
5399   if (ISD::isNormalLoad(V.getNode())) {
5400     // Is the original load suitable?
5401     LoadSDNode *LN0 = cast<LoadSDNode>(V);
5402
5403     // FIXME: avoid the multi-use bug that is preventing lots of
5404     // of foldings to be detected, this is still wrong of course, but
5405     // give the temporary desired behavior, and if it happens that
5406     // the load has real more uses, during isel it will not fold, and
5407     // will generate poor code.
5408     if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
5409       return false;
5410
5411     if (!HasShuffleIntoBitcast)
5412       return true;
5413
5414     // If there's a bitcast before the shuffle, check if the load type and
5415     // alignment is valid.
5416     unsigned Align = LN0->getAlignment();
5417     unsigned NewAlign =
5418       TLI.getTargetData()->getABITypeAlignment(
5419                                     VT.getTypeForEVT(*DAG.getContext()));
5420
5421     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
5422       return false;
5423   }
5424
5425   return true;
5426 }
5427
5428 static
5429 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
5430   EVT VT = Op.getValueType();
5431
5432   // Canonizalize to v2f64.
5433   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
5434   return DAG.getNode(ISD::BITCAST, dl, VT,
5435                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
5436                                           V1, DAG));
5437 }
5438
5439 static
5440 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
5441                         bool HasSSE2) {
5442   SDValue V1 = Op.getOperand(0);
5443   SDValue V2 = Op.getOperand(1);
5444   EVT VT = Op.getValueType();
5445
5446   assert(VT != MVT::v2i64 && "unsupported shuffle type");
5447
5448   if (HasSSE2 && VT == MVT::v2f64)
5449     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
5450
5451   // v4f32 or v4i32
5452   return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V2, DAG);
5453 }
5454
5455 static
5456 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
5457   SDValue V1 = Op.getOperand(0);
5458   SDValue V2 = Op.getOperand(1);
5459   EVT VT = Op.getValueType();
5460
5461   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
5462          "unsupported shuffle type");
5463
5464   if (V2.getOpcode() == ISD::UNDEF)
5465     V2 = V1;
5466
5467   // v4i32 or v4f32
5468   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
5469 }
5470
5471 static
5472 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
5473   SDValue V1 = Op.getOperand(0);
5474   SDValue V2 = Op.getOperand(1);
5475   EVT VT = Op.getValueType();
5476   unsigned NumElems = VT.getVectorNumElements();
5477
5478   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
5479   // operand of these instructions is only memory, so check if there's a
5480   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
5481   // same masks.
5482   bool CanFoldLoad = false;
5483
5484   // Trivial case, when V2 comes from a load.
5485   if (MayFoldVectorLoad(V2))
5486     CanFoldLoad = true;
5487
5488   // When V1 is a load, it can be folded later into a store in isel, example:
5489   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
5490   //    turns into:
5491   //  (MOVLPSmr addr:$src1, VR128:$src2)
5492   // So, recognize this potential and also use MOVLPS or MOVLPD
5493   if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
5494     CanFoldLoad = true;
5495
5496   // Both of them can't be memory operations though.
5497   if (MayFoldVectorLoad(V1) && MayFoldVectorLoad(V2))
5498     CanFoldLoad = false;
5499
5500   if (CanFoldLoad) {
5501     if (HasSSE2 && NumElems == 2)
5502       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
5503
5504     if (NumElems == 4)
5505       return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
5506   }
5507
5508   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5509   // movl and movlp will both match v2i64, but v2i64 is never matched by
5510   // movl earlier because we make it strict to avoid messing with the movlp load
5511   // folding logic (see the code above getMOVLP call). Match it here then,
5512   // this is horrible, but will stay like this until we move all shuffle
5513   // matching to x86 specific nodes. Note that for the 1st condition all
5514   // types are matched with movsd.
5515   if ((HasSSE2 && NumElems == 2) || !X86::isMOVLMask(SVOp))
5516     return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5517   else if (HasSSE2)
5518     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5519
5520
5521   assert(VT != MVT::v4i32 && "unsupported shuffle type");
5522
5523   // Invert the operand order and use SHUFPS to match it.
5524   return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V2, V1,
5525                               X86::getShuffleSHUFImmediate(SVOp), DAG);
5526 }
5527
5528 static inline unsigned getUNPCKLOpcode(EVT VT, const X86Subtarget *Subtarget) {
5529   switch(VT.getSimpleVT().SimpleTy) {
5530   case MVT::v4i32: return X86ISD::PUNPCKLDQ;
5531   case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
5532   case MVT::v4f32:
5533     return Subtarget->hasAVX() ? X86ISD::VUNPCKLPS : X86ISD::UNPCKLPS;
5534   case MVT::v2f64:
5535     return Subtarget->hasAVX() ? X86ISD::VUNPCKLPD : X86ISD::UNPCKLPD;
5536   case MVT::v8f32: return X86ISD::VUNPCKLPSY;
5537   case MVT::v4f64: return X86ISD::VUNPCKLPDY;
5538   case MVT::v16i8: return X86ISD::PUNPCKLBW;
5539   case MVT::v8i16: return X86ISD::PUNPCKLWD;
5540   default:
5541     llvm_unreachable("Unknown type for unpckl");
5542   }
5543   return 0;
5544 }
5545
5546 static inline unsigned getUNPCKHOpcode(EVT VT) {
5547   switch(VT.getSimpleVT().SimpleTy) {
5548   case MVT::v4i32: return X86ISD::PUNPCKHDQ;
5549   case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
5550   case MVT::v4f32: return X86ISD::UNPCKHPS;
5551   case MVT::v2f64: return X86ISD::UNPCKHPD;
5552   case MVT::v16i8: return X86ISD::PUNPCKHBW;
5553   case MVT::v8i16: return X86ISD::PUNPCKHWD;
5554   default:
5555     llvm_unreachable("Unknown type for unpckh");
5556   }
5557   return 0;
5558 }
5559
5560 static
5561 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
5562                                const TargetLowering &TLI,
5563                                const X86Subtarget *Subtarget) {
5564   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5565   EVT VT = Op.getValueType();
5566   DebugLoc dl = Op.getDebugLoc();
5567   SDValue V1 = Op.getOperand(0);
5568   SDValue V2 = Op.getOperand(1);
5569
5570   if (isZeroShuffle(SVOp))
5571     return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
5572
5573   // Handle splat operations
5574   if (SVOp->isSplat()) {
5575     // Special case, this is the only place now where it's
5576     // allowed to return a vector_shuffle operation without
5577     // using a target specific node, because *hopefully* it
5578     // will be optimized away by the dag combiner.
5579     if (VT.getVectorNumElements() <= 4 &&
5580         CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
5581       return Op;
5582
5583     // Handle splats by matching through known masks
5584     if (VT.getVectorNumElements() <= 4)
5585       return SDValue();
5586
5587     // Canonicalize all of the remaining to v4f32.
5588     return PromoteSplat(SVOp, DAG);
5589   }
5590
5591   // If the shuffle can be profitably rewritten as a narrower shuffle, then
5592   // do it!
5593   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
5594     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5595     if (NewOp.getNode())
5596       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
5597   } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
5598     // FIXME: Figure out a cleaner way to do this.
5599     // Try to make use of movq to zero out the top part.
5600     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
5601       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5602       if (NewOp.getNode()) {
5603         if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
5604           return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
5605                               DAG, Subtarget, dl);
5606       }
5607     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
5608       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5609       if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
5610         return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
5611                             DAG, Subtarget, dl);
5612     }
5613   }
5614   return SDValue();
5615 }
5616
5617 SDValue
5618 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
5619   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5620   SDValue V1 = Op.getOperand(0);
5621   SDValue V2 = Op.getOperand(1);
5622   EVT VT = Op.getValueType();
5623   DebugLoc dl = Op.getDebugLoc();
5624   unsigned NumElems = VT.getVectorNumElements();
5625   bool isMMX = VT.getSizeInBits() == 64;
5626   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
5627   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
5628   bool V1IsSplat = false;
5629   bool V2IsSplat = false;
5630   bool HasSSE2 = Subtarget->hasSSE2() || Subtarget->hasAVX();
5631   bool HasSSE3 = Subtarget->hasSSE3() || Subtarget->hasAVX();
5632   bool HasSSSE3 = Subtarget->hasSSSE3() || Subtarget->hasAVX();
5633   MachineFunction &MF = DAG.getMachineFunction();
5634   bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
5635
5636   // Shuffle operations on MMX not supported.
5637   if (isMMX)
5638     return Op;
5639
5640   // Vector shuffle lowering takes 3 steps:
5641   //
5642   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
5643   //    narrowing and commutation of operands should be handled.
5644   // 2) Matching of shuffles with known shuffle masks to x86 target specific
5645   //    shuffle nodes.
5646   // 3) Rewriting of unmatched masks into new generic shuffle operations,
5647   //    so the shuffle can be broken into other shuffles and the legalizer can
5648   //    try the lowering again.
5649   //
5650   // The general ideia is that no vector_shuffle operation should be left to
5651   // be matched during isel, all of them must be converted to a target specific
5652   // node here.
5653
5654   // Normalize the input vectors. Here splats, zeroed vectors, profitable
5655   // narrowing and commutation of operands should be handled. The actual code
5656   // doesn't include all of those, work in progress...
5657   SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
5658   if (NewOp.getNode())
5659     return NewOp;
5660
5661   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
5662   // unpckh_undef). Only use pshufd if speed is more important than size.
5663   if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
5664     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5665       return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()), dl, VT, V1, V1, DAG);
5666   if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
5667     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5668       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5669
5670   if (X86::isMOVDDUPMask(SVOp) && HasSSE3 && V2IsUndef &&
5671       RelaxedMayFoldVectorLoad(V1))
5672     return getMOVDDup(Op, dl, V1, DAG);
5673
5674   if (X86::isMOVHLPS_v_undef_Mask(SVOp))
5675     return getMOVHighToLow(Op, dl, DAG);
5676
5677   // Use to match splats
5678   if (HasSSE2 && X86::isUNPCKHMask(SVOp) && V2IsUndef &&
5679       (VT == MVT::v2f64 || VT == MVT::v2i64))
5680     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5681
5682   if (X86::isPSHUFDMask(SVOp)) {
5683     // The actual implementation will match the mask in the if above and then
5684     // during isel it can match several different instructions, not only pshufd
5685     // as its name says, sad but true, emulate the behavior for now...
5686     if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
5687         return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
5688
5689     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5690
5691     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
5692       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
5693
5694     if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5695       return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V1,
5696                                   TargetMask, DAG);
5697
5698     if (VT == MVT::v4f32)
5699       return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V1,
5700                                   TargetMask, DAG);
5701   }
5702
5703   // Check if this can be converted into a logical shift.
5704   bool isLeft = false;
5705   unsigned ShAmt = 0;
5706   SDValue ShVal;
5707   bool isShift = getSubtarget()->hasSSE2() &&
5708     isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
5709   if (isShift && ShVal.hasOneUse()) {
5710     // If the shifted value has multiple uses, it may be cheaper to use
5711     // v_set0 + movlhps or movhlps, etc.
5712     EVT EltVT = VT.getVectorElementType();
5713     ShAmt *= EltVT.getSizeInBits();
5714     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5715   }
5716
5717   if (X86::isMOVLMask(SVOp)) {
5718     if (V1IsUndef)
5719       return V2;
5720     if (ISD::isBuildVectorAllZeros(V1.getNode()))
5721       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
5722     if (!X86::isMOVLPMask(SVOp)) {
5723       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5724         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5725
5726       if (VT == MVT::v4i32 || VT == MVT::v4f32)
5727         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5728     }
5729   }
5730
5731   // FIXME: fold these into legal mask.
5732   if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp))
5733     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
5734
5735   if (X86::isMOVHLPSMask(SVOp))
5736     return getMOVHighToLow(Op, dl, DAG);
5737
5738   if (X86::isMOVSHDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5739     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
5740
5741   if (X86::isMOVSLDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5742     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
5743
5744   if (X86::isMOVLPMask(SVOp))
5745     return getMOVLP(Op, dl, DAG, HasSSE2);
5746
5747   if (ShouldXformToMOVHLPS(SVOp) ||
5748       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
5749     return CommuteVectorShuffle(SVOp, DAG);
5750
5751   if (isShift) {
5752     // No better options. Use a vshl / vsrl.
5753     EVT EltVT = VT.getVectorElementType();
5754     ShAmt *= EltVT.getSizeInBits();
5755     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5756   }
5757
5758   bool Commuted = false;
5759   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
5760   // 1,1,1,1 -> v8i16 though.
5761   V1IsSplat = isSplatVector(V1.getNode());
5762   V2IsSplat = isSplatVector(V2.getNode());
5763
5764   // Canonicalize the splat or undef, if present, to be on the RHS.
5765   if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
5766     Op = CommuteVectorShuffle(SVOp, DAG);
5767     SVOp = cast<ShuffleVectorSDNode>(Op);
5768     V1 = SVOp->getOperand(0);
5769     V2 = SVOp->getOperand(1);
5770     std::swap(V1IsSplat, V2IsSplat);
5771     std::swap(V1IsUndef, V2IsUndef);
5772     Commuted = true;
5773   }
5774
5775   if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
5776     // Shuffling low element of v1 into undef, just return v1.
5777     if (V2IsUndef)
5778       return V1;
5779     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
5780     // the instruction selector will not match, so get a canonical MOVL with
5781     // swapped operands to undo the commute.
5782     return getMOVL(DAG, dl, VT, V2, V1);
5783   }
5784
5785   if (X86::isUNPCKLMask(SVOp))
5786     return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
5787                                 dl, VT, V1, V2, DAG);
5788
5789   if (X86::isUNPCKHMask(SVOp))
5790     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG);
5791
5792   if (V2IsSplat) {
5793     // Normalize mask so all entries that point to V2 points to its first
5794     // element then try to match unpck{h|l} again. If match, return a
5795     // new vector_shuffle with the corrected mask.
5796     SDValue NewMask = NormalizeMask(SVOp, DAG);
5797     ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
5798     if (NSVOp != SVOp) {
5799       if (X86::isUNPCKLMask(NSVOp, true)) {
5800         return NewMask;
5801       } else if (X86::isUNPCKHMask(NSVOp, true)) {
5802         return NewMask;
5803       }
5804     }
5805   }
5806
5807   if (Commuted) {
5808     // Commute is back and try unpck* again.
5809     // FIXME: this seems wrong.
5810     SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
5811     ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
5812
5813     if (X86::isUNPCKLMask(NewSVOp))
5814       return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
5815                                   dl, VT, V2, V1, DAG);
5816
5817     if (X86::isUNPCKHMask(NewSVOp))
5818       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG);
5819   }
5820
5821   // Normalize the node to match x86 shuffle ops if needed
5822   if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
5823     return CommuteVectorShuffle(SVOp, DAG);
5824
5825   // The checks below are all present in isShuffleMaskLegal, but they are
5826   // inlined here right now to enable us to directly emit target specific
5827   // nodes, and remove one by one until they don't return Op anymore.
5828   SmallVector<int, 16> M;
5829   SVOp->getMask(M);
5830
5831   if (isPALIGNRMask(M, VT, HasSSSE3))
5832     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
5833                                 X86::getShufflePALIGNRImmediate(SVOp),
5834                                 DAG);
5835
5836   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
5837       SVOp->getSplatIndex() == 0 && V2IsUndef) {
5838     if (VT == MVT::v2f64) {
5839       X86ISD::NodeType Opcode =
5840         getSubtarget()->hasAVX() ? X86ISD::VUNPCKLPD : X86ISD::UNPCKLPD;
5841       return getTargetShuffleNode(Opcode, dl, VT, V1, V1, DAG);
5842     }
5843     if (VT == MVT::v2i64)
5844       return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
5845   }
5846
5847   if (isPSHUFHWMask(M, VT))
5848     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
5849                                 X86::getShufflePSHUFHWImmediate(SVOp),
5850                                 DAG);
5851
5852   if (isPSHUFLWMask(M, VT))
5853     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
5854                                 X86::getShufflePSHUFLWImmediate(SVOp),
5855                                 DAG);
5856
5857   if (isSHUFPMask(M, VT)) {
5858     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5859     if (VT == MVT::v4f32 || VT == MVT::v4i32)
5860       return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V2,
5861                                   TargetMask, DAG);
5862     if (VT == MVT::v2f64 || VT == MVT::v2i64)
5863       return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V2,
5864                                   TargetMask, DAG);
5865   }
5866
5867   if (X86::isUNPCKL_v_undef_Mask(SVOp))
5868     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5869       return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
5870                                   dl, VT, V1, V1, DAG);
5871   if (X86::isUNPCKH_v_undef_Mask(SVOp))
5872     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5873       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5874
5875   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
5876   if (VT == MVT::v8i16) {
5877     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
5878     if (NewOp.getNode())
5879       return NewOp;
5880   }
5881
5882   if (VT == MVT::v16i8) {
5883     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
5884     if (NewOp.getNode())
5885       return NewOp;
5886   }
5887
5888   // Handle all 4 wide cases with a number of shuffles.
5889   if (NumElems == 4)
5890     return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
5891
5892   return SDValue();
5893 }
5894
5895 SDValue
5896 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
5897                                                 SelectionDAG &DAG) const {
5898   EVT VT = Op.getValueType();
5899   DebugLoc dl = Op.getDebugLoc();
5900   if (VT.getSizeInBits() == 8) {
5901     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
5902                                     Op.getOperand(0), Op.getOperand(1));
5903     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
5904                                     DAG.getValueType(VT));
5905     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5906   } else if (VT.getSizeInBits() == 16) {
5907     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5908     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
5909     if (Idx == 0)
5910       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
5911                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5912                                      DAG.getNode(ISD::BITCAST, dl,
5913                                                  MVT::v4i32,
5914                                                  Op.getOperand(0)),
5915                                      Op.getOperand(1)));
5916     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
5917                                     Op.getOperand(0), Op.getOperand(1));
5918     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
5919                                     DAG.getValueType(VT));
5920     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5921   } else if (VT == MVT::f32) {
5922     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
5923     // the result back to FR32 register. It's only worth matching if the
5924     // result has a single use which is a store or a bitcast to i32.  And in
5925     // the case of a store, it's not worth it if the index is a constant 0,
5926     // because a MOVSSmr can be used instead, which is smaller and faster.
5927     if (!Op.hasOneUse())
5928       return SDValue();
5929     SDNode *User = *Op.getNode()->use_begin();
5930     if ((User->getOpcode() != ISD::STORE ||
5931          (isa<ConstantSDNode>(Op.getOperand(1)) &&
5932           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
5933         (User->getOpcode() != ISD::BITCAST ||
5934          User->getValueType(0) != MVT::i32))
5935       return SDValue();
5936     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5937                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
5938                                               Op.getOperand(0)),
5939                                               Op.getOperand(1));
5940     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
5941   } else if (VT == MVT::i32) {
5942     // ExtractPS works with constant index.
5943     if (isa<ConstantSDNode>(Op.getOperand(1)))
5944       return Op;
5945   }
5946   return SDValue();
5947 }
5948
5949
5950 SDValue
5951 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
5952                                            SelectionDAG &DAG) const {
5953   if (!isa<ConstantSDNode>(Op.getOperand(1)))
5954     return SDValue();
5955
5956   SDValue Vec = Op.getOperand(0);
5957   EVT VecVT = Vec.getValueType();
5958
5959   // If this is a 256-bit vector result, first extract the 128-bit
5960   // vector and then extract from the 128-bit vector.
5961   if (VecVT.getSizeInBits() > 128) {
5962     DebugLoc dl = Op.getNode()->getDebugLoc();
5963     unsigned NumElems = VecVT.getVectorNumElements();
5964     SDValue Idx = Op.getOperand(1);
5965
5966     if (!isa<ConstantSDNode>(Idx))
5967       return SDValue();
5968
5969     unsigned ExtractNumElems = NumElems / (VecVT.getSizeInBits() / 128);
5970     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
5971
5972     // Get the 128-bit vector.
5973     bool Upper = IdxVal >= ExtractNumElems;
5974     Vec = Extract128BitVector(Vec, Idx, DAG, dl);
5975
5976     // Extract from it.
5977     SDValue ScaledIdx = Idx;
5978     if (Upper)
5979       ScaledIdx = DAG.getNode(ISD::SUB, dl, Idx.getValueType(), Idx,
5980                               DAG.getConstant(ExtractNumElems,
5981                                               Idx.getValueType()));
5982     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
5983                        ScaledIdx);
5984   }
5985
5986   assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
5987
5988   if (Subtarget->hasSSE41()) {
5989     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
5990     if (Res.getNode())
5991       return Res;
5992   }
5993
5994   EVT VT = Op.getValueType();
5995   DebugLoc dl = Op.getDebugLoc();
5996   // TODO: handle v16i8.
5997   if (VT.getSizeInBits() == 16) {
5998     SDValue Vec = Op.getOperand(0);
5999     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6000     if (Idx == 0)
6001       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6002                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6003                                      DAG.getNode(ISD::BITCAST, dl,
6004                                                  MVT::v4i32, Vec),
6005                                      Op.getOperand(1)));
6006     // Transform it so it match pextrw which produces a 32-bit result.
6007     EVT EltVT = MVT::i32;
6008     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6009                                     Op.getOperand(0), Op.getOperand(1));
6010     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6011                                     DAG.getValueType(VT));
6012     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6013   } else if (VT.getSizeInBits() == 32) {
6014     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6015     if (Idx == 0)
6016       return Op;
6017
6018     // SHUFPS the element to the lowest double word, then movss.
6019     int Mask[4] = { Idx, -1, -1, -1 };
6020     EVT VVT = Op.getOperand(0).getValueType();
6021     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6022                                        DAG.getUNDEF(VVT), Mask);
6023     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6024                        DAG.getIntPtrConstant(0));
6025   } else if (VT.getSizeInBits() == 64) {
6026     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6027     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6028     //        to match extract_elt for f64.
6029     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6030     if (Idx == 0)
6031       return Op;
6032
6033     // UNPCKHPD the element to the lowest double word, then movsd.
6034     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
6035     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
6036     int Mask[2] = { 1, -1 };
6037     EVT VVT = Op.getOperand(0).getValueType();
6038     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6039                                        DAG.getUNDEF(VVT), Mask);
6040     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6041                        DAG.getIntPtrConstant(0));
6042   }
6043
6044   return SDValue();
6045 }
6046
6047 SDValue
6048 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
6049                                                SelectionDAG &DAG) const {
6050   EVT VT = Op.getValueType();
6051   EVT EltVT = VT.getVectorElementType();
6052   DebugLoc dl = Op.getDebugLoc();
6053
6054   SDValue N0 = Op.getOperand(0);
6055   SDValue N1 = Op.getOperand(1);
6056   SDValue N2 = Op.getOperand(2);
6057
6058   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
6059       isa<ConstantSDNode>(N2)) {
6060     unsigned Opc;
6061     if (VT == MVT::v8i16)
6062       Opc = X86ISD::PINSRW;
6063     else if (VT == MVT::v16i8)
6064       Opc = X86ISD::PINSRB;
6065     else
6066       Opc = X86ISD::PINSRB;
6067
6068     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
6069     // argument.
6070     if (N1.getValueType() != MVT::i32)
6071       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6072     if (N2.getValueType() != MVT::i32)
6073       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6074     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
6075   } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
6076     // Bits [7:6] of the constant are the source select.  This will always be
6077     //  zero here.  The DAG Combiner may combine an extract_elt index into these
6078     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
6079     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
6080     // Bits [5:4] of the constant are the destination select.  This is the
6081     //  value of the incoming immediate.
6082     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
6083     //   combine either bitwise AND or insert of float 0.0 to set these bits.
6084     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
6085     // Create this as a scalar to vector..
6086     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
6087     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
6088   } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
6089     // PINSR* works with constant index.
6090     return Op;
6091   }
6092   return SDValue();
6093 }
6094
6095 SDValue
6096 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
6097   EVT VT = Op.getValueType();
6098   EVT EltVT = VT.getVectorElementType();
6099
6100   DebugLoc dl = Op.getDebugLoc();
6101   SDValue N0 = Op.getOperand(0);
6102   SDValue N1 = Op.getOperand(1);
6103   SDValue N2 = Op.getOperand(2);
6104
6105   // If this is a 256-bit vector result, first insert into a 128-bit
6106   // vector and then insert into the 256-bit vector.
6107   if (VT.getSizeInBits() > 128) {
6108     if (!isa<ConstantSDNode>(N2))
6109       return SDValue();
6110
6111     // Get the 128-bit vector.
6112     unsigned NumElems = VT.getVectorNumElements();
6113     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
6114     bool Upper = IdxVal >= NumElems / 2;
6115
6116     SDValue SubN0 = Extract128BitVector(N0, N2, DAG, dl);
6117
6118     // Insert into it.
6119     SDValue ScaledN2 = N2;
6120     if (Upper)
6121       ScaledN2 = DAG.getNode(ISD::SUB, dl, N2.getValueType(), N2,
6122                              DAG.getConstant(NumElems /
6123                                              (VT.getSizeInBits() / 128),
6124                                              N2.getValueType()));
6125     Op = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubN0.getValueType(), SubN0,
6126                      N1, ScaledN2);
6127
6128     // Insert the 128-bit vector
6129     // FIXME: Why UNDEF?
6130     return Insert128BitVector(N0, Op, N2, DAG, dl);
6131   }
6132
6133   if (Subtarget->hasSSE41())
6134     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
6135
6136   if (EltVT == MVT::i8)
6137     return SDValue();
6138
6139   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
6140     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
6141     // as its second argument.
6142     if (N1.getValueType() != MVT::i32)
6143       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6144     if (N2.getValueType() != MVT::i32)
6145       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6146     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
6147   }
6148   return SDValue();
6149 }
6150
6151 SDValue
6152 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6153   LLVMContext *Context = DAG.getContext();
6154   DebugLoc dl = Op.getDebugLoc();
6155   EVT OpVT = Op.getValueType();
6156
6157   // If this is a 256-bit vector result, first insert into a 128-bit
6158   // vector and then insert into the 256-bit vector.
6159   if (OpVT.getSizeInBits() > 128) {
6160     // Insert into a 128-bit vector.
6161     EVT VT128 = EVT::getVectorVT(*Context,
6162                                  OpVT.getVectorElementType(),
6163                                  OpVT.getVectorNumElements() / 2);
6164
6165     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
6166
6167     // Insert the 128-bit vector.
6168     return Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, OpVT), Op,
6169                               DAG.getConstant(0, MVT::i32),
6170                               DAG, dl);
6171   }
6172
6173   if (Op.getValueType() == MVT::v1i64 &&
6174       Op.getOperand(0).getValueType() == MVT::i64)
6175     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
6176
6177   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
6178   assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
6179          "Expected an SSE type!");
6180   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
6181                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
6182 }
6183
6184 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
6185 // a simple subregister reference or explicit instructions to grab
6186 // upper bits of a vector.
6187 SDValue
6188 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6189   if (Subtarget->hasAVX()) {
6190     DebugLoc dl = Op.getNode()->getDebugLoc();
6191     SDValue Vec = Op.getNode()->getOperand(0);
6192     SDValue Idx = Op.getNode()->getOperand(1);
6193
6194     if (Op.getNode()->getValueType(0).getSizeInBits() == 128
6195         && Vec.getNode()->getValueType(0).getSizeInBits() == 256) {
6196         return Extract128BitVector(Vec, Idx, DAG, dl);
6197     }
6198   }
6199   return SDValue();
6200 }
6201
6202 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
6203 // simple superregister reference or explicit instructions to insert
6204 // the upper bits of a vector.
6205 SDValue
6206 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6207   if (Subtarget->hasAVX()) {
6208     DebugLoc dl = Op.getNode()->getDebugLoc();
6209     SDValue Vec = Op.getNode()->getOperand(0);
6210     SDValue SubVec = Op.getNode()->getOperand(1);
6211     SDValue Idx = Op.getNode()->getOperand(2);
6212
6213     if (Op.getNode()->getValueType(0).getSizeInBits() == 256
6214         && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) {
6215       return Insert128BitVector(Vec, SubVec, Idx, DAG, dl);
6216     }
6217   }
6218   return SDValue();
6219 }
6220
6221 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
6222 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
6223 // one of the above mentioned nodes. It has to be wrapped because otherwise
6224 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
6225 // be used to form addressing mode. These wrapped nodes will be selected
6226 // into MOV32ri.
6227 SDValue
6228 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
6229   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
6230
6231   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6232   // global base reg.
6233   unsigned char OpFlag = 0;
6234   unsigned WrapperKind = X86ISD::Wrapper;
6235   CodeModel::Model M = getTargetMachine().getCodeModel();
6236
6237   if (Subtarget->isPICStyleRIPRel() &&
6238       (M == CodeModel::Small || M == CodeModel::Kernel))
6239     WrapperKind = X86ISD::WrapperRIP;
6240   else if (Subtarget->isPICStyleGOT())
6241     OpFlag = X86II::MO_GOTOFF;
6242   else if (Subtarget->isPICStyleStubPIC())
6243     OpFlag = X86II::MO_PIC_BASE_OFFSET;
6244
6245   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
6246                                              CP->getAlignment(),
6247                                              CP->getOffset(), OpFlag);
6248   DebugLoc DL = CP->getDebugLoc();
6249   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6250   // With PIC, the address is actually $g + Offset.
6251   if (OpFlag) {
6252     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6253                          DAG.getNode(X86ISD::GlobalBaseReg,
6254                                      DebugLoc(), getPointerTy()),
6255                          Result);
6256   }
6257
6258   return Result;
6259 }
6260
6261 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
6262   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
6263
6264   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6265   // global base reg.
6266   unsigned char OpFlag = 0;
6267   unsigned WrapperKind = X86ISD::Wrapper;
6268   CodeModel::Model M = getTargetMachine().getCodeModel();
6269
6270   if (Subtarget->isPICStyleRIPRel() &&
6271       (M == CodeModel::Small || M == CodeModel::Kernel))
6272     WrapperKind = X86ISD::WrapperRIP;
6273   else if (Subtarget->isPICStyleGOT())
6274     OpFlag = X86II::MO_GOTOFF;
6275   else if (Subtarget->isPICStyleStubPIC())
6276     OpFlag = X86II::MO_PIC_BASE_OFFSET;
6277
6278   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
6279                                           OpFlag);
6280   DebugLoc DL = JT->getDebugLoc();
6281   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6282
6283   // With PIC, the address is actually $g + Offset.
6284   if (OpFlag)
6285     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6286                          DAG.getNode(X86ISD::GlobalBaseReg,
6287                                      DebugLoc(), getPointerTy()),
6288                          Result);
6289
6290   return Result;
6291 }
6292
6293 SDValue
6294 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
6295   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
6296
6297   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6298   // global base reg.
6299   unsigned char OpFlag = 0;
6300   unsigned WrapperKind = X86ISD::Wrapper;
6301   CodeModel::Model M = getTargetMachine().getCodeModel();
6302
6303   if (Subtarget->isPICStyleRIPRel() &&
6304       (M == CodeModel::Small || M == CodeModel::Kernel))
6305     WrapperKind = X86ISD::WrapperRIP;
6306   else if (Subtarget->isPICStyleGOT())
6307     OpFlag = X86II::MO_GOTOFF;
6308   else if (Subtarget->isPICStyleStubPIC())
6309     OpFlag = X86II::MO_PIC_BASE_OFFSET;
6310
6311   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
6312
6313   DebugLoc DL = Op.getDebugLoc();
6314   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6315
6316
6317   // With PIC, the address is actually $g + Offset.
6318   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
6319       !Subtarget->is64Bit()) {
6320     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6321                          DAG.getNode(X86ISD::GlobalBaseReg,
6322                                      DebugLoc(), getPointerTy()),
6323                          Result);
6324   }
6325
6326   return Result;
6327 }
6328
6329 SDValue
6330 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
6331   // Create the TargetBlockAddressAddress node.
6332   unsigned char OpFlags =
6333     Subtarget->ClassifyBlockAddressReference();
6334   CodeModel::Model M = getTargetMachine().getCodeModel();
6335   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
6336   DebugLoc dl = Op.getDebugLoc();
6337   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
6338                                        /*isTarget=*/true, OpFlags);
6339
6340   if (Subtarget->isPICStyleRIPRel() &&
6341       (M == CodeModel::Small || M == CodeModel::Kernel))
6342     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6343   else
6344     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6345
6346   // With PIC, the address is actually $g + Offset.
6347   if (isGlobalRelativeToPICBase(OpFlags)) {
6348     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6349                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6350                          Result);
6351   }
6352
6353   return Result;
6354 }
6355
6356 SDValue
6357 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
6358                                       int64_t Offset,
6359                                       SelectionDAG &DAG) const {
6360   // Create the TargetGlobalAddress node, folding in the constant
6361   // offset if it is legal.
6362   unsigned char OpFlags =
6363     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
6364   CodeModel::Model M = getTargetMachine().getCodeModel();
6365   SDValue Result;
6366   if (OpFlags == X86II::MO_NO_FLAG &&
6367       X86::isOffsetSuitableForCodeModel(Offset, M)) {
6368     // A direct static reference to a global.
6369     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
6370     Offset = 0;
6371   } else {
6372     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
6373   }
6374
6375   if (Subtarget->isPICStyleRIPRel() &&
6376       (M == CodeModel::Small || M == CodeModel::Kernel))
6377     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6378   else
6379     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6380
6381   // With PIC, the address is actually $g + Offset.
6382   if (isGlobalRelativeToPICBase(OpFlags)) {
6383     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6384                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6385                          Result);
6386   }
6387
6388   // For globals that require a load from a stub to get the address, emit the
6389   // load.
6390   if (isGlobalStubReference(OpFlags))
6391     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
6392                          MachinePointerInfo::getGOT(), false, false, 0);
6393
6394   // If there was a non-zero offset that we didn't fold, create an explicit
6395   // addition for it.
6396   if (Offset != 0)
6397     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
6398                          DAG.getConstant(Offset, getPointerTy()));
6399
6400   return Result;
6401 }
6402
6403 SDValue
6404 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
6405   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
6406   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
6407   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
6408 }
6409
6410 static SDValue
6411 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
6412            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
6413            unsigned char OperandFlags) {
6414   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6415   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6416   DebugLoc dl = GA->getDebugLoc();
6417   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6418                                            GA->getValueType(0),
6419                                            GA->getOffset(),
6420                                            OperandFlags);
6421   if (InFlag) {
6422     SDValue Ops[] = { Chain,  TGA, *InFlag };
6423     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
6424   } else {
6425     SDValue Ops[]  = { Chain, TGA };
6426     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
6427   }
6428
6429   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
6430   MFI->setAdjustsStack(true);
6431
6432   SDValue Flag = Chain.getValue(1);
6433   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
6434 }
6435
6436 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
6437 static SDValue
6438 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6439                                 const EVT PtrVT) {
6440   SDValue InFlag;
6441   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
6442   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
6443                                      DAG.getNode(X86ISD::GlobalBaseReg,
6444                                                  DebugLoc(), PtrVT), InFlag);
6445   InFlag = Chain.getValue(1);
6446
6447   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
6448 }
6449
6450 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
6451 static SDValue
6452 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6453                                 const EVT PtrVT) {
6454   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
6455                     X86::RAX, X86II::MO_TLSGD);
6456 }
6457
6458 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
6459 // "local exec" model.
6460 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6461                                    const EVT PtrVT, TLSModel::Model model,
6462                                    bool is64Bit) {
6463   DebugLoc dl = GA->getDebugLoc();
6464
6465   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
6466   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
6467                                                          is64Bit ? 257 : 256));
6468
6469   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
6470                                       DAG.getIntPtrConstant(0),
6471                                       MachinePointerInfo(Ptr), false, false, 0);
6472
6473   unsigned char OperandFlags = 0;
6474   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
6475   // initialexec.
6476   unsigned WrapperKind = X86ISD::Wrapper;
6477   if (model == TLSModel::LocalExec) {
6478     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
6479   } else if (is64Bit) {
6480     assert(model == TLSModel::InitialExec);
6481     OperandFlags = X86II::MO_GOTTPOFF;
6482     WrapperKind = X86ISD::WrapperRIP;
6483   } else {
6484     assert(model == TLSModel::InitialExec);
6485     OperandFlags = X86II::MO_INDNTPOFF;
6486   }
6487
6488   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
6489   // exec)
6490   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6491                                            GA->getValueType(0),
6492                                            GA->getOffset(), OperandFlags);
6493   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
6494
6495   if (model == TLSModel::InitialExec)
6496     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
6497                          MachinePointerInfo::getGOT(), false, false, 0);
6498
6499   // The address of the thread local variable is the add of the thread
6500   // pointer with the offset of the variable.
6501   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
6502 }
6503
6504 SDValue
6505 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
6506
6507   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
6508   const GlobalValue *GV = GA->getGlobal();
6509
6510   if (Subtarget->isTargetELF()) {
6511     // TODO: implement the "local dynamic" model
6512     // TODO: implement the "initial exec"model for pic executables
6513
6514     // If GV is an alias then use the aliasee for determining
6515     // thread-localness.
6516     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
6517       GV = GA->resolveAliasedGlobal(false);
6518
6519     TLSModel::Model model
6520       = getTLSModel(GV, getTargetMachine().getRelocationModel());
6521
6522     switch (model) {
6523       case TLSModel::GeneralDynamic:
6524       case TLSModel::LocalDynamic: // not implemented
6525         if (Subtarget->is64Bit())
6526           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
6527         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
6528
6529       case TLSModel::InitialExec:
6530       case TLSModel::LocalExec:
6531         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
6532                                    Subtarget->is64Bit());
6533     }
6534   } else if (Subtarget->isTargetDarwin()) {
6535     // Darwin only has one model of TLS.  Lower to that.
6536     unsigned char OpFlag = 0;
6537     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
6538                            X86ISD::WrapperRIP : X86ISD::Wrapper;
6539
6540     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6541     // global base reg.
6542     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
6543                   !Subtarget->is64Bit();
6544     if (PIC32)
6545       OpFlag = X86II::MO_TLVP_PIC_BASE;
6546     else
6547       OpFlag = X86II::MO_TLVP;
6548     DebugLoc DL = Op.getDebugLoc();
6549     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
6550                                                 GA->getValueType(0),
6551                                                 GA->getOffset(), OpFlag);
6552     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6553
6554     // With PIC32, the address is actually $g + Offset.
6555     if (PIC32)
6556       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6557                            DAG.getNode(X86ISD::GlobalBaseReg,
6558                                        DebugLoc(), getPointerTy()),
6559                            Offset);
6560
6561     // Lowering the machine isd will make sure everything is in the right
6562     // location.
6563     SDValue Chain = DAG.getEntryNode();
6564     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6565     SDValue Args[] = { Chain, Offset };
6566     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
6567
6568     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
6569     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6570     MFI->setAdjustsStack(true);
6571
6572     // And our return value (tls address) is in the standard call return value
6573     // location.
6574     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
6575     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
6576   }
6577
6578   assert(false &&
6579          "TLS not implemented for this target.");
6580
6581   llvm_unreachable("Unreachable");
6582   return SDValue();
6583 }
6584
6585
6586 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
6587 /// take a 2 x i32 value to shift plus a shift amount.
6588 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
6589   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6590   EVT VT = Op.getValueType();
6591   unsigned VTBits = VT.getSizeInBits();
6592   DebugLoc dl = Op.getDebugLoc();
6593   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
6594   SDValue ShOpLo = Op.getOperand(0);
6595   SDValue ShOpHi = Op.getOperand(1);
6596   SDValue ShAmt  = Op.getOperand(2);
6597   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
6598                                      DAG.getConstant(VTBits - 1, MVT::i8))
6599                        : DAG.getConstant(0, VT);
6600
6601   SDValue Tmp2, Tmp3;
6602   if (Op.getOpcode() == ISD::SHL_PARTS) {
6603     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
6604     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
6605   } else {
6606     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
6607     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
6608   }
6609
6610   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
6611                                 DAG.getConstant(VTBits, MVT::i8));
6612   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
6613                              AndNode, DAG.getConstant(0, MVT::i8));
6614
6615   SDValue Hi, Lo;
6616   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6617   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
6618   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
6619
6620   if (Op.getOpcode() == ISD::SHL_PARTS) {
6621     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6622     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6623   } else {
6624     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6625     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6626   }
6627
6628   SDValue Ops[2] = { Lo, Hi };
6629   return DAG.getMergeValues(Ops, 2, dl);
6630 }
6631
6632 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
6633                                            SelectionDAG &DAG) const {
6634   EVT SrcVT = Op.getOperand(0).getValueType();
6635
6636   if (SrcVT.isVector())
6637     return SDValue();
6638
6639   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
6640          "Unknown SINT_TO_FP to lower!");
6641
6642   // These are really Legal; return the operand so the caller accepts it as
6643   // Legal.
6644   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
6645     return Op;
6646   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
6647       Subtarget->is64Bit()) {
6648     return Op;
6649   }
6650
6651   DebugLoc dl = Op.getDebugLoc();
6652   unsigned Size = SrcVT.getSizeInBits()/8;
6653   MachineFunction &MF = DAG.getMachineFunction();
6654   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
6655   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6656   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6657                                StackSlot,
6658                                MachinePointerInfo::getFixedStack(SSFI),
6659                                false, false, 0);
6660   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
6661 }
6662
6663 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
6664                                      SDValue StackSlot,
6665                                      SelectionDAG &DAG) const {
6666   // Build the FILD
6667   DebugLoc DL = Op.getDebugLoc();
6668   SDVTList Tys;
6669   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
6670   if (useSSE)
6671     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
6672   else
6673     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
6674
6675   unsigned ByteSize = SrcVT.getSizeInBits()/8;
6676
6677   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
6678   MachineMemOperand *MMO =
6679     DAG.getMachineFunction()
6680     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6681                           MachineMemOperand::MOLoad, ByteSize, ByteSize);
6682
6683   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
6684   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
6685                                            X86ISD::FILD, DL,
6686                                            Tys, Ops, array_lengthof(Ops),
6687                                            SrcVT, MMO);
6688
6689   if (useSSE) {
6690     Chain = Result.getValue(1);
6691     SDValue InFlag = Result.getValue(2);
6692
6693     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
6694     // shouldn't be necessary except that RFP cannot be live across
6695     // multiple blocks. When stackifier is fixed, they can be uncoupled.
6696     MachineFunction &MF = DAG.getMachineFunction();
6697     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
6698     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
6699     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6700     Tys = DAG.getVTList(MVT::Other);
6701     SDValue Ops[] = {
6702       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
6703     };
6704     MachineMemOperand *MMO =
6705       DAG.getMachineFunction()
6706       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6707                             MachineMemOperand::MOStore, SSFISize, SSFISize);
6708
6709     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
6710                                     Ops, array_lengthof(Ops),
6711                                     Op.getValueType(), MMO);
6712     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
6713                          MachinePointerInfo::getFixedStack(SSFI),
6714                          false, false, 0);
6715   }
6716
6717   return Result;
6718 }
6719
6720 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
6721 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
6722                                                SelectionDAG &DAG) const {
6723   // This algorithm is not obvious. Here it is in C code, more or less:
6724   /*
6725     double uint64_to_double( uint32_t hi, uint32_t lo ) {
6726       static const __m128i exp = { 0x4330000045300000ULL, 0 };
6727       static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
6728
6729       // Copy ints to xmm registers.
6730       __m128i xh = _mm_cvtsi32_si128( hi );
6731       __m128i xl = _mm_cvtsi32_si128( lo );
6732
6733       // Combine into low half of a single xmm register.
6734       __m128i x = _mm_unpacklo_epi32( xh, xl );
6735       __m128d d;
6736       double sd;
6737
6738       // Merge in appropriate exponents to give the integer bits the right
6739       // magnitude.
6740       x = _mm_unpacklo_epi32( x, exp );
6741
6742       // Subtract away the biases to deal with the IEEE-754 double precision
6743       // implicit 1.
6744       d = _mm_sub_pd( (__m128d) x, bias );
6745
6746       // All conversions up to here are exact. The correctly rounded result is
6747       // calculated using the current rounding mode using the following
6748       // horizontal add.
6749       d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
6750       _mm_store_sd( &sd, d );   // Because we are returning doubles in XMM, this
6751                                 // store doesn't really need to be here (except
6752                                 // maybe to zero the other double)
6753       return sd;
6754     }
6755   */
6756
6757   DebugLoc dl = Op.getDebugLoc();
6758   LLVMContext *Context = DAG.getContext();
6759
6760   // Build some magic constants.
6761   std::vector<Constant*> CV0;
6762   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
6763   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
6764   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6765   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6766   Constant *C0 = ConstantVector::get(CV0);
6767   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
6768
6769   std::vector<Constant*> CV1;
6770   CV1.push_back(
6771     ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
6772   CV1.push_back(
6773     ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
6774   Constant *C1 = ConstantVector::get(CV1);
6775   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
6776
6777   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6778                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6779                                         Op.getOperand(0),
6780                                         DAG.getIntPtrConstant(1)));
6781   SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6782                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6783                                         Op.getOperand(0),
6784                                         DAG.getIntPtrConstant(0)));
6785   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
6786   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
6787                               MachinePointerInfo::getConstantPool(),
6788                               false, false, 16);
6789   SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
6790   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
6791   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
6792                               MachinePointerInfo::getConstantPool(),
6793                               false, false, 16);
6794   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
6795
6796   // Add the halves; easiest way is to swap them into another reg first.
6797   int ShufMask[2] = { 1, -1 };
6798   SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
6799                                       DAG.getUNDEF(MVT::v2f64), ShufMask);
6800   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
6801   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
6802                      DAG.getIntPtrConstant(0));
6803 }
6804
6805 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
6806 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
6807                                                SelectionDAG &DAG) const {
6808   DebugLoc dl = Op.getDebugLoc();
6809   // FP constant to bias correct the final result.
6810   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
6811                                    MVT::f64);
6812
6813   // Load the 32-bit value into an XMM register.
6814   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6815                              DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6816                                          Op.getOperand(0),
6817                                          DAG.getIntPtrConstant(0)));
6818
6819   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6820                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
6821                      DAG.getIntPtrConstant(0));
6822
6823   // Or the load with the bias.
6824   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
6825                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6826                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6827                                                    MVT::v2f64, Load)),
6828                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6829                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6830                                                    MVT::v2f64, Bias)));
6831   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6832                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
6833                    DAG.getIntPtrConstant(0));
6834
6835   // Subtract the bias.
6836   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
6837
6838   // Handle final rounding.
6839   EVT DestVT = Op.getValueType();
6840
6841   if (DestVT.bitsLT(MVT::f64)) {
6842     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
6843                        DAG.getIntPtrConstant(0));
6844   } else if (DestVT.bitsGT(MVT::f64)) {
6845     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
6846   }
6847
6848   // Handle final rounding.
6849   return Sub;
6850 }
6851
6852 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
6853                                            SelectionDAG &DAG) const {
6854   SDValue N0 = Op.getOperand(0);
6855   DebugLoc dl = Op.getDebugLoc();
6856
6857   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
6858   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
6859   // the optimization here.
6860   if (DAG.SignBitIsZero(N0))
6861     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
6862
6863   EVT SrcVT = N0.getValueType();
6864   EVT DstVT = Op.getValueType();
6865   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
6866     return LowerUINT_TO_FP_i64(Op, DAG);
6867   else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
6868     return LowerUINT_TO_FP_i32(Op, DAG);
6869
6870   // Make a 64-bit buffer, and use it to build an FILD.
6871   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
6872   if (SrcVT == MVT::i32) {
6873     SDValue WordOff = DAG.getConstant(4, getPointerTy());
6874     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
6875                                      getPointerTy(), StackSlot, WordOff);
6876     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6877                                   StackSlot, MachinePointerInfo(),
6878                                   false, false, 0);
6879     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
6880                                   OffsetSlot, MachinePointerInfo(),
6881                                   false, false, 0);
6882     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
6883     return Fild;
6884   }
6885
6886   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
6887   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6888                                 StackSlot, MachinePointerInfo(),
6889                                false, false, 0);
6890   // For i64 source, we need to add the appropriate power of 2 if the input
6891   // was negative.  This is the same as the optimization in
6892   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
6893   // we must be careful to do the computation in x87 extended precision, not
6894   // in SSE. (The generic code can't know it's OK to do this, or how to.)
6895   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
6896   MachineMemOperand *MMO =
6897     DAG.getMachineFunction()
6898     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6899                           MachineMemOperand::MOLoad, 8, 8);
6900
6901   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
6902   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
6903   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
6904                                          MVT::i64, MMO);
6905
6906   APInt FF(32, 0x5F800000ULL);
6907
6908   // Check whether the sign bit is set.
6909   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
6910                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
6911                                  ISD::SETLT);
6912
6913   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
6914   SDValue FudgePtr = DAG.getConstantPool(
6915                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
6916                                          getPointerTy());
6917
6918   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
6919   SDValue Zero = DAG.getIntPtrConstant(0);
6920   SDValue Four = DAG.getIntPtrConstant(4);
6921   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
6922                                Zero, Four);
6923   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
6924
6925   // Load the value out, extending it from f32 to f80.
6926   // FIXME: Avoid the extend by constructing the right constant pool?
6927   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
6928                                  FudgePtr, MachinePointerInfo::getConstantPool(),
6929                                  MVT::f32, false, false, 4);
6930   // Extend everything to 80 bits to force it to be done on x87.
6931   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
6932   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
6933 }
6934
6935 std::pair<SDValue,SDValue> X86TargetLowering::
6936 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
6937   DebugLoc DL = Op.getDebugLoc();
6938
6939   EVT DstTy = Op.getValueType();
6940
6941   if (!IsSigned) {
6942     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
6943     DstTy = MVT::i64;
6944   }
6945
6946   assert(DstTy.getSimpleVT() <= MVT::i64 &&
6947          DstTy.getSimpleVT() >= MVT::i16 &&
6948          "Unknown FP_TO_SINT to lower!");
6949
6950   // These are really Legal.
6951   if (DstTy == MVT::i32 &&
6952       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
6953     return std::make_pair(SDValue(), SDValue());
6954   if (Subtarget->is64Bit() &&
6955       DstTy == MVT::i64 &&
6956       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
6957     return std::make_pair(SDValue(), SDValue());
6958
6959   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
6960   // stack slot.
6961   MachineFunction &MF = DAG.getMachineFunction();
6962   unsigned MemSize = DstTy.getSizeInBits()/8;
6963   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
6964   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6965
6966
6967
6968   unsigned Opc;
6969   switch (DstTy.getSimpleVT().SimpleTy) {
6970   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
6971   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
6972   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
6973   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
6974   }
6975
6976   SDValue Chain = DAG.getEntryNode();
6977   SDValue Value = Op.getOperand(0);
6978   EVT TheVT = Op.getOperand(0).getValueType();
6979   if (isScalarFPTypeInSSEReg(TheVT)) {
6980     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
6981     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
6982                          MachinePointerInfo::getFixedStack(SSFI),
6983                          false, false, 0);
6984     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
6985     SDValue Ops[] = {
6986       Chain, StackSlot, DAG.getValueType(TheVT)
6987     };
6988
6989     MachineMemOperand *MMO =
6990       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6991                               MachineMemOperand::MOLoad, MemSize, MemSize);
6992     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
6993                                     DstTy, MMO);
6994     Chain = Value.getValue(1);
6995     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
6996     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6997   }
6998
6999   MachineMemOperand *MMO =
7000     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7001                             MachineMemOperand::MOStore, MemSize, MemSize);
7002
7003   // Build the FP_TO_INT*_IN_MEM
7004   SDValue Ops[] = { Chain, Value, StackSlot };
7005   SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
7006                                          Ops, 3, DstTy, MMO);
7007
7008   return std::make_pair(FIST, StackSlot);
7009 }
7010
7011 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
7012                                            SelectionDAG &DAG) const {
7013   if (Op.getValueType().isVector())
7014     return SDValue();
7015
7016   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
7017   SDValue FIST = Vals.first, StackSlot = Vals.second;
7018   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
7019   if (FIST.getNode() == 0) return Op;
7020
7021   // Load the result.
7022   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7023                      FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7024 }
7025
7026 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
7027                                            SelectionDAG &DAG) const {
7028   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
7029   SDValue FIST = Vals.first, StackSlot = Vals.second;
7030   assert(FIST.getNode() && "Unexpected failure");
7031
7032   // Load the result.
7033   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7034                      FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7035 }
7036
7037 SDValue X86TargetLowering::LowerFABS(SDValue Op,
7038                                      SelectionDAG &DAG) const {
7039   LLVMContext *Context = DAG.getContext();
7040   DebugLoc dl = Op.getDebugLoc();
7041   EVT VT = Op.getValueType();
7042   EVT EltVT = VT;
7043   if (VT.isVector())
7044     EltVT = VT.getVectorElementType();
7045   std::vector<Constant*> CV;
7046   if (EltVT == MVT::f64) {
7047     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
7048     CV.push_back(C);
7049     CV.push_back(C);
7050   } else {
7051     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
7052     CV.push_back(C);
7053     CV.push_back(C);
7054     CV.push_back(C);
7055     CV.push_back(C);
7056   }
7057   Constant *C = ConstantVector::get(CV);
7058   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7059   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7060                              MachinePointerInfo::getConstantPool(),
7061                              false, false, 16);
7062   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
7063 }
7064
7065 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
7066   LLVMContext *Context = DAG.getContext();
7067   DebugLoc dl = Op.getDebugLoc();
7068   EVT VT = Op.getValueType();
7069   EVT EltVT = VT;
7070   if (VT.isVector())
7071     EltVT = VT.getVectorElementType();
7072   std::vector<Constant*> CV;
7073   if (EltVT == MVT::f64) {
7074     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
7075     CV.push_back(C);
7076     CV.push_back(C);
7077   } else {
7078     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
7079     CV.push_back(C);
7080     CV.push_back(C);
7081     CV.push_back(C);
7082     CV.push_back(C);
7083   }
7084   Constant *C = ConstantVector::get(CV);
7085   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7086   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7087                              MachinePointerInfo::getConstantPool(),
7088                              false, false, 16);
7089   if (VT.isVector()) {
7090     return DAG.getNode(ISD::BITCAST, dl, VT,
7091                        DAG.getNode(ISD::XOR, dl, MVT::v2i64,
7092                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7093                                 Op.getOperand(0)),
7094                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask)));
7095   } else {
7096     return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
7097   }
7098 }
7099
7100 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
7101   LLVMContext *Context = DAG.getContext();
7102   SDValue Op0 = Op.getOperand(0);
7103   SDValue Op1 = Op.getOperand(1);
7104   DebugLoc dl = Op.getDebugLoc();
7105   EVT VT = Op.getValueType();
7106   EVT SrcVT = Op1.getValueType();
7107
7108   // If second operand is smaller, extend it first.
7109   if (SrcVT.bitsLT(VT)) {
7110     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
7111     SrcVT = VT;
7112   }
7113   // And if it is bigger, shrink it first.
7114   if (SrcVT.bitsGT(VT)) {
7115     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
7116     SrcVT = VT;
7117   }
7118
7119   // At this point the operands and the result should have the same
7120   // type, and that won't be f80 since that is not custom lowered.
7121
7122   // First get the sign bit of second operand.
7123   std::vector<Constant*> CV;
7124   if (SrcVT == MVT::f64) {
7125     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
7126     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7127   } else {
7128     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
7129     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7130     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7131     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7132   }
7133   Constant *C = ConstantVector::get(CV);
7134   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7135   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
7136                               MachinePointerInfo::getConstantPool(),
7137                               false, false, 16);
7138   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
7139
7140   // Shift sign bit right or left if the two operands have different types.
7141   if (SrcVT.bitsGT(VT)) {
7142     // Op0 is MVT::f32, Op1 is MVT::f64.
7143     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
7144     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
7145                           DAG.getConstant(32, MVT::i32));
7146     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
7147     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
7148                           DAG.getIntPtrConstant(0));
7149   }
7150
7151   // Clear first operand sign bit.
7152   CV.clear();
7153   if (VT == MVT::f64) {
7154     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
7155     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7156   } else {
7157     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
7158     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7159     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7160     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7161   }
7162   C = ConstantVector::get(CV);
7163   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7164   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7165                               MachinePointerInfo::getConstantPool(),
7166                               false, false, 16);
7167   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
7168
7169   // Or the value with the sign bit.
7170   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
7171 }
7172
7173 /// Emit nodes that will be selected as "test Op0,Op0", or something
7174 /// equivalent.
7175 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
7176                                     SelectionDAG &DAG) const {
7177   DebugLoc dl = Op.getDebugLoc();
7178
7179   // CF and OF aren't always set the way we want. Determine which
7180   // of these we need.
7181   bool NeedCF = false;
7182   bool NeedOF = false;
7183   switch (X86CC) {
7184   default: break;
7185   case X86::COND_A: case X86::COND_AE:
7186   case X86::COND_B: case X86::COND_BE:
7187     NeedCF = true;
7188     break;
7189   case X86::COND_G: case X86::COND_GE:
7190   case X86::COND_L: case X86::COND_LE:
7191   case X86::COND_O: case X86::COND_NO:
7192     NeedOF = true;
7193     break;
7194   }
7195
7196   // See if we can use the EFLAGS value from the operand instead of
7197   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
7198   // we prove that the arithmetic won't overflow, we can't use OF or CF.
7199   if (Op.getResNo() != 0 || NeedOF || NeedCF)
7200     // Emit a CMP with 0, which is the TEST pattern.
7201     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
7202                        DAG.getConstant(0, Op.getValueType()));
7203
7204   unsigned Opcode = 0;
7205   unsigned NumOperands = 0;
7206   switch (Op.getNode()->getOpcode()) {
7207   case ISD::ADD:
7208     // Due to an isel shortcoming, be conservative if this add is likely to be
7209     // selected as part of a load-modify-store instruction. When the root node
7210     // in a match is a store, isel doesn't know how to remap non-chain non-flag
7211     // uses of other nodes in the match, such as the ADD in this case. This
7212     // leads to the ADD being left around and reselected, with the result being
7213     // two adds in the output.  Alas, even if none our users are stores, that
7214     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
7215     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
7216     // climbing the DAG back to the root, and it doesn't seem to be worth the
7217     // effort.
7218     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7219            UE = Op.getNode()->use_end(); UI != UE; ++UI)
7220       if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
7221         goto default_case;
7222
7223     if (ConstantSDNode *C =
7224         dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
7225       // An add of one will be selected as an INC.
7226       if (C->getAPIntValue() == 1) {
7227         Opcode = X86ISD::INC;
7228         NumOperands = 1;
7229         break;
7230       }
7231
7232       // An add of negative one (subtract of one) will be selected as a DEC.
7233       if (C->getAPIntValue().isAllOnesValue()) {
7234         Opcode = X86ISD::DEC;
7235         NumOperands = 1;
7236         break;
7237       }
7238     }
7239
7240     // Otherwise use a regular EFLAGS-setting add.
7241     Opcode = X86ISD::ADD;
7242     NumOperands = 2;
7243     break;
7244   case ISD::AND: {
7245     // If the primary and result isn't used, don't bother using X86ISD::AND,
7246     // because a TEST instruction will be better.
7247     bool NonFlagUse = false;
7248     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7249            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
7250       SDNode *User = *UI;
7251       unsigned UOpNo = UI.getOperandNo();
7252       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
7253         // Look pass truncate.
7254         UOpNo = User->use_begin().getOperandNo();
7255         User = *User->use_begin();
7256       }
7257
7258       if (User->getOpcode() != ISD::BRCOND &&
7259           User->getOpcode() != ISD::SETCC &&
7260           (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
7261         NonFlagUse = true;
7262         break;
7263       }
7264     }
7265
7266     if (!NonFlagUse)
7267       break;
7268   }
7269     // FALL THROUGH
7270   case ISD::SUB:
7271   case ISD::OR:
7272   case ISD::XOR:
7273     // Due to the ISEL shortcoming noted above, be conservative if this op is
7274     // likely to be selected as part of a load-modify-store instruction.
7275     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7276            UE = Op.getNode()->use_end(); UI != UE; ++UI)
7277       if (UI->getOpcode() == ISD::STORE)
7278         goto default_case;
7279
7280     // Otherwise use a regular EFLAGS-setting instruction.
7281     switch (Op.getNode()->getOpcode()) {
7282     default: llvm_unreachable("unexpected operator!");
7283     case ISD::SUB: Opcode = X86ISD::SUB; break;
7284     case ISD::OR:  Opcode = X86ISD::OR;  break;
7285     case ISD::XOR: Opcode = X86ISD::XOR; break;
7286     case ISD::AND: Opcode = X86ISD::AND; break;
7287     }
7288
7289     NumOperands = 2;
7290     break;
7291   case X86ISD::ADD:
7292   case X86ISD::SUB:
7293   case X86ISD::INC:
7294   case X86ISD::DEC:
7295   case X86ISD::OR:
7296   case X86ISD::XOR:
7297   case X86ISD::AND:
7298     return SDValue(Op.getNode(), 1);
7299   default:
7300   default_case:
7301     break;
7302   }
7303
7304   if (Opcode == 0)
7305     // Emit a CMP with 0, which is the TEST pattern.
7306     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
7307                        DAG.getConstant(0, Op.getValueType()));
7308
7309   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
7310   SmallVector<SDValue, 4> Ops;
7311   for (unsigned i = 0; i != NumOperands; ++i)
7312     Ops.push_back(Op.getOperand(i));
7313
7314   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
7315   DAG.ReplaceAllUsesWith(Op, New);
7316   return SDValue(New.getNode(), 1);
7317 }
7318
7319 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
7320 /// equivalent.
7321 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
7322                                    SelectionDAG &DAG) const {
7323   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
7324     if (C->getAPIntValue() == 0)
7325       return EmitTest(Op0, X86CC, DAG);
7326
7327   DebugLoc dl = Op0.getDebugLoc();
7328   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
7329 }
7330
7331 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
7332 /// if it's possible.
7333 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
7334                                      DebugLoc dl, SelectionDAG &DAG) const {
7335   SDValue Op0 = And.getOperand(0);
7336   SDValue Op1 = And.getOperand(1);
7337   if (Op0.getOpcode() == ISD::TRUNCATE)
7338     Op0 = Op0.getOperand(0);
7339   if (Op1.getOpcode() == ISD::TRUNCATE)
7340     Op1 = Op1.getOperand(0);
7341
7342   SDValue LHS, RHS;
7343   if (Op1.getOpcode() == ISD::SHL)
7344     std::swap(Op0, Op1);
7345   if (Op0.getOpcode() == ISD::SHL) {
7346     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
7347       if (And00C->getZExtValue() == 1) {
7348         // If we looked past a truncate, check that it's only truncating away
7349         // known zeros.
7350         unsigned BitWidth = Op0.getValueSizeInBits();
7351         unsigned AndBitWidth = And.getValueSizeInBits();
7352         if (BitWidth > AndBitWidth) {
7353           APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
7354           DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
7355           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
7356             return SDValue();
7357         }
7358         LHS = Op1;
7359         RHS = Op0.getOperand(1);
7360       }
7361   } else if (Op1.getOpcode() == ISD::Constant) {
7362     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
7363     SDValue AndLHS = Op0;
7364     if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
7365       LHS = AndLHS.getOperand(0);
7366       RHS = AndLHS.getOperand(1);
7367     }
7368   }
7369
7370   if (LHS.getNode()) {
7371     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
7372     // instruction.  Since the shift amount is in-range-or-undefined, we know
7373     // that doing a bittest on the i32 value is ok.  We extend to i32 because
7374     // the encoding for the i16 version is larger than the i32 version.
7375     // Also promote i16 to i32 for performance / code size reason.
7376     if (LHS.getValueType() == MVT::i8 ||
7377         LHS.getValueType() == MVT::i16)
7378       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
7379
7380     // If the operand types disagree, extend the shift amount to match.  Since
7381     // BT ignores high bits (like shifts) we can use anyextend.
7382     if (LHS.getValueType() != RHS.getValueType())
7383       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
7384
7385     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
7386     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
7387     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7388                        DAG.getConstant(Cond, MVT::i8), BT);
7389   }
7390
7391   return SDValue();
7392 }
7393
7394 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
7395   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
7396   SDValue Op0 = Op.getOperand(0);
7397   SDValue Op1 = Op.getOperand(1);
7398   DebugLoc dl = Op.getDebugLoc();
7399   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7400
7401   // Optimize to BT if possible.
7402   // Lower (X & (1 << N)) == 0 to BT(X, N).
7403   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
7404   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
7405   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
7406       Op1.getOpcode() == ISD::Constant &&
7407       cast<ConstantSDNode>(Op1)->isNullValue() &&
7408       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7409     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
7410     if (NewSetCC.getNode())
7411       return NewSetCC;
7412   }
7413
7414   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
7415   // these.
7416   if (Op1.getOpcode() == ISD::Constant &&
7417       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
7418        cast<ConstantSDNode>(Op1)->isNullValue()) &&
7419       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7420
7421     // If the input is a setcc, then reuse the input setcc or use a new one with
7422     // the inverted condition.
7423     if (Op0.getOpcode() == X86ISD::SETCC) {
7424       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
7425       bool Invert = (CC == ISD::SETNE) ^
7426         cast<ConstantSDNode>(Op1)->isNullValue();
7427       if (!Invert) return Op0;
7428
7429       CCode = X86::GetOppositeBranchCondition(CCode);
7430       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7431                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
7432     }
7433   }
7434
7435   bool isFP = Op1.getValueType().isFloatingPoint();
7436   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
7437   if (X86CC == X86::COND_INVALID)
7438     return SDValue();
7439
7440   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
7441   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7442                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
7443 }
7444
7445 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
7446   SDValue Cond;
7447   SDValue Op0 = Op.getOperand(0);
7448   SDValue Op1 = Op.getOperand(1);
7449   SDValue CC = Op.getOperand(2);
7450   EVT VT = Op.getValueType();
7451   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
7452   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
7453   DebugLoc dl = Op.getDebugLoc();
7454
7455   if (isFP) {
7456     unsigned SSECC = 8;
7457     EVT VT0 = Op0.getValueType();
7458     assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
7459     unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
7460     bool Swap = false;
7461
7462     switch (SetCCOpcode) {
7463     default: break;
7464     case ISD::SETOEQ:
7465     case ISD::SETEQ:  SSECC = 0; break;
7466     case ISD::SETOGT:
7467     case ISD::SETGT: Swap = true; // Fallthrough
7468     case ISD::SETLT:
7469     case ISD::SETOLT: SSECC = 1; break;
7470     case ISD::SETOGE:
7471     case ISD::SETGE: Swap = true; // Fallthrough
7472     case ISD::SETLE:
7473     case ISD::SETOLE: SSECC = 2; break;
7474     case ISD::SETUO:  SSECC = 3; break;
7475     case ISD::SETUNE:
7476     case ISD::SETNE:  SSECC = 4; break;
7477     case ISD::SETULE: Swap = true;
7478     case ISD::SETUGE: SSECC = 5; break;
7479     case ISD::SETULT: Swap = true;
7480     case ISD::SETUGT: SSECC = 6; break;
7481     case ISD::SETO:   SSECC = 7; break;
7482     }
7483     if (Swap)
7484       std::swap(Op0, Op1);
7485
7486     // In the two special cases we can't handle, emit two comparisons.
7487     if (SSECC == 8) {
7488       if (SetCCOpcode == ISD::SETUEQ) {
7489         SDValue UNORD, EQ;
7490         UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
7491         EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
7492         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
7493       }
7494       else if (SetCCOpcode == ISD::SETONE) {
7495         SDValue ORD, NEQ;
7496         ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
7497         NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
7498         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
7499       }
7500       llvm_unreachable("Illegal FP comparison");
7501     }
7502     // Handle all other FP comparisons here.
7503     return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
7504   }
7505
7506   // We are handling one of the integer comparisons here.  Since SSE only has
7507   // GT and EQ comparisons for integer, swapping operands and multiple
7508   // operations may be required for some comparisons.
7509   unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
7510   bool Swap = false, Invert = false, FlipSigns = false;
7511
7512   switch (VT.getSimpleVT().SimpleTy) {
7513   default: break;
7514   case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
7515   case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
7516   case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
7517   case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
7518   }
7519
7520   switch (SetCCOpcode) {
7521   default: break;
7522   case ISD::SETNE:  Invert = true;
7523   case ISD::SETEQ:  Opc = EQOpc; break;
7524   case ISD::SETLT:  Swap = true;
7525   case ISD::SETGT:  Opc = GTOpc; break;
7526   case ISD::SETGE:  Swap = true;
7527   case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
7528   case ISD::SETULT: Swap = true;
7529   case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
7530   case ISD::SETUGE: Swap = true;
7531   case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
7532   }
7533   if (Swap)
7534     std::swap(Op0, Op1);
7535
7536   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
7537   // bits of the inputs before performing those operations.
7538   if (FlipSigns) {
7539     EVT EltVT = VT.getVectorElementType();
7540     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
7541                                       EltVT);
7542     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
7543     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
7544                                     SignBits.size());
7545     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
7546     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
7547   }
7548
7549   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
7550
7551   // If the logical-not of the result is required, perform that now.
7552   if (Invert)
7553     Result = DAG.getNOT(dl, Result, VT);
7554
7555   return Result;
7556 }
7557
7558 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
7559 static bool isX86LogicalCmp(SDValue Op) {
7560   unsigned Opc = Op.getNode()->getOpcode();
7561   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
7562     return true;
7563   if (Op.getResNo() == 1 &&
7564       (Opc == X86ISD::ADD ||
7565        Opc == X86ISD::SUB ||
7566        Opc == X86ISD::ADC ||
7567        Opc == X86ISD::SBB ||
7568        Opc == X86ISD::SMUL ||
7569        Opc == X86ISD::UMUL ||
7570        Opc == X86ISD::INC ||
7571        Opc == X86ISD::DEC ||
7572        Opc == X86ISD::OR ||
7573        Opc == X86ISD::XOR ||
7574        Opc == X86ISD::AND))
7575     return true;
7576
7577   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
7578     return true;
7579
7580   return false;
7581 }
7582
7583 static bool isZero(SDValue V) {
7584   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7585   return C && C->isNullValue();
7586 }
7587
7588 static bool isAllOnes(SDValue V) {
7589   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7590   return C && C->isAllOnesValue();
7591 }
7592
7593 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
7594   bool addTest = true;
7595   SDValue Cond  = Op.getOperand(0);
7596   SDValue Op1 = Op.getOperand(1);
7597   SDValue Op2 = Op.getOperand(2);
7598   DebugLoc DL = Op.getDebugLoc();
7599   SDValue CC;
7600
7601   if (Cond.getOpcode() == ISD::SETCC) {
7602     SDValue NewCond = LowerSETCC(Cond, DAG);
7603     if (NewCond.getNode())
7604       Cond = NewCond;
7605   }
7606
7607   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
7608   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
7609   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
7610   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
7611   if (Cond.getOpcode() == X86ISD::SETCC &&
7612       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
7613       isZero(Cond.getOperand(1).getOperand(1))) {
7614     SDValue Cmp = Cond.getOperand(1);
7615
7616     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
7617
7618     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
7619         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
7620       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
7621
7622       SDValue CmpOp0 = Cmp.getOperand(0);
7623       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
7624                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
7625
7626       SDValue Res =   // Res = 0 or -1.
7627         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7628                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
7629
7630       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
7631         Res = DAG.getNOT(DL, Res, Res.getValueType());
7632
7633       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
7634       if (N2C == 0 || !N2C->isNullValue())
7635         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
7636       return Res;
7637     }
7638   }
7639
7640   // Look past (and (setcc_carry (cmp ...)), 1).
7641   if (Cond.getOpcode() == ISD::AND &&
7642       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7643     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7644     if (C && C->getAPIntValue() == 1)
7645       Cond = Cond.getOperand(0);
7646   }
7647
7648   // If condition flag is set by a X86ISD::CMP, then use it as the condition
7649   // setting operand in place of the X86ISD::SETCC.
7650   if (Cond.getOpcode() == X86ISD::SETCC ||
7651       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7652     CC = Cond.getOperand(0);
7653
7654     SDValue Cmp = Cond.getOperand(1);
7655     unsigned Opc = Cmp.getOpcode();
7656     EVT VT = Op.getValueType();
7657
7658     bool IllegalFPCMov = false;
7659     if (VT.isFloatingPoint() && !VT.isVector() &&
7660         !isScalarFPTypeInSSEReg(VT))  // FPStack?
7661       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
7662
7663     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
7664         Opc == X86ISD::BT) { // FIXME
7665       Cond = Cmp;
7666       addTest = false;
7667     }
7668   }
7669
7670   if (addTest) {
7671     // Look pass the truncate.
7672     if (Cond.getOpcode() == ISD::TRUNCATE)
7673       Cond = Cond.getOperand(0);
7674
7675     // We know the result of AND is compared against zero. Try to match
7676     // it to BT.
7677     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7678       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
7679       if (NewSetCC.getNode()) {
7680         CC = NewSetCC.getOperand(0);
7681         Cond = NewSetCC.getOperand(1);
7682         addTest = false;
7683       }
7684     }
7685   }
7686
7687   if (addTest) {
7688     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7689     Cond = EmitTest(Cond, X86::COND_NE, DAG);
7690   }
7691
7692   // a <  b ? -1 :  0 -> RES = ~setcc_carry
7693   // a <  b ?  0 : -1 -> RES = setcc_carry
7694   // a >= b ? -1 :  0 -> RES = setcc_carry
7695   // a >= b ?  0 : -1 -> RES = ~setcc_carry
7696   if (Cond.getOpcode() == X86ISD::CMP) {
7697     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
7698
7699     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
7700         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
7701       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7702                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
7703       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
7704         return DAG.getNOT(DL, Res, Res.getValueType());
7705       return Res;
7706     }
7707   }
7708
7709   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
7710   // condition is true.
7711   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
7712   SDValue Ops[] = { Op2, Op1, CC, Cond };
7713   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
7714 }
7715
7716 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
7717 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
7718 // from the AND / OR.
7719 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
7720   Opc = Op.getOpcode();
7721   if (Opc != ISD::OR && Opc != ISD::AND)
7722     return false;
7723   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7724           Op.getOperand(0).hasOneUse() &&
7725           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
7726           Op.getOperand(1).hasOneUse());
7727 }
7728
7729 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
7730 // 1 and that the SETCC node has a single use.
7731 static bool isXor1OfSetCC(SDValue Op) {
7732   if (Op.getOpcode() != ISD::XOR)
7733     return false;
7734   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7735   if (N1C && N1C->getAPIntValue() == 1) {
7736     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7737       Op.getOperand(0).hasOneUse();
7738   }
7739   return false;
7740 }
7741
7742 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
7743   bool addTest = true;
7744   SDValue Chain = Op.getOperand(0);
7745   SDValue Cond  = Op.getOperand(1);
7746   SDValue Dest  = Op.getOperand(2);
7747   DebugLoc dl = Op.getDebugLoc();
7748   SDValue CC;
7749
7750   if (Cond.getOpcode() == ISD::SETCC) {
7751     SDValue NewCond = LowerSETCC(Cond, DAG);
7752     if (NewCond.getNode())
7753       Cond = NewCond;
7754   }
7755 #if 0
7756   // FIXME: LowerXALUO doesn't handle these!!
7757   else if (Cond.getOpcode() == X86ISD::ADD  ||
7758            Cond.getOpcode() == X86ISD::SUB  ||
7759            Cond.getOpcode() == X86ISD::SMUL ||
7760            Cond.getOpcode() == X86ISD::UMUL)
7761     Cond = LowerXALUO(Cond, DAG);
7762 #endif
7763
7764   // Look pass (and (setcc_carry (cmp ...)), 1).
7765   if (Cond.getOpcode() == ISD::AND &&
7766       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7767     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7768     if (C && C->getAPIntValue() == 1)
7769       Cond = Cond.getOperand(0);
7770   }
7771
7772   // If condition flag is set by a X86ISD::CMP, then use it as the condition
7773   // setting operand in place of the X86ISD::SETCC.
7774   if (Cond.getOpcode() == X86ISD::SETCC ||
7775       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7776     CC = Cond.getOperand(0);
7777
7778     SDValue Cmp = Cond.getOperand(1);
7779     unsigned Opc = Cmp.getOpcode();
7780     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
7781     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
7782       Cond = Cmp;
7783       addTest = false;
7784     } else {
7785       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
7786       default: break;
7787       case X86::COND_O:
7788       case X86::COND_B:
7789         // These can only come from an arithmetic instruction with overflow,
7790         // e.g. SADDO, UADDO.
7791         Cond = Cond.getNode()->getOperand(1);
7792         addTest = false;
7793         break;
7794       }
7795     }
7796   } else {
7797     unsigned CondOpc;
7798     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
7799       SDValue Cmp = Cond.getOperand(0).getOperand(1);
7800       if (CondOpc == ISD::OR) {
7801         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
7802         // two branches instead of an explicit OR instruction with a
7803         // separate test.
7804         if (Cmp == Cond.getOperand(1).getOperand(1) &&
7805             isX86LogicalCmp(Cmp)) {
7806           CC = Cond.getOperand(0).getOperand(0);
7807           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7808                               Chain, Dest, CC, Cmp);
7809           CC = Cond.getOperand(1).getOperand(0);
7810           Cond = Cmp;
7811           addTest = false;
7812         }
7813       } else { // ISD::AND
7814         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
7815         // two branches instead of an explicit AND instruction with a
7816         // separate test. However, we only do this if this block doesn't
7817         // have a fall-through edge, because this requires an explicit
7818         // jmp when the condition is false.
7819         if (Cmp == Cond.getOperand(1).getOperand(1) &&
7820             isX86LogicalCmp(Cmp) &&
7821             Op.getNode()->hasOneUse()) {
7822           X86::CondCode CCode =
7823             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7824           CCode = X86::GetOppositeBranchCondition(CCode);
7825           CC = DAG.getConstant(CCode, MVT::i8);
7826           SDNode *User = *Op.getNode()->use_begin();
7827           // Look for an unconditional branch following this conditional branch.
7828           // We need this because we need to reverse the successors in order
7829           // to implement FCMP_OEQ.
7830           if (User->getOpcode() == ISD::BR) {
7831             SDValue FalseBB = User->getOperand(1);
7832             SDNode *NewBR =
7833               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
7834             assert(NewBR == User);
7835             (void)NewBR;
7836             Dest = FalseBB;
7837
7838             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7839                                 Chain, Dest, CC, Cmp);
7840             X86::CondCode CCode =
7841               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
7842             CCode = X86::GetOppositeBranchCondition(CCode);
7843             CC = DAG.getConstant(CCode, MVT::i8);
7844             Cond = Cmp;
7845             addTest = false;
7846           }
7847         }
7848       }
7849     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
7850       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
7851       // It should be transformed during dag combiner except when the condition
7852       // is set by a arithmetics with overflow node.
7853       X86::CondCode CCode =
7854         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7855       CCode = X86::GetOppositeBranchCondition(CCode);
7856       CC = DAG.getConstant(CCode, MVT::i8);
7857       Cond = Cond.getOperand(0).getOperand(1);
7858       addTest = false;
7859     }
7860   }
7861
7862   if (addTest) {
7863     // Look pass the truncate.
7864     if (Cond.getOpcode() == ISD::TRUNCATE)
7865       Cond = Cond.getOperand(0);
7866
7867     // We know the result of AND is compared against zero. Try to match
7868     // it to BT.
7869     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7870       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
7871       if (NewSetCC.getNode()) {
7872         CC = NewSetCC.getOperand(0);
7873         Cond = NewSetCC.getOperand(1);
7874         addTest = false;
7875       }
7876     }
7877   }
7878
7879   if (addTest) {
7880     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7881     Cond = EmitTest(Cond, X86::COND_NE, DAG);
7882   }
7883   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7884                      Chain, Dest, CC, Cond);
7885 }
7886
7887
7888 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
7889 // Calls to _alloca is needed to probe the stack when allocating more than 4k
7890 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
7891 // that the guard pages used by the OS virtual memory manager are allocated in
7892 // correct sequence.
7893 SDValue
7894 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7895                                            SelectionDAG &DAG) const {
7896   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows()) &&
7897          "This should be used only on Windows targets");
7898   DebugLoc dl = Op.getDebugLoc();
7899
7900   // Get the inputs.
7901   SDValue Chain = Op.getOperand(0);
7902   SDValue Size  = Op.getOperand(1);
7903   // FIXME: Ensure alignment here
7904
7905   SDValue Flag;
7906
7907   EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
7908
7909   Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
7910   Flag = Chain.getValue(1);
7911
7912   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7913
7914   Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
7915   Flag = Chain.getValue(1);
7916
7917   Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
7918
7919   SDValue Ops1[2] = { Chain.getValue(0), Chain };
7920   return DAG.getMergeValues(Ops1, 2, dl);
7921 }
7922
7923 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
7924   MachineFunction &MF = DAG.getMachineFunction();
7925   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
7926
7927   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
7928   DebugLoc DL = Op.getDebugLoc();
7929
7930   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
7931     // vastart just stores the address of the VarArgsFrameIndex slot into the
7932     // memory location argument.
7933     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
7934                                    getPointerTy());
7935     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
7936                         MachinePointerInfo(SV), false, false, 0);
7937   }
7938
7939   // __va_list_tag:
7940   //   gp_offset         (0 - 6 * 8)
7941   //   fp_offset         (48 - 48 + 8 * 16)
7942   //   overflow_arg_area (point to parameters coming in memory).
7943   //   reg_save_area
7944   SmallVector<SDValue, 8> MemOps;
7945   SDValue FIN = Op.getOperand(1);
7946   // Store gp_offset
7947   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
7948                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
7949                                                MVT::i32),
7950                                FIN, MachinePointerInfo(SV), false, false, 0);
7951   MemOps.push_back(Store);
7952
7953   // Store fp_offset
7954   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7955                     FIN, DAG.getIntPtrConstant(4));
7956   Store = DAG.getStore(Op.getOperand(0), DL,
7957                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
7958                                        MVT::i32),
7959                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
7960   MemOps.push_back(Store);
7961
7962   // Store ptr to overflow_arg_area
7963   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7964                     FIN, DAG.getIntPtrConstant(4));
7965   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
7966                                     getPointerTy());
7967   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
7968                        MachinePointerInfo(SV, 8),
7969                        false, false, 0);
7970   MemOps.push_back(Store);
7971
7972   // Store ptr to reg_save_area.
7973   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7974                     FIN, DAG.getIntPtrConstant(8));
7975   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
7976                                     getPointerTy());
7977   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
7978                        MachinePointerInfo(SV, 16), false, false, 0);
7979   MemOps.push_back(Store);
7980   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
7981                      &MemOps[0], MemOps.size());
7982 }
7983
7984 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
7985   assert(Subtarget->is64Bit() &&
7986          "LowerVAARG only handles 64-bit va_arg!");
7987   assert((Subtarget->isTargetLinux() ||
7988           Subtarget->isTargetDarwin()) &&
7989           "Unhandled target in LowerVAARG");
7990   assert(Op.getNode()->getNumOperands() == 4);
7991   SDValue Chain = Op.getOperand(0);
7992   SDValue SrcPtr = Op.getOperand(1);
7993   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
7994   unsigned Align = Op.getConstantOperandVal(3);
7995   DebugLoc dl = Op.getDebugLoc();
7996
7997   EVT ArgVT = Op.getNode()->getValueType(0);
7998   const Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
7999   uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
8000   uint8_t ArgMode;
8001
8002   // Decide which area this value should be read from.
8003   // TODO: Implement the AMD64 ABI in its entirety. This simple
8004   // selection mechanism works only for the basic types.
8005   if (ArgVT == MVT::f80) {
8006     llvm_unreachable("va_arg for f80 not yet implemented");
8007   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
8008     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
8009   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
8010     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
8011   } else {
8012     llvm_unreachable("Unhandled argument type in LowerVAARG");
8013   }
8014
8015   if (ArgMode == 2) {
8016     // Sanity Check: Make sure using fp_offset makes sense.
8017     assert(!UseSoftFloat &&
8018            !(DAG.getMachineFunction()
8019                 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
8020            Subtarget->hasXMM());
8021   }
8022
8023   // Insert VAARG_64 node into the DAG
8024   // VAARG_64 returns two values: Variable Argument Address, Chain
8025   SmallVector<SDValue, 11> InstOps;
8026   InstOps.push_back(Chain);
8027   InstOps.push_back(SrcPtr);
8028   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
8029   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
8030   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
8031   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
8032   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
8033                                           VTs, &InstOps[0], InstOps.size(),
8034                                           MVT::i64,
8035                                           MachinePointerInfo(SV),
8036                                           /*Align=*/0,
8037                                           /*Volatile=*/false,
8038                                           /*ReadMem=*/true,
8039                                           /*WriteMem=*/true);
8040   Chain = VAARG.getValue(1);
8041
8042   // Load the next argument and return it
8043   return DAG.getLoad(ArgVT, dl,
8044                      Chain,
8045                      VAARG,
8046                      MachinePointerInfo(),
8047                      false, false, 0);
8048 }
8049
8050 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
8051   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
8052   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
8053   SDValue Chain = Op.getOperand(0);
8054   SDValue DstPtr = Op.getOperand(1);
8055   SDValue SrcPtr = Op.getOperand(2);
8056   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
8057   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8058   DebugLoc DL = Op.getDebugLoc();
8059
8060   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
8061                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
8062                        false,
8063                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
8064 }
8065
8066 SDValue
8067 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
8068   DebugLoc dl = Op.getDebugLoc();
8069   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8070   switch (IntNo) {
8071   default: return SDValue();    // Don't custom lower most intrinsics.
8072   // Comparison intrinsics.
8073   case Intrinsic::x86_sse_comieq_ss:
8074   case Intrinsic::x86_sse_comilt_ss:
8075   case Intrinsic::x86_sse_comile_ss:
8076   case Intrinsic::x86_sse_comigt_ss:
8077   case Intrinsic::x86_sse_comige_ss:
8078   case Intrinsic::x86_sse_comineq_ss:
8079   case Intrinsic::x86_sse_ucomieq_ss:
8080   case Intrinsic::x86_sse_ucomilt_ss:
8081   case Intrinsic::x86_sse_ucomile_ss:
8082   case Intrinsic::x86_sse_ucomigt_ss:
8083   case Intrinsic::x86_sse_ucomige_ss:
8084   case Intrinsic::x86_sse_ucomineq_ss:
8085   case Intrinsic::x86_sse2_comieq_sd:
8086   case Intrinsic::x86_sse2_comilt_sd:
8087   case Intrinsic::x86_sse2_comile_sd:
8088   case Intrinsic::x86_sse2_comigt_sd:
8089   case Intrinsic::x86_sse2_comige_sd:
8090   case Intrinsic::x86_sse2_comineq_sd:
8091   case Intrinsic::x86_sse2_ucomieq_sd:
8092   case Intrinsic::x86_sse2_ucomilt_sd:
8093   case Intrinsic::x86_sse2_ucomile_sd:
8094   case Intrinsic::x86_sse2_ucomigt_sd:
8095   case Intrinsic::x86_sse2_ucomige_sd:
8096   case Intrinsic::x86_sse2_ucomineq_sd: {
8097     unsigned Opc = 0;
8098     ISD::CondCode CC = ISD::SETCC_INVALID;
8099     switch (IntNo) {
8100     default: break;
8101     case Intrinsic::x86_sse_comieq_ss:
8102     case Intrinsic::x86_sse2_comieq_sd:
8103       Opc = X86ISD::COMI;
8104       CC = ISD::SETEQ;
8105       break;
8106     case Intrinsic::x86_sse_comilt_ss:
8107     case Intrinsic::x86_sse2_comilt_sd:
8108       Opc = X86ISD::COMI;
8109       CC = ISD::SETLT;
8110       break;
8111     case Intrinsic::x86_sse_comile_ss:
8112     case Intrinsic::x86_sse2_comile_sd:
8113       Opc = X86ISD::COMI;
8114       CC = ISD::SETLE;
8115       break;
8116     case Intrinsic::x86_sse_comigt_ss:
8117     case Intrinsic::x86_sse2_comigt_sd:
8118       Opc = X86ISD::COMI;
8119       CC = ISD::SETGT;
8120       break;
8121     case Intrinsic::x86_sse_comige_ss:
8122     case Intrinsic::x86_sse2_comige_sd:
8123       Opc = X86ISD::COMI;
8124       CC = ISD::SETGE;
8125       break;
8126     case Intrinsic::x86_sse_comineq_ss:
8127     case Intrinsic::x86_sse2_comineq_sd:
8128       Opc = X86ISD::COMI;
8129       CC = ISD::SETNE;
8130       break;
8131     case Intrinsic::x86_sse_ucomieq_ss:
8132     case Intrinsic::x86_sse2_ucomieq_sd:
8133       Opc = X86ISD::UCOMI;
8134       CC = ISD::SETEQ;
8135       break;
8136     case Intrinsic::x86_sse_ucomilt_ss:
8137     case Intrinsic::x86_sse2_ucomilt_sd:
8138       Opc = X86ISD::UCOMI;
8139       CC = ISD::SETLT;
8140       break;
8141     case Intrinsic::x86_sse_ucomile_ss:
8142     case Intrinsic::x86_sse2_ucomile_sd:
8143       Opc = X86ISD::UCOMI;
8144       CC = ISD::SETLE;
8145       break;
8146     case Intrinsic::x86_sse_ucomigt_ss:
8147     case Intrinsic::x86_sse2_ucomigt_sd:
8148       Opc = X86ISD::UCOMI;
8149       CC = ISD::SETGT;
8150       break;
8151     case Intrinsic::x86_sse_ucomige_ss:
8152     case Intrinsic::x86_sse2_ucomige_sd:
8153       Opc = X86ISD::UCOMI;
8154       CC = ISD::SETGE;
8155       break;
8156     case Intrinsic::x86_sse_ucomineq_ss:
8157     case Intrinsic::x86_sse2_ucomineq_sd:
8158       Opc = X86ISD::UCOMI;
8159       CC = ISD::SETNE;
8160       break;
8161     }
8162
8163     SDValue LHS = Op.getOperand(1);
8164     SDValue RHS = Op.getOperand(2);
8165     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
8166     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
8167     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
8168     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8169                                 DAG.getConstant(X86CC, MVT::i8), Cond);
8170     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
8171   }
8172   // ptest and testp intrinsics. The intrinsic these come from are designed to
8173   // return an integer value, not just an instruction so lower it to the ptest
8174   // or testp pattern and a setcc for the result.
8175   case Intrinsic::x86_sse41_ptestz:
8176   case Intrinsic::x86_sse41_ptestc:
8177   case Intrinsic::x86_sse41_ptestnzc:
8178   case Intrinsic::x86_avx_ptestz_256:
8179   case Intrinsic::x86_avx_ptestc_256:
8180   case Intrinsic::x86_avx_ptestnzc_256:
8181   case Intrinsic::x86_avx_vtestz_ps:
8182   case Intrinsic::x86_avx_vtestc_ps:
8183   case Intrinsic::x86_avx_vtestnzc_ps:
8184   case Intrinsic::x86_avx_vtestz_pd:
8185   case Intrinsic::x86_avx_vtestc_pd:
8186   case Intrinsic::x86_avx_vtestnzc_pd:
8187   case Intrinsic::x86_avx_vtestz_ps_256:
8188   case Intrinsic::x86_avx_vtestc_ps_256:
8189   case Intrinsic::x86_avx_vtestnzc_ps_256:
8190   case Intrinsic::x86_avx_vtestz_pd_256:
8191   case Intrinsic::x86_avx_vtestc_pd_256:
8192   case Intrinsic::x86_avx_vtestnzc_pd_256: {
8193     bool IsTestPacked = false;
8194     unsigned X86CC = 0;
8195     switch (IntNo) {
8196     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
8197     case Intrinsic::x86_avx_vtestz_ps:
8198     case Intrinsic::x86_avx_vtestz_pd:
8199     case Intrinsic::x86_avx_vtestz_ps_256:
8200     case Intrinsic::x86_avx_vtestz_pd_256:
8201       IsTestPacked = true; // Fallthrough
8202     case Intrinsic::x86_sse41_ptestz:
8203     case Intrinsic::x86_avx_ptestz_256:
8204       // ZF = 1
8205       X86CC = X86::COND_E;
8206       break;
8207     case Intrinsic::x86_avx_vtestc_ps:
8208     case Intrinsic::x86_avx_vtestc_pd:
8209     case Intrinsic::x86_avx_vtestc_ps_256:
8210     case Intrinsic::x86_avx_vtestc_pd_256:
8211       IsTestPacked = true; // Fallthrough
8212     case Intrinsic::x86_sse41_ptestc:
8213     case Intrinsic::x86_avx_ptestc_256:
8214       // CF = 1
8215       X86CC = X86::COND_B;
8216       break;
8217     case Intrinsic::x86_avx_vtestnzc_ps:
8218     case Intrinsic::x86_avx_vtestnzc_pd:
8219     case Intrinsic::x86_avx_vtestnzc_ps_256:
8220     case Intrinsic::x86_avx_vtestnzc_pd_256:
8221       IsTestPacked = true; // Fallthrough
8222     case Intrinsic::x86_sse41_ptestnzc:
8223     case Intrinsic::x86_avx_ptestnzc_256:
8224       // ZF and CF = 0
8225       X86CC = X86::COND_A;
8226       break;
8227     }
8228
8229     SDValue LHS = Op.getOperand(1);
8230     SDValue RHS = Op.getOperand(2);
8231     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
8232     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
8233     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
8234     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
8235     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
8236   }
8237
8238   // Fix vector shift instructions where the last operand is a non-immediate
8239   // i32 value.
8240   case Intrinsic::x86_sse2_pslli_w:
8241   case Intrinsic::x86_sse2_pslli_d:
8242   case Intrinsic::x86_sse2_pslli_q:
8243   case Intrinsic::x86_sse2_psrli_w:
8244   case Intrinsic::x86_sse2_psrli_d:
8245   case Intrinsic::x86_sse2_psrli_q:
8246   case Intrinsic::x86_sse2_psrai_w:
8247   case Intrinsic::x86_sse2_psrai_d:
8248   case Intrinsic::x86_mmx_pslli_w:
8249   case Intrinsic::x86_mmx_pslli_d:
8250   case Intrinsic::x86_mmx_pslli_q:
8251   case Intrinsic::x86_mmx_psrli_w:
8252   case Intrinsic::x86_mmx_psrli_d:
8253   case Intrinsic::x86_mmx_psrli_q:
8254   case Intrinsic::x86_mmx_psrai_w:
8255   case Intrinsic::x86_mmx_psrai_d: {
8256     SDValue ShAmt = Op.getOperand(2);
8257     if (isa<ConstantSDNode>(ShAmt))
8258       return SDValue();
8259
8260     unsigned NewIntNo = 0;
8261     EVT ShAmtVT = MVT::v4i32;
8262     switch (IntNo) {
8263     case Intrinsic::x86_sse2_pslli_w:
8264       NewIntNo = Intrinsic::x86_sse2_psll_w;
8265       break;
8266     case Intrinsic::x86_sse2_pslli_d:
8267       NewIntNo = Intrinsic::x86_sse2_psll_d;
8268       break;
8269     case Intrinsic::x86_sse2_pslli_q:
8270       NewIntNo = Intrinsic::x86_sse2_psll_q;
8271       break;
8272     case Intrinsic::x86_sse2_psrli_w:
8273       NewIntNo = Intrinsic::x86_sse2_psrl_w;
8274       break;
8275     case Intrinsic::x86_sse2_psrli_d:
8276       NewIntNo = Intrinsic::x86_sse2_psrl_d;
8277       break;
8278     case Intrinsic::x86_sse2_psrli_q:
8279       NewIntNo = Intrinsic::x86_sse2_psrl_q;
8280       break;
8281     case Intrinsic::x86_sse2_psrai_w:
8282       NewIntNo = Intrinsic::x86_sse2_psra_w;
8283       break;
8284     case Intrinsic::x86_sse2_psrai_d:
8285       NewIntNo = Intrinsic::x86_sse2_psra_d;
8286       break;
8287     default: {
8288       ShAmtVT = MVT::v2i32;
8289       switch (IntNo) {
8290       case Intrinsic::x86_mmx_pslli_w:
8291         NewIntNo = Intrinsic::x86_mmx_psll_w;
8292         break;
8293       case Intrinsic::x86_mmx_pslli_d:
8294         NewIntNo = Intrinsic::x86_mmx_psll_d;
8295         break;
8296       case Intrinsic::x86_mmx_pslli_q:
8297         NewIntNo = Intrinsic::x86_mmx_psll_q;
8298         break;
8299       case Intrinsic::x86_mmx_psrli_w:
8300         NewIntNo = Intrinsic::x86_mmx_psrl_w;
8301         break;
8302       case Intrinsic::x86_mmx_psrli_d:
8303         NewIntNo = Intrinsic::x86_mmx_psrl_d;
8304         break;
8305       case Intrinsic::x86_mmx_psrli_q:
8306         NewIntNo = Intrinsic::x86_mmx_psrl_q;
8307         break;
8308       case Intrinsic::x86_mmx_psrai_w:
8309         NewIntNo = Intrinsic::x86_mmx_psra_w;
8310         break;
8311       case Intrinsic::x86_mmx_psrai_d:
8312         NewIntNo = Intrinsic::x86_mmx_psra_d;
8313         break;
8314       default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
8315       }
8316       break;
8317     }
8318     }
8319
8320     // The vector shift intrinsics with scalars uses 32b shift amounts but
8321     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
8322     // to be zero.
8323     SDValue ShOps[4];
8324     ShOps[0] = ShAmt;
8325     ShOps[1] = DAG.getConstant(0, MVT::i32);
8326     if (ShAmtVT == MVT::v4i32) {
8327       ShOps[2] = DAG.getUNDEF(MVT::i32);
8328       ShOps[3] = DAG.getUNDEF(MVT::i32);
8329       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
8330     } else {
8331       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
8332 // FIXME this must be lowered to get rid of the invalid type.
8333     }
8334
8335     EVT VT = Op.getValueType();
8336     ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
8337     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8338                        DAG.getConstant(NewIntNo, MVT::i32),
8339                        Op.getOperand(1), ShAmt);
8340   }
8341   }
8342 }
8343
8344 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
8345                                            SelectionDAG &DAG) const {
8346   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8347   MFI->setReturnAddressIsTaken(true);
8348
8349   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8350   DebugLoc dl = Op.getDebugLoc();
8351
8352   if (Depth > 0) {
8353     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
8354     SDValue Offset =
8355       DAG.getConstant(TD->getPointerSize(),
8356                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
8357     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8358                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
8359                                    FrameAddr, Offset),
8360                        MachinePointerInfo(), false, false, 0);
8361   }
8362
8363   // Just load the return address.
8364   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
8365   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8366                      RetAddrFI, MachinePointerInfo(), false, false, 0);
8367 }
8368
8369 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
8370   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8371   MFI->setFrameAddressIsTaken(true);
8372
8373   EVT VT = Op.getValueType();
8374   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
8375   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8376   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
8377   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
8378   while (Depth--)
8379     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
8380                             MachinePointerInfo(),
8381                             false, false, 0);
8382   return FrameAddr;
8383 }
8384
8385 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
8386                                                      SelectionDAG &DAG) const {
8387   return DAG.getIntPtrConstant(2*TD->getPointerSize());
8388 }
8389
8390 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
8391   MachineFunction &MF = DAG.getMachineFunction();
8392   SDValue Chain     = Op.getOperand(0);
8393   SDValue Offset    = Op.getOperand(1);
8394   SDValue Handler   = Op.getOperand(2);
8395   DebugLoc dl       = Op.getDebugLoc();
8396
8397   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
8398                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
8399                                      getPointerTy());
8400   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
8401
8402   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
8403                                   DAG.getIntPtrConstant(TD->getPointerSize()));
8404   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
8405   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
8406                        false, false, 0);
8407   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
8408   MF.getRegInfo().addLiveOut(StoreAddrReg);
8409
8410   return DAG.getNode(X86ISD::EH_RETURN, dl,
8411                      MVT::Other,
8412                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
8413 }
8414
8415 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
8416                                              SelectionDAG &DAG) const {
8417   SDValue Root = Op.getOperand(0);
8418   SDValue Trmp = Op.getOperand(1); // trampoline
8419   SDValue FPtr = Op.getOperand(2); // nested function
8420   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
8421   DebugLoc dl  = Op.getDebugLoc();
8422
8423   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8424
8425   if (Subtarget->is64Bit()) {
8426     SDValue OutChains[6];
8427
8428     // Large code-model.
8429     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
8430     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
8431
8432     const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
8433     const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
8434
8435     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
8436
8437     // Load the pointer to the nested function into R11.
8438     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
8439     SDValue Addr = Trmp;
8440     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8441                                 Addr, MachinePointerInfo(TrmpAddr),
8442                                 false, false, 0);
8443
8444     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8445                        DAG.getConstant(2, MVT::i64));
8446     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
8447                                 MachinePointerInfo(TrmpAddr, 2),
8448                                 false, false, 2);
8449
8450     // Load the 'nest' parameter value into R10.
8451     // R10 is specified in X86CallingConv.td
8452     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
8453     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8454                        DAG.getConstant(10, MVT::i64));
8455     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8456                                 Addr, MachinePointerInfo(TrmpAddr, 10),
8457                                 false, false, 0);
8458
8459     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8460                        DAG.getConstant(12, MVT::i64));
8461     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
8462                                 MachinePointerInfo(TrmpAddr, 12),
8463                                 false, false, 2);
8464
8465     // Jump to the nested function.
8466     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
8467     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8468                        DAG.getConstant(20, MVT::i64));
8469     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8470                                 Addr, MachinePointerInfo(TrmpAddr, 20),
8471                                 false, false, 0);
8472
8473     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
8474     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8475                        DAG.getConstant(22, MVT::i64));
8476     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
8477                                 MachinePointerInfo(TrmpAddr, 22),
8478                                 false, false, 0);
8479
8480     SDValue Ops[] =
8481       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
8482     return DAG.getMergeValues(Ops, 2, dl);
8483   } else {
8484     const Function *Func =
8485       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
8486     CallingConv::ID CC = Func->getCallingConv();
8487     unsigned NestReg;
8488
8489     switch (CC) {
8490     default:
8491       llvm_unreachable("Unsupported calling convention");
8492     case CallingConv::C:
8493     case CallingConv::X86_StdCall: {
8494       // Pass 'nest' parameter in ECX.
8495       // Must be kept in sync with X86CallingConv.td
8496       NestReg = X86::ECX;
8497
8498       // Check that ECX wasn't needed by an 'inreg' parameter.
8499       const FunctionType *FTy = Func->getFunctionType();
8500       const AttrListPtr &Attrs = Func->getAttributes();
8501
8502       if (!Attrs.isEmpty() && !Func->isVarArg()) {
8503         unsigned InRegCount = 0;
8504         unsigned Idx = 1;
8505
8506         for (FunctionType::param_iterator I = FTy->param_begin(),
8507              E = FTy->param_end(); I != E; ++I, ++Idx)
8508           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
8509             // FIXME: should only count parameters that are lowered to integers.
8510             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
8511
8512         if (InRegCount > 2) {
8513           report_fatal_error("Nest register in use - reduce number of inreg"
8514                              " parameters!");
8515         }
8516       }
8517       break;
8518     }
8519     case CallingConv::X86_FastCall:
8520     case CallingConv::X86_ThisCall:
8521     case CallingConv::Fast:
8522       // Pass 'nest' parameter in EAX.
8523       // Must be kept in sync with X86CallingConv.td
8524       NestReg = X86::EAX;
8525       break;
8526     }
8527
8528     SDValue OutChains[4];
8529     SDValue Addr, Disp;
8530
8531     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8532                        DAG.getConstant(10, MVT::i32));
8533     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
8534
8535     // This is storing the opcode for MOV32ri.
8536     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
8537     const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
8538     OutChains[0] = DAG.getStore(Root, dl,
8539                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
8540                                 Trmp, MachinePointerInfo(TrmpAddr),
8541                                 false, false, 0);
8542
8543     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8544                        DAG.getConstant(1, MVT::i32));
8545     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
8546                                 MachinePointerInfo(TrmpAddr, 1),
8547                                 false, false, 1);
8548
8549     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
8550     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8551                        DAG.getConstant(5, MVT::i32));
8552     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
8553                                 MachinePointerInfo(TrmpAddr, 5),
8554                                 false, false, 1);
8555
8556     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8557                        DAG.getConstant(6, MVT::i32));
8558     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
8559                                 MachinePointerInfo(TrmpAddr, 6),
8560                                 false, false, 1);
8561
8562     SDValue Ops[] =
8563       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
8564     return DAG.getMergeValues(Ops, 2, dl);
8565   }
8566 }
8567
8568 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8569                                             SelectionDAG &DAG) const {
8570   /*
8571    The rounding mode is in bits 11:10 of FPSR, and has the following
8572    settings:
8573      00 Round to nearest
8574      01 Round to -inf
8575      10 Round to +inf
8576      11 Round to 0
8577
8578   FLT_ROUNDS, on the other hand, expects the following:
8579     -1 Undefined
8580      0 Round to 0
8581      1 Round to nearest
8582      2 Round to +inf
8583      3 Round to -inf
8584
8585   To perform the conversion, we do:
8586     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
8587   */
8588
8589   MachineFunction &MF = DAG.getMachineFunction();
8590   const TargetMachine &TM = MF.getTarget();
8591   const TargetFrameLowering &TFI = *TM.getFrameLowering();
8592   unsigned StackAlignment = TFI.getStackAlignment();
8593   EVT VT = Op.getValueType();
8594   DebugLoc DL = Op.getDebugLoc();
8595
8596   // Save FP Control Word to stack slot
8597   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
8598   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8599
8600
8601   MachineMemOperand *MMO =
8602    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8603                            MachineMemOperand::MOStore, 2, 2);
8604
8605   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
8606   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
8607                                           DAG.getVTList(MVT::Other),
8608                                           Ops, 2, MVT::i16, MMO);
8609
8610   // Load FP Control Word from stack slot
8611   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
8612                             MachinePointerInfo(), false, false, 0);
8613
8614   // Transform as necessary
8615   SDValue CWD1 =
8616     DAG.getNode(ISD::SRL, DL, MVT::i16,
8617                 DAG.getNode(ISD::AND, DL, MVT::i16,
8618                             CWD, DAG.getConstant(0x800, MVT::i16)),
8619                 DAG.getConstant(11, MVT::i8));
8620   SDValue CWD2 =
8621     DAG.getNode(ISD::SRL, DL, MVT::i16,
8622                 DAG.getNode(ISD::AND, DL, MVT::i16,
8623                             CWD, DAG.getConstant(0x400, MVT::i16)),
8624                 DAG.getConstant(9, MVT::i8));
8625
8626   SDValue RetVal =
8627     DAG.getNode(ISD::AND, DL, MVT::i16,
8628                 DAG.getNode(ISD::ADD, DL, MVT::i16,
8629                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
8630                             DAG.getConstant(1, MVT::i16)),
8631                 DAG.getConstant(3, MVT::i16));
8632
8633
8634   return DAG.getNode((VT.getSizeInBits() < 16 ?
8635                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
8636 }
8637
8638 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
8639   EVT VT = Op.getValueType();
8640   EVT OpVT = VT;
8641   unsigned NumBits = VT.getSizeInBits();
8642   DebugLoc dl = Op.getDebugLoc();
8643
8644   Op = Op.getOperand(0);
8645   if (VT == MVT::i8) {
8646     // Zero extend to i32 since there is not an i8 bsr.
8647     OpVT = MVT::i32;
8648     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8649   }
8650
8651   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
8652   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8653   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
8654
8655   // If src is zero (i.e. bsr sets ZF), returns NumBits.
8656   SDValue Ops[] = {
8657     Op,
8658     DAG.getConstant(NumBits+NumBits-1, OpVT),
8659     DAG.getConstant(X86::COND_E, MVT::i8),
8660     Op.getValue(1)
8661   };
8662   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8663
8664   // Finally xor with NumBits-1.
8665   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
8666
8667   if (VT == MVT::i8)
8668     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8669   return Op;
8670 }
8671
8672 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
8673   EVT VT = Op.getValueType();
8674   EVT OpVT = VT;
8675   unsigned NumBits = VT.getSizeInBits();
8676   DebugLoc dl = Op.getDebugLoc();
8677
8678   Op = Op.getOperand(0);
8679   if (VT == MVT::i8) {
8680     OpVT = MVT::i32;
8681     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8682   }
8683
8684   // Issue a bsf (scan bits forward) which also sets EFLAGS.
8685   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8686   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
8687
8688   // If src is zero (i.e. bsf sets ZF), returns NumBits.
8689   SDValue Ops[] = {
8690     Op,
8691     DAG.getConstant(NumBits, OpVT),
8692     DAG.getConstant(X86::COND_E, MVT::i8),
8693     Op.getValue(1)
8694   };
8695   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8696
8697   if (VT == MVT::i8)
8698     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8699   return Op;
8700 }
8701
8702 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) const {
8703   EVT VT = Op.getValueType();
8704   assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
8705   DebugLoc dl = Op.getDebugLoc();
8706
8707   //  ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
8708   //  ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
8709   //  ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
8710   //  ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
8711   //  ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
8712   //
8713   //  AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
8714   //  AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
8715   //  return AloBlo + AloBhi + AhiBlo;
8716
8717   SDValue A = Op.getOperand(0);
8718   SDValue B = Op.getOperand(1);
8719
8720   SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8721                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8722                        A, DAG.getConstant(32, MVT::i32));
8723   SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8724                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8725                        B, DAG.getConstant(32, MVT::i32));
8726   SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8727                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8728                        A, B);
8729   SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8730                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8731                        A, Bhi);
8732   SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8733                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8734                        Ahi, B);
8735   AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8736                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8737                        AloBhi, DAG.getConstant(32, MVT::i32));
8738   AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8739                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8740                        AhiBlo, DAG.getConstant(32, MVT::i32));
8741   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
8742   Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
8743   return Res;
8744 }
8745
8746 SDValue X86TargetLowering::LowerSHL(SDValue Op, SelectionDAG &DAG) const {
8747   EVT VT = Op.getValueType();
8748   DebugLoc dl = Op.getDebugLoc();
8749   SDValue R = Op.getOperand(0);
8750
8751   LLVMContext *Context = DAG.getContext();
8752
8753   assert(Subtarget->hasSSE41() && "Cannot lower SHL without SSE4.1 or later");
8754
8755   if (VT == MVT::v4i32) {
8756     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8757                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8758                      Op.getOperand(1), DAG.getConstant(23, MVT::i32));
8759
8760     ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
8761
8762     std::vector<Constant*> CV(4, CI);
8763     Constant *C = ConstantVector::get(CV);
8764     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8765     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8766                                  MachinePointerInfo::getConstantPool(),
8767                                  false, false, 16);
8768
8769     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
8770     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
8771     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
8772     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
8773   }
8774   if (VT == MVT::v16i8) {
8775     // a = a << 5;
8776     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8777                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8778                      Op.getOperand(1), DAG.getConstant(5, MVT::i32));
8779
8780     ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
8781     ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
8782
8783     std::vector<Constant*> CVM1(16, CM1);
8784     std::vector<Constant*> CVM2(16, CM2);
8785     Constant *C = ConstantVector::get(CVM1);
8786     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8787     SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8788                             MachinePointerInfo::getConstantPool(),
8789                             false, false, 16);
8790
8791     // r = pblendv(r, psllw(r & (char16)15, 4), a);
8792     M = DAG.getNode(ISD::AND, dl, VT, R, M);
8793     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8794                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8795                     DAG.getConstant(4, MVT::i32));
8796     R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
8797     // a += a
8798     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8799
8800     C = ConstantVector::get(CVM2);
8801     CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8802     M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8803                     MachinePointerInfo::getConstantPool(),
8804                     false, false, 16);
8805
8806     // r = pblendv(r, psllw(r & (char16)63, 2), a);
8807     M = DAG.getNode(ISD::AND, dl, VT, R, M);
8808     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8809                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8810                     DAG.getConstant(2, MVT::i32));
8811     R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
8812     // a += a
8813     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8814
8815     // return pblendv(r, r+r, a);
8816     R = DAG.getNode(X86ISD::PBLENDVB, dl, VT,
8817                     R, DAG.getNode(ISD::ADD, dl, VT, R, R), Op);
8818     return R;
8819   }
8820   return SDValue();
8821 }
8822
8823 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
8824   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
8825   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
8826   // looks for this combo and may remove the "setcc" instruction if the "setcc"
8827   // has only one use.
8828   SDNode *N = Op.getNode();
8829   SDValue LHS = N->getOperand(0);
8830   SDValue RHS = N->getOperand(1);
8831   unsigned BaseOp = 0;
8832   unsigned Cond = 0;
8833   DebugLoc DL = Op.getDebugLoc();
8834   switch (Op.getOpcode()) {
8835   default: llvm_unreachable("Unknown ovf instruction!");
8836   case ISD::SADDO:
8837     // A subtract of one will be selected as a INC. Note that INC doesn't
8838     // set CF, so we can't do this for UADDO.
8839     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
8840       if (C->isOne()) {
8841         BaseOp = X86ISD::INC;
8842         Cond = X86::COND_O;
8843         break;
8844       }
8845     BaseOp = X86ISD::ADD;
8846     Cond = X86::COND_O;
8847     break;
8848   case ISD::UADDO:
8849     BaseOp = X86ISD::ADD;
8850     Cond = X86::COND_B;
8851     break;
8852   case ISD::SSUBO:
8853     // A subtract of one will be selected as a DEC. Note that DEC doesn't
8854     // set CF, so we can't do this for USUBO.
8855     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
8856       if (C->isOne()) {
8857         BaseOp = X86ISD::DEC;
8858         Cond = X86::COND_O;
8859         break;
8860       }
8861     BaseOp = X86ISD::SUB;
8862     Cond = X86::COND_O;
8863     break;
8864   case ISD::USUBO:
8865     BaseOp = X86ISD::SUB;
8866     Cond = X86::COND_B;
8867     break;
8868   case ISD::SMULO:
8869     BaseOp = X86ISD::SMUL;
8870     Cond = X86::COND_O;
8871     break;
8872   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
8873     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
8874                                  MVT::i32);
8875     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
8876
8877     SDValue SetCC =
8878       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8879                   DAG.getConstant(X86::COND_O, MVT::i32),
8880                   SDValue(Sum.getNode(), 2));
8881
8882     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
8883     return Sum;
8884   }
8885   }
8886
8887   // Also sets EFLAGS.
8888   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
8889   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
8890
8891   SDValue SetCC =
8892     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
8893                 DAG.getConstant(Cond, MVT::i32),
8894                 SDValue(Sum.getNode(), 1));
8895
8896   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
8897   return Sum;
8898 }
8899
8900 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
8901   DebugLoc dl = Op.getDebugLoc();
8902
8903   if (!Subtarget->hasSSE2()) {
8904     SDValue Chain = Op.getOperand(0);
8905     SDValue Zero = DAG.getConstant(0,
8906                                    Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
8907     SDValue Ops[] = {
8908       DAG.getRegister(X86::ESP, MVT::i32), // Base
8909       DAG.getTargetConstant(1, MVT::i8),   // Scale
8910       DAG.getRegister(0, MVT::i32),        // Index
8911       DAG.getTargetConstant(0, MVT::i32),  // Disp
8912       DAG.getRegister(0, MVT::i32),        // Segment.
8913       Zero,
8914       Chain
8915     };
8916     SDNode *Res =
8917       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
8918                           array_lengthof(Ops));
8919     return SDValue(Res, 0);
8920   }
8921
8922   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
8923   if (!isDev)
8924     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
8925
8926   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8927   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
8928   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
8929   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
8930
8931   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
8932   if (!Op1 && !Op2 && !Op3 && Op4)
8933     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
8934
8935   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
8936   if (Op1 && !Op2 && !Op3 && !Op4)
8937     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
8938
8939   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
8940   //           (MFENCE)>;
8941   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
8942 }
8943
8944 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
8945   EVT T = Op.getValueType();
8946   DebugLoc DL = Op.getDebugLoc();
8947   unsigned Reg = 0;
8948   unsigned size = 0;
8949   switch(T.getSimpleVT().SimpleTy) {
8950   default:
8951     assert(false && "Invalid value type!");
8952   case MVT::i8:  Reg = X86::AL;  size = 1; break;
8953   case MVT::i16: Reg = X86::AX;  size = 2; break;
8954   case MVT::i32: Reg = X86::EAX; size = 4; break;
8955   case MVT::i64:
8956     assert(Subtarget->is64Bit() && "Node not type legal!");
8957     Reg = X86::RAX; size = 8;
8958     break;
8959   }
8960   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
8961                                     Op.getOperand(2), SDValue());
8962   SDValue Ops[] = { cpIn.getValue(0),
8963                     Op.getOperand(1),
8964                     Op.getOperand(3),
8965                     DAG.getTargetConstant(size, MVT::i8),
8966                     cpIn.getValue(1) };
8967   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
8968   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
8969   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
8970                                            Ops, 5, T, MMO);
8971   SDValue cpOut =
8972     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
8973   return cpOut;
8974 }
8975
8976 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
8977                                                  SelectionDAG &DAG) const {
8978   assert(Subtarget->is64Bit() && "Result not type legalized?");
8979   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
8980   SDValue TheChain = Op.getOperand(0);
8981   DebugLoc dl = Op.getDebugLoc();
8982   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
8983   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
8984   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
8985                                    rax.getValue(2));
8986   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
8987                             DAG.getConstant(32, MVT::i8));
8988   SDValue Ops[] = {
8989     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
8990     rdx.getValue(1)
8991   };
8992   return DAG.getMergeValues(Ops, 2, dl);
8993 }
8994
8995 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
8996                                             SelectionDAG &DAG) const {
8997   EVT SrcVT = Op.getOperand(0).getValueType();
8998   EVT DstVT = Op.getValueType();
8999   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
9000          Subtarget->hasMMX() && "Unexpected custom BITCAST");
9001   assert((DstVT == MVT::i64 ||
9002           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
9003          "Unexpected custom BITCAST");
9004   // i64 <=> MMX conversions are Legal.
9005   if (SrcVT==MVT::i64 && DstVT.isVector())
9006     return Op;
9007   if (DstVT==MVT::i64 && SrcVT.isVector())
9008     return Op;
9009   // MMX <=> MMX conversions are Legal.
9010   if (SrcVT.isVector() && DstVT.isVector())
9011     return Op;
9012   // All other conversions need to be expanded.
9013   return SDValue();
9014 }
9015
9016 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
9017   SDNode *Node = Op.getNode();
9018   DebugLoc dl = Node->getDebugLoc();
9019   EVT T = Node->getValueType(0);
9020   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
9021                               DAG.getConstant(0, T), Node->getOperand(2));
9022   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
9023                        cast<AtomicSDNode>(Node)->getMemoryVT(),
9024                        Node->getOperand(0),
9025                        Node->getOperand(1), negOp,
9026                        cast<AtomicSDNode>(Node)->getSrcValue(),
9027                        cast<AtomicSDNode>(Node)->getAlignment());
9028 }
9029
9030 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
9031   EVT VT = Op.getNode()->getValueType(0);
9032
9033   // Let legalize expand this if it isn't a legal type yet.
9034   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9035     return SDValue();
9036
9037   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
9038
9039   unsigned Opc;
9040   bool ExtraOp = false;
9041   switch (Op.getOpcode()) {
9042   default: assert(0 && "Invalid code");
9043   case ISD::ADDC: Opc = X86ISD::ADD; break;
9044   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
9045   case ISD::SUBC: Opc = X86ISD::SUB; break;
9046   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
9047   }
9048
9049   if (!ExtraOp)
9050     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
9051                        Op.getOperand(1));
9052   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
9053                      Op.getOperand(1), Op.getOperand(2));
9054 }
9055
9056 /// LowerOperation - Provide custom lowering hooks for some operations.
9057 ///
9058 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9059   switch (Op.getOpcode()) {
9060   default: llvm_unreachable("Should not custom lower this!");
9061   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op,DAG);
9062   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
9063   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
9064   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
9065   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
9066   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
9067   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
9068   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
9069   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op, DAG);
9070   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, DAG);
9071   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
9072   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
9073   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
9074   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
9075   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
9076   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
9077   case ISD::SHL_PARTS:
9078   case ISD::SRA_PARTS:
9079   case ISD::SRL_PARTS:          return LowerShift(Op, DAG);
9080   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
9081   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
9082   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
9083   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
9084   case ISD::FABS:               return LowerFABS(Op, DAG);
9085   case ISD::FNEG:               return LowerFNEG(Op, DAG);
9086   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
9087   case ISD::SETCC:              return LowerSETCC(Op, DAG);
9088   case ISD::VSETCC:             return LowerVSETCC(Op, DAG);
9089   case ISD::SELECT:             return LowerSELECT(Op, DAG);
9090   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
9091   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
9092   case ISD::VASTART:            return LowerVASTART(Op, DAG);
9093   case ISD::VAARG:              return LowerVAARG(Op, DAG);
9094   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
9095   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
9096   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
9097   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
9098   case ISD::FRAME_TO_ARGS_OFFSET:
9099                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
9100   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
9101   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
9102   case ISD::TRAMPOLINE:         return LowerTRAMPOLINE(Op, DAG);
9103   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
9104   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
9105   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
9106   case ISD::MUL:                return LowerMUL_V2I64(Op, DAG);
9107   case ISD::SHL:                return LowerSHL(Op, DAG);
9108   case ISD::SADDO:
9109   case ISD::UADDO:
9110   case ISD::SSUBO:
9111   case ISD::USUBO:
9112   case ISD::SMULO:
9113   case ISD::UMULO:              return LowerXALUO(Op, DAG);
9114   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
9115   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
9116   case ISD::ADDC:
9117   case ISD::ADDE:
9118   case ISD::SUBC:
9119   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
9120   }
9121 }
9122
9123 void X86TargetLowering::
9124 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
9125                         SelectionDAG &DAG, unsigned NewOp) const {
9126   EVT T = Node->getValueType(0);
9127   DebugLoc dl = Node->getDebugLoc();
9128   assert (T == MVT::i64 && "Only know how to expand i64 atomics");
9129
9130   SDValue Chain = Node->getOperand(0);
9131   SDValue In1 = Node->getOperand(1);
9132   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9133                              Node->getOperand(2), DAG.getIntPtrConstant(0));
9134   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9135                              Node->getOperand(2), DAG.getIntPtrConstant(1));
9136   SDValue Ops[] = { Chain, In1, In2L, In2H };
9137   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
9138   SDValue Result =
9139     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
9140                             cast<MemSDNode>(Node)->getMemOperand());
9141   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
9142   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
9143   Results.push_back(Result.getValue(2));
9144 }
9145
9146 /// ReplaceNodeResults - Replace a node with an illegal result type
9147 /// with a new node built out of custom code.
9148 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
9149                                            SmallVectorImpl<SDValue>&Results,
9150                                            SelectionDAG &DAG) const {
9151   DebugLoc dl = N->getDebugLoc();
9152   switch (N->getOpcode()) {
9153   default:
9154     assert(false && "Do not know how to custom type legalize this operation!");
9155     return;
9156   case ISD::ADDC:
9157   case ISD::ADDE:
9158   case ISD::SUBC:
9159   case ISD::SUBE:
9160     // We don't want to expand or promote these.
9161     return;
9162   case ISD::FP_TO_SINT: {
9163     std::pair<SDValue,SDValue> Vals =
9164         FP_TO_INTHelper(SDValue(N, 0), DAG, true);
9165     SDValue FIST = Vals.first, StackSlot = Vals.second;
9166     if (FIST.getNode() != 0) {
9167       EVT VT = N->getValueType(0);
9168       // Return a load from the stack slot.
9169       Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
9170                                     MachinePointerInfo(), false, false, 0));
9171     }
9172     return;
9173   }
9174   case ISD::READCYCLECOUNTER: {
9175     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9176     SDValue TheChain = N->getOperand(0);
9177     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
9178     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
9179                                      rd.getValue(1));
9180     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
9181                                      eax.getValue(2));
9182     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
9183     SDValue Ops[] = { eax, edx };
9184     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
9185     Results.push_back(edx.getValue(1));
9186     return;
9187   }
9188   case ISD::ATOMIC_CMP_SWAP: {
9189     EVT T = N->getValueType(0);
9190     assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
9191     SDValue cpInL, cpInH;
9192     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
9193                         DAG.getConstant(0, MVT::i32));
9194     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
9195                         DAG.getConstant(1, MVT::i32));
9196     cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
9197     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
9198                              cpInL.getValue(1));
9199     SDValue swapInL, swapInH;
9200     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
9201                           DAG.getConstant(0, MVT::i32));
9202     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
9203                           DAG.getConstant(1, MVT::i32));
9204     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
9205                                cpInH.getValue(1));
9206     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
9207                                swapInL.getValue(1));
9208     SDValue Ops[] = { swapInH.getValue(0),
9209                       N->getOperand(1),
9210                       swapInH.getValue(1) };
9211     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9212     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
9213     SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG8_DAG, dl, Tys,
9214                                              Ops, 3, T, MMO);
9215     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
9216                                         MVT::i32, Result.getValue(1));
9217     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
9218                                         MVT::i32, cpOutL.getValue(2));
9219     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
9220     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
9221     Results.push_back(cpOutH.getValue(1));
9222     return;
9223   }
9224   case ISD::ATOMIC_LOAD_ADD:
9225     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
9226     return;
9227   case ISD::ATOMIC_LOAD_AND:
9228     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
9229     return;
9230   case ISD::ATOMIC_LOAD_NAND:
9231     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
9232     return;
9233   case ISD::ATOMIC_LOAD_OR:
9234     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
9235     return;
9236   case ISD::ATOMIC_LOAD_SUB:
9237     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
9238     return;
9239   case ISD::ATOMIC_LOAD_XOR:
9240     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
9241     return;
9242   case ISD::ATOMIC_SWAP:
9243     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
9244     return;
9245   }
9246 }
9247
9248 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
9249   switch (Opcode) {
9250   default: return NULL;
9251   case X86ISD::BSF:                return "X86ISD::BSF";
9252   case X86ISD::BSR:                return "X86ISD::BSR";
9253   case X86ISD::SHLD:               return "X86ISD::SHLD";
9254   case X86ISD::SHRD:               return "X86ISD::SHRD";
9255   case X86ISD::FAND:               return "X86ISD::FAND";
9256   case X86ISD::FOR:                return "X86ISD::FOR";
9257   case X86ISD::FXOR:               return "X86ISD::FXOR";
9258   case X86ISD::FSRL:               return "X86ISD::FSRL";
9259   case X86ISD::FILD:               return "X86ISD::FILD";
9260   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
9261   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
9262   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
9263   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
9264   case X86ISD::FLD:                return "X86ISD::FLD";
9265   case X86ISD::FST:                return "X86ISD::FST";
9266   case X86ISD::CALL:               return "X86ISD::CALL";
9267   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
9268   case X86ISD::BT:                 return "X86ISD::BT";
9269   case X86ISD::CMP:                return "X86ISD::CMP";
9270   case X86ISD::COMI:               return "X86ISD::COMI";
9271   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
9272   case X86ISD::SETCC:              return "X86ISD::SETCC";
9273   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
9274   case X86ISD::CMOV:               return "X86ISD::CMOV";
9275   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
9276   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
9277   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
9278   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
9279   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
9280   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
9281   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
9282   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
9283   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
9284   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
9285   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
9286   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
9287   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
9288   case X86ISD::PANDN:              return "X86ISD::PANDN";
9289   case X86ISD::PSIGNB:             return "X86ISD::PSIGNB";
9290   case X86ISD::PSIGNW:             return "X86ISD::PSIGNW";
9291   case X86ISD::PSIGND:             return "X86ISD::PSIGND";
9292   case X86ISD::PBLENDVB:           return "X86ISD::PBLENDVB";
9293   case X86ISD::FMAX:               return "X86ISD::FMAX";
9294   case X86ISD::FMIN:               return "X86ISD::FMIN";
9295   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
9296   case X86ISD::FRCP:               return "X86ISD::FRCP";
9297   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
9298   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
9299   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
9300   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
9301   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
9302   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
9303   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
9304   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
9305   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
9306   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
9307   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
9308   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
9309   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
9310   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
9311   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
9312   case X86ISD::VSHL:               return "X86ISD::VSHL";
9313   case X86ISD::VSRL:               return "X86ISD::VSRL";
9314   case X86ISD::CMPPD:              return "X86ISD::CMPPD";
9315   case X86ISD::CMPPS:              return "X86ISD::CMPPS";
9316   case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
9317   case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
9318   case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
9319   case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
9320   case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
9321   case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
9322   case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
9323   case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
9324   case X86ISD::ADD:                return "X86ISD::ADD";
9325   case X86ISD::SUB:                return "X86ISD::SUB";
9326   case X86ISD::ADC:                return "X86ISD::ADC";
9327   case X86ISD::SBB:                return "X86ISD::SBB";
9328   case X86ISD::SMUL:               return "X86ISD::SMUL";
9329   case X86ISD::UMUL:               return "X86ISD::UMUL";
9330   case X86ISD::INC:                return "X86ISD::INC";
9331   case X86ISD::DEC:                return "X86ISD::DEC";
9332   case X86ISD::OR:                 return "X86ISD::OR";
9333   case X86ISD::XOR:                return "X86ISD::XOR";
9334   case X86ISD::AND:                return "X86ISD::AND";
9335   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
9336   case X86ISD::PTEST:              return "X86ISD::PTEST";
9337   case X86ISD::TESTP:              return "X86ISD::TESTP";
9338   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
9339   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
9340   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
9341   case X86ISD::PSHUFHW_LD:         return "X86ISD::PSHUFHW_LD";
9342   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
9343   case X86ISD::PSHUFLW_LD:         return "X86ISD::PSHUFLW_LD";
9344   case X86ISD::SHUFPS:             return "X86ISD::SHUFPS";
9345   case X86ISD::SHUFPD:             return "X86ISD::SHUFPD";
9346   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
9347   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
9348   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
9349   case X86ISD::MOVHLPD:            return "X86ISD::MOVHLPD";
9350   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
9351   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
9352   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
9353   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
9354   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
9355   case X86ISD::MOVSHDUP_LD:        return "X86ISD::MOVSHDUP_LD";
9356   case X86ISD::MOVSLDUP_LD:        return "X86ISD::MOVSLDUP_LD";
9357   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
9358   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
9359   case X86ISD::UNPCKLPS:           return "X86ISD::UNPCKLPS";
9360   case X86ISD::UNPCKLPD:           return "X86ISD::UNPCKLPD";
9361   case X86ISD::VUNPCKLPS:          return "X86ISD::VUNPCKLPS";
9362   case X86ISD::VUNPCKLPD:          return "X86ISD::VUNPCKLPD";
9363   case X86ISD::VUNPCKLPSY:         return "X86ISD::VUNPCKLPSY";
9364   case X86ISD::VUNPCKLPDY:         return "X86ISD::VUNPCKLPDY";
9365   case X86ISD::UNPCKHPS:           return "X86ISD::UNPCKHPS";
9366   case X86ISD::UNPCKHPD:           return "X86ISD::UNPCKHPD";
9367   case X86ISD::PUNPCKLBW:          return "X86ISD::PUNPCKLBW";
9368   case X86ISD::PUNPCKLWD:          return "X86ISD::PUNPCKLWD";
9369   case X86ISD::PUNPCKLDQ:          return "X86ISD::PUNPCKLDQ";
9370   case X86ISD::PUNPCKLQDQ:         return "X86ISD::PUNPCKLQDQ";
9371   case X86ISD::PUNPCKHBW:          return "X86ISD::PUNPCKHBW";
9372   case X86ISD::PUNPCKHWD:          return "X86ISD::PUNPCKHWD";
9373   case X86ISD::PUNPCKHDQ:          return "X86ISD::PUNPCKHDQ";
9374   case X86ISD::PUNPCKHQDQ:         return "X86ISD::PUNPCKHQDQ";
9375   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
9376   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
9377   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
9378   }
9379 }
9380
9381 // isLegalAddressingMode - Return true if the addressing mode represented
9382 // by AM is legal for this target, for a load/store of the specified type.
9383 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
9384                                               const Type *Ty) const {
9385   // X86 supports extremely general addressing modes.
9386   CodeModel::Model M = getTargetMachine().getCodeModel();
9387   Reloc::Model R = getTargetMachine().getRelocationModel();
9388
9389   // X86 allows a sign-extended 32-bit immediate field as a displacement.
9390   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
9391     return false;
9392
9393   if (AM.BaseGV) {
9394     unsigned GVFlags =
9395       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
9396
9397     // If a reference to this global requires an extra load, we can't fold it.
9398     if (isGlobalStubReference(GVFlags))
9399       return false;
9400
9401     // If BaseGV requires a register for the PIC base, we cannot also have a
9402     // BaseReg specified.
9403     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
9404       return false;
9405
9406     // If lower 4G is not available, then we must use rip-relative addressing.
9407     if ((M != CodeModel::Small || R != Reloc::Static) &&
9408         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
9409       return false;
9410   }
9411
9412   switch (AM.Scale) {
9413   case 0:
9414   case 1:
9415   case 2:
9416   case 4:
9417   case 8:
9418     // These scales always work.
9419     break;
9420   case 3:
9421   case 5:
9422   case 9:
9423     // These scales are formed with basereg+scalereg.  Only accept if there is
9424     // no basereg yet.
9425     if (AM.HasBaseReg)
9426       return false;
9427     break;
9428   default:  // Other stuff never works.
9429     return false;
9430   }
9431
9432   return true;
9433 }
9434
9435
9436 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
9437   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9438     return false;
9439   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
9440   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
9441   if (NumBits1 <= NumBits2)
9442     return false;
9443   return true;
9444 }
9445
9446 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
9447   if (!VT1.isInteger() || !VT2.isInteger())
9448     return false;
9449   unsigned NumBits1 = VT1.getSizeInBits();
9450   unsigned NumBits2 = VT2.getSizeInBits();
9451   if (NumBits1 <= NumBits2)
9452     return false;
9453   return true;
9454 }
9455
9456 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
9457   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9458   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
9459 }
9460
9461 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
9462   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9463   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
9464 }
9465
9466 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
9467   // i16 instructions are longer (0x66 prefix) and potentially slower.
9468   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
9469 }
9470
9471 /// isShuffleMaskLegal - Targets can use this to indicate that they only
9472 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
9473 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
9474 /// are assumed to be legal.
9475 bool
9476 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
9477                                       EVT VT) const {
9478   // Very little shuffling can be done for 64-bit vectors right now.
9479   if (VT.getSizeInBits() == 64)
9480     return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
9481
9482   // FIXME: pshufb, blends, shifts.
9483   return (VT.getVectorNumElements() == 2 ||
9484           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
9485           isMOVLMask(M, VT) ||
9486           isSHUFPMask(M, VT) ||
9487           isPSHUFDMask(M, VT) ||
9488           isPSHUFHWMask(M, VT) ||
9489           isPSHUFLWMask(M, VT) ||
9490           isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
9491           isUNPCKLMask(M, VT) ||
9492           isUNPCKHMask(M, VT) ||
9493           isUNPCKL_v_undef_Mask(M, VT) ||
9494           isUNPCKH_v_undef_Mask(M, VT));
9495 }
9496
9497 bool
9498 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
9499                                           EVT VT) const {
9500   unsigned NumElts = VT.getVectorNumElements();
9501   // FIXME: This collection of masks seems suspect.
9502   if (NumElts == 2)
9503     return true;
9504   if (NumElts == 4 && VT.getSizeInBits() == 128) {
9505     return (isMOVLMask(Mask, VT)  ||
9506             isCommutedMOVLMask(Mask, VT, true) ||
9507             isSHUFPMask(Mask, VT) ||
9508             isCommutedSHUFPMask(Mask, VT));
9509   }
9510   return false;
9511 }
9512
9513 //===----------------------------------------------------------------------===//
9514 //                           X86 Scheduler Hooks
9515 //===----------------------------------------------------------------------===//
9516
9517 // private utility function
9518 MachineBasicBlock *
9519 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
9520                                                        MachineBasicBlock *MBB,
9521                                                        unsigned regOpc,
9522                                                        unsigned immOpc,
9523                                                        unsigned LoadOpc,
9524                                                        unsigned CXchgOpc,
9525                                                        unsigned notOpc,
9526                                                        unsigned EAXreg,
9527                                                        TargetRegisterClass *RC,
9528                                                        bool invSrc) const {
9529   // For the atomic bitwise operator, we generate
9530   //   thisMBB:
9531   //   newMBB:
9532   //     ld  t1 = [bitinstr.addr]
9533   //     op  t2 = t1, [bitinstr.val]
9534   //     mov EAX = t1
9535   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
9536   //     bz  newMBB
9537   //     fallthrough -->nextMBB
9538   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9539   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9540   MachineFunction::iterator MBBIter = MBB;
9541   ++MBBIter;
9542
9543   /// First build the CFG
9544   MachineFunction *F = MBB->getParent();
9545   MachineBasicBlock *thisMBB = MBB;
9546   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9547   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9548   F->insert(MBBIter, newMBB);
9549   F->insert(MBBIter, nextMBB);
9550
9551   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9552   nextMBB->splice(nextMBB->begin(), thisMBB,
9553                   llvm::next(MachineBasicBlock::iterator(bInstr)),
9554                   thisMBB->end());
9555   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9556
9557   // Update thisMBB to fall through to newMBB
9558   thisMBB->addSuccessor(newMBB);
9559
9560   // newMBB jumps to itself and fall through to nextMBB
9561   newMBB->addSuccessor(nextMBB);
9562   newMBB->addSuccessor(newMBB);
9563
9564   // Insert instructions into newMBB based on incoming instruction
9565   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9566          "unexpected number of operands");
9567   DebugLoc dl = bInstr->getDebugLoc();
9568   MachineOperand& destOper = bInstr->getOperand(0);
9569   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9570   int numArgs = bInstr->getNumOperands() - 1;
9571   for (int i=0; i < numArgs; ++i)
9572     argOpers[i] = &bInstr->getOperand(i+1);
9573
9574   // x86 address has 4 operands: base, index, scale, and displacement
9575   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9576   int valArgIndx = lastAddrIndx + 1;
9577
9578   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9579   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
9580   for (int i=0; i <= lastAddrIndx; ++i)
9581     (*MIB).addOperand(*argOpers[i]);
9582
9583   unsigned tt = F->getRegInfo().createVirtualRegister(RC);
9584   if (invSrc) {
9585     MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
9586   }
9587   else
9588     tt = t1;
9589
9590   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9591   assert((argOpers[valArgIndx]->isReg() ||
9592           argOpers[valArgIndx]->isImm()) &&
9593          "invalid operand");
9594   if (argOpers[valArgIndx]->isReg())
9595     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
9596   else
9597     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
9598   MIB.addReg(tt);
9599   (*MIB).addOperand(*argOpers[valArgIndx]);
9600
9601   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
9602   MIB.addReg(t1);
9603
9604   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
9605   for (int i=0; i <= lastAddrIndx; ++i)
9606     (*MIB).addOperand(*argOpers[i]);
9607   MIB.addReg(t2);
9608   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9609   (*MIB).setMemRefs(bInstr->memoperands_begin(),
9610                     bInstr->memoperands_end());
9611
9612   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9613   MIB.addReg(EAXreg);
9614
9615   // insert branch
9616   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9617
9618   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
9619   return nextMBB;
9620 }
9621
9622 // private utility function:  64 bit atomics on 32 bit host.
9623 MachineBasicBlock *
9624 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
9625                                                        MachineBasicBlock *MBB,
9626                                                        unsigned regOpcL,
9627                                                        unsigned regOpcH,
9628                                                        unsigned immOpcL,
9629                                                        unsigned immOpcH,
9630                                                        bool invSrc) const {
9631   // For the atomic bitwise operator, we generate
9632   //   thisMBB (instructions are in pairs, except cmpxchg8b)
9633   //     ld t1,t2 = [bitinstr.addr]
9634   //   newMBB:
9635   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
9636   //     op  t5, t6 <- out1, out2, [bitinstr.val]
9637   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
9638   //     mov ECX, EBX <- t5, t6
9639   //     mov EAX, EDX <- t1, t2
9640   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
9641   //     mov t3, t4 <- EAX, EDX
9642   //     bz  newMBB
9643   //     result in out1, out2
9644   //     fallthrough -->nextMBB
9645
9646   const TargetRegisterClass *RC = X86::GR32RegisterClass;
9647   const unsigned LoadOpc = X86::MOV32rm;
9648   const unsigned NotOpc = X86::NOT32r;
9649   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9650   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9651   MachineFunction::iterator MBBIter = MBB;
9652   ++MBBIter;
9653
9654   /// First build the CFG
9655   MachineFunction *F = MBB->getParent();
9656   MachineBasicBlock *thisMBB = MBB;
9657   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9658   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9659   F->insert(MBBIter, newMBB);
9660   F->insert(MBBIter, nextMBB);
9661
9662   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9663   nextMBB->splice(nextMBB->begin(), thisMBB,
9664                   llvm::next(MachineBasicBlock::iterator(bInstr)),
9665                   thisMBB->end());
9666   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9667
9668   // Update thisMBB to fall through to newMBB
9669   thisMBB->addSuccessor(newMBB);
9670
9671   // newMBB jumps to itself and fall through to nextMBB
9672   newMBB->addSuccessor(nextMBB);
9673   newMBB->addSuccessor(newMBB);
9674
9675   DebugLoc dl = bInstr->getDebugLoc();
9676   // Insert instructions into newMBB based on incoming instruction
9677   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
9678   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
9679          "unexpected number of operands");
9680   MachineOperand& dest1Oper = bInstr->getOperand(0);
9681   MachineOperand& dest2Oper = bInstr->getOperand(1);
9682   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9683   for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
9684     argOpers[i] = &bInstr->getOperand(i+2);
9685
9686     // We use some of the operands multiple times, so conservatively just
9687     // clear any kill flags that might be present.
9688     if (argOpers[i]->isReg() && argOpers[i]->isUse())
9689       argOpers[i]->setIsKill(false);
9690   }
9691
9692   // x86 address has 5 operands: base, index, scale, displacement, and segment.
9693   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9694
9695   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9696   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
9697   for (int i=0; i <= lastAddrIndx; ++i)
9698     (*MIB).addOperand(*argOpers[i]);
9699   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9700   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
9701   // add 4 to displacement.
9702   for (int i=0; i <= lastAddrIndx-2; ++i)
9703     (*MIB).addOperand(*argOpers[i]);
9704   MachineOperand newOp3 = *(argOpers[3]);
9705   if (newOp3.isImm())
9706     newOp3.setImm(newOp3.getImm()+4);
9707   else
9708     newOp3.setOffset(newOp3.getOffset()+4);
9709   (*MIB).addOperand(newOp3);
9710   (*MIB).addOperand(*argOpers[lastAddrIndx]);
9711
9712   // t3/4 are defined later, at the bottom of the loop
9713   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
9714   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
9715   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
9716     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
9717   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
9718     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
9719
9720   // The subsequent operations should be using the destination registers of
9721   //the PHI instructions.
9722   if (invSrc) {
9723     t1 = F->getRegInfo().createVirtualRegister(RC);
9724     t2 = F->getRegInfo().createVirtualRegister(RC);
9725     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
9726     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
9727   } else {
9728     t1 = dest1Oper.getReg();
9729     t2 = dest2Oper.getReg();
9730   }
9731
9732   int valArgIndx = lastAddrIndx + 1;
9733   assert((argOpers[valArgIndx]->isReg() ||
9734           argOpers[valArgIndx]->isImm()) &&
9735          "invalid operand");
9736   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
9737   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
9738   if (argOpers[valArgIndx]->isReg())
9739     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
9740   else
9741     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
9742   if (regOpcL != X86::MOV32rr)
9743     MIB.addReg(t1);
9744   (*MIB).addOperand(*argOpers[valArgIndx]);
9745   assert(argOpers[valArgIndx + 1]->isReg() ==
9746          argOpers[valArgIndx]->isReg());
9747   assert(argOpers[valArgIndx + 1]->isImm() ==
9748          argOpers[valArgIndx]->isImm());
9749   if (argOpers[valArgIndx + 1]->isReg())
9750     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
9751   else
9752     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
9753   if (regOpcH != X86::MOV32rr)
9754     MIB.addReg(t2);
9755   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
9756
9757   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9758   MIB.addReg(t1);
9759   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
9760   MIB.addReg(t2);
9761
9762   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
9763   MIB.addReg(t5);
9764   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
9765   MIB.addReg(t6);
9766
9767   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
9768   for (int i=0; i <= lastAddrIndx; ++i)
9769     (*MIB).addOperand(*argOpers[i]);
9770
9771   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9772   (*MIB).setMemRefs(bInstr->memoperands_begin(),
9773                     bInstr->memoperands_end());
9774
9775   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
9776   MIB.addReg(X86::EAX);
9777   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
9778   MIB.addReg(X86::EDX);
9779
9780   // insert branch
9781   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9782
9783   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
9784   return nextMBB;
9785 }
9786
9787 // private utility function
9788 MachineBasicBlock *
9789 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
9790                                                       MachineBasicBlock *MBB,
9791                                                       unsigned cmovOpc) const {
9792   // For the atomic min/max operator, we generate
9793   //   thisMBB:
9794   //   newMBB:
9795   //     ld t1 = [min/max.addr]
9796   //     mov t2 = [min/max.val]
9797   //     cmp  t1, t2
9798   //     cmov[cond] t2 = t1
9799   //     mov EAX = t1
9800   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
9801   //     bz   newMBB
9802   //     fallthrough -->nextMBB
9803   //
9804   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9805   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9806   MachineFunction::iterator MBBIter = MBB;
9807   ++MBBIter;
9808
9809   /// First build the CFG
9810   MachineFunction *F = MBB->getParent();
9811   MachineBasicBlock *thisMBB = MBB;
9812   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9813   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9814   F->insert(MBBIter, newMBB);
9815   F->insert(MBBIter, nextMBB);
9816
9817   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9818   nextMBB->splice(nextMBB->begin(), thisMBB,
9819                   llvm::next(MachineBasicBlock::iterator(mInstr)),
9820                   thisMBB->end());
9821   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9822
9823   // Update thisMBB to fall through to newMBB
9824   thisMBB->addSuccessor(newMBB);
9825
9826   // newMBB jumps to newMBB and fall through to nextMBB
9827   newMBB->addSuccessor(nextMBB);
9828   newMBB->addSuccessor(newMBB);
9829
9830   DebugLoc dl = mInstr->getDebugLoc();
9831   // Insert instructions into newMBB based on incoming instruction
9832   assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9833          "unexpected number of operands");
9834   MachineOperand& destOper = mInstr->getOperand(0);
9835   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9836   int numArgs = mInstr->getNumOperands() - 1;
9837   for (int i=0; i < numArgs; ++i)
9838     argOpers[i] = &mInstr->getOperand(i+1);
9839
9840   // x86 address has 4 operands: base, index, scale, and displacement
9841   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9842   int valArgIndx = lastAddrIndx + 1;
9843
9844   unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9845   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
9846   for (int i=0; i <= lastAddrIndx; ++i)
9847     (*MIB).addOperand(*argOpers[i]);
9848
9849   // We only support register and immediate values
9850   assert((argOpers[valArgIndx]->isReg() ||
9851           argOpers[valArgIndx]->isImm()) &&
9852          "invalid operand");
9853
9854   unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9855   if (argOpers[valArgIndx]->isReg())
9856     MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
9857   else
9858     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
9859   (*MIB).addOperand(*argOpers[valArgIndx]);
9860
9861   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9862   MIB.addReg(t1);
9863
9864   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
9865   MIB.addReg(t1);
9866   MIB.addReg(t2);
9867
9868   // Generate movc
9869   unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9870   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
9871   MIB.addReg(t2);
9872   MIB.addReg(t1);
9873
9874   // Cmp and exchange if none has modified the memory location
9875   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
9876   for (int i=0; i <= lastAddrIndx; ++i)
9877     (*MIB).addOperand(*argOpers[i]);
9878   MIB.addReg(t3);
9879   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9880   (*MIB).setMemRefs(mInstr->memoperands_begin(),
9881                     mInstr->memoperands_end());
9882
9883   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9884   MIB.addReg(X86::EAX);
9885
9886   // insert branch
9887   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9888
9889   mInstr->eraseFromParent();   // The pseudo instruction is gone now.
9890   return nextMBB;
9891 }
9892
9893 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
9894 // or XMM0_V32I8 in AVX all of this code can be replaced with that
9895 // in the .td file.
9896 MachineBasicBlock *
9897 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
9898                             unsigned numArgs, bool memArg) const {
9899   assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
9900          "Target must have SSE4.2 or AVX features enabled");
9901
9902   DebugLoc dl = MI->getDebugLoc();
9903   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9904   unsigned Opc;
9905   if (!Subtarget->hasAVX()) {
9906     if (memArg)
9907       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
9908     else
9909       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
9910   } else {
9911     if (memArg)
9912       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
9913     else
9914       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
9915   }
9916
9917   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
9918   for (unsigned i = 0; i < numArgs; ++i) {
9919     MachineOperand &Op = MI->getOperand(i+1);
9920     if (!(Op.isReg() && Op.isImplicit()))
9921       MIB.addOperand(Op);
9922   }
9923   BuildMI(*BB, MI, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
9924     .addReg(X86::XMM0);
9925
9926   MI->eraseFromParent();
9927   return BB;
9928 }
9929
9930 MachineBasicBlock *
9931 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
9932   DebugLoc dl = MI->getDebugLoc();
9933   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9934
9935   // Address into RAX/EAX, other two args into ECX, EDX.
9936   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
9937   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
9938   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
9939   for (int i = 0; i < X86::AddrNumOperands; ++i)
9940     MIB.addOperand(MI->getOperand(i));
9941
9942   unsigned ValOps = X86::AddrNumOperands;
9943   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
9944     .addReg(MI->getOperand(ValOps).getReg());
9945   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
9946     .addReg(MI->getOperand(ValOps+1).getReg());
9947
9948   // The instruction doesn't actually take any operands though.
9949   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
9950
9951   MI->eraseFromParent(); // The pseudo is gone now.
9952   return BB;
9953 }
9954
9955 MachineBasicBlock *
9956 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
9957   DebugLoc dl = MI->getDebugLoc();
9958   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9959
9960   // First arg in ECX, the second in EAX.
9961   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
9962     .addReg(MI->getOperand(0).getReg());
9963   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
9964     .addReg(MI->getOperand(1).getReg());
9965
9966   // The instruction doesn't actually take any operands though.
9967   BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
9968
9969   MI->eraseFromParent(); // The pseudo is gone now.
9970   return BB;
9971 }
9972
9973 MachineBasicBlock *
9974 X86TargetLowering::EmitVAARG64WithCustomInserter(
9975                    MachineInstr *MI,
9976                    MachineBasicBlock *MBB) const {
9977   // Emit va_arg instruction on X86-64.
9978
9979   // Operands to this pseudo-instruction:
9980   // 0  ) Output        : destination address (reg)
9981   // 1-5) Input         : va_list address (addr, i64mem)
9982   // 6  ) ArgSize       : Size (in bytes) of vararg type
9983   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
9984   // 8  ) Align         : Alignment of type
9985   // 9  ) EFLAGS (implicit-def)
9986
9987   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
9988   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
9989
9990   unsigned DestReg = MI->getOperand(0).getReg();
9991   MachineOperand &Base = MI->getOperand(1);
9992   MachineOperand &Scale = MI->getOperand(2);
9993   MachineOperand &Index = MI->getOperand(3);
9994   MachineOperand &Disp = MI->getOperand(4);
9995   MachineOperand &Segment = MI->getOperand(5);
9996   unsigned ArgSize = MI->getOperand(6).getImm();
9997   unsigned ArgMode = MI->getOperand(7).getImm();
9998   unsigned Align = MI->getOperand(8).getImm();
9999
10000   // Memory Reference
10001   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
10002   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
10003   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
10004
10005   // Machine Information
10006   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10007   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
10008   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
10009   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
10010   DebugLoc DL = MI->getDebugLoc();
10011
10012   // struct va_list {
10013   //   i32   gp_offset
10014   //   i32   fp_offset
10015   //   i64   overflow_area (address)
10016   //   i64   reg_save_area (address)
10017   // }
10018   // sizeof(va_list) = 24
10019   // alignment(va_list) = 8
10020
10021   unsigned TotalNumIntRegs = 6;
10022   unsigned TotalNumXMMRegs = 8;
10023   bool UseGPOffset = (ArgMode == 1);
10024   bool UseFPOffset = (ArgMode == 2);
10025   unsigned MaxOffset = TotalNumIntRegs * 8 +
10026                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
10027
10028   /* Align ArgSize to a multiple of 8 */
10029   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
10030   bool NeedsAlign = (Align > 8);
10031
10032   MachineBasicBlock *thisMBB = MBB;
10033   MachineBasicBlock *overflowMBB;
10034   MachineBasicBlock *offsetMBB;
10035   MachineBasicBlock *endMBB;
10036
10037   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
10038   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
10039   unsigned OffsetReg = 0;
10040
10041   if (!UseGPOffset && !UseFPOffset) {
10042     // If we only pull from the overflow region, we don't create a branch.
10043     // We don't need to alter control flow.
10044     OffsetDestReg = 0; // unused
10045     OverflowDestReg = DestReg;
10046
10047     offsetMBB = NULL;
10048     overflowMBB = thisMBB;
10049     endMBB = thisMBB;
10050   } else {
10051     // First emit code to check if gp_offset (or fp_offset) is below the bound.
10052     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
10053     // If not, pull from overflow_area. (branch to overflowMBB)
10054     //
10055     //       thisMBB
10056     //         |     .
10057     //         |        .
10058     //     offsetMBB   overflowMBB
10059     //         |        .
10060     //         |     .
10061     //        endMBB
10062
10063     // Registers for the PHI in endMBB
10064     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
10065     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
10066
10067     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10068     MachineFunction *MF = MBB->getParent();
10069     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10070     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10071     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10072
10073     MachineFunction::iterator MBBIter = MBB;
10074     ++MBBIter;
10075
10076     // Insert the new basic blocks
10077     MF->insert(MBBIter, offsetMBB);
10078     MF->insert(MBBIter, overflowMBB);
10079     MF->insert(MBBIter, endMBB);
10080
10081     // Transfer the remainder of MBB and its successor edges to endMBB.
10082     endMBB->splice(endMBB->begin(), thisMBB,
10083                     llvm::next(MachineBasicBlock::iterator(MI)),
10084                     thisMBB->end());
10085     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
10086
10087     // Make offsetMBB and overflowMBB successors of thisMBB
10088     thisMBB->addSuccessor(offsetMBB);
10089     thisMBB->addSuccessor(overflowMBB);
10090
10091     // endMBB is a successor of both offsetMBB and overflowMBB
10092     offsetMBB->addSuccessor(endMBB);
10093     overflowMBB->addSuccessor(endMBB);
10094
10095     // Load the offset value into a register
10096     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
10097     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
10098       .addOperand(Base)
10099       .addOperand(Scale)
10100       .addOperand(Index)
10101       .addDisp(Disp, UseFPOffset ? 4 : 0)
10102       .addOperand(Segment)
10103       .setMemRefs(MMOBegin, MMOEnd);
10104
10105     // Check if there is enough room left to pull this argument.
10106     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
10107       .addReg(OffsetReg)
10108       .addImm(MaxOffset + 8 - ArgSizeA8);
10109
10110     // Branch to "overflowMBB" if offset >= max
10111     // Fall through to "offsetMBB" otherwise
10112     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
10113       .addMBB(overflowMBB);
10114   }
10115
10116   // In offsetMBB, emit code to use the reg_save_area.
10117   if (offsetMBB) {
10118     assert(OffsetReg != 0);
10119
10120     // Read the reg_save_area address.
10121     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
10122     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
10123       .addOperand(Base)
10124       .addOperand(Scale)
10125       .addOperand(Index)
10126       .addDisp(Disp, 16)
10127       .addOperand(Segment)
10128       .setMemRefs(MMOBegin, MMOEnd);
10129
10130     // Zero-extend the offset
10131     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
10132       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
10133         .addImm(0)
10134         .addReg(OffsetReg)
10135         .addImm(X86::sub_32bit);
10136
10137     // Add the offset to the reg_save_area to get the final address.
10138     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
10139       .addReg(OffsetReg64)
10140       .addReg(RegSaveReg);
10141
10142     // Compute the offset for the next argument
10143     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
10144     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
10145       .addReg(OffsetReg)
10146       .addImm(UseFPOffset ? 16 : 8);
10147
10148     // Store it back into the va_list.
10149     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
10150       .addOperand(Base)
10151       .addOperand(Scale)
10152       .addOperand(Index)
10153       .addDisp(Disp, UseFPOffset ? 4 : 0)
10154       .addOperand(Segment)
10155       .addReg(NextOffsetReg)
10156       .setMemRefs(MMOBegin, MMOEnd);
10157
10158     // Jump to endMBB
10159     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
10160       .addMBB(endMBB);
10161   }
10162
10163   //
10164   // Emit code to use overflow area
10165   //
10166
10167   // Load the overflow_area address into a register.
10168   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
10169   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
10170     .addOperand(Base)
10171     .addOperand(Scale)
10172     .addOperand(Index)
10173     .addDisp(Disp, 8)
10174     .addOperand(Segment)
10175     .setMemRefs(MMOBegin, MMOEnd);
10176
10177   // If we need to align it, do so. Otherwise, just copy the address
10178   // to OverflowDestReg.
10179   if (NeedsAlign) {
10180     // Align the overflow address
10181     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
10182     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
10183
10184     // aligned_addr = (addr + (align-1)) & ~(align-1)
10185     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
10186       .addReg(OverflowAddrReg)
10187       .addImm(Align-1);
10188
10189     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
10190       .addReg(TmpReg)
10191       .addImm(~(uint64_t)(Align-1));
10192   } else {
10193     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
10194       .addReg(OverflowAddrReg);
10195   }
10196
10197   // Compute the next overflow address after this argument.
10198   // (the overflow address should be kept 8-byte aligned)
10199   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
10200   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
10201     .addReg(OverflowDestReg)
10202     .addImm(ArgSizeA8);
10203
10204   // Store the new overflow address.
10205   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
10206     .addOperand(Base)
10207     .addOperand(Scale)
10208     .addOperand(Index)
10209     .addDisp(Disp, 8)
10210     .addOperand(Segment)
10211     .addReg(NextAddrReg)
10212     .setMemRefs(MMOBegin, MMOEnd);
10213
10214   // If we branched, emit the PHI to the front of endMBB.
10215   if (offsetMBB) {
10216     BuildMI(*endMBB, endMBB->begin(), DL,
10217             TII->get(X86::PHI), DestReg)
10218       .addReg(OffsetDestReg).addMBB(offsetMBB)
10219       .addReg(OverflowDestReg).addMBB(overflowMBB);
10220   }
10221
10222   // Erase the pseudo instruction
10223   MI->eraseFromParent();
10224
10225   return endMBB;
10226 }
10227
10228 MachineBasicBlock *
10229 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
10230                                                  MachineInstr *MI,
10231                                                  MachineBasicBlock *MBB) const {
10232   // Emit code to save XMM registers to the stack. The ABI says that the
10233   // number of registers to save is given in %al, so it's theoretically
10234   // possible to do an indirect jump trick to avoid saving all of them,
10235   // however this code takes a simpler approach and just executes all
10236   // of the stores if %al is non-zero. It's less code, and it's probably
10237   // easier on the hardware branch predictor, and stores aren't all that
10238   // expensive anyway.
10239
10240   // Create the new basic blocks. One block contains all the XMM stores,
10241   // and one block is the final destination regardless of whether any
10242   // stores were performed.
10243   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10244   MachineFunction *F = MBB->getParent();
10245   MachineFunction::iterator MBBIter = MBB;
10246   ++MBBIter;
10247   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
10248   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
10249   F->insert(MBBIter, XMMSaveMBB);
10250   F->insert(MBBIter, EndMBB);
10251
10252   // Transfer the remainder of MBB and its successor edges to EndMBB.
10253   EndMBB->splice(EndMBB->begin(), MBB,
10254                  llvm::next(MachineBasicBlock::iterator(MI)),
10255                  MBB->end());
10256   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
10257
10258   // The original block will now fall through to the XMM save block.
10259   MBB->addSuccessor(XMMSaveMBB);
10260   // The XMMSaveMBB will fall through to the end block.
10261   XMMSaveMBB->addSuccessor(EndMBB);
10262
10263   // Now add the instructions.
10264   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10265   DebugLoc DL = MI->getDebugLoc();
10266
10267   unsigned CountReg = MI->getOperand(0).getReg();
10268   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
10269   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
10270
10271   if (!Subtarget->isTargetWin64()) {
10272     // If %al is 0, branch around the XMM save block.
10273     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
10274     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
10275     MBB->addSuccessor(EndMBB);
10276   }
10277
10278   // In the XMM save block, save all the XMM argument registers.
10279   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
10280     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
10281     MachineMemOperand *MMO =
10282       F->getMachineMemOperand(
10283           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
10284         MachineMemOperand::MOStore,
10285         /*Size=*/16, /*Align=*/16);
10286     BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
10287       .addFrameIndex(RegSaveFrameIndex)
10288       .addImm(/*Scale=*/1)
10289       .addReg(/*IndexReg=*/0)
10290       .addImm(/*Disp=*/Offset)
10291       .addReg(/*Segment=*/0)
10292       .addReg(MI->getOperand(i).getReg())
10293       .addMemOperand(MMO);
10294   }
10295
10296   MI->eraseFromParent();   // The pseudo instruction is gone now.
10297
10298   return EndMBB;
10299 }
10300
10301 MachineBasicBlock *
10302 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
10303                                      MachineBasicBlock *BB) const {
10304   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10305   DebugLoc DL = MI->getDebugLoc();
10306
10307   // To "insert" a SELECT_CC instruction, we actually have to insert the
10308   // diamond control-flow pattern.  The incoming instruction knows the
10309   // destination vreg to set, the condition code register to branch on, the
10310   // true/false values to select between, and a branch opcode to use.
10311   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10312   MachineFunction::iterator It = BB;
10313   ++It;
10314
10315   //  thisMBB:
10316   //  ...
10317   //   TrueVal = ...
10318   //   cmpTY ccX, r1, r2
10319   //   bCC copy1MBB
10320   //   fallthrough --> copy0MBB
10321   MachineBasicBlock *thisMBB = BB;
10322   MachineFunction *F = BB->getParent();
10323   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
10324   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
10325   F->insert(It, copy0MBB);
10326   F->insert(It, sinkMBB);
10327
10328   // If the EFLAGS register isn't dead in the terminator, then claim that it's
10329   // live into the sink and copy blocks.
10330   const MachineFunction *MF = BB->getParent();
10331   const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
10332   BitVector ReservedRegs = TRI->getReservedRegs(*MF);
10333
10334   for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
10335     const MachineOperand &MO = MI->getOperand(I);
10336     if (!MO.isReg() || !MO.isUse() || MO.isKill()) continue;
10337     unsigned Reg = MO.getReg();
10338     if (Reg != X86::EFLAGS) continue;
10339     copy0MBB->addLiveIn(Reg);
10340     sinkMBB->addLiveIn(Reg);
10341   }
10342
10343   // Transfer the remainder of BB and its successor edges to sinkMBB.
10344   sinkMBB->splice(sinkMBB->begin(), BB,
10345                   llvm::next(MachineBasicBlock::iterator(MI)),
10346                   BB->end());
10347   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
10348
10349   // Add the true and fallthrough blocks as its successors.
10350   BB->addSuccessor(copy0MBB);
10351   BB->addSuccessor(sinkMBB);
10352
10353   // Create the conditional branch instruction.
10354   unsigned Opc =
10355     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
10356   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
10357
10358   //  copy0MBB:
10359   //   %FalseValue = ...
10360   //   # fallthrough to sinkMBB
10361   copy0MBB->addSuccessor(sinkMBB);
10362
10363   //  sinkMBB:
10364   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
10365   //  ...
10366   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
10367           TII->get(X86::PHI), MI->getOperand(0).getReg())
10368     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
10369     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
10370
10371   MI->eraseFromParent();   // The pseudo instruction is gone now.
10372   return sinkMBB;
10373 }
10374
10375 MachineBasicBlock *
10376 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
10377                                           MachineBasicBlock *BB) const {
10378   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10379   DebugLoc DL = MI->getDebugLoc();
10380
10381   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
10382   // non-trivial part is impdef of ESP.
10383   // FIXME: The code should be tweaked as soon as we'll try to do codegen for
10384   // mingw-w64.
10385
10386   const char *StackProbeSymbol =
10387       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
10388
10389   BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
10390     .addExternalSymbol(StackProbeSymbol)
10391     .addReg(X86::EAX, RegState::Implicit)
10392     .addReg(X86::ESP, RegState::Implicit)
10393     .addReg(X86::EAX, RegState::Define | RegState::Implicit)
10394     .addReg(X86::ESP, RegState::Define | RegState::Implicit)
10395     .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10396
10397   MI->eraseFromParent();   // The pseudo instruction is gone now.
10398   return BB;
10399 }
10400
10401 MachineBasicBlock *
10402 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
10403                                       MachineBasicBlock *BB) const {
10404   // This is pretty easy.  We're taking the value that we received from
10405   // our load from the relocation, sticking it in either RDI (x86-64)
10406   // or EAX and doing an indirect call.  The return value will then
10407   // be in the normal return register.
10408   const X86InstrInfo *TII
10409     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
10410   DebugLoc DL = MI->getDebugLoc();
10411   MachineFunction *F = BB->getParent();
10412
10413   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
10414   assert(MI->getOperand(3).isGlobal() && "This should be a global");
10415
10416   if (Subtarget->is64Bit()) {
10417     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10418                                       TII->get(X86::MOV64rm), X86::RDI)
10419     .addReg(X86::RIP)
10420     .addImm(0).addReg(0)
10421     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10422                       MI->getOperand(3).getTargetFlags())
10423     .addReg(0);
10424     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
10425     addDirectMem(MIB, X86::RDI);
10426   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
10427     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10428                                       TII->get(X86::MOV32rm), X86::EAX)
10429     .addReg(0)
10430     .addImm(0).addReg(0)
10431     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10432                       MI->getOperand(3).getTargetFlags())
10433     .addReg(0);
10434     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10435     addDirectMem(MIB, X86::EAX);
10436   } else {
10437     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10438                                       TII->get(X86::MOV32rm), X86::EAX)
10439     .addReg(TII->getGlobalBaseReg(F))
10440     .addImm(0).addReg(0)
10441     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10442                       MI->getOperand(3).getTargetFlags())
10443     .addReg(0);
10444     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10445     addDirectMem(MIB, X86::EAX);
10446   }
10447
10448   MI->eraseFromParent(); // The pseudo instruction is gone now.
10449   return BB;
10450 }
10451
10452 MachineBasicBlock *
10453 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
10454                                                MachineBasicBlock *BB) const {
10455   switch (MI->getOpcode()) {
10456   default: assert(false && "Unexpected instr type to insert");
10457   case X86::TAILJMPd64:
10458   case X86::TAILJMPr64:
10459   case X86::TAILJMPm64:
10460     assert(!"TAILJMP64 would not be touched here.");
10461   case X86::TCRETURNdi64:
10462   case X86::TCRETURNri64:
10463   case X86::TCRETURNmi64:
10464     // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset.
10465     // On AMD64, additional defs should be added before register allocation.
10466     if (!Subtarget->isTargetWin64()) {
10467       MI->addRegisterDefined(X86::RSI);
10468       MI->addRegisterDefined(X86::RDI);
10469       MI->addRegisterDefined(X86::XMM6);
10470       MI->addRegisterDefined(X86::XMM7);
10471       MI->addRegisterDefined(X86::XMM8);
10472       MI->addRegisterDefined(X86::XMM9);
10473       MI->addRegisterDefined(X86::XMM10);
10474       MI->addRegisterDefined(X86::XMM11);
10475       MI->addRegisterDefined(X86::XMM12);
10476       MI->addRegisterDefined(X86::XMM13);
10477       MI->addRegisterDefined(X86::XMM14);
10478       MI->addRegisterDefined(X86::XMM15);
10479     }
10480     return BB;
10481   case X86::WIN_ALLOCA:
10482     return EmitLoweredWinAlloca(MI, BB);
10483   case X86::TLSCall_32:
10484   case X86::TLSCall_64:
10485     return EmitLoweredTLSCall(MI, BB);
10486   case X86::CMOV_GR8:
10487   case X86::CMOV_FR32:
10488   case X86::CMOV_FR64:
10489   case X86::CMOV_V4F32:
10490   case X86::CMOV_V2F64:
10491   case X86::CMOV_V2I64:
10492   case X86::CMOV_GR16:
10493   case X86::CMOV_GR32:
10494   case X86::CMOV_RFP32:
10495   case X86::CMOV_RFP64:
10496   case X86::CMOV_RFP80:
10497     return EmitLoweredSelect(MI, BB);
10498
10499   case X86::FP32_TO_INT16_IN_MEM:
10500   case X86::FP32_TO_INT32_IN_MEM:
10501   case X86::FP32_TO_INT64_IN_MEM:
10502   case X86::FP64_TO_INT16_IN_MEM:
10503   case X86::FP64_TO_INT32_IN_MEM:
10504   case X86::FP64_TO_INT64_IN_MEM:
10505   case X86::FP80_TO_INT16_IN_MEM:
10506   case X86::FP80_TO_INT32_IN_MEM:
10507   case X86::FP80_TO_INT64_IN_MEM: {
10508     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10509     DebugLoc DL = MI->getDebugLoc();
10510
10511     // Change the floating point control register to use "round towards zero"
10512     // mode when truncating to an integer value.
10513     MachineFunction *F = BB->getParent();
10514     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
10515     addFrameReference(BuildMI(*BB, MI, DL,
10516                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
10517
10518     // Load the old value of the high byte of the control word...
10519     unsigned OldCW =
10520       F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
10521     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
10522                       CWFrameIdx);
10523
10524     // Set the high part to be round to zero...
10525     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
10526       .addImm(0xC7F);
10527
10528     // Reload the modified control word now...
10529     addFrameReference(BuildMI(*BB, MI, DL,
10530                               TII->get(X86::FLDCW16m)), CWFrameIdx);
10531
10532     // Restore the memory image of control word to original value
10533     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
10534       .addReg(OldCW);
10535
10536     // Get the X86 opcode to use.
10537     unsigned Opc;
10538     switch (MI->getOpcode()) {
10539     default: llvm_unreachable("illegal opcode!");
10540     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
10541     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
10542     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
10543     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
10544     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
10545     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
10546     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
10547     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
10548     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
10549     }
10550
10551     X86AddressMode AM;
10552     MachineOperand &Op = MI->getOperand(0);
10553     if (Op.isReg()) {
10554       AM.BaseType = X86AddressMode::RegBase;
10555       AM.Base.Reg = Op.getReg();
10556     } else {
10557       AM.BaseType = X86AddressMode::FrameIndexBase;
10558       AM.Base.FrameIndex = Op.getIndex();
10559     }
10560     Op = MI->getOperand(1);
10561     if (Op.isImm())
10562       AM.Scale = Op.getImm();
10563     Op = MI->getOperand(2);
10564     if (Op.isImm())
10565       AM.IndexReg = Op.getImm();
10566     Op = MI->getOperand(3);
10567     if (Op.isGlobal()) {
10568       AM.GV = Op.getGlobal();
10569     } else {
10570       AM.Disp = Op.getImm();
10571     }
10572     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
10573                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
10574
10575     // Reload the original control word now.
10576     addFrameReference(BuildMI(*BB, MI, DL,
10577                               TII->get(X86::FLDCW16m)), CWFrameIdx);
10578
10579     MI->eraseFromParent();   // The pseudo instruction is gone now.
10580     return BB;
10581   }
10582     // String/text processing lowering.
10583   case X86::PCMPISTRM128REG:
10584   case X86::VPCMPISTRM128REG:
10585     return EmitPCMP(MI, BB, 3, false /* in-mem */);
10586   case X86::PCMPISTRM128MEM:
10587   case X86::VPCMPISTRM128MEM:
10588     return EmitPCMP(MI, BB, 3, true /* in-mem */);
10589   case X86::PCMPESTRM128REG:
10590   case X86::VPCMPESTRM128REG:
10591     return EmitPCMP(MI, BB, 5, false /* in mem */);
10592   case X86::PCMPESTRM128MEM:
10593   case X86::VPCMPESTRM128MEM:
10594     return EmitPCMP(MI, BB, 5, true /* in mem */);
10595
10596     // Thread synchronization.
10597   case X86::MONITOR:
10598     return EmitMonitor(MI, BB);
10599   case X86::MWAIT:
10600     return EmitMwait(MI, BB);
10601
10602     // Atomic Lowering.
10603   case X86::ATOMAND32:
10604     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10605                                                X86::AND32ri, X86::MOV32rm,
10606                                                X86::LCMPXCHG32,
10607                                                X86::NOT32r, X86::EAX,
10608                                                X86::GR32RegisterClass);
10609   case X86::ATOMOR32:
10610     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
10611                                                X86::OR32ri, X86::MOV32rm,
10612                                                X86::LCMPXCHG32,
10613                                                X86::NOT32r, X86::EAX,
10614                                                X86::GR32RegisterClass);
10615   case X86::ATOMXOR32:
10616     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
10617                                                X86::XOR32ri, X86::MOV32rm,
10618                                                X86::LCMPXCHG32,
10619                                                X86::NOT32r, X86::EAX,
10620                                                X86::GR32RegisterClass);
10621   case X86::ATOMNAND32:
10622     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10623                                                X86::AND32ri, X86::MOV32rm,
10624                                                X86::LCMPXCHG32,
10625                                                X86::NOT32r, X86::EAX,
10626                                                X86::GR32RegisterClass, true);
10627   case X86::ATOMMIN32:
10628     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
10629   case X86::ATOMMAX32:
10630     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
10631   case X86::ATOMUMIN32:
10632     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
10633   case X86::ATOMUMAX32:
10634     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
10635
10636   case X86::ATOMAND16:
10637     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10638                                                X86::AND16ri, X86::MOV16rm,
10639                                                X86::LCMPXCHG16,
10640                                                X86::NOT16r, X86::AX,
10641                                                X86::GR16RegisterClass);
10642   case X86::ATOMOR16:
10643     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
10644                                                X86::OR16ri, X86::MOV16rm,
10645                                                X86::LCMPXCHG16,
10646                                                X86::NOT16r, X86::AX,
10647                                                X86::GR16RegisterClass);
10648   case X86::ATOMXOR16:
10649     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
10650                                                X86::XOR16ri, X86::MOV16rm,
10651                                                X86::LCMPXCHG16,
10652                                                X86::NOT16r, X86::AX,
10653                                                X86::GR16RegisterClass);
10654   case X86::ATOMNAND16:
10655     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10656                                                X86::AND16ri, X86::MOV16rm,
10657                                                X86::LCMPXCHG16,
10658                                                X86::NOT16r, X86::AX,
10659                                                X86::GR16RegisterClass, true);
10660   case X86::ATOMMIN16:
10661     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
10662   case X86::ATOMMAX16:
10663     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
10664   case X86::ATOMUMIN16:
10665     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
10666   case X86::ATOMUMAX16:
10667     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
10668
10669   case X86::ATOMAND8:
10670     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10671                                                X86::AND8ri, X86::MOV8rm,
10672                                                X86::LCMPXCHG8,
10673                                                X86::NOT8r, X86::AL,
10674                                                X86::GR8RegisterClass);
10675   case X86::ATOMOR8:
10676     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
10677                                                X86::OR8ri, X86::MOV8rm,
10678                                                X86::LCMPXCHG8,
10679                                                X86::NOT8r, X86::AL,
10680                                                X86::GR8RegisterClass);
10681   case X86::ATOMXOR8:
10682     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
10683                                                X86::XOR8ri, X86::MOV8rm,
10684                                                X86::LCMPXCHG8,
10685                                                X86::NOT8r, X86::AL,
10686                                                X86::GR8RegisterClass);
10687   case X86::ATOMNAND8:
10688     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10689                                                X86::AND8ri, X86::MOV8rm,
10690                                                X86::LCMPXCHG8,
10691                                                X86::NOT8r, X86::AL,
10692                                                X86::GR8RegisterClass, true);
10693   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
10694   // This group is for 64-bit host.
10695   case X86::ATOMAND64:
10696     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10697                                                X86::AND64ri32, X86::MOV64rm,
10698                                                X86::LCMPXCHG64,
10699                                                X86::NOT64r, X86::RAX,
10700                                                X86::GR64RegisterClass);
10701   case X86::ATOMOR64:
10702     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
10703                                                X86::OR64ri32, X86::MOV64rm,
10704                                                X86::LCMPXCHG64,
10705                                                X86::NOT64r, X86::RAX,
10706                                                X86::GR64RegisterClass);
10707   case X86::ATOMXOR64:
10708     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
10709                                                X86::XOR64ri32, X86::MOV64rm,
10710                                                X86::LCMPXCHG64,
10711                                                X86::NOT64r, X86::RAX,
10712                                                X86::GR64RegisterClass);
10713   case X86::ATOMNAND64:
10714     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10715                                                X86::AND64ri32, X86::MOV64rm,
10716                                                X86::LCMPXCHG64,
10717                                                X86::NOT64r, X86::RAX,
10718                                                X86::GR64RegisterClass, true);
10719   case X86::ATOMMIN64:
10720     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
10721   case X86::ATOMMAX64:
10722     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
10723   case X86::ATOMUMIN64:
10724     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
10725   case X86::ATOMUMAX64:
10726     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
10727
10728   // This group does 64-bit operations on a 32-bit host.
10729   case X86::ATOMAND6432:
10730     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10731                                                X86::AND32rr, X86::AND32rr,
10732                                                X86::AND32ri, X86::AND32ri,
10733                                                false);
10734   case X86::ATOMOR6432:
10735     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10736                                                X86::OR32rr, X86::OR32rr,
10737                                                X86::OR32ri, X86::OR32ri,
10738                                                false);
10739   case X86::ATOMXOR6432:
10740     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10741                                                X86::XOR32rr, X86::XOR32rr,
10742                                                X86::XOR32ri, X86::XOR32ri,
10743                                                false);
10744   case X86::ATOMNAND6432:
10745     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10746                                                X86::AND32rr, X86::AND32rr,
10747                                                X86::AND32ri, X86::AND32ri,
10748                                                true);
10749   case X86::ATOMADD6432:
10750     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10751                                                X86::ADD32rr, X86::ADC32rr,
10752                                                X86::ADD32ri, X86::ADC32ri,
10753                                                false);
10754   case X86::ATOMSUB6432:
10755     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10756                                                X86::SUB32rr, X86::SBB32rr,
10757                                                X86::SUB32ri, X86::SBB32ri,
10758                                                false);
10759   case X86::ATOMSWAP6432:
10760     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10761                                                X86::MOV32rr, X86::MOV32rr,
10762                                                X86::MOV32ri, X86::MOV32ri,
10763                                                false);
10764   case X86::VASTART_SAVE_XMM_REGS:
10765     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
10766
10767   case X86::VAARG_64:
10768     return EmitVAARG64WithCustomInserter(MI, BB);
10769   }
10770 }
10771
10772 //===----------------------------------------------------------------------===//
10773 //                           X86 Optimization Hooks
10774 //===----------------------------------------------------------------------===//
10775
10776 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
10777                                                        const APInt &Mask,
10778                                                        APInt &KnownZero,
10779                                                        APInt &KnownOne,
10780                                                        const SelectionDAG &DAG,
10781                                                        unsigned Depth) const {
10782   unsigned Opc = Op.getOpcode();
10783   assert((Opc >= ISD::BUILTIN_OP_END ||
10784           Opc == ISD::INTRINSIC_WO_CHAIN ||
10785           Opc == ISD::INTRINSIC_W_CHAIN ||
10786           Opc == ISD::INTRINSIC_VOID) &&
10787          "Should use MaskedValueIsZero if you don't know whether Op"
10788          " is a target node!");
10789
10790   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
10791   switch (Opc) {
10792   default: break;
10793   case X86ISD::ADD:
10794   case X86ISD::SUB:
10795   case X86ISD::ADC:
10796   case X86ISD::SBB:
10797   case X86ISD::SMUL:
10798   case X86ISD::UMUL:
10799   case X86ISD::INC:
10800   case X86ISD::DEC:
10801   case X86ISD::OR:
10802   case X86ISD::XOR:
10803   case X86ISD::AND:
10804     // These nodes' second result is a boolean.
10805     if (Op.getResNo() == 0)
10806       break;
10807     // Fallthrough
10808   case X86ISD::SETCC:
10809     KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
10810                                        Mask.getBitWidth() - 1);
10811     break;
10812   }
10813 }
10814
10815 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
10816                                                          unsigned Depth) const {
10817   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
10818   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
10819     return Op.getValueType().getScalarType().getSizeInBits();
10820
10821   // Fallback case.
10822   return 1;
10823 }
10824
10825 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
10826 /// node is a GlobalAddress + offset.
10827 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
10828                                        const GlobalValue* &GA,
10829                                        int64_t &Offset) const {
10830   if (N->getOpcode() == X86ISD::Wrapper) {
10831     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
10832       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
10833       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
10834       return true;
10835     }
10836   }
10837   return TargetLowering::isGAPlusOffset(N, GA, Offset);
10838 }
10839
10840 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
10841 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
10842 /// if the load addresses are consecutive, non-overlapping, and in the right
10843 /// order.
10844 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
10845                                      TargetLowering::DAGCombinerInfo &DCI) {
10846   DebugLoc dl = N->getDebugLoc();
10847   EVT VT = N->getValueType(0);
10848
10849   if (VT.getSizeInBits() != 128)
10850     return SDValue();
10851
10852   // Don't create instructions with illegal types after legalize types has run.
10853   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10854   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
10855     return SDValue();
10856
10857   SmallVector<SDValue, 16> Elts;
10858   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
10859     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
10860
10861   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
10862 }
10863
10864 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
10865 /// generation and convert it from being a bunch of shuffles and extracts
10866 /// to a simple store and scalar loads to extract the elements.
10867 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
10868                                                 const TargetLowering &TLI) {
10869   SDValue InputVector = N->getOperand(0);
10870
10871   // Only operate on vectors of 4 elements, where the alternative shuffling
10872   // gets to be more expensive.
10873   if (InputVector.getValueType() != MVT::v4i32)
10874     return SDValue();
10875
10876   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
10877   // single use which is a sign-extend or zero-extend, and all elements are
10878   // used.
10879   SmallVector<SDNode *, 4> Uses;
10880   unsigned ExtractedElements = 0;
10881   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
10882        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
10883     if (UI.getUse().getResNo() != InputVector.getResNo())
10884       return SDValue();
10885
10886     SDNode *Extract = *UI;
10887     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10888       return SDValue();
10889
10890     if (Extract->getValueType(0) != MVT::i32)
10891       return SDValue();
10892     if (!Extract->hasOneUse())
10893       return SDValue();
10894     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
10895         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
10896       return SDValue();
10897     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
10898       return SDValue();
10899
10900     // Record which element was extracted.
10901     ExtractedElements |=
10902       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
10903
10904     Uses.push_back(Extract);
10905   }
10906
10907   // If not all the elements were used, this may not be worthwhile.
10908   if (ExtractedElements != 15)
10909     return SDValue();
10910
10911   // Ok, we've now decided to do the transformation.
10912   DebugLoc dl = InputVector.getDebugLoc();
10913
10914   // Store the value to a temporary stack slot.
10915   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
10916   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
10917                             MachinePointerInfo(), false, false, 0);
10918
10919   // Replace each use (extract) with a load of the appropriate element.
10920   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
10921        UE = Uses.end(); UI != UE; ++UI) {
10922     SDNode *Extract = *UI;
10923
10924     // Compute the element's address.
10925     SDValue Idx = Extract->getOperand(1);
10926     unsigned EltSize =
10927         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
10928     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
10929     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
10930
10931     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(),
10932                                      StackPtr, OffsetVal);
10933
10934     // Load the scalar.
10935     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
10936                                      ScalarAddr, MachinePointerInfo(),
10937                                      false, false, 0);
10938
10939     // Replace the exact with the load.
10940     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
10941   }
10942
10943   // The replacement was made in place; don't return anything.
10944   return SDValue();
10945 }
10946
10947 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
10948 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
10949                                     const X86Subtarget *Subtarget) {
10950   DebugLoc DL = N->getDebugLoc();
10951   SDValue Cond = N->getOperand(0);
10952   // Get the LHS/RHS of the select.
10953   SDValue LHS = N->getOperand(1);
10954   SDValue RHS = N->getOperand(2);
10955
10956   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
10957   // instructions match the semantics of the common C idiom x<y?x:y but not
10958   // x<=y?x:y, because of how they handle negative zero (which can be
10959   // ignored in unsafe-math mode).
10960   if (Subtarget->hasSSE2() &&
10961       (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
10962       Cond.getOpcode() == ISD::SETCC) {
10963     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
10964
10965     unsigned Opcode = 0;
10966     // Check for x CC y ? x : y.
10967     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
10968         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
10969       switch (CC) {
10970       default: break;
10971       case ISD::SETULT:
10972         // Converting this to a min would handle NaNs incorrectly, and swapping
10973         // the operands would cause it to handle comparisons between positive
10974         // and negative zero incorrectly.
10975         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
10976           if (!UnsafeFPMath &&
10977               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10978             break;
10979           std::swap(LHS, RHS);
10980         }
10981         Opcode = X86ISD::FMIN;
10982         break;
10983       case ISD::SETOLE:
10984         // Converting this to a min would handle comparisons between positive
10985         // and negative zero incorrectly.
10986         if (!UnsafeFPMath &&
10987             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
10988           break;
10989         Opcode = X86ISD::FMIN;
10990         break;
10991       case ISD::SETULE:
10992         // Converting this to a min would handle both negative zeros and NaNs
10993         // incorrectly, but we can swap the operands to fix both.
10994         std::swap(LHS, RHS);
10995       case ISD::SETOLT:
10996       case ISD::SETLT:
10997       case ISD::SETLE:
10998         Opcode = X86ISD::FMIN;
10999         break;
11000
11001       case ISD::SETOGE:
11002         // Converting this to a max would handle comparisons between positive
11003         // and negative zero incorrectly.
11004         if (!UnsafeFPMath &&
11005             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS))
11006           break;
11007         Opcode = X86ISD::FMAX;
11008         break;
11009       case ISD::SETUGT:
11010         // Converting this to a max would handle NaNs incorrectly, and swapping
11011         // the operands would cause it to handle comparisons between positive
11012         // and negative zero incorrectly.
11013         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
11014           if (!UnsafeFPMath &&
11015               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
11016             break;
11017           std::swap(LHS, RHS);
11018         }
11019         Opcode = X86ISD::FMAX;
11020         break;
11021       case ISD::SETUGE:
11022         // Converting this to a max would handle both negative zeros and NaNs
11023         // incorrectly, but we can swap the operands to fix both.
11024         std::swap(LHS, RHS);
11025       case ISD::SETOGT:
11026       case ISD::SETGT:
11027       case ISD::SETGE:
11028         Opcode = X86ISD::FMAX;
11029         break;
11030       }
11031     // Check for x CC y ? y : x -- a min/max with reversed arms.
11032     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
11033                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
11034       switch (CC) {
11035       default: break;
11036       case ISD::SETOGE:
11037         // Converting this to a min would handle comparisons between positive
11038         // and negative zero incorrectly, and swapping the operands would
11039         // cause it to handle NaNs incorrectly.
11040         if (!UnsafeFPMath &&
11041             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
11042           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11043             break;
11044           std::swap(LHS, RHS);
11045         }
11046         Opcode = X86ISD::FMIN;
11047         break;
11048       case ISD::SETUGT:
11049         // Converting this to a min would handle NaNs incorrectly.
11050         if (!UnsafeFPMath &&
11051             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
11052           break;
11053         Opcode = X86ISD::FMIN;
11054         break;
11055       case ISD::SETUGE:
11056         // Converting this to a min would handle both negative zeros and NaNs
11057         // incorrectly, but we can swap the operands to fix both.
11058         std::swap(LHS, RHS);
11059       case ISD::SETOGT:
11060       case ISD::SETGT:
11061       case ISD::SETGE:
11062         Opcode = X86ISD::FMIN;
11063         break;
11064
11065       case ISD::SETULT:
11066         // Converting this to a max would handle NaNs incorrectly.
11067         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11068           break;
11069         Opcode = X86ISD::FMAX;
11070         break;
11071       case ISD::SETOLE:
11072         // Converting this to a max would handle comparisons between positive
11073         // and negative zero incorrectly, and swapping the operands would
11074         // cause it to handle NaNs incorrectly.
11075         if (!UnsafeFPMath &&
11076             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
11077           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11078             break;
11079           std::swap(LHS, RHS);
11080         }
11081         Opcode = X86ISD::FMAX;
11082         break;
11083       case ISD::SETULE:
11084         // Converting this to a max would handle both negative zeros and NaNs
11085         // incorrectly, but we can swap the operands to fix both.
11086         std::swap(LHS, RHS);
11087       case ISD::SETOLT:
11088       case ISD::SETLT:
11089       case ISD::SETLE:
11090         Opcode = X86ISD::FMAX;
11091         break;
11092       }
11093     }
11094
11095     if (Opcode)
11096       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
11097   }
11098
11099   // If this is a select between two integer constants, try to do some
11100   // optimizations.
11101   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
11102     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
11103       // Don't do this for crazy integer types.
11104       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
11105         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
11106         // so that TrueC (the true value) is larger than FalseC.
11107         bool NeedsCondInvert = false;
11108
11109         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
11110             // Efficiently invertible.
11111             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
11112              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
11113               isa<ConstantSDNode>(Cond.getOperand(1))))) {
11114           NeedsCondInvert = true;
11115           std::swap(TrueC, FalseC);
11116         }
11117
11118         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
11119         if (FalseC->getAPIntValue() == 0 &&
11120             TrueC->getAPIntValue().isPowerOf2()) {
11121           if (NeedsCondInvert) // Invert the condition if needed.
11122             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11123                                DAG.getConstant(1, Cond.getValueType()));
11124
11125           // Zero extend the condition if needed.
11126           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
11127
11128           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
11129           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
11130                              DAG.getConstant(ShAmt, MVT::i8));
11131         }
11132
11133         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
11134         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
11135           if (NeedsCondInvert) // Invert the condition if needed.
11136             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11137                                DAG.getConstant(1, Cond.getValueType()));
11138
11139           // Zero extend the condition if needed.
11140           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
11141                              FalseC->getValueType(0), Cond);
11142           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11143                              SDValue(FalseC, 0));
11144         }
11145
11146         // Optimize cases that will turn into an LEA instruction.  This requires
11147         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
11148         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
11149           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
11150           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
11151
11152           bool isFastMultiplier = false;
11153           if (Diff < 10) {
11154             switch ((unsigned char)Diff) {
11155               default: break;
11156               case 1:  // result = add base, cond
11157               case 2:  // result = lea base(    , cond*2)
11158               case 3:  // result = lea base(cond, cond*2)
11159               case 4:  // result = lea base(    , cond*4)
11160               case 5:  // result = lea base(cond, cond*4)
11161               case 8:  // result = lea base(    , cond*8)
11162               case 9:  // result = lea base(cond, cond*8)
11163                 isFastMultiplier = true;
11164                 break;
11165             }
11166           }
11167
11168           if (isFastMultiplier) {
11169             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
11170             if (NeedsCondInvert) // Invert the condition if needed.
11171               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11172                                  DAG.getConstant(1, Cond.getValueType()));
11173
11174             // Zero extend the condition if needed.
11175             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
11176                                Cond);
11177             // Scale the condition by the difference.
11178             if (Diff != 1)
11179               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
11180                                  DAG.getConstant(Diff, Cond.getValueType()));
11181
11182             // Add the base if non-zero.
11183             if (FalseC->getAPIntValue() != 0)
11184               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11185                                  SDValue(FalseC, 0));
11186             return Cond;
11187           }
11188         }
11189       }
11190   }
11191
11192   return SDValue();
11193 }
11194
11195 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
11196 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
11197                                   TargetLowering::DAGCombinerInfo &DCI) {
11198   DebugLoc DL = N->getDebugLoc();
11199
11200   // If the flag operand isn't dead, don't touch this CMOV.
11201   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
11202     return SDValue();
11203
11204   // If this is a select between two integer constants, try to do some
11205   // optimizations.  Note that the operands are ordered the opposite of SELECT
11206   // operands.
11207   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
11208     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
11209       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
11210       // larger than FalseC (the false value).
11211       X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
11212
11213       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
11214         CC = X86::GetOppositeBranchCondition(CC);
11215         std::swap(TrueC, FalseC);
11216       }
11217
11218       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
11219       // This is efficient for any integer data type (including i8/i16) and
11220       // shift amount.
11221       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
11222         SDValue Cond = N->getOperand(3);
11223         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11224                            DAG.getConstant(CC, MVT::i8), Cond);
11225
11226         // Zero extend the condition if needed.
11227         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
11228
11229         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
11230         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
11231                            DAG.getConstant(ShAmt, MVT::i8));
11232         if (N->getNumValues() == 2)  // Dead flag value?
11233           return DCI.CombineTo(N, Cond, SDValue());
11234         return Cond;
11235       }
11236
11237       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
11238       // for any integer data type, including i8/i16.
11239       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
11240         SDValue Cond = N->getOperand(3);
11241         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11242                            DAG.getConstant(CC, MVT::i8), Cond);
11243
11244         // Zero extend the condition if needed.
11245         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
11246                            FalseC->getValueType(0), Cond);
11247         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11248                            SDValue(FalseC, 0));
11249
11250         if (N->getNumValues() == 2)  // Dead flag value?
11251           return DCI.CombineTo(N, Cond, SDValue());
11252         return Cond;
11253       }
11254
11255       // Optimize cases that will turn into an LEA instruction.  This requires
11256       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
11257       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
11258         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
11259         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
11260
11261         bool isFastMultiplier = false;
11262         if (Diff < 10) {
11263           switch ((unsigned char)Diff) {
11264           default: break;
11265           case 1:  // result = add base, cond
11266           case 2:  // result = lea base(    , cond*2)
11267           case 3:  // result = lea base(cond, cond*2)
11268           case 4:  // result = lea base(    , cond*4)
11269           case 5:  // result = lea base(cond, cond*4)
11270           case 8:  // result = lea base(    , cond*8)
11271           case 9:  // result = lea base(cond, cond*8)
11272             isFastMultiplier = true;
11273             break;
11274           }
11275         }
11276
11277         if (isFastMultiplier) {
11278           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
11279           SDValue Cond = N->getOperand(3);
11280           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11281                              DAG.getConstant(CC, MVT::i8), Cond);
11282           // Zero extend the condition if needed.
11283           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
11284                              Cond);
11285           // Scale the condition by the difference.
11286           if (Diff != 1)
11287             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
11288                                DAG.getConstant(Diff, Cond.getValueType()));
11289
11290           // Add the base if non-zero.
11291           if (FalseC->getAPIntValue() != 0)
11292             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11293                                SDValue(FalseC, 0));
11294           if (N->getNumValues() == 2)  // Dead flag value?
11295             return DCI.CombineTo(N, Cond, SDValue());
11296           return Cond;
11297         }
11298       }
11299     }
11300   }
11301   return SDValue();
11302 }
11303
11304
11305 /// PerformMulCombine - Optimize a single multiply with constant into two
11306 /// in order to implement it with two cheaper instructions, e.g.
11307 /// LEA + SHL, LEA + LEA.
11308 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
11309                                  TargetLowering::DAGCombinerInfo &DCI) {
11310   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11311     return SDValue();
11312
11313   EVT VT = N->getValueType(0);
11314   if (VT != MVT::i64)
11315     return SDValue();
11316
11317   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
11318   if (!C)
11319     return SDValue();
11320   uint64_t MulAmt = C->getZExtValue();
11321   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
11322     return SDValue();
11323
11324   uint64_t MulAmt1 = 0;
11325   uint64_t MulAmt2 = 0;
11326   if ((MulAmt % 9) == 0) {
11327     MulAmt1 = 9;
11328     MulAmt2 = MulAmt / 9;
11329   } else if ((MulAmt % 5) == 0) {
11330     MulAmt1 = 5;
11331     MulAmt2 = MulAmt / 5;
11332   } else if ((MulAmt % 3) == 0) {
11333     MulAmt1 = 3;
11334     MulAmt2 = MulAmt / 3;
11335   }
11336   if (MulAmt2 &&
11337       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
11338     DebugLoc DL = N->getDebugLoc();
11339
11340     if (isPowerOf2_64(MulAmt2) &&
11341         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
11342       // If second multiplifer is pow2, issue it first. We want the multiply by
11343       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
11344       // is an add.
11345       std::swap(MulAmt1, MulAmt2);
11346
11347     SDValue NewMul;
11348     if (isPowerOf2_64(MulAmt1))
11349       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
11350                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
11351     else
11352       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
11353                            DAG.getConstant(MulAmt1, VT));
11354
11355     if (isPowerOf2_64(MulAmt2))
11356       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
11357                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
11358     else
11359       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
11360                            DAG.getConstant(MulAmt2, VT));
11361
11362     // Do not add new nodes to DAG combiner worklist.
11363     DCI.CombineTo(N, NewMul, false);
11364   }
11365   return SDValue();
11366 }
11367
11368 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
11369   SDValue N0 = N->getOperand(0);
11370   SDValue N1 = N->getOperand(1);
11371   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
11372   EVT VT = N0.getValueType();
11373
11374   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
11375   // since the result of setcc_c is all zero's or all ones.
11376   if (N1C && N0.getOpcode() == ISD::AND &&
11377       N0.getOperand(1).getOpcode() == ISD::Constant) {
11378     SDValue N00 = N0.getOperand(0);
11379     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
11380         ((N00.getOpcode() == ISD::ANY_EXTEND ||
11381           N00.getOpcode() == ISD::ZERO_EXTEND) &&
11382          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
11383       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
11384       APInt ShAmt = N1C->getAPIntValue();
11385       Mask = Mask.shl(ShAmt);
11386       if (Mask != 0)
11387         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
11388                            N00, DAG.getConstant(Mask, VT));
11389     }
11390   }
11391
11392   return SDValue();
11393 }
11394
11395 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
11396 ///                       when possible.
11397 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
11398                                    const X86Subtarget *Subtarget) {
11399   EVT VT = N->getValueType(0);
11400   if (!VT.isVector() && VT.isInteger() &&
11401       N->getOpcode() == ISD::SHL)
11402     return PerformSHLCombine(N, DAG);
11403
11404   // On X86 with SSE2 support, we can transform this to a vector shift if
11405   // all elements are shifted by the same amount.  We can't do this in legalize
11406   // because the a constant vector is typically transformed to a constant pool
11407   // so we have no knowledge of the shift amount.
11408   if (!Subtarget->hasSSE2())
11409     return SDValue();
11410
11411   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
11412     return SDValue();
11413
11414   SDValue ShAmtOp = N->getOperand(1);
11415   EVT EltVT = VT.getVectorElementType();
11416   DebugLoc DL = N->getDebugLoc();
11417   SDValue BaseShAmt = SDValue();
11418   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
11419     unsigned NumElts = VT.getVectorNumElements();
11420     unsigned i = 0;
11421     for (; i != NumElts; ++i) {
11422       SDValue Arg = ShAmtOp.getOperand(i);
11423       if (Arg.getOpcode() == ISD::UNDEF) continue;
11424       BaseShAmt = Arg;
11425       break;
11426     }
11427     for (; i != NumElts; ++i) {
11428       SDValue Arg = ShAmtOp.getOperand(i);
11429       if (Arg.getOpcode() == ISD::UNDEF) continue;
11430       if (Arg != BaseShAmt) {
11431         return SDValue();
11432       }
11433     }
11434   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
11435              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
11436     SDValue InVec = ShAmtOp.getOperand(0);
11437     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
11438       unsigned NumElts = InVec.getValueType().getVectorNumElements();
11439       unsigned i = 0;
11440       for (; i != NumElts; ++i) {
11441         SDValue Arg = InVec.getOperand(i);
11442         if (Arg.getOpcode() == ISD::UNDEF) continue;
11443         BaseShAmt = Arg;
11444         break;
11445       }
11446     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
11447        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
11448          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
11449          if (C->getZExtValue() == SplatIdx)
11450            BaseShAmt = InVec.getOperand(1);
11451        }
11452     }
11453     if (BaseShAmt.getNode() == 0)
11454       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
11455                               DAG.getIntPtrConstant(0));
11456   } else
11457     return SDValue();
11458
11459   // The shift amount is an i32.
11460   if (EltVT.bitsGT(MVT::i32))
11461     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
11462   else if (EltVT.bitsLT(MVT::i32))
11463     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
11464
11465   // The shift amount is identical so we can do a vector shift.
11466   SDValue  ValOp = N->getOperand(0);
11467   switch (N->getOpcode()) {
11468   default:
11469     llvm_unreachable("Unknown shift opcode!");
11470     break;
11471   case ISD::SHL:
11472     if (VT == MVT::v2i64)
11473       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11474                          DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
11475                          ValOp, BaseShAmt);
11476     if (VT == MVT::v4i32)
11477       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11478                          DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
11479                          ValOp, BaseShAmt);
11480     if (VT == MVT::v8i16)
11481       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11482                          DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
11483                          ValOp, BaseShAmt);
11484     break;
11485   case ISD::SRA:
11486     if (VT == MVT::v4i32)
11487       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11488                          DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
11489                          ValOp, BaseShAmt);
11490     if (VT == MVT::v8i16)
11491       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11492                          DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
11493                          ValOp, BaseShAmt);
11494     break;
11495   case ISD::SRL:
11496     if (VT == MVT::v2i64)
11497       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11498                          DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
11499                          ValOp, BaseShAmt);
11500     if (VT == MVT::v4i32)
11501       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11502                          DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
11503                          ValOp, BaseShAmt);
11504     if (VT ==  MVT::v8i16)
11505       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11506                          DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
11507                          ValOp, BaseShAmt);
11508     break;
11509   }
11510   return SDValue();
11511 }
11512
11513
11514 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
11515                                  TargetLowering::DAGCombinerInfo &DCI,
11516                                  const X86Subtarget *Subtarget) {
11517   if (DCI.isBeforeLegalizeOps())
11518     return SDValue();
11519
11520   // Want to form PANDN nodes, in the hopes of then easily combining them with
11521   // OR and AND nodes to form PBLEND/PSIGN.
11522   EVT VT = N->getValueType(0);
11523   if (VT != MVT::v2i64)
11524     return SDValue();
11525
11526   SDValue N0 = N->getOperand(0);
11527   SDValue N1 = N->getOperand(1);
11528   DebugLoc DL = N->getDebugLoc();
11529
11530   // Check LHS for vnot
11531   if (N0.getOpcode() == ISD::XOR &&
11532       ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
11533     return DAG.getNode(X86ISD::PANDN, DL, VT, N0.getOperand(0), N1);
11534
11535   // Check RHS for vnot
11536   if (N1.getOpcode() == ISD::XOR &&
11537       ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
11538     return DAG.getNode(X86ISD::PANDN, DL, VT, N1.getOperand(0), N0);
11539
11540   return SDValue();
11541 }
11542
11543 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
11544                                 TargetLowering::DAGCombinerInfo &DCI,
11545                                 const X86Subtarget *Subtarget) {
11546   if (DCI.isBeforeLegalizeOps())
11547     return SDValue();
11548
11549   EVT VT = N->getValueType(0);
11550   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64 && VT != MVT::v2i64)
11551     return SDValue();
11552
11553   SDValue N0 = N->getOperand(0);
11554   SDValue N1 = N->getOperand(1);
11555
11556   // look for psign/blend
11557   if (Subtarget->hasSSSE3()) {
11558     if (VT == MVT::v2i64) {
11559       // Canonicalize pandn to RHS
11560       if (N0.getOpcode() == X86ISD::PANDN)
11561         std::swap(N0, N1);
11562       // or (and (m, x), (pandn m, y))
11563       if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::PANDN) {
11564         SDValue Mask = N1.getOperand(0);
11565         SDValue X    = N1.getOperand(1);
11566         SDValue Y;
11567         if (N0.getOperand(0) == Mask)
11568           Y = N0.getOperand(1);
11569         if (N0.getOperand(1) == Mask)
11570           Y = N0.getOperand(0);
11571
11572         // Check to see if the mask appeared in both the AND and PANDN and
11573         if (!Y.getNode())
11574           return SDValue();
11575
11576         // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
11577         if (Mask.getOpcode() != ISD::BITCAST ||
11578             X.getOpcode() != ISD::BITCAST ||
11579             Y.getOpcode() != ISD::BITCAST)
11580           return SDValue();
11581
11582         // Look through mask bitcast.
11583         Mask = Mask.getOperand(0);
11584         EVT MaskVT = Mask.getValueType();
11585
11586         // Validate that the Mask operand is a vector sra node.  The sra node
11587         // will be an intrinsic.
11588         if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
11589           return SDValue();
11590
11591         // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
11592         // there is no psrai.b
11593         switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
11594         case Intrinsic::x86_sse2_psrai_w:
11595         case Intrinsic::x86_sse2_psrai_d:
11596           break;
11597         default: return SDValue();
11598         }
11599
11600         // Check that the SRA is all signbits.
11601         SDValue SraC = Mask.getOperand(2);
11602         unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
11603         unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
11604         if ((SraAmt + 1) != EltBits)
11605           return SDValue();
11606
11607         DebugLoc DL = N->getDebugLoc();
11608
11609         // Now we know we at least have a plendvb with the mask val.  See if
11610         // we can form a psignb/w/d.
11611         // psign = x.type == y.type == mask.type && y = sub(0, x);
11612         X = X.getOperand(0);
11613         Y = Y.getOperand(0);
11614         if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
11615             ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
11616             X.getValueType() == MaskVT && X.getValueType() == Y.getValueType()){
11617           unsigned Opc = 0;
11618           switch (EltBits) {
11619           case 8: Opc = X86ISD::PSIGNB; break;
11620           case 16: Opc = X86ISD::PSIGNW; break;
11621           case 32: Opc = X86ISD::PSIGND; break;
11622           default: break;
11623           }
11624           if (Opc) {
11625             SDValue Sign = DAG.getNode(Opc, DL, MaskVT, X, Mask.getOperand(1));
11626             return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Sign);
11627           }
11628         }
11629         // PBLENDVB only available on SSE 4.1
11630         if (!Subtarget->hasSSE41())
11631           return SDValue();
11632
11633         X = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, X);
11634         Y = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Y);
11635         Mask = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Mask);
11636         Mask = DAG.getNode(X86ISD::PBLENDVB, DL, MVT::v16i8, X, Y, Mask);
11637         return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Mask);
11638       }
11639     }
11640   }
11641
11642   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
11643   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
11644     std::swap(N0, N1);
11645   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
11646     return SDValue();
11647   if (!N0.hasOneUse() || !N1.hasOneUse())
11648     return SDValue();
11649
11650   SDValue ShAmt0 = N0.getOperand(1);
11651   if (ShAmt0.getValueType() != MVT::i8)
11652     return SDValue();
11653   SDValue ShAmt1 = N1.getOperand(1);
11654   if (ShAmt1.getValueType() != MVT::i8)
11655     return SDValue();
11656   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
11657     ShAmt0 = ShAmt0.getOperand(0);
11658   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
11659     ShAmt1 = ShAmt1.getOperand(0);
11660
11661   DebugLoc DL = N->getDebugLoc();
11662   unsigned Opc = X86ISD::SHLD;
11663   SDValue Op0 = N0.getOperand(0);
11664   SDValue Op1 = N1.getOperand(0);
11665   if (ShAmt0.getOpcode() == ISD::SUB) {
11666     Opc = X86ISD::SHRD;
11667     std::swap(Op0, Op1);
11668     std::swap(ShAmt0, ShAmt1);
11669   }
11670
11671   unsigned Bits = VT.getSizeInBits();
11672   if (ShAmt1.getOpcode() == ISD::SUB) {
11673     SDValue Sum = ShAmt1.getOperand(0);
11674     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
11675       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
11676       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
11677         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
11678       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
11679         return DAG.getNode(Opc, DL, VT,
11680                            Op0, Op1,
11681                            DAG.getNode(ISD::TRUNCATE, DL,
11682                                        MVT::i8, ShAmt0));
11683     }
11684   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
11685     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
11686     if (ShAmt0C &&
11687         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
11688       return DAG.getNode(Opc, DL, VT,
11689                          N0.getOperand(0), N1.getOperand(0),
11690                          DAG.getNode(ISD::TRUNCATE, DL,
11691                                        MVT::i8, ShAmt0));
11692   }
11693
11694   return SDValue();
11695 }
11696
11697 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
11698 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
11699                                    const X86Subtarget *Subtarget) {
11700   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
11701   // the FP state in cases where an emms may be missing.
11702   // A preferable solution to the general problem is to figure out the right
11703   // places to insert EMMS.  This qualifies as a quick hack.
11704
11705   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
11706   StoreSDNode *St = cast<StoreSDNode>(N);
11707   EVT VT = St->getValue().getValueType();
11708   if (VT.getSizeInBits() != 64)
11709     return SDValue();
11710
11711   const Function *F = DAG.getMachineFunction().getFunction();
11712   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
11713   bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
11714     && Subtarget->hasSSE2();
11715   if ((VT.isVector() ||
11716        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
11717       isa<LoadSDNode>(St->getValue()) &&
11718       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
11719       St->getChain().hasOneUse() && !St->isVolatile()) {
11720     SDNode* LdVal = St->getValue().getNode();
11721     LoadSDNode *Ld = 0;
11722     int TokenFactorIndex = -1;
11723     SmallVector<SDValue, 8> Ops;
11724     SDNode* ChainVal = St->getChain().getNode();
11725     // Must be a store of a load.  We currently handle two cases:  the load
11726     // is a direct child, and it's under an intervening TokenFactor.  It is
11727     // possible to dig deeper under nested TokenFactors.
11728     if (ChainVal == LdVal)
11729       Ld = cast<LoadSDNode>(St->getChain());
11730     else if (St->getValue().hasOneUse() &&
11731              ChainVal->getOpcode() == ISD::TokenFactor) {
11732       for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
11733         if (ChainVal->getOperand(i).getNode() == LdVal) {
11734           TokenFactorIndex = i;
11735           Ld = cast<LoadSDNode>(St->getValue());
11736         } else
11737           Ops.push_back(ChainVal->getOperand(i));
11738       }
11739     }
11740
11741     if (!Ld || !ISD::isNormalLoad(Ld))
11742       return SDValue();
11743
11744     // If this is not the MMX case, i.e. we are just turning i64 load/store
11745     // into f64 load/store, avoid the transformation if there are multiple
11746     // uses of the loaded value.
11747     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
11748       return SDValue();
11749
11750     DebugLoc LdDL = Ld->getDebugLoc();
11751     DebugLoc StDL = N->getDebugLoc();
11752     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
11753     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
11754     // pair instead.
11755     if (Subtarget->is64Bit() || F64IsLegal) {
11756       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
11757       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
11758                                   Ld->getPointerInfo(), Ld->isVolatile(),
11759                                   Ld->isNonTemporal(), Ld->getAlignment());
11760       SDValue NewChain = NewLd.getValue(1);
11761       if (TokenFactorIndex != -1) {
11762         Ops.push_back(NewChain);
11763         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
11764                                Ops.size());
11765       }
11766       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
11767                           St->getPointerInfo(),
11768                           St->isVolatile(), St->isNonTemporal(),
11769                           St->getAlignment());
11770     }
11771
11772     // Otherwise, lower to two pairs of 32-bit loads / stores.
11773     SDValue LoAddr = Ld->getBasePtr();
11774     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
11775                                  DAG.getConstant(4, MVT::i32));
11776
11777     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
11778                                Ld->getPointerInfo(),
11779                                Ld->isVolatile(), Ld->isNonTemporal(),
11780                                Ld->getAlignment());
11781     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
11782                                Ld->getPointerInfo().getWithOffset(4),
11783                                Ld->isVolatile(), Ld->isNonTemporal(),
11784                                MinAlign(Ld->getAlignment(), 4));
11785
11786     SDValue NewChain = LoLd.getValue(1);
11787     if (TokenFactorIndex != -1) {
11788       Ops.push_back(LoLd);
11789       Ops.push_back(HiLd);
11790       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
11791                              Ops.size());
11792     }
11793
11794     LoAddr = St->getBasePtr();
11795     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
11796                          DAG.getConstant(4, MVT::i32));
11797
11798     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
11799                                 St->getPointerInfo(),
11800                                 St->isVolatile(), St->isNonTemporal(),
11801                                 St->getAlignment());
11802     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
11803                                 St->getPointerInfo().getWithOffset(4),
11804                                 St->isVolatile(),
11805                                 St->isNonTemporal(),
11806                                 MinAlign(St->getAlignment(), 4));
11807     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
11808   }
11809   return SDValue();
11810 }
11811
11812 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
11813 /// X86ISD::FXOR nodes.
11814 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
11815   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
11816   // F[X]OR(0.0, x) -> x
11817   // F[X]OR(x, 0.0) -> x
11818   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
11819     if (C->getValueAPF().isPosZero())
11820       return N->getOperand(1);
11821   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
11822     if (C->getValueAPF().isPosZero())
11823       return N->getOperand(0);
11824   return SDValue();
11825 }
11826
11827 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
11828 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
11829   // FAND(0.0, x) -> 0.0
11830   // FAND(x, 0.0) -> 0.0
11831   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
11832     if (C->getValueAPF().isPosZero())
11833       return N->getOperand(0);
11834   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
11835     if (C->getValueAPF().isPosZero())
11836       return N->getOperand(1);
11837   return SDValue();
11838 }
11839
11840 static SDValue PerformBTCombine(SDNode *N,
11841                                 SelectionDAG &DAG,
11842                                 TargetLowering::DAGCombinerInfo &DCI) {
11843   // BT ignores high bits in the bit index operand.
11844   SDValue Op1 = N->getOperand(1);
11845   if (Op1.hasOneUse()) {
11846     unsigned BitWidth = Op1.getValueSizeInBits();
11847     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
11848     APInt KnownZero, KnownOne;
11849     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
11850                                           !DCI.isBeforeLegalizeOps());
11851     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11852     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
11853         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
11854       DCI.CommitTargetLoweringOpt(TLO);
11855   }
11856   return SDValue();
11857 }
11858
11859 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
11860   SDValue Op = N->getOperand(0);
11861   if (Op.getOpcode() == ISD::BITCAST)
11862     Op = Op.getOperand(0);
11863   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
11864   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
11865       VT.getVectorElementType().getSizeInBits() ==
11866       OpVT.getVectorElementType().getSizeInBits()) {
11867     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
11868   }
11869   return SDValue();
11870 }
11871
11872 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
11873   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
11874   //           (and (i32 x86isd::setcc_carry), 1)
11875   // This eliminates the zext. This transformation is necessary because
11876   // ISD::SETCC is always legalized to i8.
11877   DebugLoc dl = N->getDebugLoc();
11878   SDValue N0 = N->getOperand(0);
11879   EVT VT = N->getValueType(0);
11880   if (N0.getOpcode() == ISD::AND &&
11881       N0.hasOneUse() &&
11882       N0.getOperand(0).hasOneUse()) {
11883     SDValue N00 = N0.getOperand(0);
11884     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
11885       return SDValue();
11886     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
11887     if (!C || C->getZExtValue() != 1)
11888       return SDValue();
11889     return DAG.getNode(ISD::AND, dl, VT,
11890                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
11891                                    N00.getOperand(0), N00.getOperand(1)),
11892                        DAG.getConstant(1, VT));
11893   }
11894
11895   return SDValue();
11896 }
11897
11898 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
11899 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
11900   unsigned X86CC = N->getConstantOperandVal(0);
11901   SDValue EFLAG = N->getOperand(1);
11902   DebugLoc DL = N->getDebugLoc();
11903
11904   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
11905   // a zext and produces an all-ones bit which is more useful than 0/1 in some
11906   // cases.
11907   if (X86CC == X86::COND_B)
11908     return DAG.getNode(ISD::AND, DL, MVT::i8,
11909                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
11910                                    DAG.getConstant(X86CC, MVT::i8), EFLAG),
11911                        DAG.getConstant(1, MVT::i8));
11912
11913   return SDValue();
11914 }
11915
11916 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
11917 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
11918                                  X86TargetLowering::DAGCombinerInfo &DCI) {
11919   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
11920   // the result is either zero or one (depending on the input carry bit).
11921   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
11922   if (X86::isZeroNode(N->getOperand(0)) &&
11923       X86::isZeroNode(N->getOperand(1)) &&
11924       // We don't have a good way to replace an EFLAGS use, so only do this when
11925       // dead right now.
11926       SDValue(N, 1).use_empty()) {
11927     DebugLoc DL = N->getDebugLoc();
11928     EVT VT = N->getValueType(0);
11929     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
11930     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
11931                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
11932                                            DAG.getConstant(X86::COND_B,MVT::i8),
11933                                            N->getOperand(2)),
11934                                DAG.getConstant(1, VT));
11935     return DCI.CombineTo(N, Res1, CarryOut);
11936   }
11937
11938   return SDValue();
11939 }
11940
11941 // fold (add Y, (sete  X, 0)) -> adc  0, Y
11942 //      (add Y, (setne X, 0)) -> sbb -1, Y
11943 //      (sub (sete  X, 0), Y) -> sbb  0, Y
11944 //      (sub (setne X, 0), Y) -> adc -1, Y
11945 static SDValue OptimizeConditonalInDecrement(SDNode *N, SelectionDAG &DAG) {
11946   DebugLoc DL = N->getDebugLoc();
11947
11948   // Look through ZExts.
11949   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
11950   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
11951     return SDValue();
11952
11953   SDValue SetCC = Ext.getOperand(0);
11954   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
11955     return SDValue();
11956
11957   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
11958   if (CC != X86::COND_E && CC != X86::COND_NE)
11959     return SDValue();
11960
11961   SDValue Cmp = SetCC.getOperand(1);
11962   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
11963       !X86::isZeroNode(Cmp.getOperand(1)) ||
11964       !Cmp.getOperand(0).getValueType().isInteger())
11965     return SDValue();
11966
11967   SDValue CmpOp0 = Cmp.getOperand(0);
11968   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
11969                                DAG.getConstant(1, CmpOp0.getValueType()));
11970
11971   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
11972   if (CC == X86::COND_NE)
11973     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
11974                        DL, OtherVal.getValueType(), OtherVal,
11975                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
11976   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
11977                      DL, OtherVal.getValueType(), OtherVal,
11978                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
11979 }
11980
11981 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
11982                                              DAGCombinerInfo &DCI) const {
11983   SelectionDAG &DAG = DCI.DAG;
11984   switch (N->getOpcode()) {
11985   default: break;
11986   case ISD::EXTRACT_VECTOR_ELT:
11987     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
11988   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
11989   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
11990   case ISD::ADD:
11991   case ISD::SUB:            return OptimizeConditonalInDecrement(N, DAG);
11992   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
11993   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
11994   case ISD::SHL:
11995   case ISD::SRA:
11996   case ISD::SRL:            return PerformShiftCombine(N, DAG, Subtarget);
11997   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
11998   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
11999   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
12000   case X86ISD::FXOR:
12001   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
12002   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
12003   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
12004   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
12005   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG);
12006   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG);
12007   case X86ISD::SHUFPS:      // Handle all target specific shuffles
12008   case X86ISD::SHUFPD:
12009   case X86ISD::PALIGN:
12010   case X86ISD::PUNPCKHBW:
12011   case X86ISD::PUNPCKHWD:
12012   case X86ISD::PUNPCKHDQ:
12013   case X86ISD::PUNPCKHQDQ:
12014   case X86ISD::UNPCKHPS:
12015   case X86ISD::UNPCKHPD:
12016   case X86ISD::PUNPCKLBW:
12017   case X86ISD::PUNPCKLWD:
12018   case X86ISD::PUNPCKLDQ:
12019   case X86ISD::PUNPCKLQDQ:
12020   case X86ISD::UNPCKLPS:
12021   case X86ISD::UNPCKLPD:
12022   case X86ISD::VUNPCKLPS:
12023   case X86ISD::VUNPCKLPD:
12024   case X86ISD::VUNPCKLPSY:
12025   case X86ISD::VUNPCKLPDY:
12026   case X86ISD::MOVHLPS:
12027   case X86ISD::MOVLHPS:
12028   case X86ISD::PSHUFD:
12029   case X86ISD::PSHUFHW:
12030   case X86ISD::PSHUFLW:
12031   case X86ISD::MOVSS:
12032   case X86ISD::MOVSD:
12033   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI);
12034   }
12035
12036   return SDValue();
12037 }
12038
12039 /// isTypeDesirableForOp - Return true if the target has native support for
12040 /// the specified value type and it is 'desirable' to use the type for the
12041 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
12042 /// instruction encodings are longer and some i16 instructions are slow.
12043 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
12044   if (!isTypeLegal(VT))
12045     return false;
12046   if (VT != MVT::i16)
12047     return true;
12048
12049   switch (Opc) {
12050   default:
12051     return true;
12052   case ISD::LOAD:
12053   case ISD::SIGN_EXTEND:
12054   case ISD::ZERO_EXTEND:
12055   case ISD::ANY_EXTEND:
12056   case ISD::SHL:
12057   case ISD::SRL:
12058   case ISD::SUB:
12059   case ISD::ADD:
12060   case ISD::MUL:
12061   case ISD::AND:
12062   case ISD::OR:
12063   case ISD::XOR:
12064     return false;
12065   }
12066 }
12067
12068 /// IsDesirableToPromoteOp - This method query the target whether it is
12069 /// beneficial for dag combiner to promote the specified node. If true, it
12070 /// should return the desired promotion type by reference.
12071 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
12072   EVT VT = Op.getValueType();
12073   if (VT != MVT::i16)
12074     return false;
12075
12076   bool Promote = false;
12077   bool Commute = false;
12078   switch (Op.getOpcode()) {
12079   default: break;
12080   case ISD::LOAD: {
12081     LoadSDNode *LD = cast<LoadSDNode>(Op);
12082     // If the non-extending load has a single use and it's not live out, then it
12083     // might be folded.
12084     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
12085                                                      Op.hasOneUse()*/) {
12086       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12087              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
12088         // The only case where we'd want to promote LOAD (rather then it being
12089         // promoted as an operand is when it's only use is liveout.
12090         if (UI->getOpcode() != ISD::CopyToReg)
12091           return false;
12092       }
12093     }
12094     Promote = true;
12095     break;
12096   }
12097   case ISD::SIGN_EXTEND:
12098   case ISD::ZERO_EXTEND:
12099   case ISD::ANY_EXTEND:
12100     Promote = true;
12101     break;
12102   case ISD::SHL:
12103   case ISD::SRL: {
12104     SDValue N0 = Op.getOperand(0);
12105     // Look out for (store (shl (load), x)).
12106     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
12107       return false;
12108     Promote = true;
12109     break;
12110   }
12111   case ISD::ADD:
12112   case ISD::MUL:
12113   case ISD::AND:
12114   case ISD::OR:
12115   case ISD::XOR:
12116     Commute = true;
12117     // fallthrough
12118   case ISD::SUB: {
12119     SDValue N0 = Op.getOperand(0);
12120     SDValue N1 = Op.getOperand(1);
12121     if (!Commute && MayFoldLoad(N1))
12122       return false;
12123     // Avoid disabling potential load folding opportunities.
12124     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
12125       return false;
12126     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
12127       return false;
12128     Promote = true;
12129   }
12130   }
12131
12132   PVT = MVT::i32;
12133   return Promote;
12134 }
12135
12136 //===----------------------------------------------------------------------===//
12137 //                           X86 Inline Assembly Support
12138 //===----------------------------------------------------------------------===//
12139
12140 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
12141   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
12142
12143   std::string AsmStr = IA->getAsmString();
12144
12145   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
12146   SmallVector<StringRef, 4> AsmPieces;
12147   SplitString(AsmStr, AsmPieces, ";\n");
12148
12149   switch (AsmPieces.size()) {
12150   default: return false;
12151   case 1:
12152     AsmStr = AsmPieces[0];
12153     AsmPieces.clear();
12154     SplitString(AsmStr, AsmPieces, " \t");  // Split with whitespace.
12155
12156     // FIXME: this should verify that we are targetting a 486 or better.  If not,
12157     // we will turn this bswap into something that will be lowered to logical ops
12158     // instead of emitting the bswap asm.  For now, we don't support 486 or lower
12159     // so don't worry about this.
12160     // bswap $0
12161     if (AsmPieces.size() == 2 &&
12162         (AsmPieces[0] == "bswap" ||
12163          AsmPieces[0] == "bswapq" ||
12164          AsmPieces[0] == "bswapl") &&
12165         (AsmPieces[1] == "$0" ||
12166          AsmPieces[1] == "${0:q}")) {
12167       // No need to check constraints, nothing other than the equivalent of
12168       // "=r,0" would be valid here.
12169       const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12170       if (!Ty || Ty->getBitWidth() % 16 != 0)
12171         return false;
12172       return IntrinsicLowering::LowerToByteSwap(CI);
12173     }
12174     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
12175     if (CI->getType()->isIntegerTy(16) &&
12176         AsmPieces.size() == 3 &&
12177         (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
12178         AsmPieces[1] == "$$8," &&
12179         AsmPieces[2] == "${0:w}" &&
12180         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
12181       AsmPieces.clear();
12182       const std::string &ConstraintsStr = IA->getConstraintString();
12183       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
12184       std::sort(AsmPieces.begin(), AsmPieces.end());
12185       if (AsmPieces.size() == 4 &&
12186           AsmPieces[0] == "~{cc}" &&
12187           AsmPieces[1] == "~{dirflag}" &&
12188           AsmPieces[2] == "~{flags}" &&
12189           AsmPieces[3] == "~{fpsr}") {
12190         const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12191         if (!Ty || Ty->getBitWidth() % 16 != 0)
12192           return false;
12193         return IntrinsicLowering::LowerToByteSwap(CI);
12194       }
12195     }
12196     break;
12197   case 3:
12198     if (CI->getType()->isIntegerTy(32) &&
12199         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
12200       SmallVector<StringRef, 4> Words;
12201       SplitString(AsmPieces[0], Words, " \t,");
12202       if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
12203           Words[2] == "${0:w}") {
12204         Words.clear();
12205         SplitString(AsmPieces[1], Words, " \t,");
12206         if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" &&
12207             Words[2] == "$0") {
12208           Words.clear();
12209           SplitString(AsmPieces[2], Words, " \t,");
12210           if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
12211               Words[2] == "${0:w}") {
12212             AsmPieces.clear();
12213             const std::string &ConstraintsStr = IA->getConstraintString();
12214             SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
12215             std::sort(AsmPieces.begin(), AsmPieces.end());
12216             if (AsmPieces.size() == 4 &&
12217                 AsmPieces[0] == "~{cc}" &&
12218                 AsmPieces[1] == "~{dirflag}" &&
12219                 AsmPieces[2] == "~{flags}" &&
12220                 AsmPieces[3] == "~{fpsr}") {
12221               const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12222               if (!Ty || Ty->getBitWidth() % 16 != 0)
12223                 return false;
12224               return IntrinsicLowering::LowerToByteSwap(CI);
12225             }
12226           }
12227         }
12228       }
12229     }
12230
12231     if (CI->getType()->isIntegerTy(64)) {
12232       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
12233       if (Constraints.size() >= 2 &&
12234           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
12235           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
12236         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
12237         SmallVector<StringRef, 4> Words;
12238         SplitString(AsmPieces[0], Words, " \t");
12239         if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
12240           Words.clear();
12241           SplitString(AsmPieces[1], Words, " \t");
12242           if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
12243             Words.clear();
12244             SplitString(AsmPieces[2], Words, " \t,");
12245             if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
12246                 Words[2] == "%edx") {
12247               const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12248               if (!Ty || Ty->getBitWidth() % 16 != 0)
12249                 return false;
12250               return IntrinsicLowering::LowerToByteSwap(CI);
12251             }
12252           }
12253         }
12254       }
12255     }
12256     break;
12257   }
12258   return false;
12259 }
12260
12261
12262
12263 /// getConstraintType - Given a constraint letter, return the type of
12264 /// constraint it is for this target.
12265 X86TargetLowering::ConstraintType
12266 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
12267   if (Constraint.size() == 1) {
12268     switch (Constraint[0]) {
12269     case 'R':
12270     case 'q':
12271     case 'Q':
12272     case 'f':
12273     case 't':
12274     case 'u':
12275     case 'y':
12276     case 'x':
12277     case 'Y':
12278       return C_RegisterClass;
12279     case 'a':
12280     case 'b':
12281     case 'c':
12282     case 'd':
12283     case 'S':
12284     case 'D':
12285     case 'A':
12286       return C_Register;
12287     case 'I':
12288     case 'J':
12289     case 'K':
12290     case 'L':
12291     case 'M':
12292     case 'N':
12293     case 'G':
12294     case 'C':
12295     case 'e':
12296     case 'Z':
12297       return C_Other;
12298     default:
12299       break;
12300     }
12301   }
12302   return TargetLowering::getConstraintType(Constraint);
12303 }
12304
12305 /// Examine constraint type and operand type and determine a weight value.
12306 /// This object must already have been set up with the operand type
12307 /// and the current alternative constraint selected.
12308 TargetLowering::ConstraintWeight
12309   X86TargetLowering::getSingleConstraintMatchWeight(
12310     AsmOperandInfo &info, const char *constraint) const {
12311   ConstraintWeight weight = CW_Invalid;
12312   Value *CallOperandVal = info.CallOperandVal;
12313     // If we don't have a value, we can't do a match,
12314     // but allow it at the lowest weight.
12315   if (CallOperandVal == NULL)
12316     return CW_Default;
12317   const Type *type = CallOperandVal->getType();
12318   // Look at the constraint type.
12319   switch (*constraint) {
12320   default:
12321     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
12322   case 'R':
12323   case 'q':
12324   case 'Q':
12325   case 'a':
12326   case 'b':
12327   case 'c':
12328   case 'd':
12329   case 'S':
12330   case 'D':
12331   case 'A':
12332     if (CallOperandVal->getType()->isIntegerTy())
12333       weight = CW_SpecificReg;
12334     break;
12335   case 'f':
12336   case 't':
12337   case 'u':
12338       if (type->isFloatingPointTy())
12339         weight = CW_SpecificReg;
12340       break;
12341   case 'y':
12342       if (type->isX86_MMXTy() && Subtarget->hasMMX())
12343         weight = CW_SpecificReg;
12344       break;
12345   case 'x':
12346   case 'Y':
12347     if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
12348       weight = CW_Register;
12349     break;
12350   case 'I':
12351     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
12352       if (C->getZExtValue() <= 31)
12353         weight = CW_Constant;
12354     }
12355     break;
12356   case 'J':
12357     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12358       if (C->getZExtValue() <= 63)
12359         weight = CW_Constant;
12360     }
12361     break;
12362   case 'K':
12363     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12364       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
12365         weight = CW_Constant;
12366     }
12367     break;
12368   case 'L':
12369     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12370       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
12371         weight = CW_Constant;
12372     }
12373     break;
12374   case 'M':
12375     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12376       if (C->getZExtValue() <= 3)
12377         weight = CW_Constant;
12378     }
12379     break;
12380   case 'N':
12381     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12382       if (C->getZExtValue() <= 0xff)
12383         weight = CW_Constant;
12384     }
12385     break;
12386   case 'G':
12387   case 'C':
12388     if (dyn_cast<ConstantFP>(CallOperandVal)) {
12389       weight = CW_Constant;
12390     }
12391     break;
12392   case 'e':
12393     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12394       if ((C->getSExtValue() >= -0x80000000LL) &&
12395           (C->getSExtValue() <= 0x7fffffffLL))
12396         weight = CW_Constant;
12397     }
12398     break;
12399   case 'Z':
12400     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12401       if (C->getZExtValue() <= 0xffffffff)
12402         weight = CW_Constant;
12403     }
12404     break;
12405   }
12406   return weight;
12407 }
12408
12409 /// LowerXConstraint - try to replace an X constraint, which matches anything,
12410 /// with another that has more specific requirements based on the type of the
12411 /// corresponding operand.
12412 const char *X86TargetLowering::
12413 LowerXConstraint(EVT ConstraintVT) const {
12414   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
12415   // 'f' like normal targets.
12416   if (ConstraintVT.isFloatingPoint()) {
12417     if (Subtarget->hasXMMInt())
12418       return "Y";
12419     if (Subtarget->hasXMM())
12420       return "x";
12421   }
12422
12423   return TargetLowering::LowerXConstraint(ConstraintVT);
12424 }
12425
12426 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
12427 /// vector.  If it is invalid, don't add anything to Ops.
12428 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
12429                                                      char Constraint,
12430                                                      std::vector<SDValue>&Ops,
12431                                                      SelectionDAG &DAG) const {
12432   SDValue Result(0, 0);
12433
12434   switch (Constraint) {
12435   default: break;
12436   case 'I':
12437     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12438       if (C->getZExtValue() <= 31) {
12439         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12440         break;
12441       }
12442     }
12443     return;
12444   case 'J':
12445     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12446       if (C->getZExtValue() <= 63) {
12447         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12448         break;
12449       }
12450     }
12451     return;
12452   case 'K':
12453     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12454       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
12455         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12456         break;
12457       }
12458     }
12459     return;
12460   case 'N':
12461     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12462       if (C->getZExtValue() <= 255) {
12463         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12464         break;
12465       }
12466     }
12467     return;
12468   case 'e': {
12469     // 32-bit signed value
12470     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12471       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
12472                                            C->getSExtValue())) {
12473         // Widen to 64 bits here to get it sign extended.
12474         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
12475         break;
12476       }
12477     // FIXME gcc accepts some relocatable values here too, but only in certain
12478     // memory models; it's complicated.
12479     }
12480     return;
12481   }
12482   case 'Z': {
12483     // 32-bit unsigned value
12484     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12485       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
12486                                            C->getZExtValue())) {
12487         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12488         break;
12489       }
12490     }
12491     // FIXME gcc accepts some relocatable values here too, but only in certain
12492     // memory models; it's complicated.
12493     return;
12494   }
12495   case 'i': {
12496     // Literal immediates are always ok.
12497     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
12498       // Widen to 64 bits here to get it sign extended.
12499       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
12500       break;
12501     }
12502
12503     // In any sort of PIC mode addresses need to be computed at runtime by
12504     // adding in a register or some sort of table lookup.  These can't
12505     // be used as immediates.
12506     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
12507       return;
12508
12509     // If we are in non-pic codegen mode, we allow the address of a global (with
12510     // an optional displacement) to be used with 'i'.
12511     GlobalAddressSDNode *GA = 0;
12512     int64_t Offset = 0;
12513
12514     // Match either (GA), (GA+C), (GA+C1+C2), etc.
12515     while (1) {
12516       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
12517         Offset += GA->getOffset();
12518         break;
12519       } else if (Op.getOpcode() == ISD::ADD) {
12520         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
12521           Offset += C->getZExtValue();
12522           Op = Op.getOperand(0);
12523           continue;
12524         }
12525       } else if (Op.getOpcode() == ISD::SUB) {
12526         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
12527           Offset += -C->getZExtValue();
12528           Op = Op.getOperand(0);
12529           continue;
12530         }
12531       }
12532
12533       // Otherwise, this isn't something we can handle, reject it.
12534       return;
12535     }
12536
12537     const GlobalValue *GV = GA->getGlobal();
12538     // If we require an extra load to get this address, as in PIC mode, we
12539     // can't accept it.
12540     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
12541                                                         getTargetMachine())))
12542       return;
12543
12544     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
12545                                         GA->getValueType(0), Offset);
12546     break;
12547   }
12548   }
12549
12550   if (Result.getNode()) {
12551     Ops.push_back(Result);
12552     return;
12553   }
12554   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
12555 }
12556
12557 std::vector<unsigned> X86TargetLowering::
12558 getRegClassForInlineAsmConstraint(const std::string &Constraint,
12559                                   EVT VT) const {
12560   if (Constraint.size() == 1) {
12561     // FIXME: not handling fp-stack yet!
12562     switch (Constraint[0]) {      // GCC X86 Constraint Letters
12563     default: break;  // Unknown constraint letter
12564     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
12565       if (Subtarget->is64Bit()) {
12566         if (VT == MVT::i32)
12567           return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
12568                                        X86::ESI, X86::EDI, X86::R8D, X86::R9D,
12569                                        X86::R10D,X86::R11D,X86::R12D,
12570                                        X86::R13D,X86::R14D,X86::R15D,
12571                                        X86::EBP, X86::ESP, 0);
12572         else if (VT == MVT::i16)
12573           return make_vector<unsigned>(X86::AX,  X86::DX,  X86::CX, X86::BX,
12574                                        X86::SI,  X86::DI,  X86::R8W,X86::R9W,
12575                                        X86::R10W,X86::R11W,X86::R12W,
12576                                        X86::R13W,X86::R14W,X86::R15W,
12577                                        X86::BP,  X86::SP, 0);
12578         else if (VT == MVT::i8)
12579           return make_vector<unsigned>(X86::AL,  X86::DL,  X86::CL, X86::BL,
12580                                        X86::SIL, X86::DIL, X86::R8B,X86::R9B,
12581                                        X86::R10B,X86::R11B,X86::R12B,
12582                                        X86::R13B,X86::R14B,X86::R15B,
12583                                        X86::BPL, X86::SPL, 0);
12584
12585         else if (VT == MVT::i64)
12586           return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
12587                                        X86::RSI, X86::RDI, X86::R8,  X86::R9,
12588                                        X86::R10, X86::R11, X86::R12,
12589                                        X86::R13, X86::R14, X86::R15,
12590                                        X86::RBP, X86::RSP, 0);
12591
12592         break;
12593       }
12594       // 32-bit fallthrough
12595     case 'Q':   // Q_REGS
12596       if (VT == MVT::i32)
12597         return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
12598       else if (VT == MVT::i16)
12599         return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
12600       else if (VT == MVT::i8)
12601         return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
12602       else if (VT == MVT::i64)
12603         return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
12604       break;
12605     }
12606   }
12607
12608   return std::vector<unsigned>();
12609 }
12610
12611 std::pair<unsigned, const TargetRegisterClass*>
12612 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
12613                                                 EVT VT) const {
12614   // First, see if this is a constraint that directly corresponds to an LLVM
12615   // register class.
12616   if (Constraint.size() == 1) {
12617     // GCC Constraint Letters
12618     switch (Constraint[0]) {
12619     default: break;
12620     case 'r':   // GENERAL_REGS
12621     case 'l':   // INDEX_REGS
12622       if (VT == MVT::i8)
12623         return std::make_pair(0U, X86::GR8RegisterClass);
12624       if (VT == MVT::i16)
12625         return std::make_pair(0U, X86::GR16RegisterClass);
12626       if (VT == MVT::i32 || !Subtarget->is64Bit())
12627         return std::make_pair(0U, X86::GR32RegisterClass);
12628       return std::make_pair(0U, X86::GR64RegisterClass);
12629     case 'R':   // LEGACY_REGS
12630       if (VT == MVT::i8)
12631         return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
12632       if (VT == MVT::i16)
12633         return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
12634       if (VT == MVT::i32 || !Subtarget->is64Bit())
12635         return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
12636       return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
12637     case 'f':  // FP Stack registers.
12638       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
12639       // value to the correct fpstack register class.
12640       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
12641         return std::make_pair(0U, X86::RFP32RegisterClass);
12642       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
12643         return std::make_pair(0U, X86::RFP64RegisterClass);
12644       return std::make_pair(0U, X86::RFP80RegisterClass);
12645     case 'y':   // MMX_REGS if MMX allowed.
12646       if (!Subtarget->hasMMX()) break;
12647       return std::make_pair(0U, X86::VR64RegisterClass);
12648     case 'Y':   // SSE_REGS if SSE2 allowed
12649       if (!Subtarget->hasXMMInt()) break;
12650       // FALL THROUGH.
12651     case 'x':   // SSE_REGS if SSE1 allowed
12652       if (!Subtarget->hasXMM()) break;
12653
12654       switch (VT.getSimpleVT().SimpleTy) {
12655       default: break;
12656       // Scalar SSE types.
12657       case MVT::f32:
12658       case MVT::i32:
12659         return std::make_pair(0U, X86::FR32RegisterClass);
12660       case MVT::f64:
12661       case MVT::i64:
12662         return std::make_pair(0U, X86::FR64RegisterClass);
12663       // Vector types.
12664       case MVT::v16i8:
12665       case MVT::v8i16:
12666       case MVT::v4i32:
12667       case MVT::v2i64:
12668       case MVT::v4f32:
12669       case MVT::v2f64:
12670         return std::make_pair(0U, X86::VR128RegisterClass);
12671       }
12672       break;
12673     }
12674   }
12675
12676   // Use the default implementation in TargetLowering to convert the register
12677   // constraint into a member of a register class.
12678   std::pair<unsigned, const TargetRegisterClass*> Res;
12679   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
12680
12681   // Not found as a standard register?
12682   if (Res.second == 0) {
12683     // Map st(0) -> st(7) -> ST0
12684     if (Constraint.size() == 7 && Constraint[0] == '{' &&
12685         tolower(Constraint[1]) == 's' &&
12686         tolower(Constraint[2]) == 't' &&
12687         Constraint[3] == '(' &&
12688         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
12689         Constraint[5] == ')' &&
12690         Constraint[6] == '}') {
12691
12692       Res.first = X86::ST0+Constraint[4]-'0';
12693       Res.second = X86::RFP80RegisterClass;
12694       return Res;
12695     }
12696
12697     // GCC allows "st(0)" to be called just plain "st".
12698     if (StringRef("{st}").equals_lower(Constraint)) {
12699       Res.first = X86::ST0;
12700       Res.second = X86::RFP80RegisterClass;
12701       return Res;
12702     }
12703
12704     // flags -> EFLAGS
12705     if (StringRef("{flags}").equals_lower(Constraint)) {
12706       Res.first = X86::EFLAGS;
12707       Res.second = X86::CCRRegisterClass;
12708       return Res;
12709     }
12710
12711     // 'A' means EAX + EDX.
12712     if (Constraint == "A") {
12713       Res.first = X86::EAX;
12714       Res.second = X86::GR32_ADRegisterClass;
12715       return Res;
12716     }
12717     return Res;
12718   }
12719
12720   // Otherwise, check to see if this is a register class of the wrong value
12721   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
12722   // turn into {ax},{dx}.
12723   if (Res.second->hasType(VT))
12724     return Res;   // Correct type already, nothing to do.
12725
12726   // All of the single-register GCC register classes map their values onto
12727   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
12728   // really want an 8-bit or 32-bit register, map to the appropriate register
12729   // class and return the appropriate register.
12730   if (Res.second == X86::GR16RegisterClass) {
12731     if (VT == MVT::i8) {
12732       unsigned DestReg = 0;
12733       switch (Res.first) {
12734       default: break;
12735       case X86::AX: DestReg = X86::AL; break;
12736       case X86::DX: DestReg = X86::DL; break;
12737       case X86::CX: DestReg = X86::CL; break;
12738       case X86::BX: DestReg = X86::BL; break;
12739       }
12740       if (DestReg) {
12741         Res.first = DestReg;
12742         Res.second = X86::GR8RegisterClass;
12743       }
12744     } else if (VT == MVT::i32) {
12745       unsigned DestReg = 0;
12746       switch (Res.first) {
12747       default: break;
12748       case X86::AX: DestReg = X86::EAX; break;
12749       case X86::DX: DestReg = X86::EDX; break;
12750       case X86::CX: DestReg = X86::ECX; break;
12751       case X86::BX: DestReg = X86::EBX; break;
12752       case X86::SI: DestReg = X86::ESI; break;
12753       case X86::DI: DestReg = X86::EDI; break;
12754       case X86::BP: DestReg = X86::EBP; break;
12755       case X86::SP: DestReg = X86::ESP; break;
12756       }
12757       if (DestReg) {
12758         Res.first = DestReg;
12759         Res.second = X86::GR32RegisterClass;
12760       }
12761     } else if (VT == MVT::i64) {
12762       unsigned DestReg = 0;
12763       switch (Res.first) {
12764       default: break;
12765       case X86::AX: DestReg = X86::RAX; break;
12766       case X86::DX: DestReg = X86::RDX; break;
12767       case X86::CX: DestReg = X86::RCX; break;
12768       case X86::BX: DestReg = X86::RBX; break;
12769       case X86::SI: DestReg = X86::RSI; break;
12770       case X86::DI: DestReg = X86::RDI; break;
12771       case X86::BP: DestReg = X86::RBP; break;
12772       case X86::SP: DestReg = X86::RSP; break;
12773       }
12774       if (DestReg) {
12775         Res.first = DestReg;
12776         Res.second = X86::GR64RegisterClass;
12777       }
12778     }
12779   } else if (Res.second == X86::FR32RegisterClass ||
12780              Res.second == X86::FR64RegisterClass ||
12781              Res.second == X86::VR128RegisterClass) {
12782     // Handle references to XMM physical registers that got mapped into the
12783     // wrong class.  This can happen with constraints like {xmm0} where the
12784     // target independent register mapper will just pick the first match it can
12785     // find, ignoring the required type.
12786     if (VT == MVT::f32)
12787       Res.second = X86::FR32RegisterClass;
12788     else if (VT == MVT::f64)
12789       Res.second = X86::FR64RegisterClass;
12790     else if (X86::VR128RegisterClass->hasType(VT))
12791       Res.second = X86::VR128RegisterClass;
12792   }
12793
12794   return Res;
12795 }