Move more logic into getTypeForExtArgOrReturn.
[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     
225   // For 64-bit since we have so many registers use the ILP scheduler, for
226   // 32-bit code use the register pressure specific scheduling.
227   if (Subtarget->is64Bit())
228     setSchedulingPreference(Sched::ILP);
229   else
230     setSchedulingPreference(Sched::RegPressure);
231   setStackPointerRegisterToSaveRestore(X86StackPtr);
232
233   if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
234     // Setup Windows compiler runtime calls.
235     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
236     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
237     setLibcallName(RTLIB::FPTOUINT_F64_I64, "_ftol2");
238     setLibcallName(RTLIB::FPTOUINT_F32_I64, "_ftol2");
239     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
240     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
241     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::C);
242     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::C);
243   }
244
245   if (Subtarget->isTargetDarwin()) {
246     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
247     setUseUnderscoreSetJmp(false);
248     setUseUnderscoreLongJmp(false);
249   } else if (Subtarget->isTargetMingw()) {
250     // MS runtime is weird: it exports _setjmp, but longjmp!
251     setUseUnderscoreSetJmp(true);
252     setUseUnderscoreLongJmp(false);
253   } else {
254     setUseUnderscoreSetJmp(true);
255     setUseUnderscoreLongJmp(true);
256   }
257
258   // Set up the register classes.
259   addRegisterClass(MVT::i8, X86::GR8RegisterClass);
260   addRegisterClass(MVT::i16, X86::GR16RegisterClass);
261   addRegisterClass(MVT::i32, X86::GR32RegisterClass);
262   if (Subtarget->is64Bit())
263     addRegisterClass(MVT::i64, X86::GR64RegisterClass);
264
265   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
266
267   // We don't accept any truncstore of integer registers.
268   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
269   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
270   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
271   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
272   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
273   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
274
275   // SETOEQ and SETUNE require checking two conditions.
276   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
277   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
278   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
279   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
280   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
281   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
282
283   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
284   // operation.
285   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
286   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
287   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
288
289   if (Subtarget->is64Bit()) {
290     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
291     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Expand);
292   } else if (!UseSoftFloat) {
293     // We have an algorithm for SSE2->double, and we turn this into a
294     // 64-bit FILD followed by conditional FADD for other targets.
295     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
296     // We have an algorithm for SSE2, and we turn this into a 64-bit
297     // FILD for other targets.
298     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
299   }
300
301   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
302   // this operation.
303   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
304   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
305
306   if (!UseSoftFloat) {
307     // SSE has no i16 to fp conversion, only i32
308     if (X86ScalarSSEf32) {
309       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
310       // f32 and f64 cases are Legal, f80 case is not
311       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
312     } else {
313       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
314       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
315     }
316   } else {
317     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
318     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
319   }
320
321   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
322   // are Legal, f80 is custom lowered.
323   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
324   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
325
326   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
327   // this operation.
328   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
329   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
330
331   if (X86ScalarSSEf32) {
332     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
333     // f32 and f64 cases are Legal, f80 case is not
334     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
335   } else {
336     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
337     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
338   }
339
340   // Handle FP_TO_UINT by promoting the destination to a larger signed
341   // conversion.
342   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
343   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
344   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
345
346   if (Subtarget->is64Bit()) {
347     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
348     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
349   } else if (!UseSoftFloat) {
350     if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
351       // Expand FP_TO_UINT into a select.
352       // FIXME: We would like to use a Custom expander here eventually to do
353       // the optimal thing for SSE vs. the default expansion in the legalizer.
354       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
355     else
356       // With SSE3 we can use fisttpll to convert to a signed i64; without
357       // SSE, we're stuck with a fistpll.
358       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
359   }
360
361   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
362   if (!X86ScalarSSEf64) {
363     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
364     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
365     if (Subtarget->is64Bit()) {
366       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
367       // Without SSE, i64->f64 goes through memory.
368       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
369     }
370   }
371
372   // Scalar integer divide and remainder are lowered to use operations that
373   // produce two results, to match the available instructions. This exposes
374   // the two-result form to trivial CSE, which is able to combine x/y and x%y
375   // into a single instruction.
376   //
377   // Scalar integer multiply-high is also lowered to use two-result
378   // operations, to match the available instructions. However, plain multiply
379   // (low) operations are left as Legal, as there are single-result
380   // instructions for this in x86. Using the two-result multiply instructions
381   // when both high and low results are needed must be arranged by dagcombine.
382   for (unsigned i = 0, e = 4; i != e; ++i) {
383     MVT VT = IntVTs[i];
384     setOperationAction(ISD::MULHS, VT, Expand);
385     setOperationAction(ISD::MULHU, VT, Expand);
386     setOperationAction(ISD::SDIV, VT, Expand);
387     setOperationAction(ISD::UDIV, VT, Expand);
388     setOperationAction(ISD::SREM, VT, Expand);
389     setOperationAction(ISD::UREM, VT, Expand);
390
391     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
392     setOperationAction(ISD::ADDC, VT, Custom);
393     setOperationAction(ISD::ADDE, VT, Custom);
394     setOperationAction(ISD::SUBC, VT, Custom);
395     setOperationAction(ISD::SUBE, VT, Custom);
396   }
397
398   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
399   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
400   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
401   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
402   if (Subtarget->is64Bit())
403     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
404   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
405   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
406   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
407   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
408   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
409   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
410   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
411   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
412
413   setOperationAction(ISD::CTTZ             , MVT::i8   , Custom);
414   setOperationAction(ISD::CTLZ             , MVT::i8   , Custom);
415   setOperationAction(ISD::CTTZ             , MVT::i16  , Custom);
416   setOperationAction(ISD::CTLZ             , MVT::i16  , Custom);
417   setOperationAction(ISD::CTTZ             , MVT::i32  , Custom);
418   setOperationAction(ISD::CTLZ             , MVT::i32  , Custom);
419   if (Subtarget->is64Bit()) {
420     setOperationAction(ISD::CTTZ           , MVT::i64  , Custom);
421     setOperationAction(ISD::CTLZ           , MVT::i64  , Custom);
422   }
423
424   if (Subtarget->hasPOPCNT()) {
425     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
426   } else {
427     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
428     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
429     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
430     if (Subtarget->is64Bit())
431       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
432   }
433
434   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
435   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
436
437   // These should be promoted to a larger select which is supported.
438   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
439   // X86 wants to expand cmov itself.
440   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
441   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
442   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
443   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
444   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
445   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
446   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
447   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
448   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
449   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
450   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
451   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
452   if (Subtarget->is64Bit()) {
453     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
454     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
455   }
456   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
457
458   // Darwin ABI issue.
459   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
460   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
461   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
462   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
463   if (Subtarget->is64Bit())
464     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
465   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
466   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
467   if (Subtarget->is64Bit()) {
468     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
469     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
470     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
471     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
472     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
473   }
474   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
475   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
476   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
477   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
478   if (Subtarget->is64Bit()) {
479     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
480     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
481     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
482   }
483
484   if (Subtarget->hasXMM())
485     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
486
487   // We may not have a libcall for MEMBARRIER so we should lower this.
488   setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
489
490   // On X86 and X86-64, atomic operations are lowered to locked instructions.
491   // Locked instructions, in turn, have implicit fence semantics (all memory
492   // operations are flushed before issuing the locked instruction, and they
493   // are not buffered), so we can fold away the common pattern of
494   // fence-atomic-fence.
495   setShouldFoldAtomicFences(true);
496
497   // Expand certain atomics
498   for (unsigned i = 0, e = 4; i != e; ++i) {
499     MVT VT = IntVTs[i];
500     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
501     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
502   }
503
504   if (!Subtarget->is64Bit()) {
505     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
506     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
507     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
508     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
509     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
510     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
511     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
512   }
513
514   // FIXME - use subtarget debug flags
515   if (!Subtarget->isTargetDarwin() &&
516       !Subtarget->isTargetELF() &&
517       !Subtarget->isTargetCygMing()) {
518     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
519   }
520
521   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
522   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
523   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
524   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
525   if (Subtarget->is64Bit()) {
526     setExceptionPointerRegister(X86::RAX);
527     setExceptionSelectorRegister(X86::RDX);
528   } else {
529     setExceptionPointerRegister(X86::EAX);
530     setExceptionSelectorRegister(X86::EDX);
531   }
532   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
533   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
534
535   setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
536
537   setOperationAction(ISD::TRAP, MVT::Other, Legal);
538
539   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
540   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
541   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
542   if (Subtarget->is64Bit()) {
543     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
544     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
545   } else {
546     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
547     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
548   }
549
550   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
551   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
552   if (Subtarget->is64Bit())
553     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
554   if (Subtarget->isTargetCygMing() || Subtarget->isTargetWindows())
555     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
556   else
557     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
558
559   if (!UseSoftFloat && X86ScalarSSEf64) {
560     // f32 and f64 use SSE.
561     // Set up the FP register classes.
562     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
563     addRegisterClass(MVT::f64, X86::FR64RegisterClass);
564
565     // Use ANDPD to simulate FABS.
566     setOperationAction(ISD::FABS , MVT::f64, Custom);
567     setOperationAction(ISD::FABS , MVT::f32, Custom);
568
569     // Use XORP to simulate FNEG.
570     setOperationAction(ISD::FNEG , MVT::f64, Custom);
571     setOperationAction(ISD::FNEG , MVT::f32, Custom);
572
573     // Use ANDPD and ORPD to simulate FCOPYSIGN.
574     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
575     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
576
577     // We don't support sin/cos/fmod
578     setOperationAction(ISD::FSIN , MVT::f64, Expand);
579     setOperationAction(ISD::FCOS , MVT::f64, Expand);
580     setOperationAction(ISD::FSIN , MVT::f32, Expand);
581     setOperationAction(ISD::FCOS , MVT::f32, Expand);
582
583     // Expand FP immediates into loads from the stack, except for the special
584     // cases we handle.
585     addLegalFPImmediate(APFloat(+0.0)); // xorpd
586     addLegalFPImmediate(APFloat(+0.0f)); // xorps
587   } else if (!UseSoftFloat && X86ScalarSSEf32) {
588     // Use SSE for f32, x87 for f64.
589     // Set up the FP register classes.
590     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
591     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
592
593     // Use ANDPS to simulate FABS.
594     setOperationAction(ISD::FABS , MVT::f32, Custom);
595
596     // Use XORP to simulate FNEG.
597     setOperationAction(ISD::FNEG , MVT::f32, Custom);
598
599     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
600
601     // Use ANDPS and ORPS to simulate FCOPYSIGN.
602     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
603     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
604
605     // We don't support sin/cos/fmod
606     setOperationAction(ISD::FSIN , MVT::f32, Expand);
607     setOperationAction(ISD::FCOS , MVT::f32, Expand);
608
609     // Special cases we handle for FP constants.
610     addLegalFPImmediate(APFloat(+0.0f)); // xorps
611     addLegalFPImmediate(APFloat(+0.0)); // FLD0
612     addLegalFPImmediate(APFloat(+1.0)); // FLD1
613     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
614     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
615
616     if (!UnsafeFPMath) {
617       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
618       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
619     }
620   } else if (!UseSoftFloat) {
621     // f32 and f64 in x87.
622     // Set up the FP register classes.
623     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
624     addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
625
626     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
627     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
628     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
629     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
630
631     if (!UnsafeFPMath) {
632       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
633       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
634     }
635     addLegalFPImmediate(APFloat(+0.0)); // FLD0
636     addLegalFPImmediate(APFloat(+1.0)); // FLD1
637     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
638     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
639     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
640     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
641     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
642     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
643   }
644
645   // Long double always uses X87.
646   if (!UseSoftFloat) {
647     addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
648     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
649     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
650     {
651       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
652       addLegalFPImmediate(TmpFlt);  // FLD0
653       TmpFlt.changeSign();
654       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
655
656       bool ignored;
657       APFloat TmpFlt2(+1.0);
658       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
659                       &ignored);
660       addLegalFPImmediate(TmpFlt2);  // FLD1
661       TmpFlt2.changeSign();
662       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
663     }
664
665     if (!UnsafeFPMath) {
666       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
667       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
668     }
669   }
670
671   // Always use a library call for pow.
672   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
673   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
674   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
675
676   setOperationAction(ISD::FLOG, MVT::f80, Expand);
677   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
678   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
679   setOperationAction(ISD::FEXP, MVT::f80, Expand);
680   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
681
682   // First set operation action for all vector types to either promote
683   // (for widening) or expand (for scalarization). Then we will selectively
684   // turn on ones that can be effectively codegen'd.
685   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
686        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
687     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
688     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
689     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
690     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
691     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
692     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
693     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
694     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
695     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
696     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
697     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
698     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
699     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
700     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
701     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
702     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
703     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
704     setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
705     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
706     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
707     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
708     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
709     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
710     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
711     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
712     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
713     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
714     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
715     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
716     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
717     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
718     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
719     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
720     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
721     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
722     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
723     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
724     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
725     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
726     setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
727     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
728     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
729     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
730     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
731     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
732     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
733     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
734     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
735     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
736     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
737     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
738     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
739     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
740     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
741     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
742          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
743       setTruncStoreAction((MVT::SimpleValueType)VT,
744                           (MVT::SimpleValueType)InnerVT, Expand);
745     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
746     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
747     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
748   }
749
750   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
751   // with -msoft-float, disable use of MMX as well.
752   if (!UseSoftFloat && Subtarget->hasMMX()) {
753     addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass);
754     // No operations on x86mmx supported, everything uses intrinsics.
755   }
756
757   // MMX-sized vectors (other than x86mmx) are expected to be expanded
758   // into smaller operations.
759   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
760   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
761   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
762   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
763   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
764   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
765   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
766   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
767   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
768   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
769   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
770   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
771   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
772   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
773   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
774   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
775   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
776   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
777   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
778   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
779   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
780   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
781   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
782   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
783   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
784   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
785   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
786   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
787   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
788
789   if (!UseSoftFloat && Subtarget->hasXMM()) {
790     addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
791
792     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
793     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
794     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
795     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
796     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
797     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
798     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
799     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
800     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
801     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
802     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
803     setOperationAction(ISD::VSETCC,             MVT::v4f32, Custom);
804   }
805
806   if (!UseSoftFloat && Subtarget->hasXMMInt()) {
807     addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
808
809     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
810     // registers cannot be used even for integer operations.
811     addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
812     addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
813     addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
814     addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
815
816     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
817     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
818     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
819     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
820     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
821     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
822     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
823     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
824     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
825     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
826     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
827     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
828     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
829     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
830     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
831     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
832
833     setOperationAction(ISD::VSETCC,             MVT::v2f64, Custom);
834     setOperationAction(ISD::VSETCC,             MVT::v16i8, Custom);
835     setOperationAction(ISD::VSETCC,             MVT::v8i16, Custom);
836     setOperationAction(ISD::VSETCC,             MVT::v4i32, Custom);
837
838     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
839     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
840     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
841     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
842     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
843
844     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2f64, Custom);
845     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2i64, Custom);
846     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i8, Custom);
847     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i16, Custom);
848     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i32, Custom);
849
850     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
851     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
852       EVT VT = (MVT::SimpleValueType)i;
853       // Do not attempt to custom lower non-power-of-2 vectors
854       if (!isPowerOf2_32(VT.getVectorNumElements()))
855         continue;
856       // Do not attempt to custom lower non-128-bit vectors
857       if (!VT.is128BitVector())
858         continue;
859       setOperationAction(ISD::BUILD_VECTOR,
860                          VT.getSimpleVT().SimpleTy, Custom);
861       setOperationAction(ISD::VECTOR_SHUFFLE,
862                          VT.getSimpleVT().SimpleTy, Custom);
863       setOperationAction(ISD::EXTRACT_VECTOR_ELT,
864                          VT.getSimpleVT().SimpleTy, Custom);
865     }
866
867     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
868     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
869     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
870     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
871     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
872     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
873
874     if (Subtarget->is64Bit()) {
875       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
876       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
877     }
878
879     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
880     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
881       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
882       EVT VT = SVT;
883
884       // Do not attempt to promote non-128-bit vectors
885       if (!VT.is128BitVector())
886         continue;
887
888       setOperationAction(ISD::AND,    SVT, Promote);
889       AddPromotedToType (ISD::AND,    SVT, MVT::v2i64);
890       setOperationAction(ISD::OR,     SVT, Promote);
891       AddPromotedToType (ISD::OR,     SVT, MVT::v2i64);
892       setOperationAction(ISD::XOR,    SVT, Promote);
893       AddPromotedToType (ISD::XOR,    SVT, MVT::v2i64);
894       setOperationAction(ISD::LOAD,   SVT, Promote);
895       AddPromotedToType (ISD::LOAD,   SVT, MVT::v2i64);
896       setOperationAction(ISD::SELECT, SVT, Promote);
897       AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
898     }
899
900     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
901
902     // Custom lower v2i64 and v2f64 selects.
903     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
904     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
905     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
906     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
907
908     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
909     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
910   }
911
912   if (Subtarget->hasSSE41()) {
913     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
914     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
915     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
916     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
917     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
918     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
919     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
920     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
921     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
922     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
923
924     // FIXME: Do we need to handle scalar-to-vector here?
925     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
926
927     // Can turn SHL into an integer multiply.
928     setOperationAction(ISD::SHL,                MVT::v4i32, Custom);
929     setOperationAction(ISD::SHL,                MVT::v16i8, Custom);
930
931     // i8 and i16 vectors are custom , because the source register and source
932     // source memory operand types are not the same width.  f32 vectors are
933     // custom since the immediate controlling the insert encodes additional
934     // information.
935     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
936     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
937     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
938     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
939
940     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
941     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
942     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
943     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
944
945     if (Subtarget->is64Bit()) {
946       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Legal);
947       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
948     }
949   }
950
951   if (Subtarget->hasSSE42())
952     setOperationAction(ISD::VSETCC,             MVT::v2i64, Custom);
953
954   if (!UseSoftFloat && Subtarget->hasAVX()) {
955     addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
956     addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
957     addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
958     addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
959     addRegisterClass(MVT::v32i8, X86::VR256RegisterClass);
960
961     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
962     setOperationAction(ISD::LOAD,               MVT::v8i32, Legal);
963     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
964     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
965
966     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
967     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
968     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
969     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
970     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
971     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
972
973     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
974     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
975     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
976     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
977     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
978     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
979
980     // Custom lower build_vector, vector_shuffle, scalar_to_vector,
981     // insert_vector_elt extract_subvector and extract_vector_elt for
982     // 256-bit types.
983     for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
984          i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE;
985          ++i) {
986       MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
987       // Do not attempt to custom lower non-256-bit vectors
988       if (!isPowerOf2_32(MVT(VT).getVectorNumElements())
989           || (MVT(VT).getSizeInBits() < 256))
990         continue;
991       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
992       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
993       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
994       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
995       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
996     }
997     // Custom-lower insert_subvector and extract_subvector based on
998     // the result type.
999     for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1000          i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE;
1001          ++i) {
1002       MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
1003       // Do not attempt to custom lower non-256-bit vectors
1004       if (!isPowerOf2_32(MVT(VT).getVectorNumElements()))
1005         continue;
1006
1007       if (MVT(VT).getSizeInBits() == 128) {
1008         setOperationAction(ISD::EXTRACT_SUBVECTOR,  VT, Custom);
1009       }
1010       else if (MVT(VT).getSizeInBits() == 256) {
1011         setOperationAction(ISD::INSERT_SUBVECTOR,  VT, Custom);
1012       }
1013     }
1014
1015     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1016     // Don't promote loads because we need them for VPERM vector index versions.
1017
1018     for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1019          VT != (unsigned)MVT::LAST_VECTOR_VALUETYPE;
1020          VT++) {
1021       if (!isPowerOf2_32(MVT((MVT::SimpleValueType)VT).getVectorNumElements())
1022           || (MVT((MVT::SimpleValueType)VT).getSizeInBits() < 256))
1023         continue;
1024       setOperationAction(ISD::AND,    (MVT::SimpleValueType)VT, Promote);
1025       AddPromotedToType (ISD::AND,    (MVT::SimpleValueType)VT, MVT::v4i64);
1026       setOperationAction(ISD::OR,     (MVT::SimpleValueType)VT, Promote);
1027       AddPromotedToType (ISD::OR,     (MVT::SimpleValueType)VT, MVT::v4i64);
1028       setOperationAction(ISD::XOR,    (MVT::SimpleValueType)VT, Promote);
1029       AddPromotedToType (ISD::XOR,    (MVT::SimpleValueType)VT, MVT::v4i64);
1030       //setOperationAction(ISD::LOAD,   (MVT::SimpleValueType)VT, Promote);
1031       //AddPromotedToType (ISD::LOAD,   (MVT::SimpleValueType)VT, MVT::v4i64);
1032       setOperationAction(ISD::SELECT, (MVT::SimpleValueType)VT, Promote);
1033       AddPromotedToType (ISD::SELECT, (MVT::SimpleValueType)VT, MVT::v4i64);
1034     }
1035   }
1036
1037   // We want to custom lower some of our intrinsics.
1038   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1039
1040
1041   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1042   // handle type legalization for these operations here.
1043   //
1044   // FIXME: We really should do custom legalization for addition and
1045   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1046   // than generic legalization for 64-bit multiplication-with-overflow, though.
1047   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1048     // Add/Sub/Mul with overflow operations are custom lowered.
1049     MVT VT = IntVTs[i];
1050     setOperationAction(ISD::SADDO, VT, Custom);
1051     setOperationAction(ISD::UADDO, VT, Custom);
1052     setOperationAction(ISD::SSUBO, VT, Custom);
1053     setOperationAction(ISD::USUBO, VT, Custom);
1054     setOperationAction(ISD::SMULO, VT, Custom);
1055     setOperationAction(ISD::UMULO, VT, Custom);
1056   }
1057
1058   // There are no 8-bit 3-address imul/mul instructions
1059   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1060   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1061
1062   if (!Subtarget->is64Bit()) {
1063     // These libcalls are not available in 32-bit.
1064     setLibcallName(RTLIB::SHL_I128, 0);
1065     setLibcallName(RTLIB::SRL_I128, 0);
1066     setLibcallName(RTLIB::SRA_I128, 0);
1067   }
1068
1069   // We have target-specific dag combine patterns for the following nodes:
1070   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1071   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1072   setTargetDAGCombine(ISD::BUILD_VECTOR);
1073   setTargetDAGCombine(ISD::SELECT);
1074   setTargetDAGCombine(ISD::SHL);
1075   setTargetDAGCombine(ISD::SRA);
1076   setTargetDAGCombine(ISD::SRL);
1077   setTargetDAGCombine(ISD::OR);
1078   setTargetDAGCombine(ISD::AND);
1079   setTargetDAGCombine(ISD::ADD);
1080   setTargetDAGCombine(ISD::SUB);
1081   setTargetDAGCombine(ISD::STORE);
1082   setTargetDAGCombine(ISD::ZERO_EXTEND);
1083   if (Subtarget->is64Bit())
1084     setTargetDAGCombine(ISD::MUL);
1085
1086   computeRegisterProperties();
1087
1088   // On Darwin, -Os means optimize for size without hurting performance,
1089   // do not reduce the limit.
1090   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1091   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1092   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1093   maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1094   maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1095   maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1096   setPrefLoopAlignment(16);
1097   benefitFromCodePlacementOpt = true;
1098 }
1099
1100
1101 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
1102   return MVT::i8;
1103 }
1104
1105
1106 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1107 /// the desired ByVal argument alignment.
1108 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
1109   if (MaxAlign == 16)
1110     return;
1111   if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1112     if (VTy->getBitWidth() == 128)
1113       MaxAlign = 16;
1114   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1115     unsigned EltAlign = 0;
1116     getMaxByValAlign(ATy->getElementType(), EltAlign);
1117     if (EltAlign > MaxAlign)
1118       MaxAlign = EltAlign;
1119   } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1120     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1121       unsigned EltAlign = 0;
1122       getMaxByValAlign(STy->getElementType(i), EltAlign);
1123       if (EltAlign > MaxAlign)
1124         MaxAlign = EltAlign;
1125       if (MaxAlign == 16)
1126         break;
1127     }
1128   }
1129   return;
1130 }
1131
1132 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1133 /// function arguments in the caller parameter area. For X86, aggregates
1134 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1135 /// are at 4-byte boundaries.
1136 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1137   if (Subtarget->is64Bit()) {
1138     // Max of 8 and alignment of type.
1139     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1140     if (TyAlign > 8)
1141       return TyAlign;
1142     return 8;
1143   }
1144
1145   unsigned Align = 4;
1146   if (Subtarget->hasXMM())
1147     getMaxByValAlign(Ty, Align);
1148   return Align;
1149 }
1150
1151 /// getOptimalMemOpType - Returns the target specific optimal type for load
1152 /// and store operations as a result of memset, memcpy, and memmove
1153 /// lowering. If DstAlign is zero that means it's safe to destination
1154 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1155 /// means there isn't a need to check it against alignment requirement,
1156 /// probably because the source does not need to be loaded. If
1157 /// 'NonScalarIntSafe' is true, that means it's safe to return a
1158 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1159 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1160 /// constant so it does not need to be loaded.
1161 /// It returns EVT::Other if the type should be determined using generic
1162 /// target-independent logic.
1163 EVT
1164 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1165                                        unsigned DstAlign, unsigned SrcAlign,
1166                                        bool NonScalarIntSafe,
1167                                        bool MemcpyStrSrc,
1168                                        MachineFunction &MF) const {
1169   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1170   // linux.  This is because the stack realignment code can't handle certain
1171   // cases like PR2962.  This should be removed when PR2962 is fixed.
1172   const Function *F = MF.getFunction();
1173   if (NonScalarIntSafe &&
1174       !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1175     if (Size >= 16 &&
1176         (Subtarget->isUnalignedMemAccessFast() ||
1177          ((DstAlign == 0 || DstAlign >= 16) &&
1178           (SrcAlign == 0 || SrcAlign >= 16))) &&
1179         Subtarget->getStackAlignment() >= 16) {
1180       if (Subtarget->hasSSE2())
1181         return MVT::v4i32;
1182       if (Subtarget->hasSSE1())
1183         return MVT::v4f32;
1184     } else if (!MemcpyStrSrc && Size >= 8 &&
1185                !Subtarget->is64Bit() &&
1186                Subtarget->getStackAlignment() >= 8 &&
1187                Subtarget->hasXMMInt()) {
1188       // Do not use f64 to lower memcpy if source is string constant. It's
1189       // better to use i32 to avoid the loads.
1190       return MVT::f64;
1191     }
1192   }
1193   if (Subtarget->is64Bit() && Size >= 8)
1194     return MVT::i64;
1195   return MVT::i32;
1196 }
1197
1198 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1199 /// current function.  The returned value is a member of the
1200 /// MachineJumpTableInfo::JTEntryKind enum.
1201 unsigned X86TargetLowering::getJumpTableEncoding() const {
1202   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1203   // symbol.
1204   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1205       Subtarget->isPICStyleGOT())
1206     return MachineJumpTableInfo::EK_Custom32;
1207
1208   // Otherwise, use the normal jump table encoding heuristics.
1209   return TargetLowering::getJumpTableEncoding();
1210 }
1211
1212 const MCExpr *
1213 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1214                                              const MachineBasicBlock *MBB,
1215                                              unsigned uid,MCContext &Ctx) const{
1216   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1217          Subtarget->isPICStyleGOT());
1218   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1219   // entries.
1220   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1221                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1222 }
1223
1224 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1225 /// jumptable.
1226 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1227                                                     SelectionDAG &DAG) const {
1228   if (!Subtarget->is64Bit())
1229     // This doesn't have DebugLoc associated with it, but is not really the
1230     // same as a Register.
1231     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1232   return Table;
1233 }
1234
1235 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1236 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1237 /// MCExpr.
1238 const MCExpr *X86TargetLowering::
1239 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1240                              MCContext &Ctx) const {
1241   // X86-64 uses RIP relative addressing based on the jump table label.
1242   if (Subtarget->isPICStyleRIPRel())
1243     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1244
1245   // Otherwise, the reference is relative to the PIC base.
1246   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1247 }
1248
1249 /// getFunctionAlignment - Return the Log2 alignment of this function.
1250 unsigned X86TargetLowering::getFunctionAlignment(const Function *F) const {
1251   return F->hasFnAttr(Attribute::OptimizeForSize) ? 0 : 4;
1252 }
1253
1254 // FIXME: Why this routine is here? Move to RegInfo!
1255 std::pair<const TargetRegisterClass*, uint8_t>
1256 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1257   const TargetRegisterClass *RRC = 0;
1258   uint8_t Cost = 1;
1259   switch (VT.getSimpleVT().SimpleTy) {
1260   default:
1261     return TargetLowering::findRepresentativeClass(VT);
1262   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1263     RRC = (Subtarget->is64Bit()
1264            ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1265     break;
1266   case MVT::x86mmx:
1267     RRC = X86::VR64RegisterClass;
1268     break;
1269   case MVT::f32: case MVT::f64:
1270   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1271   case MVT::v4f32: case MVT::v2f64:
1272   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1273   case MVT::v4f64:
1274     RRC = X86::VR128RegisterClass;
1275     break;
1276   }
1277   return std::make_pair(RRC, Cost);
1278 }
1279
1280 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1281                                                unsigned &Offset) const {
1282   if (!Subtarget->isTargetLinux())
1283     return false;
1284
1285   if (Subtarget->is64Bit()) {
1286     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1287     Offset = 0x28;
1288     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1289       AddressSpace = 256;
1290     else
1291       AddressSpace = 257;
1292   } else {
1293     // %gs:0x14 on i386
1294     Offset = 0x14;
1295     AddressSpace = 256;
1296   }
1297   return true;
1298 }
1299
1300
1301 //===----------------------------------------------------------------------===//
1302 //               Return Value Calling Convention Implementation
1303 //===----------------------------------------------------------------------===//
1304
1305 #include "X86GenCallingConv.inc"
1306
1307 bool
1308 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv, bool isVarArg,
1309                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1310                         LLVMContext &Context) const {
1311   SmallVector<CCValAssign, 16> RVLocs;
1312   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1313                  RVLocs, Context);
1314   return CCInfo.CheckReturn(Outs, RetCC_X86);
1315 }
1316
1317 SDValue
1318 X86TargetLowering::LowerReturn(SDValue Chain,
1319                                CallingConv::ID CallConv, bool isVarArg,
1320                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1321                                const SmallVectorImpl<SDValue> &OutVals,
1322                                DebugLoc dl, SelectionDAG &DAG) const {
1323   MachineFunction &MF = DAG.getMachineFunction();
1324   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1325
1326   SmallVector<CCValAssign, 16> RVLocs;
1327   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1328                  RVLocs, *DAG.getContext());
1329   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1330
1331   // Add the regs to the liveout set for the function.
1332   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1333   for (unsigned i = 0; i != RVLocs.size(); ++i)
1334     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1335       MRI.addLiveOut(RVLocs[i].getLocReg());
1336
1337   SDValue Flag;
1338
1339   SmallVector<SDValue, 6> RetOps;
1340   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1341   // Operand #1 = Bytes To Pop
1342   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1343                    MVT::i16));
1344
1345   // Copy the result values into the output registers.
1346   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1347     CCValAssign &VA = RVLocs[i];
1348     assert(VA.isRegLoc() && "Can only return in registers!");
1349     SDValue ValToCopy = OutVals[i];
1350     EVT ValVT = ValToCopy.getValueType();
1351
1352     // If this is x86-64, and we disabled SSE, we can't return FP values,
1353     // or SSE or MMX vectors.
1354     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1355          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1356           (Subtarget->is64Bit() && !Subtarget->hasXMM())) {
1357       report_fatal_error("SSE register return with SSE disabled");
1358     }
1359     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1360     // llvm-gcc has never done it right and no one has noticed, so this
1361     // should be OK for now.
1362     if (ValVT == MVT::f64 &&
1363         (Subtarget->is64Bit() && !Subtarget->hasXMMInt()))
1364       report_fatal_error("SSE2 register return with SSE2 disabled");
1365
1366     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1367     // the RET instruction and handled by the FP Stackifier.
1368     if (VA.getLocReg() == X86::ST0 ||
1369         VA.getLocReg() == X86::ST1) {
1370       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1371       // change the value to the FP stack register class.
1372       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1373         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1374       RetOps.push_back(ValToCopy);
1375       // Don't emit a copytoreg.
1376       continue;
1377     }
1378
1379     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1380     // which is returned in RAX / RDX.
1381     if (Subtarget->is64Bit()) {
1382       if (ValVT == MVT::x86mmx) {
1383         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1384           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1385           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1386                                   ValToCopy);
1387           // If we don't have SSE2 available, convert to v4f32 so the generated
1388           // register is legal.
1389           if (!Subtarget->hasSSE2())
1390             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1391         }
1392       }
1393     }
1394
1395     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1396     Flag = Chain.getValue(1);
1397   }
1398
1399   // The x86-64 ABI for returning structs by value requires that we copy
1400   // the sret argument into %rax for the return. We saved the argument into
1401   // a virtual register in the entry block, so now we copy the value out
1402   // and into %rax.
1403   if (Subtarget->is64Bit() &&
1404       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1405     MachineFunction &MF = DAG.getMachineFunction();
1406     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1407     unsigned Reg = FuncInfo->getSRetReturnReg();
1408     assert(Reg &&
1409            "SRetReturnReg should have been set in LowerFormalArguments().");
1410     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1411
1412     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1413     Flag = Chain.getValue(1);
1414
1415     // RAX now acts like a return value.
1416     MRI.addLiveOut(X86::RAX);
1417   }
1418
1419   RetOps[0] = Chain;  // Update chain.
1420
1421   // Add the flag if we have it.
1422   if (Flag.getNode())
1423     RetOps.push_back(Flag);
1424
1425   return DAG.getNode(X86ISD::RET_FLAG, dl,
1426                      MVT::Other, &RetOps[0], RetOps.size());
1427 }
1428
1429 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1430   if (N->getNumValues() != 1)
1431     return false;
1432   if (!N->hasNUsesOfValue(1, 0))
1433     return false;
1434
1435   SDNode *Copy = *N->use_begin();
1436   if (Copy->getOpcode() != ISD::CopyToReg &&
1437       Copy->getOpcode() != ISD::FP_EXTEND)
1438     return false;
1439
1440   bool HasRet = false;
1441   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1442        UI != UE; ++UI) {
1443     if (UI->getOpcode() != X86ISD::RET_FLAG)
1444       return false;
1445     HasRet = true;
1446   }
1447
1448   return HasRet;
1449 }
1450
1451 EVT
1452 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1453                                             ISD::NodeType ExtendKind) const {
1454   MVT ReturnMVT;
1455   // TODO: Is this also valid on 32-bit?
1456   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1457     ReturnMVT = MVT::i8;
1458   else
1459     ReturnMVT = MVT::i32;
1460
1461   EVT MinVT = getRegisterType(Context, ReturnMVT);
1462   return VT.bitsLT(MinVT) ? MinVT : VT;
1463 }
1464
1465 /// LowerCallResult - Lower the result values of a call into the
1466 /// appropriate copies out of appropriate physical registers.
1467 ///
1468 SDValue
1469 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1470                                    CallingConv::ID CallConv, bool isVarArg,
1471                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1472                                    DebugLoc dl, SelectionDAG &DAG,
1473                                    SmallVectorImpl<SDValue> &InVals) const {
1474
1475   // Assign locations to each value returned by this call.
1476   SmallVector<CCValAssign, 16> RVLocs;
1477   bool Is64Bit = Subtarget->is64Bit();
1478   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1479                  RVLocs, *DAG.getContext());
1480   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1481
1482   // Copy all of the result registers out of their specified physreg.
1483   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1484     CCValAssign &VA = RVLocs[i];
1485     EVT CopyVT = VA.getValVT();
1486
1487     // If this is x86-64, and we disabled SSE, we can't return FP values
1488     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1489         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) {
1490       report_fatal_error("SSE register return with SSE disabled");
1491     }
1492
1493     SDValue Val;
1494
1495     // If this is a call to a function that returns an fp value on the floating
1496     // point stack, we must guarantee the the value is popped from the stack, so
1497     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1498     // if the return value is not used. We use the FpGET_ST0 instructions
1499     // instead.
1500     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1501       // If we prefer to use the value in xmm registers, copy it out as f80 and
1502       // use a truncate to move it from fp stack reg to xmm reg.
1503       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1504       bool isST0 = VA.getLocReg() == X86::ST0;
1505       unsigned Opc = 0;
1506       if (CopyVT == MVT::f32) Opc = isST0 ? X86::FpGET_ST0_32:X86::FpGET_ST1_32;
1507       if (CopyVT == MVT::f64) Opc = isST0 ? X86::FpGET_ST0_64:X86::FpGET_ST1_64;
1508       if (CopyVT == MVT::f80) Opc = isST0 ? X86::FpGET_ST0_80:X86::FpGET_ST1_80;
1509       SDValue Ops[] = { Chain, InFlag };
1510       Chain = SDValue(DAG.getMachineNode(Opc, dl, CopyVT, MVT::Other, MVT::Glue,
1511                                          Ops, 2), 1);
1512       Val = Chain.getValue(0);
1513
1514       // Round the f80 to the right size, which also moves it to the appropriate
1515       // xmm register.
1516       if (CopyVT != VA.getValVT())
1517         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1518                           // This truncation won't change the value.
1519                           DAG.getIntPtrConstant(1));
1520     } else if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1521       // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1522       if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1523         Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1524                                    MVT::v2i64, InFlag).getValue(1);
1525         Val = Chain.getValue(0);
1526         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1527                           Val, DAG.getConstant(0, MVT::i64));
1528       } else {
1529         Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1530                                    MVT::i64, InFlag).getValue(1);
1531         Val = Chain.getValue(0);
1532       }
1533       Val = DAG.getNode(ISD::BITCAST, dl, CopyVT, Val);
1534     } else {
1535       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1536                                  CopyVT, InFlag).getValue(1);
1537       Val = Chain.getValue(0);
1538     }
1539     InFlag = Chain.getValue(2);
1540     InVals.push_back(Val);
1541   }
1542
1543   return Chain;
1544 }
1545
1546
1547 //===----------------------------------------------------------------------===//
1548 //                C & StdCall & Fast Calling Convention implementation
1549 //===----------------------------------------------------------------------===//
1550 //  StdCall calling convention seems to be standard for many Windows' API
1551 //  routines and around. It differs from C calling convention just a little:
1552 //  callee should clean up the stack, not caller. Symbols should be also
1553 //  decorated in some fancy way :) It doesn't support any vector arguments.
1554 //  For info on fast calling convention see Fast Calling Convention (tail call)
1555 //  implementation LowerX86_32FastCCCallTo.
1556
1557 /// CallIsStructReturn - Determines whether a call uses struct return
1558 /// semantics.
1559 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1560   if (Outs.empty())
1561     return false;
1562
1563   return Outs[0].Flags.isSRet();
1564 }
1565
1566 /// ArgsAreStructReturn - Determines whether a function uses struct
1567 /// return semantics.
1568 static bool
1569 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1570   if (Ins.empty())
1571     return false;
1572
1573   return Ins[0].Flags.isSRet();
1574 }
1575
1576 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1577 /// by "Src" to address "Dst" with size and alignment information specified by
1578 /// the specific parameter attribute. The copy will be passed as a byval
1579 /// function parameter.
1580 static SDValue
1581 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1582                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1583                           DebugLoc dl) {
1584   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1585
1586   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1587                        /*isVolatile*/false, /*AlwaysInline=*/true,
1588                        MachinePointerInfo(), MachinePointerInfo());
1589 }
1590
1591 /// IsTailCallConvention - Return true if the calling convention is one that
1592 /// supports tail call optimization.
1593 static bool IsTailCallConvention(CallingConv::ID CC) {
1594   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1595 }
1596
1597 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1598 /// a tailcall target by changing its ABI.
1599 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1600   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1601 }
1602
1603 SDValue
1604 X86TargetLowering::LowerMemArgument(SDValue Chain,
1605                                     CallingConv::ID CallConv,
1606                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1607                                     DebugLoc dl, SelectionDAG &DAG,
1608                                     const CCValAssign &VA,
1609                                     MachineFrameInfo *MFI,
1610                                     unsigned i) const {
1611   // Create the nodes corresponding to a load from this parameter slot.
1612   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1613   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1614   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1615   EVT ValVT;
1616
1617   // If value is passed by pointer we have address passed instead of the value
1618   // itself.
1619   if (VA.getLocInfo() == CCValAssign::Indirect)
1620     ValVT = VA.getLocVT();
1621   else
1622     ValVT = VA.getValVT();
1623
1624   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1625   // changed with more analysis.
1626   // In case of tail call optimization mark all arguments mutable. Since they
1627   // could be overwritten by lowering of arguments in case of a tail call.
1628   if (Flags.isByVal()) {
1629     int FI = MFI->CreateFixedObject(Flags.getByValSize(),
1630                                     VA.getLocMemOffset(), isImmutable);
1631     return DAG.getFrameIndex(FI, getPointerTy());
1632   } else {
1633     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1634                                     VA.getLocMemOffset(), isImmutable);
1635     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1636     return DAG.getLoad(ValVT, dl, Chain, FIN,
1637                        MachinePointerInfo::getFixedStack(FI),
1638                        false, false, 0);
1639   }
1640 }
1641
1642 SDValue
1643 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1644                                         CallingConv::ID CallConv,
1645                                         bool isVarArg,
1646                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1647                                         DebugLoc dl,
1648                                         SelectionDAG &DAG,
1649                                         SmallVectorImpl<SDValue> &InVals)
1650                                           const {
1651   MachineFunction &MF = DAG.getMachineFunction();
1652   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1653
1654   const Function* Fn = MF.getFunction();
1655   if (Fn->hasExternalLinkage() &&
1656       Subtarget->isTargetCygMing() &&
1657       Fn->getName() == "main")
1658     FuncInfo->setForceFramePointer(true);
1659
1660   MachineFrameInfo *MFI = MF.getFrameInfo();
1661   bool Is64Bit = Subtarget->is64Bit();
1662   bool IsWin64 = Subtarget->isTargetWin64();
1663
1664   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1665          "Var args not supported with calling convention fastcc or ghc");
1666
1667   // Assign locations to all of the incoming arguments.
1668   SmallVector<CCValAssign, 16> ArgLocs;
1669   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1670                  ArgLocs, *DAG.getContext());
1671
1672   // Allocate shadow area for Win64
1673   if (IsWin64) {
1674     CCInfo.AllocateStack(32, 8);
1675   }
1676
1677   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1678
1679   unsigned LastVal = ~0U;
1680   SDValue ArgValue;
1681   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1682     CCValAssign &VA = ArgLocs[i];
1683     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1684     // places.
1685     assert(VA.getValNo() != LastVal &&
1686            "Don't support value assigned to multiple locs yet");
1687     LastVal = VA.getValNo();
1688
1689     if (VA.isRegLoc()) {
1690       EVT RegVT = VA.getLocVT();
1691       TargetRegisterClass *RC = NULL;
1692       if (RegVT == MVT::i32)
1693         RC = X86::GR32RegisterClass;
1694       else if (Is64Bit && RegVT == MVT::i64)
1695         RC = X86::GR64RegisterClass;
1696       else if (RegVT == MVT::f32)
1697         RC = X86::FR32RegisterClass;
1698       else if (RegVT == MVT::f64)
1699         RC = X86::FR64RegisterClass;
1700       else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1701         RC = X86::VR256RegisterClass;
1702       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1703         RC = X86::VR128RegisterClass;
1704       else if (RegVT == MVT::x86mmx)
1705         RC = X86::VR64RegisterClass;
1706       else
1707         llvm_unreachable("Unknown argument type!");
1708
1709       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1710       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1711
1712       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1713       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1714       // right size.
1715       if (VA.getLocInfo() == CCValAssign::SExt)
1716         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1717                                DAG.getValueType(VA.getValVT()));
1718       else if (VA.getLocInfo() == CCValAssign::ZExt)
1719         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1720                                DAG.getValueType(VA.getValVT()));
1721       else if (VA.getLocInfo() == CCValAssign::BCvt)
1722         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1723
1724       if (VA.isExtInLoc()) {
1725         // Handle MMX values passed in XMM regs.
1726         if (RegVT.isVector()) {
1727           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1728                                  ArgValue);
1729         } else
1730           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1731       }
1732     } else {
1733       assert(VA.isMemLoc());
1734       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1735     }
1736
1737     // If value is passed via pointer - do a load.
1738     if (VA.getLocInfo() == CCValAssign::Indirect)
1739       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1740                              MachinePointerInfo(), false, false, 0);
1741
1742     InVals.push_back(ArgValue);
1743   }
1744
1745   // The x86-64 ABI for returning structs by value requires that we copy
1746   // the sret argument into %rax for the return. Save the argument into
1747   // a virtual register so that we can access it from the return points.
1748   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1749     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1750     unsigned Reg = FuncInfo->getSRetReturnReg();
1751     if (!Reg) {
1752       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1753       FuncInfo->setSRetReturnReg(Reg);
1754     }
1755     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1756     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1757   }
1758
1759   unsigned StackSize = CCInfo.getNextStackOffset();
1760   // Align stack specially for tail calls.
1761   if (FuncIsMadeTailCallSafe(CallConv))
1762     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1763
1764   // If the function takes variable number of arguments, make a frame index for
1765   // the start of the first vararg value... for expansion of llvm.va_start.
1766   if (isVarArg) {
1767     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1768                     CallConv != CallingConv::X86_ThisCall)) {
1769       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1770     }
1771     if (Is64Bit) {
1772       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1773
1774       // FIXME: We should really autogenerate these arrays
1775       static const unsigned GPR64ArgRegsWin64[] = {
1776         X86::RCX, X86::RDX, X86::R8,  X86::R9
1777       };
1778       static const unsigned GPR64ArgRegs64Bit[] = {
1779         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1780       };
1781       static const unsigned XMMArgRegs64Bit[] = {
1782         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1783         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1784       };
1785       const unsigned *GPR64ArgRegs;
1786       unsigned NumXMMRegs = 0;
1787
1788       if (IsWin64) {
1789         // The XMM registers which might contain var arg parameters are shadowed
1790         // in their paired GPR.  So we only need to save the GPR to their home
1791         // slots.
1792         TotalNumIntRegs = 4;
1793         GPR64ArgRegs = GPR64ArgRegsWin64;
1794       } else {
1795         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1796         GPR64ArgRegs = GPR64ArgRegs64Bit;
1797
1798         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1799       }
1800       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1801                                                        TotalNumIntRegs);
1802
1803       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1804       assert(!(NumXMMRegs && !Subtarget->hasXMM()) &&
1805              "SSE register cannot be used when SSE is disabled!");
1806       assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1807              "SSE register cannot be used when SSE is disabled!");
1808       if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasXMM())
1809         // Kernel mode asks for SSE to be disabled, so don't push them
1810         // on the stack.
1811         TotalNumXMMRegs = 0;
1812
1813       if (IsWin64) {
1814         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1815         // Get to the caller-allocated home save location.  Add 8 to account
1816         // for the return address.
1817         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1818         FuncInfo->setRegSaveFrameIndex(
1819           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1820         // Fixup to set vararg frame on shadow area (4 x i64).
1821         if (NumIntRegs < 4)
1822           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1823       } else {
1824         // For X86-64, if there are vararg parameters that are passed via
1825         // registers, then we must store them to their spots on the stack so they
1826         // may be loaded by deferencing the result of va_next.
1827         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1828         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1829         FuncInfo->setRegSaveFrameIndex(
1830           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1831                                false));
1832       }
1833
1834       // Store the integer parameter registers.
1835       SmallVector<SDValue, 8> MemOps;
1836       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1837                                         getPointerTy());
1838       unsigned Offset = FuncInfo->getVarArgsGPOffset();
1839       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1840         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1841                                   DAG.getIntPtrConstant(Offset));
1842         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1843                                      X86::GR64RegisterClass);
1844         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1845         SDValue Store =
1846           DAG.getStore(Val.getValue(1), dl, Val, FIN,
1847                        MachinePointerInfo::getFixedStack(
1848                          FuncInfo->getRegSaveFrameIndex(), Offset),
1849                        false, false, 0);
1850         MemOps.push_back(Store);
1851         Offset += 8;
1852       }
1853
1854       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1855         // Now store the XMM (fp + vector) parameter registers.
1856         SmallVector<SDValue, 11> SaveXMMOps;
1857         SaveXMMOps.push_back(Chain);
1858
1859         unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1860         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1861         SaveXMMOps.push_back(ALVal);
1862
1863         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1864                                FuncInfo->getRegSaveFrameIndex()));
1865         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1866                                FuncInfo->getVarArgsFPOffset()));
1867
1868         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1869           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
1870                                        X86::VR128RegisterClass);
1871           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1872           SaveXMMOps.push_back(Val);
1873         }
1874         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1875                                      MVT::Other,
1876                                      &SaveXMMOps[0], SaveXMMOps.size()));
1877       }
1878
1879       if (!MemOps.empty())
1880         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1881                             &MemOps[0], MemOps.size());
1882     }
1883   }
1884
1885   // Some CCs need callee pop.
1886   if (Subtarget->IsCalleePop(isVarArg, CallConv)) {
1887     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1888   } else {
1889     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1890     // If this is an sret function, the return should pop the hidden pointer.
1891     if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1892       FuncInfo->setBytesToPopOnReturn(4);
1893   }
1894
1895   if (!Is64Bit) {
1896     // RegSaveFrameIndex is X86-64 only.
1897     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1898     if (CallConv == CallingConv::X86_FastCall ||
1899         CallConv == CallingConv::X86_ThisCall)
1900       // fastcc functions can't have varargs.
1901       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1902   }
1903
1904   return Chain;
1905 }
1906
1907 SDValue
1908 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1909                                     SDValue StackPtr, SDValue Arg,
1910                                     DebugLoc dl, SelectionDAG &DAG,
1911                                     const CCValAssign &VA,
1912                                     ISD::ArgFlagsTy Flags) const {
1913   unsigned LocMemOffset = VA.getLocMemOffset();
1914   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1915   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1916   if (Flags.isByVal())
1917     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1918
1919   return DAG.getStore(Chain, dl, Arg, PtrOff,
1920                       MachinePointerInfo::getStack(LocMemOffset),
1921                       false, false, 0);
1922 }
1923
1924 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1925 /// optimization is performed and it is required.
1926 SDValue
1927 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1928                                            SDValue &OutRetAddr, SDValue Chain,
1929                                            bool IsTailCall, bool Is64Bit,
1930                                            int FPDiff, DebugLoc dl) const {
1931   // Adjust the Return address stack slot.
1932   EVT VT = getPointerTy();
1933   OutRetAddr = getReturnAddressFrameIndex(DAG);
1934
1935   // Load the "old" Return address.
1936   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
1937                            false, false, 0);
1938   return SDValue(OutRetAddr.getNode(), 1);
1939 }
1940
1941 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1942 /// optimization is performed and it is required (FPDiff!=0).
1943 static SDValue
1944 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1945                          SDValue Chain, SDValue RetAddrFrIdx,
1946                          bool Is64Bit, int FPDiff, DebugLoc dl) {
1947   // Store the return address to the appropriate stack slot.
1948   if (!FPDiff) return Chain;
1949   // Calculate the new stack slot for the return address.
1950   int SlotSize = Is64Bit ? 8 : 4;
1951   int NewReturnAddrFI =
1952     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
1953   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1954   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1955   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1956                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
1957                        false, false, 0);
1958   return Chain;
1959 }
1960
1961 SDValue
1962 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1963                              CallingConv::ID CallConv, bool isVarArg,
1964                              bool &isTailCall,
1965                              const SmallVectorImpl<ISD::OutputArg> &Outs,
1966                              const SmallVectorImpl<SDValue> &OutVals,
1967                              const SmallVectorImpl<ISD::InputArg> &Ins,
1968                              DebugLoc dl, SelectionDAG &DAG,
1969                              SmallVectorImpl<SDValue> &InVals) const {
1970   MachineFunction &MF = DAG.getMachineFunction();
1971   bool Is64Bit        = Subtarget->is64Bit();
1972   bool IsWin64        = Subtarget->isTargetWin64();
1973   bool IsStructRet    = CallIsStructReturn(Outs);
1974   bool IsSibcall      = false;
1975
1976   if (isTailCall) {
1977     // Check if it's really possible to do a tail call.
1978     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1979                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1980                                                    Outs, OutVals, Ins, DAG);
1981
1982     // Sibcalls are automatically detected tailcalls which do not require
1983     // ABI changes.
1984     if (!GuaranteedTailCallOpt && isTailCall)
1985       IsSibcall = true;
1986
1987     if (isTailCall)
1988       ++NumTailCalls;
1989   }
1990
1991   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1992          "Var args not supported with calling convention fastcc or ghc");
1993
1994   // Analyze operands of the call, assigning locations to each operand.
1995   SmallVector<CCValAssign, 16> ArgLocs;
1996   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1997                  ArgLocs, *DAG.getContext());
1998
1999   // Allocate shadow area for Win64
2000   if (IsWin64) {
2001     CCInfo.AllocateStack(32, 8);
2002   }
2003
2004   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2005
2006   // Get a count of how many bytes are to be pushed on the stack.
2007   unsigned NumBytes = CCInfo.getNextStackOffset();
2008   if (IsSibcall)
2009     // This is a sibcall. The memory operands are available in caller's
2010     // own caller's stack.
2011     NumBytes = 0;
2012   else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
2013     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2014
2015   int FPDiff = 0;
2016   if (isTailCall && !IsSibcall) {
2017     // Lower arguments at fp - stackoffset + fpdiff.
2018     unsigned NumBytesCallerPushed =
2019       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2020     FPDiff = NumBytesCallerPushed - NumBytes;
2021
2022     // Set the delta of movement of the returnaddr stackslot.
2023     // But only set if delta is greater than previous delta.
2024     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2025       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2026   }
2027
2028   if (!IsSibcall)
2029     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2030
2031   SDValue RetAddrFrIdx;
2032   // Load return adress for tail calls.
2033   if (isTailCall && FPDiff)
2034     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2035                                     Is64Bit, FPDiff, dl);
2036
2037   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2038   SmallVector<SDValue, 8> MemOpChains;
2039   SDValue StackPtr;
2040
2041   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2042   // of tail call optimization arguments are handle later.
2043   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2044     CCValAssign &VA = ArgLocs[i];
2045     EVT RegVT = VA.getLocVT();
2046     SDValue Arg = OutVals[i];
2047     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2048     bool isByVal = Flags.isByVal();
2049
2050     // Promote the value if needed.
2051     switch (VA.getLocInfo()) {
2052     default: llvm_unreachable("Unknown loc info!");
2053     case CCValAssign::Full: break;
2054     case CCValAssign::SExt:
2055       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2056       break;
2057     case CCValAssign::ZExt:
2058       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2059       break;
2060     case CCValAssign::AExt:
2061       if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2062         // Special case: passing MMX values in XMM registers.
2063         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2064         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2065         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2066       } else
2067         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2068       break;
2069     case CCValAssign::BCvt:
2070       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2071       break;
2072     case CCValAssign::Indirect: {
2073       // Store the argument.
2074       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2075       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2076       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2077                            MachinePointerInfo::getFixedStack(FI),
2078                            false, false, 0);
2079       Arg = SpillSlot;
2080       break;
2081     }
2082     }
2083
2084     if (VA.isRegLoc()) {
2085       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2086       if (isVarArg && IsWin64) {
2087         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2088         // shadow reg if callee is a varargs function.
2089         unsigned ShadowReg = 0;
2090         switch (VA.getLocReg()) {
2091         case X86::XMM0: ShadowReg = X86::RCX; break;
2092         case X86::XMM1: ShadowReg = X86::RDX; break;
2093         case X86::XMM2: ShadowReg = X86::R8; break;
2094         case X86::XMM3: ShadowReg = X86::R9; break;
2095         }
2096         if (ShadowReg)
2097           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2098       }
2099     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2100       assert(VA.isMemLoc());
2101       if (StackPtr.getNode() == 0)
2102         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2103       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2104                                              dl, DAG, VA, Flags));
2105     }
2106   }
2107
2108   if (!MemOpChains.empty())
2109     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2110                         &MemOpChains[0], MemOpChains.size());
2111
2112   // Build a sequence of copy-to-reg nodes chained together with token chain
2113   // and flag operands which copy the outgoing args into registers.
2114   SDValue InFlag;
2115   // Tail call byval lowering might overwrite argument registers so in case of
2116   // tail call optimization the copies to registers are lowered later.
2117   if (!isTailCall)
2118     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2119       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2120                                RegsToPass[i].second, InFlag);
2121       InFlag = Chain.getValue(1);
2122     }
2123
2124   if (Subtarget->isPICStyleGOT()) {
2125     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2126     // GOT pointer.
2127     if (!isTailCall) {
2128       Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2129                                DAG.getNode(X86ISD::GlobalBaseReg,
2130                                            DebugLoc(), getPointerTy()),
2131                                InFlag);
2132       InFlag = Chain.getValue(1);
2133     } else {
2134       // If we are tail calling and generating PIC/GOT style code load the
2135       // address of the callee into ECX. The value in ecx is used as target of
2136       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2137       // for tail calls on PIC/GOT architectures. Normally we would just put the
2138       // address of GOT into ebx and then call target@PLT. But for tail calls
2139       // ebx would be restored (since ebx is callee saved) before jumping to the
2140       // target@PLT.
2141
2142       // Note: The actual moving to ECX is done further down.
2143       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2144       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2145           !G->getGlobal()->hasProtectedVisibility())
2146         Callee = LowerGlobalAddress(Callee, DAG);
2147       else if (isa<ExternalSymbolSDNode>(Callee))
2148         Callee = LowerExternalSymbol(Callee, DAG);
2149     }
2150   }
2151
2152   if (Is64Bit && isVarArg && !IsWin64) {
2153     // From AMD64 ABI document:
2154     // For calls that may call functions that use varargs or stdargs
2155     // (prototype-less calls or calls to functions containing ellipsis (...) in
2156     // the declaration) %al is used as hidden argument to specify the number
2157     // of SSE registers used. The contents of %al do not need to match exactly
2158     // the number of registers, but must be an ubound on the number of SSE
2159     // registers used and is in the range 0 - 8 inclusive.
2160
2161     // Count the number of XMM registers allocated.
2162     static const unsigned XMMArgRegs[] = {
2163       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2164       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2165     };
2166     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2167     assert((Subtarget->hasXMM() || !NumXMMRegs)
2168            && "SSE registers cannot be used when SSE is disabled");
2169
2170     Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2171                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2172     InFlag = Chain.getValue(1);
2173   }
2174
2175
2176   // For tail calls lower the arguments to the 'real' stack slot.
2177   if (isTailCall) {
2178     // Force all the incoming stack arguments to be loaded from the stack
2179     // before any new outgoing arguments are stored to the stack, because the
2180     // outgoing stack slots may alias the incoming argument stack slots, and
2181     // the alias isn't otherwise explicit. This is slightly more conservative
2182     // than necessary, because it means that each store effectively depends
2183     // on every argument instead of just those arguments it would clobber.
2184     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2185
2186     SmallVector<SDValue, 8> MemOpChains2;
2187     SDValue FIN;
2188     int FI = 0;
2189     // Do not flag preceeding copytoreg stuff together with the following stuff.
2190     InFlag = SDValue();
2191     if (GuaranteedTailCallOpt) {
2192       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2193         CCValAssign &VA = ArgLocs[i];
2194         if (VA.isRegLoc())
2195           continue;
2196         assert(VA.isMemLoc());
2197         SDValue Arg = OutVals[i];
2198         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2199         // Create frame index.
2200         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2201         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2202         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2203         FIN = DAG.getFrameIndex(FI, getPointerTy());
2204
2205         if (Flags.isByVal()) {
2206           // Copy relative to framepointer.
2207           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2208           if (StackPtr.getNode() == 0)
2209             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2210                                           getPointerTy());
2211           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2212
2213           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2214                                                            ArgChain,
2215                                                            Flags, DAG, dl));
2216         } else {
2217           // Store relative to framepointer.
2218           MemOpChains2.push_back(
2219             DAG.getStore(ArgChain, dl, Arg, FIN,
2220                          MachinePointerInfo::getFixedStack(FI),
2221                          false, false, 0));
2222         }
2223       }
2224     }
2225
2226     if (!MemOpChains2.empty())
2227       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2228                           &MemOpChains2[0], MemOpChains2.size());
2229
2230     // Copy arguments to their registers.
2231     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2232       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2233                                RegsToPass[i].second, InFlag);
2234       InFlag = Chain.getValue(1);
2235     }
2236     InFlag =SDValue();
2237
2238     // Store the return address to the appropriate stack slot.
2239     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2240                                      FPDiff, dl);
2241   }
2242
2243   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2244     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2245     // In the 64-bit large code model, we have to make all calls
2246     // through a register, since the call instruction's 32-bit
2247     // pc-relative offset may not be large enough to hold the whole
2248     // address.
2249   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2250     // If the callee is a GlobalAddress node (quite common, every direct call
2251     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2252     // it.
2253
2254     // We should use extra load for direct calls to dllimported functions in
2255     // non-JIT mode.
2256     const GlobalValue *GV = G->getGlobal();
2257     if (!GV->hasDLLImportLinkage()) {
2258       unsigned char OpFlags = 0;
2259
2260       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2261       // external symbols most go through the PLT in PIC mode.  If the symbol
2262       // has hidden or protected visibility, or if it is static or local, then
2263       // we don't need to use the PLT - we can directly call it.
2264       if (Subtarget->isTargetELF() &&
2265           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2266           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2267         OpFlags = X86II::MO_PLT;
2268       } else if (Subtarget->isPICStyleStubAny() &&
2269                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2270                  Subtarget->getDarwinVers() < 9) {
2271         // PC-relative references to external symbols should go through $stub,
2272         // unless we're building with the leopard linker or later, which
2273         // automatically synthesizes these stubs.
2274         OpFlags = X86II::MO_DARWIN_STUB;
2275       }
2276
2277       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2278                                           G->getOffset(), OpFlags);
2279     }
2280   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2281     unsigned char OpFlags = 0;
2282
2283     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2284     // external symbols should go through the PLT.
2285     if (Subtarget->isTargetELF() &&
2286         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2287       OpFlags = X86II::MO_PLT;
2288     } else if (Subtarget->isPICStyleStubAny() &&
2289                Subtarget->getDarwinVers() < 9) {
2290       // PC-relative references to external symbols should go through $stub,
2291       // unless we're building with the leopard linker or later, which
2292       // automatically synthesizes these stubs.
2293       OpFlags = X86II::MO_DARWIN_STUB;
2294     }
2295
2296     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2297                                          OpFlags);
2298   }
2299
2300   // Returns a chain & a flag for retval copy to use.
2301   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2302   SmallVector<SDValue, 8> Ops;
2303
2304   if (!IsSibcall && isTailCall) {
2305     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2306                            DAG.getIntPtrConstant(0, true), InFlag);
2307     InFlag = Chain.getValue(1);
2308   }
2309
2310   Ops.push_back(Chain);
2311   Ops.push_back(Callee);
2312
2313   if (isTailCall)
2314     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2315
2316   // Add argument registers to the end of the list so that they are known live
2317   // into the call.
2318   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2319     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2320                                   RegsToPass[i].second.getValueType()));
2321
2322   // Add an implicit use GOT pointer in EBX.
2323   if (!isTailCall && Subtarget->isPICStyleGOT())
2324     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2325
2326   // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2327   if (Is64Bit && isVarArg && !IsWin64)
2328     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2329
2330   if (InFlag.getNode())
2331     Ops.push_back(InFlag);
2332
2333   if (isTailCall) {
2334     // We used to do:
2335     //// If this is the first return lowered for this function, add the regs
2336     //// to the liveout set for the function.
2337     // This isn't right, although it's probably harmless on x86; liveouts
2338     // should be computed from returns not tail calls.  Consider a void
2339     // function making a tail call to a function returning int.
2340     return DAG.getNode(X86ISD::TC_RETURN, dl,
2341                        NodeTys, &Ops[0], Ops.size());
2342   }
2343
2344   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2345   InFlag = Chain.getValue(1);
2346
2347   // Create the CALLSEQ_END node.
2348   unsigned NumBytesForCalleeToPush;
2349   if (Subtarget->IsCalleePop(isVarArg, CallConv))
2350     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2351   else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2352     // If this is a call to a struct-return function, the callee
2353     // pops the hidden struct pointer, so we have to push it back.
2354     // This is common for Darwin/X86, Linux & Mingw32 targets.
2355     NumBytesForCalleeToPush = 4;
2356   else
2357     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2358
2359   // Returns a flag for retval copy to use.
2360   if (!IsSibcall) {
2361     Chain = DAG.getCALLSEQ_END(Chain,
2362                                DAG.getIntPtrConstant(NumBytes, true),
2363                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2364                                                      true),
2365                                InFlag);
2366     InFlag = Chain.getValue(1);
2367   }
2368
2369   // Handle result values, copying them out of physregs into vregs that we
2370   // return.
2371   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2372                          Ins, dl, DAG, InVals);
2373 }
2374
2375
2376 //===----------------------------------------------------------------------===//
2377 //                Fast Calling Convention (tail call) implementation
2378 //===----------------------------------------------------------------------===//
2379
2380 //  Like std call, callee cleans arguments, convention except that ECX is
2381 //  reserved for storing the tail called function address. Only 2 registers are
2382 //  free for argument passing (inreg). Tail call optimization is performed
2383 //  provided:
2384 //                * tailcallopt is enabled
2385 //                * caller/callee are fastcc
2386 //  On X86_64 architecture with GOT-style position independent code only local
2387 //  (within module) calls are supported at the moment.
2388 //  To keep the stack aligned according to platform abi the function
2389 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2390 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2391 //  If a tail called function callee has more arguments than the caller the
2392 //  caller needs to make sure that there is room to move the RETADDR to. This is
2393 //  achieved by reserving an area the size of the argument delta right after the
2394 //  original REtADDR, but before the saved framepointer or the spilled registers
2395 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2396 //  stack layout:
2397 //    arg1
2398 //    arg2
2399 //    RETADDR
2400 //    [ new RETADDR
2401 //      move area ]
2402 //    (possible EBP)
2403 //    ESI
2404 //    EDI
2405 //    local1 ..
2406
2407 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2408 /// for a 16 byte align requirement.
2409 unsigned
2410 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2411                                                SelectionDAG& DAG) const {
2412   MachineFunction &MF = DAG.getMachineFunction();
2413   const TargetMachine &TM = MF.getTarget();
2414   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2415   unsigned StackAlignment = TFI.getStackAlignment();
2416   uint64_t AlignMask = StackAlignment - 1;
2417   int64_t Offset = StackSize;
2418   uint64_t SlotSize = TD->getPointerSize();
2419   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2420     // Number smaller than 12 so just add the difference.
2421     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2422   } else {
2423     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2424     Offset = ((~AlignMask) & Offset) + StackAlignment +
2425       (StackAlignment-SlotSize);
2426   }
2427   return Offset;
2428 }
2429
2430 /// MatchingStackOffset - Return true if the given stack call argument is
2431 /// already available in the same position (relatively) of the caller's
2432 /// incoming argument stack.
2433 static
2434 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2435                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2436                          const X86InstrInfo *TII) {
2437   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2438   int FI = INT_MAX;
2439   if (Arg.getOpcode() == ISD::CopyFromReg) {
2440     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2441     if (!TargetRegisterInfo::isVirtualRegister(VR))
2442       return false;
2443     MachineInstr *Def = MRI->getVRegDef(VR);
2444     if (!Def)
2445       return false;
2446     if (!Flags.isByVal()) {
2447       if (!TII->isLoadFromStackSlot(Def, FI))
2448         return false;
2449     } else {
2450       unsigned Opcode = Def->getOpcode();
2451       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2452           Def->getOperand(1).isFI()) {
2453         FI = Def->getOperand(1).getIndex();
2454         Bytes = Flags.getByValSize();
2455       } else
2456         return false;
2457     }
2458   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2459     if (Flags.isByVal())
2460       // ByVal argument is passed in as a pointer but it's now being
2461       // dereferenced. e.g.
2462       // define @foo(%struct.X* %A) {
2463       //   tail call @bar(%struct.X* byval %A)
2464       // }
2465       return false;
2466     SDValue Ptr = Ld->getBasePtr();
2467     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2468     if (!FINode)
2469       return false;
2470     FI = FINode->getIndex();
2471   } else
2472     return false;
2473
2474   assert(FI != INT_MAX);
2475   if (!MFI->isFixedObjectIndex(FI))
2476     return false;
2477   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2478 }
2479
2480 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2481 /// for tail call optimization. Targets which want to do tail call
2482 /// optimization should implement this function.
2483 bool
2484 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2485                                                      CallingConv::ID CalleeCC,
2486                                                      bool isVarArg,
2487                                                      bool isCalleeStructRet,
2488                                                      bool isCallerStructRet,
2489                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2490                                     const SmallVectorImpl<SDValue> &OutVals,
2491                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2492                                                      SelectionDAG& DAG) const {
2493   if (!IsTailCallConvention(CalleeCC) &&
2494       CalleeCC != CallingConv::C)
2495     return false;
2496
2497   // If -tailcallopt is specified, make fastcc functions tail-callable.
2498   const MachineFunction &MF = DAG.getMachineFunction();
2499   const Function *CallerF = DAG.getMachineFunction().getFunction();
2500   CallingConv::ID CallerCC = CallerF->getCallingConv();
2501   bool CCMatch = CallerCC == CalleeCC;
2502
2503   if (GuaranteedTailCallOpt) {
2504     if (IsTailCallConvention(CalleeCC) && CCMatch)
2505       return true;
2506     return false;
2507   }
2508
2509   // Look for obvious safe cases to perform tail call optimization that do not
2510   // require ABI changes. This is what gcc calls sibcall.
2511
2512   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2513   // emit a special epilogue.
2514   if (RegInfo->needsStackRealignment(MF))
2515     return false;
2516
2517   // Do not sibcall optimize vararg calls unless the call site is not passing
2518   // any arguments.
2519   if (isVarArg && !Outs.empty())
2520     return false;
2521
2522   // Also avoid sibcall optimization if either caller or callee uses struct
2523   // return semantics.
2524   if (isCalleeStructRet || isCallerStructRet)
2525     return false;
2526
2527   // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2528   // Therefore if it's not used by the call it is not safe to optimize this into
2529   // a sibcall.
2530   bool Unused = false;
2531   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2532     if (!Ins[i].Used) {
2533       Unused = true;
2534       break;
2535     }
2536   }
2537   if (Unused) {
2538     SmallVector<CCValAssign, 16> RVLocs;
2539     CCState CCInfo(CalleeCC, false, getTargetMachine(),
2540                    RVLocs, *DAG.getContext());
2541     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2542     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2543       CCValAssign &VA = RVLocs[i];
2544       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2545         return false;
2546     }
2547   }
2548
2549   // If the calling conventions do not match, then we'd better make sure the
2550   // results are returned in the same way as what the caller expects.
2551   if (!CCMatch) {
2552     SmallVector<CCValAssign, 16> RVLocs1;
2553     CCState CCInfo1(CalleeCC, false, getTargetMachine(),
2554                     RVLocs1, *DAG.getContext());
2555     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2556
2557     SmallVector<CCValAssign, 16> RVLocs2;
2558     CCState CCInfo2(CallerCC, false, getTargetMachine(),
2559                     RVLocs2, *DAG.getContext());
2560     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2561
2562     if (RVLocs1.size() != RVLocs2.size())
2563       return false;
2564     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2565       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2566         return false;
2567       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2568         return false;
2569       if (RVLocs1[i].isRegLoc()) {
2570         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2571           return false;
2572       } else {
2573         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2574           return false;
2575       }
2576     }
2577   }
2578
2579   // If the callee takes no arguments then go on to check the results of the
2580   // call.
2581   if (!Outs.empty()) {
2582     // Check if stack adjustment is needed. For now, do not do this if any
2583     // argument is passed on the stack.
2584     SmallVector<CCValAssign, 16> ArgLocs;
2585     CCState CCInfo(CalleeCC, isVarArg, getTargetMachine(),
2586                    ArgLocs, *DAG.getContext());
2587
2588     // Allocate shadow area for Win64
2589     if (Subtarget->isTargetWin64()) {
2590       CCInfo.AllocateStack(32, 8);
2591     }
2592
2593     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2594     if (CCInfo.getNextStackOffset()) {
2595       MachineFunction &MF = DAG.getMachineFunction();
2596       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2597         return false;
2598
2599       // Check if the arguments are already laid out in the right way as
2600       // the caller's fixed stack objects.
2601       MachineFrameInfo *MFI = MF.getFrameInfo();
2602       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2603       const X86InstrInfo *TII =
2604         ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2605       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2606         CCValAssign &VA = ArgLocs[i];
2607         SDValue Arg = OutVals[i];
2608         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2609         if (VA.getLocInfo() == CCValAssign::Indirect)
2610           return false;
2611         if (!VA.isRegLoc()) {
2612           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2613                                    MFI, MRI, TII))
2614             return false;
2615         }
2616       }
2617     }
2618
2619     // If the tailcall address may be in a register, then make sure it's
2620     // possible to register allocate for it. In 32-bit, the call address can
2621     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2622     // callee-saved registers are restored. These happen to be the same
2623     // registers used to pass 'inreg' arguments so watch out for those.
2624     if (!Subtarget->is64Bit() &&
2625         !isa<GlobalAddressSDNode>(Callee) &&
2626         !isa<ExternalSymbolSDNode>(Callee)) {
2627       unsigned NumInRegs = 0;
2628       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2629         CCValAssign &VA = ArgLocs[i];
2630         if (!VA.isRegLoc())
2631           continue;
2632         unsigned Reg = VA.getLocReg();
2633         switch (Reg) {
2634         default: break;
2635         case X86::EAX: case X86::EDX: case X86::ECX:
2636           if (++NumInRegs == 3)
2637             return false;
2638           break;
2639         }
2640       }
2641     }
2642   }
2643
2644   // An stdcall caller is expected to clean up its arguments; the callee
2645   // isn't going to do that.
2646   if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2647     return false;
2648
2649   return true;
2650 }
2651
2652 FastISel *
2653 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2654   return X86::createFastISel(funcInfo);
2655 }
2656
2657
2658 //===----------------------------------------------------------------------===//
2659 //                           Other Lowering Hooks
2660 //===----------------------------------------------------------------------===//
2661
2662 static bool MayFoldLoad(SDValue Op) {
2663   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2664 }
2665
2666 static bool MayFoldIntoStore(SDValue Op) {
2667   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2668 }
2669
2670 static bool isTargetShuffle(unsigned Opcode) {
2671   switch(Opcode) {
2672   default: return false;
2673   case X86ISD::PSHUFD:
2674   case X86ISD::PSHUFHW:
2675   case X86ISD::PSHUFLW:
2676   case X86ISD::SHUFPD:
2677   case X86ISD::PALIGN:
2678   case X86ISD::SHUFPS:
2679   case X86ISD::MOVLHPS:
2680   case X86ISD::MOVLHPD:
2681   case X86ISD::MOVHLPS:
2682   case X86ISD::MOVLPS:
2683   case X86ISD::MOVLPD:
2684   case X86ISD::MOVSHDUP:
2685   case X86ISD::MOVSLDUP:
2686   case X86ISD::MOVDDUP:
2687   case X86ISD::MOVSS:
2688   case X86ISD::MOVSD:
2689   case X86ISD::UNPCKLPS:
2690   case X86ISD::UNPCKLPD:
2691   case X86ISD::VUNPCKLPS:
2692   case X86ISD::VUNPCKLPD:
2693   case X86ISD::VUNPCKLPSY:
2694   case X86ISD::VUNPCKLPDY:
2695   case X86ISD::PUNPCKLWD:
2696   case X86ISD::PUNPCKLBW:
2697   case X86ISD::PUNPCKLDQ:
2698   case X86ISD::PUNPCKLQDQ:
2699   case X86ISD::UNPCKHPS:
2700   case X86ISD::UNPCKHPD:
2701   case X86ISD::PUNPCKHWD:
2702   case X86ISD::PUNPCKHBW:
2703   case X86ISD::PUNPCKHDQ:
2704   case X86ISD::PUNPCKHQDQ:
2705     return true;
2706   }
2707   return false;
2708 }
2709
2710 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2711                                                SDValue V1, SelectionDAG &DAG) {
2712   switch(Opc) {
2713   default: llvm_unreachable("Unknown x86 shuffle node");
2714   case X86ISD::MOVSHDUP:
2715   case X86ISD::MOVSLDUP:
2716   case X86ISD::MOVDDUP:
2717     return DAG.getNode(Opc, dl, VT, V1);
2718   }
2719
2720   return SDValue();
2721 }
2722
2723 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2724                           SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2725   switch(Opc) {
2726   default: llvm_unreachable("Unknown x86 shuffle node");
2727   case X86ISD::PSHUFD:
2728   case X86ISD::PSHUFHW:
2729   case X86ISD::PSHUFLW:
2730     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2731   }
2732
2733   return SDValue();
2734 }
2735
2736 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2737                SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2738   switch(Opc) {
2739   default: llvm_unreachable("Unknown x86 shuffle node");
2740   case X86ISD::PALIGN:
2741   case X86ISD::SHUFPD:
2742   case X86ISD::SHUFPS:
2743     return DAG.getNode(Opc, dl, VT, V1, V2,
2744                        DAG.getConstant(TargetMask, MVT::i8));
2745   }
2746   return SDValue();
2747 }
2748
2749 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2750                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
2751   switch(Opc) {
2752   default: llvm_unreachable("Unknown x86 shuffle node");
2753   case X86ISD::MOVLHPS:
2754   case X86ISD::MOVLHPD:
2755   case X86ISD::MOVHLPS:
2756   case X86ISD::MOVLPS:
2757   case X86ISD::MOVLPD:
2758   case X86ISD::MOVSS:
2759   case X86ISD::MOVSD:
2760   case X86ISD::UNPCKLPS:
2761   case X86ISD::UNPCKLPD:
2762   case X86ISD::VUNPCKLPS:
2763   case X86ISD::VUNPCKLPD:
2764   case X86ISD::VUNPCKLPSY:
2765   case X86ISD::VUNPCKLPDY:
2766   case X86ISD::PUNPCKLWD:
2767   case X86ISD::PUNPCKLBW:
2768   case X86ISD::PUNPCKLDQ:
2769   case X86ISD::PUNPCKLQDQ:
2770   case X86ISD::UNPCKHPS:
2771   case X86ISD::UNPCKHPD:
2772   case X86ISD::PUNPCKHWD:
2773   case X86ISD::PUNPCKHBW:
2774   case X86ISD::PUNPCKHDQ:
2775   case X86ISD::PUNPCKHQDQ:
2776     return DAG.getNode(Opc, dl, VT, V1, V2);
2777   }
2778   return SDValue();
2779 }
2780
2781 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2782   MachineFunction &MF = DAG.getMachineFunction();
2783   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2784   int ReturnAddrIndex = FuncInfo->getRAIndex();
2785
2786   if (ReturnAddrIndex == 0) {
2787     // Set up a frame object for the return address.
2788     uint64_t SlotSize = TD->getPointerSize();
2789     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2790                                                            false);
2791     FuncInfo->setRAIndex(ReturnAddrIndex);
2792   }
2793
2794   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2795 }
2796
2797
2798 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2799                                        bool hasSymbolicDisplacement) {
2800   // Offset should fit into 32 bit immediate field.
2801   if (!isInt<32>(Offset))
2802     return false;
2803
2804   // If we don't have a symbolic displacement - we don't have any extra
2805   // restrictions.
2806   if (!hasSymbolicDisplacement)
2807     return true;
2808
2809   // FIXME: Some tweaks might be needed for medium code model.
2810   if (M != CodeModel::Small && M != CodeModel::Kernel)
2811     return false;
2812
2813   // For small code model we assume that latest object is 16MB before end of 31
2814   // bits boundary. We may also accept pretty large negative constants knowing
2815   // that all objects are in the positive half of address space.
2816   if (M == CodeModel::Small && Offset < 16*1024*1024)
2817     return true;
2818
2819   // For kernel code model we know that all object resist in the negative half
2820   // of 32bits address space. We may not accept negative offsets, since they may
2821   // be just off and we may accept pretty large positive ones.
2822   if (M == CodeModel::Kernel && Offset > 0)
2823     return true;
2824
2825   return false;
2826 }
2827
2828 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2829 /// specific condition code, returning the condition code and the LHS/RHS of the
2830 /// comparison to make.
2831 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2832                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2833   if (!isFP) {
2834     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2835       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2836         // X > -1   -> X == 0, jump !sign.
2837         RHS = DAG.getConstant(0, RHS.getValueType());
2838         return X86::COND_NS;
2839       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2840         // X < 0   -> X == 0, jump on sign.
2841         return X86::COND_S;
2842       } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2843         // X < 1   -> X <= 0
2844         RHS = DAG.getConstant(0, RHS.getValueType());
2845         return X86::COND_LE;
2846       }
2847     }
2848
2849     switch (SetCCOpcode) {
2850     default: llvm_unreachable("Invalid integer condition!");
2851     case ISD::SETEQ:  return X86::COND_E;
2852     case ISD::SETGT:  return X86::COND_G;
2853     case ISD::SETGE:  return X86::COND_GE;
2854     case ISD::SETLT:  return X86::COND_L;
2855     case ISD::SETLE:  return X86::COND_LE;
2856     case ISD::SETNE:  return X86::COND_NE;
2857     case ISD::SETULT: return X86::COND_B;
2858     case ISD::SETUGT: return X86::COND_A;
2859     case ISD::SETULE: return X86::COND_BE;
2860     case ISD::SETUGE: return X86::COND_AE;
2861     }
2862   }
2863
2864   // First determine if it is required or is profitable to flip the operands.
2865
2866   // If LHS is a foldable load, but RHS is not, flip the condition.
2867   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
2868       !ISD::isNON_EXTLoad(RHS.getNode())) {
2869     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2870     std::swap(LHS, RHS);
2871   }
2872
2873   switch (SetCCOpcode) {
2874   default: break;
2875   case ISD::SETOLT:
2876   case ISD::SETOLE:
2877   case ISD::SETUGT:
2878   case ISD::SETUGE:
2879     std::swap(LHS, RHS);
2880     break;
2881   }
2882
2883   // On a floating point condition, the flags are set as follows:
2884   // ZF  PF  CF   op
2885   //  0 | 0 | 0 | X > Y
2886   //  0 | 0 | 1 | X < Y
2887   //  1 | 0 | 0 | X == Y
2888   //  1 | 1 | 1 | unordered
2889   switch (SetCCOpcode) {
2890   default: llvm_unreachable("Condcode should be pre-legalized away");
2891   case ISD::SETUEQ:
2892   case ISD::SETEQ:   return X86::COND_E;
2893   case ISD::SETOLT:              // flipped
2894   case ISD::SETOGT:
2895   case ISD::SETGT:   return X86::COND_A;
2896   case ISD::SETOLE:              // flipped
2897   case ISD::SETOGE:
2898   case ISD::SETGE:   return X86::COND_AE;
2899   case ISD::SETUGT:              // flipped
2900   case ISD::SETULT:
2901   case ISD::SETLT:   return X86::COND_B;
2902   case ISD::SETUGE:              // flipped
2903   case ISD::SETULE:
2904   case ISD::SETLE:   return X86::COND_BE;
2905   case ISD::SETONE:
2906   case ISD::SETNE:   return X86::COND_NE;
2907   case ISD::SETUO:   return X86::COND_P;
2908   case ISD::SETO:    return X86::COND_NP;
2909   case ISD::SETOEQ:
2910   case ISD::SETUNE:  return X86::COND_INVALID;
2911   }
2912 }
2913
2914 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2915 /// code. Current x86 isa includes the following FP cmov instructions:
2916 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2917 static bool hasFPCMov(unsigned X86CC) {
2918   switch (X86CC) {
2919   default:
2920     return false;
2921   case X86::COND_B:
2922   case X86::COND_BE:
2923   case X86::COND_E:
2924   case X86::COND_P:
2925   case X86::COND_A:
2926   case X86::COND_AE:
2927   case X86::COND_NE:
2928   case X86::COND_NP:
2929     return true;
2930   }
2931 }
2932
2933 /// isFPImmLegal - Returns true if the target can instruction select the
2934 /// specified FP immediate natively. If false, the legalizer will
2935 /// materialize the FP immediate as a load from a constant pool.
2936 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2937   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
2938     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
2939       return true;
2940   }
2941   return false;
2942 }
2943
2944 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2945 /// the specified range (L, H].
2946 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2947   return (Val < 0) || (Val >= Low && Val < Hi);
2948 }
2949
2950 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2951 /// specified value.
2952 static bool isUndefOrEqual(int Val, int CmpVal) {
2953   if (Val < 0 || Val == CmpVal)
2954     return true;
2955   return false;
2956 }
2957
2958 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2959 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
2960 /// the second operand.
2961 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2962   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
2963     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2964   if (VT == MVT::v2f64 || VT == MVT::v2i64)
2965     return (Mask[0] < 2 && Mask[1] < 2);
2966   return false;
2967 }
2968
2969 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2970   SmallVector<int, 8> M;
2971   N->getMask(M);
2972   return ::isPSHUFDMask(M, N->getValueType(0));
2973 }
2974
2975 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2976 /// is suitable for input to PSHUFHW.
2977 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2978   if (VT != MVT::v8i16)
2979     return false;
2980
2981   // Lower quadword copied in order or undef.
2982   for (int i = 0; i != 4; ++i)
2983     if (Mask[i] >= 0 && Mask[i] != i)
2984       return false;
2985
2986   // Upper quadword shuffled.
2987   for (int i = 4; i != 8; ++i)
2988     if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2989       return false;
2990
2991   return true;
2992 }
2993
2994 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2995   SmallVector<int, 8> M;
2996   N->getMask(M);
2997   return ::isPSHUFHWMask(M, N->getValueType(0));
2998 }
2999
3000 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3001 /// is suitable for input to PSHUFLW.
3002 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3003   if (VT != MVT::v8i16)
3004     return false;
3005
3006   // Upper quadword copied in order.
3007   for (int i = 4; i != 8; ++i)
3008     if (Mask[i] >= 0 && Mask[i] != i)
3009       return false;
3010
3011   // Lower quadword shuffled.
3012   for (int i = 0; i != 4; ++i)
3013     if (Mask[i] >= 4)
3014       return false;
3015
3016   return true;
3017 }
3018
3019 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
3020   SmallVector<int, 8> M;
3021   N->getMask(M);
3022   return ::isPSHUFLWMask(M, N->getValueType(0));
3023 }
3024
3025 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3026 /// is suitable for input to PALIGNR.
3027 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
3028                           bool hasSSSE3) {
3029   int i, e = VT.getVectorNumElements();
3030
3031   // Do not handle v2i64 / v2f64 shuffles with palignr.
3032   if (e < 4 || !hasSSSE3)
3033     return false;
3034
3035   for (i = 0; i != e; ++i)
3036     if (Mask[i] >= 0)
3037       break;
3038
3039   // All undef, not a palignr.
3040   if (i == e)
3041     return false;
3042
3043   // Determine if it's ok to perform a palignr with only the LHS, since we
3044   // don't have access to the actual shuffle elements to see if RHS is undef.
3045   bool Unary = Mask[i] < (int)e;
3046   bool NeedsUnary = false;
3047
3048   int s = Mask[i] - i;
3049
3050   // Check the rest of the elements to see if they are consecutive.
3051   for (++i; i != e; ++i) {
3052     int m = Mask[i];
3053     if (m < 0)
3054       continue;
3055
3056     Unary = Unary && (m < (int)e);
3057     NeedsUnary = NeedsUnary || (m < s);
3058
3059     if (NeedsUnary && !Unary)
3060       return false;
3061     if (Unary && m != ((s+i) & (e-1)))
3062       return false;
3063     if (!Unary && m != (s+i))
3064       return false;
3065   }
3066   return true;
3067 }
3068
3069 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
3070   SmallVector<int, 8> M;
3071   N->getMask(M);
3072   return ::isPALIGNRMask(M, N->getValueType(0), true);
3073 }
3074
3075 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3076 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
3077 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3078   int NumElems = VT.getVectorNumElements();
3079   if (NumElems != 2 && NumElems != 4)
3080     return false;
3081
3082   int Half = NumElems / 2;
3083   for (int i = 0; i < Half; ++i)
3084     if (!isUndefOrInRange(Mask[i], 0, NumElems))
3085       return false;
3086   for (int i = Half; i < NumElems; ++i)
3087     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3088       return false;
3089
3090   return true;
3091 }
3092
3093 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
3094   SmallVector<int, 8> M;
3095   N->getMask(M);
3096   return ::isSHUFPMask(M, N->getValueType(0));
3097 }
3098
3099 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
3100 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
3101 /// half elements to come from vector 1 (which would equal the dest.) and
3102 /// the upper half to come from vector 2.
3103 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3104   int NumElems = VT.getVectorNumElements();
3105
3106   if (NumElems != 2 && NumElems != 4)
3107     return false;
3108
3109   int Half = NumElems / 2;
3110   for (int i = 0; i < Half; ++i)
3111     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3112       return false;
3113   for (int i = Half; i < NumElems; ++i)
3114     if (!isUndefOrInRange(Mask[i], 0, NumElems))
3115       return false;
3116   return true;
3117 }
3118
3119 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
3120   SmallVector<int, 8> M;
3121   N->getMask(M);
3122   return isCommutedSHUFPMask(M, N->getValueType(0));
3123 }
3124
3125 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3126 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3127 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3128   if (N->getValueType(0).getVectorNumElements() != 4)
3129     return false;
3130
3131   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3132   return isUndefOrEqual(N->getMaskElt(0), 6) &&
3133          isUndefOrEqual(N->getMaskElt(1), 7) &&
3134          isUndefOrEqual(N->getMaskElt(2), 2) &&
3135          isUndefOrEqual(N->getMaskElt(3), 3);
3136 }
3137
3138 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3139 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3140 /// <2, 3, 2, 3>
3141 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3142   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3143
3144   if (NumElems != 4)
3145     return false;
3146
3147   return isUndefOrEqual(N->getMaskElt(0), 2) &&
3148   isUndefOrEqual(N->getMaskElt(1), 3) &&
3149   isUndefOrEqual(N->getMaskElt(2), 2) &&
3150   isUndefOrEqual(N->getMaskElt(3), 3);
3151 }
3152
3153 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3154 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3155 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3156   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3157
3158   if (NumElems != 2 && NumElems != 4)
3159     return false;
3160
3161   for (unsigned i = 0; i < NumElems/2; ++i)
3162     if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3163       return false;
3164
3165   for (unsigned i = NumElems/2; i < NumElems; ++i)
3166     if (!isUndefOrEqual(N->getMaskElt(i), i))
3167       return false;
3168
3169   return true;
3170 }
3171
3172 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3173 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3174 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3175   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3176
3177   if ((NumElems != 2 && NumElems != 4)
3178       || N->getValueType(0).getSizeInBits() > 128)
3179     return false;
3180
3181   for (unsigned i = 0; i < NumElems/2; ++i)
3182     if (!isUndefOrEqual(N->getMaskElt(i), i))
3183       return false;
3184
3185   for (unsigned i = 0; i < NumElems/2; ++i)
3186     if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3187       return false;
3188
3189   return true;
3190 }
3191
3192 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3193 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3194 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3195                          bool V2IsSplat = false) {
3196   int NumElts = VT.getVectorNumElements();
3197   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3198     return false;
3199
3200   // Handle vector lengths > 128 bits.  Define a "section" as a set of
3201   // 128 bits.  AVX defines UNPCK* to operate independently on 128-bit
3202   // sections.
3203   unsigned NumSections = VT.getSizeInBits() / 128;
3204   if (NumSections == 0 ) NumSections = 1;  // Handle MMX
3205   unsigned NumSectionElts = NumElts / NumSections;
3206
3207   unsigned Start = 0;
3208   unsigned End = NumSectionElts;
3209   for (unsigned s = 0; s < NumSections; ++s) {
3210     for (unsigned i = Start, j = s * NumSectionElts;
3211          i != End;
3212          i += 2, ++j) {
3213       int BitI  = Mask[i];
3214       int BitI1 = Mask[i+1];
3215       if (!isUndefOrEqual(BitI, j))
3216         return false;
3217       if (V2IsSplat) {
3218         if (!isUndefOrEqual(BitI1, NumElts))
3219           return false;
3220       } else {
3221         if (!isUndefOrEqual(BitI1, j + NumElts))
3222           return false;
3223       }
3224     }
3225     // Process the next 128 bits.
3226     Start += NumSectionElts;
3227     End += NumSectionElts;
3228   }
3229
3230   return true;
3231 }
3232
3233 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3234   SmallVector<int, 8> M;
3235   N->getMask(M);
3236   return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
3237 }
3238
3239 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3240 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3241 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3242                          bool V2IsSplat = false) {
3243   int NumElts = VT.getVectorNumElements();
3244   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3245     return false;
3246
3247   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3248     int BitI  = Mask[i];
3249     int BitI1 = Mask[i+1];
3250     if (!isUndefOrEqual(BitI, j + NumElts/2))
3251       return false;
3252     if (V2IsSplat) {
3253       if (isUndefOrEqual(BitI1, NumElts))
3254         return false;
3255     } else {
3256       if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
3257         return false;
3258     }
3259   }
3260   return true;
3261 }
3262
3263 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3264   SmallVector<int, 8> M;
3265   N->getMask(M);
3266   return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
3267 }
3268
3269 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3270 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3271 /// <0, 0, 1, 1>
3272 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3273   int NumElems = VT.getVectorNumElements();
3274   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3275     return false;
3276
3277   // Handle vector lengths > 128 bits.  Define a "section" as a set of
3278   // 128 bits.  AVX defines UNPCK* to operate independently on 128-bit
3279   // sections.
3280   unsigned NumSections = VT.getSizeInBits() / 128;
3281   if (NumSections == 0 ) NumSections = 1;  // Handle MMX
3282   unsigned NumSectionElts = NumElems / NumSections;
3283
3284   for (unsigned s = 0; s < NumSections; ++s) {
3285     for (unsigned i = s * NumSectionElts, j = s * NumSectionElts;
3286          i != NumSectionElts * (s + 1);
3287          i += 2, ++j) {
3288       int BitI  = Mask[i];
3289       int BitI1 = Mask[i+1];
3290
3291       if (!isUndefOrEqual(BitI, j))
3292         return false;
3293       if (!isUndefOrEqual(BitI1, j))
3294         return false;
3295     }
3296   }
3297
3298   return true;
3299 }
3300
3301 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3302   SmallVector<int, 8> M;
3303   N->getMask(M);
3304   return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3305 }
3306
3307 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3308 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3309 /// <2, 2, 3, 3>
3310 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3311   int NumElems = VT.getVectorNumElements();
3312   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3313     return false;
3314
3315   for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3316     int BitI  = Mask[i];
3317     int BitI1 = Mask[i+1];
3318     if (!isUndefOrEqual(BitI, j))
3319       return false;
3320     if (!isUndefOrEqual(BitI1, j))
3321       return false;
3322   }
3323   return true;
3324 }
3325
3326 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3327   SmallVector<int, 8> M;
3328   N->getMask(M);
3329   return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3330 }
3331
3332 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3333 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3334 /// MOVSD, and MOVD, i.e. setting the lowest element.
3335 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3336   if (VT.getVectorElementType().getSizeInBits() < 32)
3337     return false;
3338
3339   int NumElts = VT.getVectorNumElements();
3340
3341   if (!isUndefOrEqual(Mask[0], NumElts))
3342     return false;
3343
3344   for (int i = 1; i < NumElts; ++i)
3345     if (!isUndefOrEqual(Mask[i], i))
3346       return false;
3347
3348   return true;
3349 }
3350
3351 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3352   SmallVector<int, 8> M;
3353   N->getMask(M);
3354   return ::isMOVLMask(M, N->getValueType(0));
3355 }
3356
3357 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3358 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3359 /// element of vector 2 and the other elements to come from vector 1 in order.
3360 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3361                                bool V2IsSplat = false, bool V2IsUndef = false) {
3362   int NumOps = VT.getVectorNumElements();
3363   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3364     return false;
3365
3366   if (!isUndefOrEqual(Mask[0], 0))
3367     return false;
3368
3369   for (int i = 1; i < NumOps; ++i)
3370     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3371           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3372           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3373       return false;
3374
3375   return true;
3376 }
3377
3378 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3379                            bool V2IsUndef = false) {
3380   SmallVector<int, 8> M;
3381   N->getMask(M);
3382   return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3383 }
3384
3385 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3386 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3387 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
3388   if (N->getValueType(0).getVectorNumElements() != 4)
3389     return false;
3390
3391   // Expect 1, 1, 3, 3
3392   for (unsigned i = 0; i < 2; ++i) {
3393     int Elt = N->getMaskElt(i);
3394     if (Elt >= 0 && Elt != 1)
3395       return false;
3396   }
3397
3398   bool HasHi = false;
3399   for (unsigned i = 2; i < 4; ++i) {
3400     int Elt = N->getMaskElt(i);
3401     if (Elt >= 0 && Elt != 3)
3402       return false;
3403     if (Elt == 3)
3404       HasHi = true;
3405   }
3406   // Don't use movshdup if it can be done with a shufps.
3407   // FIXME: verify that matching u, u, 3, 3 is what we want.
3408   return HasHi;
3409 }
3410
3411 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3412 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3413 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
3414   if (N->getValueType(0).getVectorNumElements() != 4)
3415     return false;
3416
3417   // Expect 0, 0, 2, 2
3418   for (unsigned i = 0; i < 2; ++i)
3419     if (N->getMaskElt(i) > 0)
3420       return false;
3421
3422   bool HasHi = false;
3423   for (unsigned i = 2; i < 4; ++i) {
3424     int Elt = N->getMaskElt(i);
3425     if (Elt >= 0 && Elt != 2)
3426       return false;
3427     if (Elt == 2)
3428       HasHi = true;
3429   }
3430   // Don't use movsldup if it can be done with a shufps.
3431   return HasHi;
3432 }
3433
3434 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3435 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3436 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3437   int e = N->getValueType(0).getVectorNumElements() / 2;
3438
3439   for (int i = 0; i < e; ++i)
3440     if (!isUndefOrEqual(N->getMaskElt(i), i))
3441       return false;
3442   for (int i = 0; i < e; ++i)
3443     if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3444       return false;
3445   return true;
3446 }
3447
3448 /// isVEXTRACTF128Index - Return true if the specified
3449 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3450 /// suitable for input to VEXTRACTF128.
3451 bool X86::isVEXTRACTF128Index(SDNode *N) {
3452   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3453     return false;
3454
3455   // The index should be aligned on a 128-bit boundary.
3456   uint64_t Index =
3457     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3458
3459   unsigned VL = N->getValueType(0).getVectorNumElements();
3460   unsigned VBits = N->getValueType(0).getSizeInBits();
3461   unsigned ElSize = VBits / VL;
3462   bool Result = (Index * ElSize) % 128 == 0;
3463
3464   return Result;
3465 }
3466
3467 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3468 /// operand specifies a subvector insert that is suitable for input to
3469 /// VINSERTF128.
3470 bool X86::isVINSERTF128Index(SDNode *N) {
3471   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3472     return false;
3473
3474   // The index should be aligned on a 128-bit boundary.
3475   uint64_t Index =
3476     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3477
3478   unsigned VL = N->getValueType(0).getVectorNumElements();
3479   unsigned VBits = N->getValueType(0).getSizeInBits();
3480   unsigned ElSize = VBits / VL;
3481   bool Result = (Index * ElSize) % 128 == 0;
3482
3483   return Result;
3484 }
3485
3486 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3487 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3488 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3489   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3490   int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3491
3492   unsigned Shift = (NumOperands == 4) ? 2 : 1;
3493   unsigned Mask = 0;
3494   for (int i = 0; i < NumOperands; ++i) {
3495     int Val = SVOp->getMaskElt(NumOperands-i-1);
3496     if (Val < 0) Val = 0;
3497     if (Val >= NumOperands) Val -= NumOperands;
3498     Mask |= Val;
3499     if (i != NumOperands - 1)
3500       Mask <<= Shift;
3501   }
3502   return Mask;
3503 }
3504
3505 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3506 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3507 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3508   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3509   unsigned Mask = 0;
3510   // 8 nodes, but we only care about the last 4.
3511   for (unsigned i = 7; i >= 4; --i) {
3512     int Val = SVOp->getMaskElt(i);
3513     if (Val >= 0)
3514       Mask |= (Val - 4);
3515     if (i != 4)
3516       Mask <<= 2;
3517   }
3518   return Mask;
3519 }
3520
3521 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3522 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3523 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3524   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3525   unsigned Mask = 0;
3526   // 8 nodes, but we only care about the first 4.
3527   for (int i = 3; i >= 0; --i) {
3528     int Val = SVOp->getMaskElt(i);
3529     if (Val >= 0)
3530       Mask |= Val;
3531     if (i != 0)
3532       Mask <<= 2;
3533   }
3534   return Mask;
3535 }
3536
3537 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3538 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3539 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3540   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3541   EVT VVT = N->getValueType(0);
3542   unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3543   int Val = 0;
3544
3545   unsigned i, e;
3546   for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3547     Val = SVOp->getMaskElt(i);
3548     if (Val >= 0)
3549       break;
3550   }
3551   return (Val - i) * EltSize;
3552 }
3553
3554 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
3555 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
3556 /// instructions.
3557 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
3558   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3559     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
3560
3561   uint64_t Index =
3562     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3563
3564   EVT VecVT = N->getOperand(0).getValueType();
3565   EVT ElVT = VecVT.getVectorElementType();
3566
3567   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3568
3569   return Index / NumElemsPerChunk;
3570 }
3571
3572 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
3573 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
3574 /// instructions.
3575 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
3576   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3577     llvm_unreachable("Illegal insert subvector for VINSERTF128");
3578
3579   uint64_t Index =
3580     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3581
3582   EVT VecVT = N->getValueType(0);
3583   EVT ElVT = VecVT.getVectorElementType();
3584
3585   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3586
3587   return Index / NumElemsPerChunk;
3588 }
3589
3590 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3591 /// constant +0.0.
3592 bool X86::isZeroNode(SDValue Elt) {
3593   return ((isa<ConstantSDNode>(Elt) &&
3594            cast<ConstantSDNode>(Elt)->isNullValue()) ||
3595           (isa<ConstantFPSDNode>(Elt) &&
3596            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3597 }
3598
3599 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3600 /// their permute mask.
3601 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3602                                     SelectionDAG &DAG) {
3603   EVT VT = SVOp->getValueType(0);
3604   unsigned NumElems = VT.getVectorNumElements();
3605   SmallVector<int, 8> MaskVec;
3606
3607   for (unsigned i = 0; i != NumElems; ++i) {
3608     int idx = SVOp->getMaskElt(i);
3609     if (idx < 0)
3610       MaskVec.push_back(idx);
3611     else if (idx < (int)NumElems)
3612       MaskVec.push_back(idx + NumElems);
3613     else
3614       MaskVec.push_back(idx - NumElems);
3615   }
3616   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3617                               SVOp->getOperand(0), &MaskVec[0]);
3618 }
3619
3620 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3621 /// the two vector operands have swapped position.
3622 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3623   unsigned NumElems = VT.getVectorNumElements();
3624   for (unsigned i = 0; i != NumElems; ++i) {
3625     int idx = Mask[i];
3626     if (idx < 0)
3627       continue;
3628     else if (idx < (int)NumElems)
3629       Mask[i] = idx + NumElems;
3630     else
3631       Mask[i] = idx - NumElems;
3632   }
3633 }
3634
3635 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3636 /// match movhlps. The lower half elements should come from upper half of
3637 /// V1 (and in order), and the upper half elements should come from the upper
3638 /// half of V2 (and in order).
3639 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3640   if (Op->getValueType(0).getVectorNumElements() != 4)
3641     return false;
3642   for (unsigned i = 0, e = 2; i != e; ++i)
3643     if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3644       return false;
3645   for (unsigned i = 2; i != 4; ++i)
3646     if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3647       return false;
3648   return true;
3649 }
3650
3651 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3652 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3653 /// required.
3654 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3655   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3656     return false;
3657   N = N->getOperand(0).getNode();
3658   if (!ISD::isNON_EXTLoad(N))
3659     return false;
3660   if (LD)
3661     *LD = cast<LoadSDNode>(N);
3662   return true;
3663 }
3664
3665 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3666 /// match movlp{s|d}. The lower half elements should come from lower half of
3667 /// V1 (and in order), and the upper half elements should come from the upper
3668 /// half of V2 (and in order). And since V1 will become the source of the
3669 /// MOVLP, it must be either a vector load or a scalar load to vector.
3670 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3671                                ShuffleVectorSDNode *Op) {
3672   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3673     return false;
3674   // Is V2 is a vector load, don't do this transformation. We will try to use
3675   // load folding shufps op.
3676   if (ISD::isNON_EXTLoad(V2))
3677     return false;
3678
3679   unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3680
3681   if (NumElems != 2 && NumElems != 4)
3682     return false;
3683   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3684     if (!isUndefOrEqual(Op->getMaskElt(i), i))
3685       return false;
3686   for (unsigned i = NumElems/2; i != NumElems; ++i)
3687     if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3688       return false;
3689   return true;
3690 }
3691
3692 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3693 /// all the same.
3694 static bool isSplatVector(SDNode *N) {
3695   if (N->getOpcode() != ISD::BUILD_VECTOR)
3696     return false;
3697
3698   SDValue SplatValue = N->getOperand(0);
3699   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3700     if (N->getOperand(i) != SplatValue)
3701       return false;
3702   return true;
3703 }
3704
3705 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3706 /// to an zero vector.
3707 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3708 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3709   SDValue V1 = N->getOperand(0);
3710   SDValue V2 = N->getOperand(1);
3711   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3712   for (unsigned i = 0; i != NumElems; ++i) {
3713     int Idx = N->getMaskElt(i);
3714     if (Idx >= (int)NumElems) {
3715       unsigned Opc = V2.getOpcode();
3716       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3717         continue;
3718       if (Opc != ISD::BUILD_VECTOR ||
3719           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3720         return false;
3721     } else if (Idx >= 0) {
3722       unsigned Opc = V1.getOpcode();
3723       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3724         continue;
3725       if (Opc != ISD::BUILD_VECTOR ||
3726           !X86::isZeroNode(V1.getOperand(Idx)))
3727         return false;
3728     }
3729   }
3730   return true;
3731 }
3732
3733 /// getZeroVector - Returns a vector of specified type with all zero elements.
3734 ///
3735 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3736                              DebugLoc dl) {
3737   assert(VT.isVector() && "Expected a vector type");
3738
3739   // Always build SSE zero vectors as <4 x i32> bitcasted
3740   // to their dest type. This ensures they get CSE'd.
3741   SDValue Vec;
3742   if (VT.getSizeInBits() == 128) {  // SSE
3743     if (HasSSE2) {  // SSE2
3744       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3745       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3746     } else { // SSE1
3747       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3748       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3749     }
3750   } else if (VT.getSizeInBits() == 256) { // AVX
3751     // 256-bit logic and arithmetic instructions in AVX are
3752     // all floating-point, no support for integer ops. Default
3753     // to emitting fp zeroed vectors then.
3754     SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3755     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3756     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
3757   }
3758   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3759 }
3760
3761 /// getOnesVector - Returns a vector of specified type with all bits set.
3762 ///
3763 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3764   assert(VT.isVector() && "Expected a vector type");
3765
3766   // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3767   // type.  This ensures they get CSE'd.
3768   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3769   SDValue Vec;
3770   Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3771   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3772 }
3773
3774
3775 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3776 /// that point to V2 points to its first element.
3777 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3778   EVT VT = SVOp->getValueType(0);
3779   unsigned NumElems = VT.getVectorNumElements();
3780
3781   bool Changed = false;
3782   SmallVector<int, 8> MaskVec;
3783   SVOp->getMask(MaskVec);
3784
3785   for (unsigned i = 0; i != NumElems; ++i) {
3786     if (MaskVec[i] > (int)NumElems) {
3787       MaskVec[i] = NumElems;
3788       Changed = true;
3789     }
3790   }
3791   if (Changed)
3792     return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3793                                 SVOp->getOperand(1), &MaskVec[0]);
3794   return SDValue(SVOp, 0);
3795 }
3796
3797 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3798 /// operation of specified width.
3799 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3800                        SDValue V2) {
3801   unsigned NumElems = VT.getVectorNumElements();
3802   SmallVector<int, 8> Mask;
3803   Mask.push_back(NumElems);
3804   for (unsigned i = 1; i != NumElems; ++i)
3805     Mask.push_back(i);
3806   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3807 }
3808
3809 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3810 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3811                           SDValue V2) {
3812   unsigned NumElems = VT.getVectorNumElements();
3813   SmallVector<int, 8> Mask;
3814   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3815     Mask.push_back(i);
3816     Mask.push_back(i + NumElems);
3817   }
3818   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3819 }
3820
3821 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3822 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3823                           SDValue V2) {
3824   unsigned NumElems = VT.getVectorNumElements();
3825   unsigned Half = NumElems/2;
3826   SmallVector<int, 8> Mask;
3827   for (unsigned i = 0; i != Half; ++i) {
3828     Mask.push_back(i + Half);
3829     Mask.push_back(i + NumElems + Half);
3830   }
3831   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3832 }
3833
3834 /// PromoteSplat - Promote a splat of v4i32, v8i16 or v16i8 to v4f32.
3835 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
3836   EVT PVT = MVT::v4f32;
3837   EVT VT = SV->getValueType(0);
3838   DebugLoc dl = SV->getDebugLoc();
3839   SDValue V1 = SV->getOperand(0);
3840   int NumElems = VT.getVectorNumElements();
3841   int EltNo = SV->getSplatIndex();
3842
3843   // unpack elements to the correct location
3844   while (NumElems > 4) {
3845     if (EltNo < NumElems/2) {
3846       V1 = getUnpackl(DAG, dl, VT, V1, V1);
3847     } else {
3848       V1 = getUnpackh(DAG, dl, VT, V1, V1);
3849       EltNo -= NumElems/2;
3850     }
3851     NumElems >>= 1;
3852   }
3853
3854   // Perform the splat.
3855   int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3856   V1 = DAG.getNode(ISD::BITCAST, dl, PVT, V1);
3857   V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3858   return DAG.getNode(ISD::BITCAST, dl, VT, V1);
3859 }
3860
3861 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3862 /// vector of zero or undef vector.  This produces a shuffle where the low
3863 /// element of V2 is swizzled into the zero/undef vector, landing at element
3864 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
3865 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3866                                              bool isZero, bool HasSSE2,
3867                                              SelectionDAG &DAG) {
3868   EVT VT = V2.getValueType();
3869   SDValue V1 = isZero
3870     ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3871   unsigned NumElems = VT.getVectorNumElements();
3872   SmallVector<int, 16> MaskVec;
3873   for (unsigned i = 0; i != NumElems; ++i)
3874     // If this is the insertion idx, put the low elt of V2 here.
3875     MaskVec.push_back(i == Idx ? NumElems : i);
3876   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3877 }
3878
3879 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
3880 /// element of the result of the vector shuffle.
3881 SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
3882                             unsigned Depth) {
3883   if (Depth == 6)
3884     return SDValue();  // Limit search depth.
3885
3886   SDValue V = SDValue(N, 0);
3887   EVT VT = V.getValueType();
3888   unsigned Opcode = V.getOpcode();
3889
3890   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
3891   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
3892     Index = SV->getMaskElt(Index);
3893
3894     if (Index < 0)
3895       return DAG.getUNDEF(VT.getVectorElementType());
3896
3897     int NumElems = VT.getVectorNumElements();
3898     SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
3899     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
3900   }
3901
3902   // Recurse into target specific vector shuffles to find scalars.
3903   if (isTargetShuffle(Opcode)) {
3904     int NumElems = VT.getVectorNumElements();
3905     SmallVector<unsigned, 16> ShuffleMask;
3906     SDValue ImmN;
3907
3908     switch(Opcode) {
3909     case X86ISD::SHUFPS:
3910     case X86ISD::SHUFPD:
3911       ImmN = N->getOperand(N->getNumOperands()-1);
3912       DecodeSHUFPSMask(NumElems,
3913                        cast<ConstantSDNode>(ImmN)->getZExtValue(),
3914                        ShuffleMask);
3915       break;
3916     case X86ISD::PUNPCKHBW:
3917     case X86ISD::PUNPCKHWD:
3918     case X86ISD::PUNPCKHDQ:
3919     case X86ISD::PUNPCKHQDQ:
3920       DecodePUNPCKHMask(NumElems, ShuffleMask);
3921       break;
3922     case X86ISD::UNPCKHPS:
3923     case X86ISD::UNPCKHPD:
3924       DecodeUNPCKHPMask(NumElems, ShuffleMask);
3925       break;
3926     case X86ISD::PUNPCKLBW:
3927     case X86ISD::PUNPCKLWD:
3928     case X86ISD::PUNPCKLDQ:
3929     case X86ISD::PUNPCKLQDQ:
3930       DecodePUNPCKLMask(VT, ShuffleMask);
3931       break;
3932     case X86ISD::UNPCKLPS:
3933     case X86ISD::UNPCKLPD:
3934     case X86ISD::VUNPCKLPS:
3935     case X86ISD::VUNPCKLPD:
3936     case X86ISD::VUNPCKLPSY:
3937     case X86ISD::VUNPCKLPDY:
3938       DecodeUNPCKLPMask(VT, ShuffleMask);
3939       break;
3940     case X86ISD::MOVHLPS:
3941       DecodeMOVHLPSMask(NumElems, ShuffleMask);
3942       break;
3943     case X86ISD::MOVLHPS:
3944       DecodeMOVLHPSMask(NumElems, ShuffleMask);
3945       break;
3946     case X86ISD::PSHUFD:
3947       ImmN = N->getOperand(N->getNumOperands()-1);
3948       DecodePSHUFMask(NumElems,
3949                       cast<ConstantSDNode>(ImmN)->getZExtValue(),
3950                       ShuffleMask);
3951       break;
3952     case X86ISD::PSHUFHW:
3953       ImmN = N->getOperand(N->getNumOperands()-1);
3954       DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
3955                         ShuffleMask);
3956       break;
3957     case X86ISD::PSHUFLW:
3958       ImmN = N->getOperand(N->getNumOperands()-1);
3959       DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
3960                         ShuffleMask);
3961       break;
3962     case X86ISD::MOVSS:
3963     case X86ISD::MOVSD: {
3964       // The index 0 always comes from the first element of the second source,
3965       // this is why MOVSS and MOVSD are used in the first place. The other
3966       // elements come from the other positions of the first source vector.
3967       unsigned OpNum = (Index == 0) ? 1 : 0;
3968       return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
3969                                  Depth+1);
3970     }
3971     default:
3972       assert("not implemented for target shuffle node");
3973       return SDValue();
3974     }
3975
3976     Index = ShuffleMask[Index];
3977     if (Index < 0)
3978       return DAG.getUNDEF(VT.getVectorElementType());
3979
3980     SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
3981     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
3982                                Depth+1);
3983   }
3984
3985   // Actual nodes that may contain scalar elements
3986   if (Opcode == ISD::BITCAST) {
3987     V = V.getOperand(0);
3988     EVT SrcVT = V.getValueType();
3989     unsigned NumElems = VT.getVectorNumElements();
3990
3991     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
3992       return SDValue();
3993   }
3994
3995   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
3996     return (Index == 0) ? V.getOperand(0)
3997                           : DAG.getUNDEF(VT.getVectorElementType());
3998
3999   if (V.getOpcode() == ISD::BUILD_VECTOR)
4000     return V.getOperand(Index);
4001
4002   return SDValue();
4003 }
4004
4005 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4006 /// shuffle operation which come from a consecutively from a zero. The
4007 /// search can start in two diferent directions, from left or right.
4008 static
4009 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
4010                                   bool ZerosFromLeft, SelectionDAG &DAG) {
4011   int i = 0;
4012
4013   while (i < NumElems) {
4014     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4015     SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
4016     if (!(Elt.getNode() &&
4017          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4018       break;
4019     ++i;
4020   }
4021
4022   return i;
4023 }
4024
4025 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
4026 /// MaskE correspond consecutively to elements from one of the vector operands,
4027 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4028 static
4029 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
4030                               int OpIdx, int NumElems, unsigned &OpNum) {
4031   bool SeenV1 = false;
4032   bool SeenV2 = false;
4033
4034   for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
4035     int Idx = SVOp->getMaskElt(i);
4036     // Ignore undef indicies
4037     if (Idx < 0)
4038       continue;
4039
4040     if (Idx < NumElems)
4041       SeenV1 = true;
4042     else
4043       SeenV2 = true;
4044
4045     // Only accept consecutive elements from the same vector
4046     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4047       return false;
4048   }
4049
4050   OpNum = SeenV1 ? 0 : 1;
4051   return true;
4052 }
4053
4054 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4055 /// logical left shift of a vector.
4056 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4057                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4058   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4059   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4060               false /* check zeros from right */, DAG);
4061   unsigned OpSrc;
4062
4063   if (!NumZeros)
4064     return false;
4065
4066   // Considering the elements in the mask that are not consecutive zeros,
4067   // check if they consecutively come from only one of the source vectors.
4068   //
4069   //               V1 = {X, A, B, C}     0
4070   //                         \  \  \    /
4071   //   vector_shuffle V1, V2 <1, 2, 3, X>
4072   //
4073   if (!isShuffleMaskConsecutive(SVOp,
4074             0,                   // Mask Start Index
4075             NumElems-NumZeros-1, // Mask End Index
4076             NumZeros,            // Where to start looking in the src vector
4077             NumElems,            // Number of elements in vector
4078             OpSrc))              // Which source operand ?
4079     return false;
4080
4081   isLeft = false;
4082   ShAmt = NumZeros;
4083   ShVal = SVOp->getOperand(OpSrc);
4084   return true;
4085 }
4086
4087 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4088 /// logical left shift of a vector.
4089 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4090                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4091   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4092   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4093               true /* check zeros from left */, DAG);
4094   unsigned OpSrc;
4095
4096   if (!NumZeros)
4097     return false;
4098
4099   // Considering the elements in the mask that are not consecutive zeros,
4100   // check if they consecutively come from only one of the source vectors.
4101   //
4102   //                           0    { A, B, X, X } = V2
4103   //                          / \    /  /
4104   //   vector_shuffle V1, V2 <X, X, 4, 5>
4105   //
4106   if (!isShuffleMaskConsecutive(SVOp,
4107             NumZeros,     // Mask Start Index
4108             NumElems-1,   // Mask End Index
4109             0,            // Where to start looking in the src vector
4110             NumElems,     // Number of elements in vector
4111             OpSrc))       // Which source operand ?
4112     return false;
4113
4114   isLeft = true;
4115   ShAmt = NumZeros;
4116   ShVal = SVOp->getOperand(OpSrc);
4117   return true;
4118 }
4119
4120 /// isVectorShift - Returns true if the shuffle can be implemented as a
4121 /// logical left or right shift of a vector.
4122 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4123                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4124   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4125       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4126     return true;
4127
4128   return false;
4129 }
4130
4131 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4132 ///
4133 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4134                                        unsigned NumNonZero, unsigned NumZero,
4135                                        SelectionDAG &DAG,
4136                                        const TargetLowering &TLI) {
4137   if (NumNonZero > 8)
4138     return SDValue();
4139
4140   DebugLoc dl = Op.getDebugLoc();
4141   SDValue V(0, 0);
4142   bool First = true;
4143   for (unsigned i = 0; i < 16; ++i) {
4144     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4145     if (ThisIsNonZero && First) {
4146       if (NumZero)
4147         V = getZeroVector(MVT::v8i16, true, DAG, dl);
4148       else
4149         V = DAG.getUNDEF(MVT::v8i16);
4150       First = false;
4151     }
4152
4153     if ((i & 1) != 0) {
4154       SDValue ThisElt(0, 0), LastElt(0, 0);
4155       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4156       if (LastIsNonZero) {
4157         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4158                               MVT::i16, Op.getOperand(i-1));
4159       }
4160       if (ThisIsNonZero) {
4161         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4162         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4163                               ThisElt, DAG.getConstant(8, MVT::i8));
4164         if (LastIsNonZero)
4165           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4166       } else
4167         ThisElt = LastElt;
4168
4169       if (ThisElt.getNode())
4170         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4171                         DAG.getIntPtrConstant(i/2));
4172     }
4173   }
4174
4175   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4176 }
4177
4178 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4179 ///
4180 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4181                                      unsigned NumNonZero, unsigned NumZero,
4182                                      SelectionDAG &DAG,
4183                                      const TargetLowering &TLI) {
4184   if (NumNonZero > 4)
4185     return SDValue();
4186
4187   DebugLoc dl = Op.getDebugLoc();
4188   SDValue V(0, 0);
4189   bool First = true;
4190   for (unsigned i = 0; i < 8; ++i) {
4191     bool isNonZero = (NonZeros & (1 << i)) != 0;
4192     if (isNonZero) {
4193       if (First) {
4194         if (NumZero)
4195           V = getZeroVector(MVT::v8i16, true, DAG, dl);
4196         else
4197           V = DAG.getUNDEF(MVT::v8i16);
4198         First = false;
4199       }
4200       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4201                       MVT::v8i16, V, Op.getOperand(i),
4202                       DAG.getIntPtrConstant(i));
4203     }
4204   }
4205
4206   return V;
4207 }
4208
4209 /// getVShift - Return a vector logical shift node.
4210 ///
4211 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4212                          unsigned NumBits, SelectionDAG &DAG,
4213                          const TargetLowering &TLI, DebugLoc dl) {
4214   EVT ShVT = MVT::v2i64;
4215   unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
4216   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4217   return DAG.getNode(ISD::BITCAST, dl, VT,
4218                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4219                              DAG.getConstant(NumBits,
4220                                   TLI.getShiftAmountTy(SrcOp.getValueType()))));
4221 }
4222
4223 SDValue
4224 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4225                                           SelectionDAG &DAG) const {
4226
4227   // Check if the scalar load can be widened into a vector load. And if
4228   // the address is "base + cst" see if the cst can be "absorbed" into
4229   // the shuffle mask.
4230   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4231     SDValue Ptr = LD->getBasePtr();
4232     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4233       return SDValue();
4234     EVT PVT = LD->getValueType(0);
4235     if (PVT != MVT::i32 && PVT != MVT::f32)
4236       return SDValue();
4237
4238     int FI = -1;
4239     int64_t Offset = 0;
4240     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4241       FI = FINode->getIndex();
4242       Offset = 0;
4243     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4244                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4245       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4246       Offset = Ptr.getConstantOperandVal(1);
4247       Ptr = Ptr.getOperand(0);
4248     } else {
4249       return SDValue();
4250     }
4251
4252     SDValue Chain = LD->getChain();
4253     // Make sure the stack object alignment is at least 16.
4254     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4255     if (DAG.InferPtrAlignment(Ptr) < 16) {
4256       if (MFI->isFixedObjectIndex(FI)) {
4257         // Can't change the alignment. FIXME: It's possible to compute
4258         // the exact stack offset and reference FI + adjust offset instead.
4259         // If someone *really* cares about this. That's the way to implement it.
4260         return SDValue();
4261       } else {
4262         MFI->setObjectAlignment(FI, 16);
4263       }
4264     }
4265
4266     // (Offset % 16) must be multiple of 4. Then address is then
4267     // Ptr + (Offset & ~15).
4268     if (Offset < 0)
4269       return SDValue();
4270     if ((Offset % 16) & 3)
4271       return SDValue();
4272     int64_t StartOffset = Offset & ~15;
4273     if (StartOffset)
4274       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4275                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4276
4277     int EltNo = (Offset - StartOffset) >> 2;
4278     int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
4279     EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
4280     SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,
4281                              LD->getPointerInfo().getWithOffset(StartOffset),
4282                              false, false, 0);
4283     // Canonicalize it to a v4i32 shuffle.
4284     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
4285     return DAG.getNode(ISD::BITCAST, dl, VT,
4286                        DAG.getVectorShuffle(MVT::v4i32, dl, V1,
4287                                             DAG.getUNDEF(MVT::v4i32),&Mask[0]));
4288   }
4289
4290   return SDValue();
4291 }
4292
4293 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4294 /// vector of type 'VT', see if the elements can be replaced by a single large
4295 /// load which has the same value as a build_vector whose operands are 'elts'.
4296 ///
4297 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4298 ///
4299 /// FIXME: we'd also like to handle the case where the last elements are zero
4300 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4301 /// There's even a handy isZeroNode for that purpose.
4302 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4303                                         DebugLoc &DL, SelectionDAG &DAG) {
4304   EVT EltVT = VT.getVectorElementType();
4305   unsigned NumElems = Elts.size();
4306
4307   LoadSDNode *LDBase = NULL;
4308   unsigned LastLoadedElt = -1U;
4309
4310   // For each element in the initializer, see if we've found a load or an undef.
4311   // If we don't find an initial load element, or later load elements are
4312   // non-consecutive, bail out.
4313   for (unsigned i = 0; i < NumElems; ++i) {
4314     SDValue Elt = Elts[i];
4315
4316     if (!Elt.getNode() ||
4317         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4318       return SDValue();
4319     if (!LDBase) {
4320       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4321         return SDValue();
4322       LDBase = cast<LoadSDNode>(Elt.getNode());
4323       LastLoadedElt = i;
4324       continue;
4325     }
4326     if (Elt.getOpcode() == ISD::UNDEF)
4327       continue;
4328
4329     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4330     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4331       return SDValue();
4332     LastLoadedElt = i;
4333   }
4334
4335   // If we have found an entire vector of loads and undefs, then return a large
4336   // load of the entire vector width starting at the base pointer.  If we found
4337   // consecutive loads for the low half, generate a vzext_load node.
4338   if (LastLoadedElt == NumElems - 1) {
4339     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4340       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4341                          LDBase->getPointerInfo(),
4342                          LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
4343     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4344                        LDBase->getPointerInfo(),
4345                        LDBase->isVolatile(), LDBase->isNonTemporal(),
4346                        LDBase->getAlignment());
4347   } else if (NumElems == 4 && LastLoadedElt == 1) {
4348     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4349     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4350     SDValue ResNode = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys,
4351                                               Ops, 2, MVT::i32,
4352                                               LDBase->getMemOperand());
4353     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4354   }
4355   return SDValue();
4356 }
4357
4358 SDValue
4359 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
4360   DebugLoc dl = Op.getDebugLoc();
4361
4362   EVT VT = Op.getValueType();
4363   EVT ExtVT = VT.getVectorElementType();
4364
4365   unsigned NumElems = Op.getNumOperands();
4366
4367   // For AVX-length vectors, build the individual 128-bit pieces and
4368   // use shuffles to put them in place.
4369   if (VT.getSizeInBits() > 256 &&
4370       Subtarget->hasAVX() &&
4371       !ISD::isBuildVectorAllZeros(Op.getNode())) {
4372     SmallVector<SDValue, 8> V;
4373     V.resize(NumElems);
4374     for (unsigned i = 0; i < NumElems; ++i) {
4375       V[i] = Op.getOperand(i);
4376     }
4377
4378     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
4379
4380     // Build the lower subvector.
4381     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
4382     // Build the upper subvector.
4383     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
4384                                 NumElems/2);
4385
4386     return ConcatVectors(Lower, Upper, DAG);
4387   }
4388
4389   // All zero's are handled with pxor in SSE2 and above, xorps in SSE1.
4390   // All one's are handled with pcmpeqd. In AVX, zero's are handled with
4391   // vpxor in 128-bit and xor{pd,ps} in 256-bit, but no 256 version of pcmpeqd
4392   // is present, so AllOnes is ignored.
4393   if (ISD::isBuildVectorAllZeros(Op.getNode()) ||
4394       (Op.getValueType().getSizeInBits() != 256 &&
4395        ISD::isBuildVectorAllOnes(Op.getNode()))) {
4396     // Canonicalize this to <4 x i32> (SSE) to
4397     // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
4398     // eliminated on x86-32 hosts.
4399     if (Op.getValueType() == MVT::v4i32)
4400       return Op;
4401
4402     if (ISD::isBuildVectorAllOnes(Op.getNode()))
4403       return getOnesVector(Op.getValueType(), DAG, dl);
4404     return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
4405   }
4406
4407   unsigned EVTBits = ExtVT.getSizeInBits();
4408
4409   unsigned NumZero  = 0;
4410   unsigned NumNonZero = 0;
4411   unsigned NonZeros = 0;
4412   bool IsAllConstants = true;
4413   SmallSet<SDValue, 8> Values;
4414   for (unsigned i = 0; i < NumElems; ++i) {
4415     SDValue Elt = Op.getOperand(i);
4416     if (Elt.getOpcode() == ISD::UNDEF)
4417       continue;
4418     Values.insert(Elt);
4419     if (Elt.getOpcode() != ISD::Constant &&
4420         Elt.getOpcode() != ISD::ConstantFP)
4421       IsAllConstants = false;
4422     if (X86::isZeroNode(Elt))
4423       NumZero++;
4424     else {
4425       NonZeros |= (1 << i);
4426       NumNonZero++;
4427     }
4428   }
4429
4430   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
4431   if (NumNonZero == 0)
4432     return DAG.getUNDEF(VT);
4433
4434   // Special case for single non-zero, non-undef, element.
4435   if (NumNonZero == 1) {
4436     unsigned Idx = CountTrailingZeros_32(NonZeros);
4437     SDValue Item = Op.getOperand(Idx);
4438
4439     // If this is an insertion of an i64 value on x86-32, and if the top bits of
4440     // the value are obviously zero, truncate the value to i32 and do the
4441     // insertion that way.  Only do this if the value is non-constant or if the
4442     // value is a constant being inserted into element 0.  It is cheaper to do
4443     // a constant pool load than it is to do a movd + shuffle.
4444     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
4445         (!IsAllConstants || Idx == 0)) {
4446       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
4447         // Handle SSE only.
4448         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
4449         EVT VecVT = MVT::v4i32;
4450         unsigned VecElts = 4;
4451
4452         // Truncate the value (which may itself be a constant) to i32, and
4453         // convert it to a vector with movd (S2V+shuffle to zero extend).
4454         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
4455         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
4456         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4457                                            Subtarget->hasSSE2(), DAG);
4458
4459         // Now we have our 32-bit value zero extended in the low element of
4460         // a vector.  If Idx != 0, swizzle it into place.
4461         if (Idx != 0) {
4462           SmallVector<int, 4> Mask;
4463           Mask.push_back(Idx);
4464           for (unsigned i = 1; i != VecElts; ++i)
4465             Mask.push_back(i);
4466           Item = DAG.getVectorShuffle(VecVT, dl, Item,
4467                                       DAG.getUNDEF(Item.getValueType()),
4468                                       &Mask[0]);
4469         }
4470         return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
4471       }
4472     }
4473
4474     // If we have a constant or non-constant insertion into the low element of
4475     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
4476     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
4477     // depending on what the source datatype is.
4478     if (Idx == 0) {
4479       if (NumZero == 0) {
4480         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4481       } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
4482           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
4483         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4484         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
4485         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
4486                                            DAG);
4487       } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
4488         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
4489         assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
4490         EVT MiddleVT = MVT::v4i32;
4491         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
4492         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4493                                            Subtarget->hasSSE2(), DAG);
4494         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
4495       }
4496     }
4497
4498     // Is it a vector logical left shift?
4499     if (NumElems == 2 && Idx == 1 &&
4500         X86::isZeroNode(Op.getOperand(0)) &&
4501         !X86::isZeroNode(Op.getOperand(1))) {
4502       unsigned NumBits = VT.getSizeInBits();
4503       return getVShift(true, VT,
4504                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4505                                    VT, Op.getOperand(1)),
4506                        NumBits/2, DAG, *this, dl);
4507     }
4508
4509     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
4510       return SDValue();
4511
4512     // Otherwise, if this is a vector with i32 or f32 elements, and the element
4513     // is a non-constant being inserted into an element other than the low one,
4514     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
4515     // movd/movss) to move this into the low element, then shuffle it into
4516     // place.
4517     if (EVTBits == 32) {
4518       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4519
4520       // Turn it into a shuffle of zero and zero-extended scalar to vector.
4521       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
4522                                          Subtarget->hasSSE2(), DAG);
4523       SmallVector<int, 8> MaskVec;
4524       for (unsigned i = 0; i < NumElems; i++)
4525         MaskVec.push_back(i == Idx ? 0 : 1);
4526       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
4527     }
4528   }
4529
4530   // Splat is obviously ok. Let legalizer expand it to a shuffle.
4531   if (Values.size() == 1) {
4532     if (EVTBits == 32) {
4533       // Instead of a shuffle like this:
4534       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
4535       // Check if it's possible to issue this instead.
4536       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
4537       unsigned Idx = CountTrailingZeros_32(NonZeros);
4538       SDValue Item = Op.getOperand(Idx);
4539       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
4540         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
4541     }
4542     return SDValue();
4543   }
4544
4545   // A vector full of immediates; various special cases are already
4546   // handled, so this is best done with a single constant-pool load.
4547   if (IsAllConstants)
4548     return SDValue();
4549
4550   // Let legalizer expand 2-wide build_vectors.
4551   if (EVTBits == 64) {
4552     if (NumNonZero == 1) {
4553       // One half is zero or undef.
4554       unsigned Idx = CountTrailingZeros_32(NonZeros);
4555       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
4556                                  Op.getOperand(Idx));
4557       return getShuffleVectorZeroOrUndef(V2, Idx, true,
4558                                          Subtarget->hasSSE2(), DAG);
4559     }
4560     return SDValue();
4561   }
4562
4563   // If element VT is < 32 bits, convert it to inserts into a zero vector.
4564   if (EVTBits == 8 && NumElems == 16) {
4565     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
4566                                         *this);
4567     if (V.getNode()) return V;
4568   }
4569
4570   if (EVTBits == 16 && NumElems == 8) {
4571     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
4572                                       *this);
4573     if (V.getNode()) return V;
4574   }
4575
4576   // If element VT is == 32 bits, turn it into a number of shuffles.
4577   SmallVector<SDValue, 8> V;
4578   V.resize(NumElems);
4579   if (NumElems == 4 && NumZero > 0) {
4580     for (unsigned i = 0; i < 4; ++i) {
4581       bool isZero = !(NonZeros & (1 << i));
4582       if (isZero)
4583         V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4584       else
4585         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4586     }
4587
4588     for (unsigned i = 0; i < 2; ++i) {
4589       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
4590         default: break;
4591         case 0:
4592           V[i] = V[i*2];  // Must be a zero vector.
4593           break;
4594         case 1:
4595           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
4596           break;
4597         case 2:
4598           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
4599           break;
4600         case 3:
4601           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
4602           break;
4603       }
4604     }
4605
4606     SmallVector<int, 8> MaskVec;
4607     bool Reverse = (NonZeros & 0x3) == 2;
4608     for (unsigned i = 0; i < 2; ++i)
4609       MaskVec.push_back(Reverse ? 1-i : i);
4610     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
4611     for (unsigned i = 0; i < 2; ++i)
4612       MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
4613     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
4614   }
4615
4616   if (Values.size() > 1 && VT.getSizeInBits() == 128) {
4617     // Check for a build vector of consecutive loads.
4618     for (unsigned i = 0; i < NumElems; ++i)
4619       V[i] = Op.getOperand(i);
4620
4621     // Check for elements which are consecutive loads.
4622     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
4623     if (LD.getNode())
4624       return LD;
4625
4626     // For SSE 4.1, use insertps to put the high elements into the low element.
4627     if (getSubtarget()->hasSSE41()) {
4628       SDValue Result;
4629       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
4630         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
4631       else
4632         Result = DAG.getUNDEF(VT);
4633
4634       for (unsigned i = 1; i < NumElems; ++i) {
4635         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
4636         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
4637                              Op.getOperand(i), DAG.getIntPtrConstant(i));
4638       }
4639       return Result;
4640     }
4641
4642     // Otherwise, expand into a number of unpckl*, start by extending each of
4643     // our (non-undef) elements to the full vector width with the element in the
4644     // bottom slot of the vector (which generates no code for SSE).
4645     for (unsigned i = 0; i < NumElems; ++i) {
4646       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
4647         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4648       else
4649         V[i] = DAG.getUNDEF(VT);
4650     }
4651
4652     // Next, we iteratively mix elements, e.g. for v4f32:
4653     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
4654     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
4655     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
4656     unsigned EltStride = NumElems >> 1;
4657     while (EltStride != 0) {
4658       for (unsigned i = 0; i < EltStride; ++i) {
4659         // If V[i+EltStride] is undef and this is the first round of mixing,
4660         // then it is safe to just drop this shuffle: V[i] is already in the
4661         // right place, the one element (since it's the first round) being
4662         // inserted as undef can be dropped.  This isn't safe for successive
4663         // rounds because they will permute elements within both vectors.
4664         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
4665             EltStride == NumElems/2)
4666           continue;
4667
4668         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
4669       }
4670       EltStride >>= 1;
4671     }
4672     return V[0];
4673   }
4674   return SDValue();
4675 }
4676
4677 SDValue
4678 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
4679   // We support concatenate two MMX registers and place them in a MMX
4680   // register.  This is better than doing a stack convert.
4681   DebugLoc dl = Op.getDebugLoc();
4682   EVT ResVT = Op.getValueType();
4683   assert(Op.getNumOperands() == 2);
4684   assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
4685          ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
4686   int Mask[2];
4687   SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
4688   SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4689   InVec = Op.getOperand(1);
4690   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4691     unsigned NumElts = ResVT.getVectorNumElements();
4692     VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4693     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
4694                        InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
4695   } else {
4696     InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
4697     SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4698     Mask[0] = 0; Mask[1] = 2;
4699     VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
4700   }
4701   return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4702 }
4703
4704 // v8i16 shuffles - Prefer shuffles in the following order:
4705 // 1. [all]   pshuflw, pshufhw, optional move
4706 // 2. [ssse3] 1 x pshufb
4707 // 3. [ssse3] 2 x pshufb + 1 x por
4708 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
4709 SDValue
4710 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
4711                                             SelectionDAG &DAG) const {
4712   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4713   SDValue V1 = SVOp->getOperand(0);
4714   SDValue V2 = SVOp->getOperand(1);
4715   DebugLoc dl = SVOp->getDebugLoc();
4716   SmallVector<int, 8> MaskVals;
4717
4718   // Determine if more than 1 of the words in each of the low and high quadwords
4719   // of the result come from the same quadword of one of the two inputs.  Undef
4720   // mask values count as coming from any quadword, for better codegen.
4721   SmallVector<unsigned, 4> LoQuad(4);
4722   SmallVector<unsigned, 4> HiQuad(4);
4723   BitVector InputQuads(4);
4724   for (unsigned i = 0; i < 8; ++i) {
4725     SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
4726     int EltIdx = SVOp->getMaskElt(i);
4727     MaskVals.push_back(EltIdx);
4728     if (EltIdx < 0) {
4729       ++Quad[0];
4730       ++Quad[1];
4731       ++Quad[2];
4732       ++Quad[3];
4733       continue;
4734     }
4735     ++Quad[EltIdx / 4];
4736     InputQuads.set(EltIdx / 4);
4737   }
4738
4739   int BestLoQuad = -1;
4740   unsigned MaxQuad = 1;
4741   for (unsigned i = 0; i < 4; ++i) {
4742     if (LoQuad[i] > MaxQuad) {
4743       BestLoQuad = i;
4744       MaxQuad = LoQuad[i];
4745     }
4746   }
4747
4748   int BestHiQuad = -1;
4749   MaxQuad = 1;
4750   for (unsigned i = 0; i < 4; ++i) {
4751     if (HiQuad[i] > MaxQuad) {
4752       BestHiQuad = i;
4753       MaxQuad = HiQuad[i];
4754     }
4755   }
4756
4757   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
4758   // of the two input vectors, shuffle them into one input vector so only a
4759   // single pshufb instruction is necessary. If There are more than 2 input
4760   // quads, disable the next transformation since it does not help SSSE3.
4761   bool V1Used = InputQuads[0] || InputQuads[1];
4762   bool V2Used = InputQuads[2] || InputQuads[3];
4763   if (Subtarget->hasSSSE3()) {
4764     if (InputQuads.count() == 2 && V1Used && V2Used) {
4765       BestLoQuad = InputQuads.find_first();
4766       BestHiQuad = InputQuads.find_next(BestLoQuad);
4767     }
4768     if (InputQuads.count() > 2) {
4769       BestLoQuad = -1;
4770       BestHiQuad = -1;
4771     }
4772   }
4773
4774   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
4775   // the shuffle mask.  If a quad is scored as -1, that means that it contains
4776   // words from all 4 input quadwords.
4777   SDValue NewV;
4778   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
4779     SmallVector<int, 8> MaskV;
4780     MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
4781     MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
4782     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
4783                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
4784                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
4785     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
4786
4787     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
4788     // source words for the shuffle, to aid later transformations.
4789     bool AllWordsInNewV = true;
4790     bool InOrder[2] = { true, true };
4791     for (unsigned i = 0; i != 8; ++i) {
4792       int idx = MaskVals[i];
4793       if (idx != (int)i)
4794         InOrder[i/4] = false;
4795       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
4796         continue;
4797       AllWordsInNewV = false;
4798       break;
4799     }
4800
4801     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
4802     if (AllWordsInNewV) {
4803       for (int i = 0; i != 8; ++i) {
4804         int idx = MaskVals[i];
4805         if (idx < 0)
4806           continue;
4807         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
4808         if ((idx != i) && idx < 4)
4809           pshufhw = false;
4810         if ((idx != i) && idx > 3)
4811           pshuflw = false;
4812       }
4813       V1 = NewV;
4814       V2Used = false;
4815       BestLoQuad = 0;
4816       BestHiQuad = 1;
4817     }
4818
4819     // If we've eliminated the use of V2, and the new mask is a pshuflw or
4820     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
4821     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
4822       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
4823       unsigned TargetMask = 0;
4824       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
4825                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
4826       TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
4827                              X86::getShufflePSHUFLWImmediate(NewV.getNode());
4828       V1 = NewV.getOperand(0);
4829       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
4830     }
4831   }
4832
4833   // If we have SSSE3, and all words of the result are from 1 input vector,
4834   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
4835   // is present, fall back to case 4.
4836   if (Subtarget->hasSSSE3()) {
4837     SmallVector<SDValue,16> pshufbMask;
4838
4839     // If we have elements from both input vectors, set the high bit of the
4840     // shuffle mask element to zero out elements that come from V2 in the V1
4841     // mask, and elements that come from V1 in the V2 mask, so that the two
4842     // results can be OR'd together.
4843     bool TwoInputs = V1Used && V2Used;
4844     for (unsigned i = 0; i != 8; ++i) {
4845       int EltIdx = MaskVals[i] * 2;
4846       if (TwoInputs && (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,   MVT::i8));
4852       pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
4853     }
4854     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
4855     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4856                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4857                                  MVT::v16i8, &pshufbMask[0], 16));
4858     if (!TwoInputs)
4859       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4860
4861     // Calculate the shuffle mask for the second input, shuffle it, and
4862     // OR it with the first shuffled input.
4863     pshufbMask.clear();
4864     for (unsigned i = 0; i != 8; ++i) {
4865       int EltIdx = MaskVals[i] * 2;
4866       if (EltIdx < 16) {
4867         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4868         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4869         continue;
4870       }
4871       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4872       pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
4873     }
4874     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
4875     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4876                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4877                                  MVT::v16i8, &pshufbMask[0], 16));
4878     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4879     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4880   }
4881
4882   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
4883   // and update MaskVals with new element order.
4884   BitVector InOrder(8);
4885   if (BestLoQuad >= 0) {
4886     SmallVector<int, 8> MaskV;
4887     for (int i = 0; i != 4; ++i) {
4888       int idx = MaskVals[i];
4889       if (idx < 0) {
4890         MaskV.push_back(-1);
4891         InOrder.set(i);
4892       } else if ((idx / 4) == BestLoQuad) {
4893         MaskV.push_back(idx & 3);
4894         InOrder.set(i);
4895       } else {
4896         MaskV.push_back(-1);
4897       }
4898     }
4899     for (unsigned i = 4; i != 8; ++i)
4900       MaskV.push_back(i);
4901     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4902                                 &MaskV[0]);
4903
4904     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4905       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
4906                                NewV.getOperand(0),
4907                                X86::getShufflePSHUFLWImmediate(NewV.getNode()),
4908                                DAG);
4909   }
4910
4911   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
4912   // and update MaskVals with the new element order.
4913   if (BestHiQuad >= 0) {
4914     SmallVector<int, 8> MaskV;
4915     for (unsigned i = 0; i != 4; ++i)
4916       MaskV.push_back(i);
4917     for (unsigned i = 4; i != 8; ++i) {
4918       int idx = MaskVals[i];
4919       if (idx < 0) {
4920         MaskV.push_back(-1);
4921         InOrder.set(i);
4922       } else if ((idx / 4) == BestHiQuad) {
4923         MaskV.push_back((idx & 3) + 4);
4924         InOrder.set(i);
4925       } else {
4926         MaskV.push_back(-1);
4927       }
4928     }
4929     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4930                                 &MaskV[0]);
4931
4932     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4933       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
4934                               NewV.getOperand(0),
4935                               X86::getShufflePSHUFHWImmediate(NewV.getNode()),
4936                               DAG);
4937   }
4938
4939   // In case BestHi & BestLo were both -1, which means each quadword has a word
4940   // from each of the four input quadwords, calculate the InOrder bitvector now
4941   // before falling through to the insert/extract cleanup.
4942   if (BestLoQuad == -1 && BestHiQuad == -1) {
4943     NewV = V1;
4944     for (int i = 0; i != 8; ++i)
4945       if (MaskVals[i] < 0 || MaskVals[i] == i)
4946         InOrder.set(i);
4947   }
4948
4949   // The other elements are put in the right place using pextrw and pinsrw.
4950   for (unsigned i = 0; i != 8; ++i) {
4951     if (InOrder[i])
4952       continue;
4953     int EltIdx = MaskVals[i];
4954     if (EltIdx < 0)
4955       continue;
4956     SDValue ExtOp = (EltIdx < 8)
4957     ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
4958                   DAG.getIntPtrConstant(EltIdx))
4959     : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
4960                   DAG.getIntPtrConstant(EltIdx - 8));
4961     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
4962                        DAG.getIntPtrConstant(i));
4963   }
4964   return NewV;
4965 }
4966
4967 // v16i8 shuffles - Prefer shuffles in the following order:
4968 // 1. [ssse3] 1 x pshufb
4969 // 2. [ssse3] 2 x pshufb + 1 x por
4970 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
4971 static
4972 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
4973                                  SelectionDAG &DAG,
4974                                  const X86TargetLowering &TLI) {
4975   SDValue V1 = SVOp->getOperand(0);
4976   SDValue V2 = SVOp->getOperand(1);
4977   DebugLoc dl = SVOp->getDebugLoc();
4978   SmallVector<int, 16> MaskVals;
4979   SVOp->getMask(MaskVals);
4980
4981   // If we have SSSE3, case 1 is generated when all result bytes come from
4982   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
4983   // present, fall back to case 3.
4984   // FIXME: kill V2Only once shuffles are canonizalized by getNode.
4985   bool V1Only = true;
4986   bool V2Only = true;
4987   for (unsigned i = 0; i < 16; ++i) {
4988     int EltIdx = MaskVals[i];
4989     if (EltIdx < 0)
4990       continue;
4991     if (EltIdx < 16)
4992       V2Only = false;
4993     else
4994       V1Only = false;
4995   }
4996
4997   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
4998   if (TLI.getSubtarget()->hasSSSE3()) {
4999     SmallVector<SDValue,16> pshufbMask;
5000
5001     // If all result elements are from one input vector, then only translate
5002     // undef mask values to 0x80 (zero out result) in the pshufb mask.
5003     //
5004     // Otherwise, we have elements from both input vectors, and must zero out
5005     // elements that come from V2 in the first mask, and V1 in the second mask
5006     // so that we can OR them together.
5007     bool TwoInputs = !(V1Only || V2Only);
5008     for (unsigned i = 0; i != 16; ++i) {
5009       int EltIdx = MaskVals[i];
5010       if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
5011         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5012         continue;
5013       }
5014       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5015     }
5016     // If all the elements are from V2, assign it to V1 and return after
5017     // building the first pshufb.
5018     if (V2Only)
5019       V1 = V2;
5020     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5021                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5022                                  MVT::v16i8, &pshufbMask[0], 16));
5023     if (!TwoInputs)
5024       return V1;
5025
5026     // Calculate the shuffle mask for the second input, shuffle it, and
5027     // OR it with the first shuffled input.
5028     pshufbMask.clear();
5029     for (unsigned i = 0; i != 16; ++i) {
5030       int EltIdx = MaskVals[i];
5031       if (EltIdx < 16) {
5032         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5033         continue;
5034       }
5035       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5036     }
5037     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5038                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5039                                  MVT::v16i8, &pshufbMask[0], 16));
5040     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5041   }
5042
5043   // No SSSE3 - Calculate in place words and then fix all out of place words
5044   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
5045   // the 16 different words that comprise the two doublequadword input vectors.
5046   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5047   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5048   SDValue NewV = V2Only ? V2 : V1;
5049   for (int i = 0; i != 8; ++i) {
5050     int Elt0 = MaskVals[i*2];
5051     int Elt1 = MaskVals[i*2+1];
5052
5053     // This word of the result is all undef, skip it.
5054     if (Elt0 < 0 && Elt1 < 0)
5055       continue;
5056
5057     // This word of the result is already in the correct place, skip it.
5058     if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
5059       continue;
5060     if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
5061       continue;
5062
5063     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5064     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5065     SDValue InsElt;
5066
5067     // If Elt0 and Elt1 are defined, are consecutive, and can be load
5068     // using a single extract together, load it and store it.
5069     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5070       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5071                            DAG.getIntPtrConstant(Elt1 / 2));
5072       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5073                         DAG.getIntPtrConstant(i));
5074       continue;
5075     }
5076
5077     // If Elt1 is defined, extract it from the appropriate source.  If the
5078     // source byte is not also odd, shift the extracted word left 8 bits
5079     // otherwise clear the bottom 8 bits if we need to do an or.
5080     if (Elt1 >= 0) {
5081       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5082                            DAG.getIntPtrConstant(Elt1 / 2));
5083       if ((Elt1 & 1) == 0)
5084         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5085                              DAG.getConstant(8,
5086                                   TLI.getShiftAmountTy(InsElt.getValueType())));
5087       else if (Elt0 >= 0)
5088         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5089                              DAG.getConstant(0xFF00, MVT::i16));
5090     }
5091     // If Elt0 is defined, extract it from the appropriate source.  If the
5092     // source byte is not also even, shift the extracted word right 8 bits. If
5093     // Elt1 was also defined, OR the extracted values together before
5094     // inserting them in the result.
5095     if (Elt0 >= 0) {
5096       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5097                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5098       if ((Elt0 & 1) != 0)
5099         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5100                               DAG.getConstant(8,
5101                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
5102       else if (Elt1 >= 0)
5103         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5104                              DAG.getConstant(0x00FF, MVT::i16));
5105       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5106                          : InsElt0;
5107     }
5108     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5109                        DAG.getIntPtrConstant(i));
5110   }
5111   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5112 }
5113
5114 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5115 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5116 /// done when every pair / quad of shuffle mask elements point to elements in
5117 /// the right sequence. e.g.
5118 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5119 static
5120 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5121                                  SelectionDAG &DAG, DebugLoc dl) {
5122   EVT VT = SVOp->getValueType(0);
5123   SDValue V1 = SVOp->getOperand(0);
5124   SDValue V2 = SVOp->getOperand(1);
5125   unsigned NumElems = VT.getVectorNumElements();
5126   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
5127   EVT NewVT;
5128   switch (VT.getSimpleVT().SimpleTy) {
5129   default: assert(false && "Unexpected!");
5130   case MVT::v4f32: NewVT = MVT::v2f64; break;
5131   case MVT::v4i32: NewVT = MVT::v2i64; break;
5132   case MVT::v8i16: NewVT = MVT::v4i32; break;
5133   case MVT::v16i8: NewVT = MVT::v4i32; break;
5134   }
5135
5136   int Scale = NumElems / NewWidth;
5137   SmallVector<int, 8> MaskVec;
5138   for (unsigned i = 0; i < NumElems; i += Scale) {
5139     int StartIdx = -1;
5140     for (int j = 0; j < Scale; ++j) {
5141       int EltIdx = SVOp->getMaskElt(i+j);
5142       if (EltIdx < 0)
5143         continue;
5144       if (StartIdx == -1)
5145         StartIdx = EltIdx - (EltIdx % Scale);
5146       if (EltIdx != StartIdx + j)
5147         return SDValue();
5148     }
5149     if (StartIdx == -1)
5150       MaskVec.push_back(-1);
5151     else
5152       MaskVec.push_back(StartIdx / Scale);
5153   }
5154
5155   V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
5156   V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
5157   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5158 }
5159
5160 /// getVZextMovL - Return a zero-extending vector move low node.
5161 ///
5162 static SDValue getVZextMovL(EVT VT, EVT OpVT,
5163                             SDValue SrcOp, SelectionDAG &DAG,
5164                             const X86Subtarget *Subtarget, DebugLoc dl) {
5165   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
5166     LoadSDNode *LD = NULL;
5167     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
5168       LD = dyn_cast<LoadSDNode>(SrcOp);
5169     if (!LD) {
5170       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
5171       // instead.
5172       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
5173       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
5174           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5175           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
5176           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
5177         // PR2108
5178         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
5179         return DAG.getNode(ISD::BITCAST, dl, VT,
5180                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5181                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5182                                                    OpVT,
5183                                                    SrcOp.getOperand(0)
5184                                                           .getOperand(0))));
5185       }
5186     }
5187   }
5188
5189   return DAG.getNode(ISD::BITCAST, dl, VT,
5190                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5191                                  DAG.getNode(ISD::BITCAST, dl,
5192                                              OpVT, SrcOp)));
5193 }
5194
5195 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
5196 /// shuffles.
5197 static SDValue
5198 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5199   SDValue V1 = SVOp->getOperand(0);
5200   SDValue V2 = SVOp->getOperand(1);
5201   DebugLoc dl = SVOp->getDebugLoc();
5202   EVT VT = SVOp->getValueType(0);
5203
5204   SmallVector<std::pair<int, int>, 8> Locs;
5205   Locs.resize(4);
5206   SmallVector<int, 8> Mask1(4U, -1);
5207   SmallVector<int, 8> PermMask;
5208   SVOp->getMask(PermMask);
5209
5210   unsigned NumHi = 0;
5211   unsigned NumLo = 0;
5212   for (unsigned i = 0; i != 4; ++i) {
5213     int Idx = PermMask[i];
5214     if (Idx < 0) {
5215       Locs[i] = std::make_pair(-1, -1);
5216     } else {
5217       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
5218       if (Idx < 4) {
5219         Locs[i] = std::make_pair(0, NumLo);
5220         Mask1[NumLo] = Idx;
5221         NumLo++;
5222       } else {
5223         Locs[i] = std::make_pair(1, NumHi);
5224         if (2+NumHi < 4)
5225           Mask1[2+NumHi] = Idx;
5226         NumHi++;
5227       }
5228     }
5229   }
5230
5231   if (NumLo <= 2 && NumHi <= 2) {
5232     // If no more than two elements come from either vector. This can be
5233     // implemented with two shuffles. First shuffle gather the elements.
5234     // The second shuffle, which takes the first shuffle as both of its
5235     // vector operands, put the elements into the right order.
5236     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5237
5238     SmallVector<int, 8> Mask2(4U, -1);
5239
5240     for (unsigned i = 0; i != 4; ++i) {
5241       if (Locs[i].first == -1)
5242         continue;
5243       else {
5244         unsigned Idx = (i < 2) ? 0 : 4;
5245         Idx += Locs[i].first * 2 + Locs[i].second;
5246         Mask2[i] = Idx;
5247       }
5248     }
5249
5250     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
5251   } else if (NumLo == 3 || NumHi == 3) {
5252     // Otherwise, we must have three elements from one vector, call it X, and
5253     // one element from the other, call it Y.  First, use a shufps to build an
5254     // intermediate vector with the one element from Y and the element from X
5255     // that will be in the same half in the final destination (the indexes don't
5256     // matter). Then, use a shufps to build the final vector, taking the half
5257     // containing the element from Y from the intermediate, and the other half
5258     // from X.
5259     if (NumHi == 3) {
5260       // Normalize it so the 3 elements come from V1.
5261       CommuteVectorShuffleMask(PermMask, VT);
5262       std::swap(V1, V2);
5263     }
5264
5265     // Find the element from V2.
5266     unsigned HiIndex;
5267     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
5268       int Val = PermMask[HiIndex];
5269       if (Val < 0)
5270         continue;
5271       if (Val >= 4)
5272         break;
5273     }
5274
5275     Mask1[0] = PermMask[HiIndex];
5276     Mask1[1] = -1;
5277     Mask1[2] = PermMask[HiIndex^1];
5278     Mask1[3] = -1;
5279     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5280
5281     if (HiIndex >= 2) {
5282       Mask1[0] = PermMask[0];
5283       Mask1[1] = PermMask[1];
5284       Mask1[2] = HiIndex & 1 ? 6 : 4;
5285       Mask1[3] = HiIndex & 1 ? 4 : 6;
5286       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5287     } else {
5288       Mask1[0] = HiIndex & 1 ? 2 : 0;
5289       Mask1[1] = HiIndex & 1 ? 0 : 2;
5290       Mask1[2] = PermMask[2];
5291       Mask1[3] = PermMask[3];
5292       if (Mask1[2] >= 0)
5293         Mask1[2] += 4;
5294       if (Mask1[3] >= 0)
5295         Mask1[3] += 4;
5296       return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
5297     }
5298   }
5299
5300   // Break it into (shuffle shuffle_hi, shuffle_lo).
5301   Locs.clear();
5302   Locs.resize(4);
5303   SmallVector<int,8> LoMask(4U, -1);
5304   SmallVector<int,8> HiMask(4U, -1);
5305
5306   SmallVector<int,8> *MaskPtr = &LoMask;
5307   unsigned MaskIdx = 0;
5308   unsigned LoIdx = 0;
5309   unsigned HiIdx = 2;
5310   for (unsigned i = 0; i != 4; ++i) {
5311     if (i == 2) {
5312       MaskPtr = &HiMask;
5313       MaskIdx = 1;
5314       LoIdx = 0;
5315       HiIdx = 2;
5316     }
5317     int Idx = PermMask[i];
5318     if (Idx < 0) {
5319       Locs[i] = std::make_pair(-1, -1);
5320     } else if (Idx < 4) {
5321       Locs[i] = std::make_pair(MaskIdx, LoIdx);
5322       (*MaskPtr)[LoIdx] = Idx;
5323       LoIdx++;
5324     } else {
5325       Locs[i] = std::make_pair(MaskIdx, HiIdx);
5326       (*MaskPtr)[HiIdx] = Idx;
5327       HiIdx++;
5328     }
5329   }
5330
5331   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
5332   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
5333   SmallVector<int, 8> MaskOps;
5334   for (unsigned i = 0; i != 4; ++i) {
5335     if (Locs[i].first == -1) {
5336       MaskOps.push_back(-1);
5337     } else {
5338       unsigned Idx = Locs[i].first * 4 + Locs[i].second;
5339       MaskOps.push_back(Idx);
5340     }
5341   }
5342   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
5343 }
5344
5345 static bool MayFoldVectorLoad(SDValue V) {
5346   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5347     V = V.getOperand(0);
5348   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5349     V = V.getOperand(0);
5350   if (MayFoldLoad(V))
5351     return true;
5352   return false;
5353 }
5354
5355 // FIXME: the version above should always be used. Since there's
5356 // a bug where several vector shuffles can't be folded because the
5357 // DAG is not updated during lowering and a node claims to have two
5358 // uses while it only has one, use this version, and let isel match
5359 // another instruction if the load really happens to have more than
5360 // one use. Remove this version after this bug get fixed.
5361 // rdar://8434668, PR8156
5362 static bool RelaxedMayFoldVectorLoad(SDValue V) {
5363   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5364     V = V.getOperand(0);
5365   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5366     V = V.getOperand(0);
5367   if (ISD::isNormalLoad(V.getNode()))
5368     return true;
5369   return false;
5370 }
5371
5372 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
5373 /// a vector extract, and if both can be later optimized into a single load.
5374 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
5375 /// here because otherwise a target specific shuffle node is going to be
5376 /// emitted for this shuffle, and the optimization not done.
5377 /// FIXME: This is probably not the best approach, but fix the problem
5378 /// until the right path is decided.
5379 static
5380 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
5381                                          const TargetLowering &TLI) {
5382   EVT VT = V.getValueType();
5383   ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
5384
5385   // Be sure that the vector shuffle is present in a pattern like this:
5386   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
5387   if (!V.hasOneUse())
5388     return false;
5389
5390   SDNode *N = *V.getNode()->use_begin();
5391   if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5392     return false;
5393
5394   SDValue EltNo = N->getOperand(1);
5395   if (!isa<ConstantSDNode>(EltNo))
5396     return false;
5397
5398   // If the bit convert changed the number of elements, it is unsafe
5399   // to examine the mask.
5400   bool HasShuffleIntoBitcast = false;
5401   if (V.getOpcode() == ISD::BITCAST) {
5402     EVT SrcVT = V.getOperand(0).getValueType();
5403     if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
5404       return false;
5405     V = V.getOperand(0);
5406     HasShuffleIntoBitcast = true;
5407   }
5408
5409   // Select the input vector, guarding against out of range extract vector.
5410   unsigned NumElems = VT.getVectorNumElements();
5411   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5412   int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
5413   V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
5414
5415   // Skip one more bit_convert if necessary
5416   if (V.getOpcode() == ISD::BITCAST)
5417     V = V.getOperand(0);
5418
5419   if (ISD::isNormalLoad(V.getNode())) {
5420     // Is the original load suitable?
5421     LoadSDNode *LN0 = cast<LoadSDNode>(V);
5422
5423     // FIXME: avoid the multi-use bug that is preventing lots of
5424     // of foldings to be detected, this is still wrong of course, but
5425     // give the temporary desired behavior, and if it happens that
5426     // the load has real more uses, during isel it will not fold, and
5427     // will generate poor code.
5428     if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
5429       return false;
5430
5431     if (!HasShuffleIntoBitcast)
5432       return true;
5433
5434     // If there's a bitcast before the shuffle, check if the load type and
5435     // alignment is valid.
5436     unsigned Align = LN0->getAlignment();
5437     unsigned NewAlign =
5438       TLI.getTargetData()->getABITypeAlignment(
5439                                     VT.getTypeForEVT(*DAG.getContext()));
5440
5441     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
5442       return false;
5443   }
5444
5445   return true;
5446 }
5447
5448 static
5449 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
5450   EVT VT = Op.getValueType();
5451
5452   // Canonizalize to v2f64.
5453   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
5454   return DAG.getNode(ISD::BITCAST, dl, VT,
5455                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
5456                                           V1, DAG));
5457 }
5458
5459 static
5460 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
5461                         bool HasSSE2) {
5462   SDValue V1 = Op.getOperand(0);
5463   SDValue V2 = Op.getOperand(1);
5464   EVT VT = Op.getValueType();
5465
5466   assert(VT != MVT::v2i64 && "unsupported shuffle type");
5467
5468   if (HasSSE2 && VT == MVT::v2f64)
5469     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
5470
5471   // v4f32 or v4i32
5472   return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V2, DAG);
5473 }
5474
5475 static
5476 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
5477   SDValue V1 = Op.getOperand(0);
5478   SDValue V2 = Op.getOperand(1);
5479   EVT VT = Op.getValueType();
5480
5481   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
5482          "unsupported shuffle type");
5483
5484   if (V2.getOpcode() == ISD::UNDEF)
5485     V2 = V1;
5486
5487   // v4i32 or v4f32
5488   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
5489 }
5490
5491 static
5492 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
5493   SDValue V1 = Op.getOperand(0);
5494   SDValue V2 = Op.getOperand(1);
5495   EVT VT = Op.getValueType();
5496   unsigned NumElems = VT.getVectorNumElements();
5497
5498   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
5499   // operand of these instructions is only memory, so check if there's a
5500   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
5501   // same masks.
5502   bool CanFoldLoad = false;
5503
5504   // Trivial case, when V2 comes from a load.
5505   if (MayFoldVectorLoad(V2))
5506     CanFoldLoad = true;
5507
5508   // When V1 is a load, it can be folded later into a store in isel, example:
5509   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
5510   //    turns into:
5511   //  (MOVLPSmr addr:$src1, VR128:$src2)
5512   // So, recognize this potential and also use MOVLPS or MOVLPD
5513   if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
5514     CanFoldLoad = true;
5515
5516   // Both of them can't be memory operations though.
5517   if (MayFoldVectorLoad(V1) && MayFoldVectorLoad(V2))
5518     CanFoldLoad = false;
5519
5520   if (CanFoldLoad) {
5521     if (HasSSE2 && NumElems == 2)
5522       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
5523
5524     if (NumElems == 4)
5525       return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
5526   }
5527
5528   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5529   // movl and movlp will both match v2i64, but v2i64 is never matched by
5530   // movl earlier because we make it strict to avoid messing with the movlp load
5531   // folding logic (see the code above getMOVLP call). Match it here then,
5532   // this is horrible, but will stay like this until we move all shuffle
5533   // matching to x86 specific nodes. Note that for the 1st condition all
5534   // types are matched with movsd.
5535   if ((HasSSE2 && NumElems == 2) || !X86::isMOVLMask(SVOp))
5536     return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5537   else if (HasSSE2)
5538     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5539
5540
5541   assert(VT != MVT::v4i32 && "unsupported shuffle type");
5542
5543   // Invert the operand order and use SHUFPS to match it.
5544   return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V2, V1,
5545                               X86::getShuffleSHUFImmediate(SVOp), DAG);
5546 }
5547
5548 static inline unsigned getUNPCKLOpcode(EVT VT, const X86Subtarget *Subtarget) {
5549   switch(VT.getSimpleVT().SimpleTy) {
5550   case MVT::v4i32: return X86ISD::PUNPCKLDQ;
5551   case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
5552   case MVT::v4f32:
5553     return Subtarget->hasAVX() ? X86ISD::VUNPCKLPS : X86ISD::UNPCKLPS;
5554   case MVT::v2f64:
5555     return Subtarget->hasAVX() ? X86ISD::VUNPCKLPD : X86ISD::UNPCKLPD;
5556   case MVT::v8f32: return X86ISD::VUNPCKLPSY;
5557   case MVT::v4f64: return X86ISD::VUNPCKLPDY;
5558   case MVT::v16i8: return X86ISD::PUNPCKLBW;
5559   case MVT::v8i16: return X86ISD::PUNPCKLWD;
5560   default:
5561     llvm_unreachable("Unknown type for unpckl");
5562   }
5563   return 0;
5564 }
5565
5566 static inline unsigned getUNPCKHOpcode(EVT VT) {
5567   switch(VT.getSimpleVT().SimpleTy) {
5568   case MVT::v4i32: return X86ISD::PUNPCKHDQ;
5569   case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
5570   case MVT::v4f32: return X86ISD::UNPCKHPS;
5571   case MVT::v2f64: return X86ISD::UNPCKHPD;
5572   case MVT::v16i8: return X86ISD::PUNPCKHBW;
5573   case MVT::v8i16: return X86ISD::PUNPCKHWD;
5574   default:
5575     llvm_unreachable("Unknown type for unpckh");
5576   }
5577   return 0;
5578 }
5579
5580 static
5581 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
5582                                const TargetLowering &TLI,
5583                                const X86Subtarget *Subtarget) {
5584   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5585   EVT VT = Op.getValueType();
5586   DebugLoc dl = Op.getDebugLoc();
5587   SDValue V1 = Op.getOperand(0);
5588   SDValue V2 = Op.getOperand(1);
5589
5590   if (isZeroShuffle(SVOp))
5591     return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
5592
5593   // Handle splat operations
5594   if (SVOp->isSplat()) {
5595     // Special case, this is the only place now where it's
5596     // allowed to return a vector_shuffle operation without
5597     // using a target specific node, because *hopefully* it
5598     // will be optimized away by the dag combiner.
5599     if (VT.getVectorNumElements() <= 4 &&
5600         CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
5601       return Op;
5602
5603     // Handle splats by matching through known masks
5604     if (VT.getVectorNumElements() <= 4)
5605       return SDValue();
5606
5607     // Canonicalize all of the remaining to v4f32.
5608     return PromoteSplat(SVOp, DAG);
5609   }
5610
5611   // If the shuffle can be profitably rewritten as a narrower shuffle, then
5612   // do it!
5613   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
5614     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5615     if (NewOp.getNode())
5616       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
5617   } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
5618     // FIXME: Figure out a cleaner way to do this.
5619     // Try to make use of movq to zero out the top part.
5620     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
5621       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5622       if (NewOp.getNode()) {
5623         if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
5624           return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
5625                               DAG, Subtarget, dl);
5626       }
5627     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
5628       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5629       if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
5630         return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
5631                             DAG, Subtarget, dl);
5632     }
5633   }
5634   return SDValue();
5635 }
5636
5637 SDValue
5638 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
5639   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5640   SDValue V1 = Op.getOperand(0);
5641   SDValue V2 = Op.getOperand(1);
5642   EVT VT = Op.getValueType();
5643   DebugLoc dl = Op.getDebugLoc();
5644   unsigned NumElems = VT.getVectorNumElements();
5645   bool isMMX = VT.getSizeInBits() == 64;
5646   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
5647   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
5648   bool V1IsSplat = false;
5649   bool V2IsSplat = false;
5650   bool HasSSE2 = Subtarget->hasSSE2() || Subtarget->hasAVX();
5651   bool HasSSE3 = Subtarget->hasSSE3() || Subtarget->hasAVX();
5652   bool HasSSSE3 = Subtarget->hasSSSE3() || Subtarget->hasAVX();
5653   MachineFunction &MF = DAG.getMachineFunction();
5654   bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
5655
5656   // Shuffle operations on MMX not supported.
5657   if (isMMX)
5658     return Op;
5659
5660   // Vector shuffle lowering takes 3 steps:
5661   //
5662   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
5663   //    narrowing and commutation of operands should be handled.
5664   // 2) Matching of shuffles with known shuffle masks to x86 target specific
5665   //    shuffle nodes.
5666   // 3) Rewriting of unmatched masks into new generic shuffle operations,
5667   //    so the shuffle can be broken into other shuffles and the legalizer can
5668   //    try the lowering again.
5669   //
5670   // The general ideia is that no vector_shuffle operation should be left to
5671   // be matched during isel, all of them must be converted to a target specific
5672   // node here.
5673
5674   // Normalize the input vectors. Here splats, zeroed vectors, profitable
5675   // narrowing and commutation of operands should be handled. The actual code
5676   // doesn't include all of those, work in progress...
5677   SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
5678   if (NewOp.getNode())
5679     return NewOp;
5680
5681   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
5682   // unpckh_undef). Only use pshufd if speed is more important than size.
5683   if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
5684     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5685       return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()), dl, VT, V1, V1, DAG);
5686   if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
5687     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5688       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5689
5690   if (X86::isMOVDDUPMask(SVOp) && HasSSE3 && V2IsUndef &&
5691       RelaxedMayFoldVectorLoad(V1))
5692     return getMOVDDup(Op, dl, V1, DAG);
5693
5694   if (X86::isMOVHLPS_v_undef_Mask(SVOp))
5695     return getMOVHighToLow(Op, dl, DAG);
5696
5697   // Use to match splats
5698   if (HasSSE2 && X86::isUNPCKHMask(SVOp) && V2IsUndef &&
5699       (VT == MVT::v2f64 || VT == MVT::v2i64))
5700     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5701
5702   if (X86::isPSHUFDMask(SVOp)) {
5703     // The actual implementation will match the mask in the if above and then
5704     // during isel it can match several different instructions, not only pshufd
5705     // as its name says, sad but true, emulate the behavior for now...
5706     if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
5707         return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
5708
5709     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5710
5711     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
5712       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
5713
5714     if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5715       return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V1,
5716                                   TargetMask, DAG);
5717
5718     if (VT == MVT::v4f32)
5719       return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V1,
5720                                   TargetMask, DAG);
5721   }
5722
5723   // Check if this can be converted into a logical shift.
5724   bool isLeft = false;
5725   unsigned ShAmt = 0;
5726   SDValue ShVal;
5727   bool isShift = getSubtarget()->hasSSE2() &&
5728     isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
5729   if (isShift && ShVal.hasOneUse()) {
5730     // If the shifted value has multiple uses, it may be cheaper to use
5731     // v_set0 + movlhps or movhlps, etc.
5732     EVT EltVT = VT.getVectorElementType();
5733     ShAmt *= EltVT.getSizeInBits();
5734     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5735   }
5736
5737   if (X86::isMOVLMask(SVOp)) {
5738     if (V1IsUndef)
5739       return V2;
5740     if (ISD::isBuildVectorAllZeros(V1.getNode()))
5741       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
5742     if (!X86::isMOVLPMask(SVOp)) {
5743       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5744         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5745
5746       if (VT == MVT::v4i32 || VT == MVT::v4f32)
5747         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5748     }
5749   }
5750
5751   // FIXME: fold these into legal mask.
5752   if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp))
5753     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
5754
5755   if (X86::isMOVHLPSMask(SVOp))
5756     return getMOVHighToLow(Op, dl, DAG);
5757
5758   if (X86::isMOVSHDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5759     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
5760
5761   if (X86::isMOVSLDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5762     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
5763
5764   if (X86::isMOVLPMask(SVOp))
5765     return getMOVLP(Op, dl, DAG, HasSSE2);
5766
5767   if (ShouldXformToMOVHLPS(SVOp) ||
5768       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
5769     return CommuteVectorShuffle(SVOp, DAG);
5770
5771   if (isShift) {
5772     // No better options. Use a vshl / vsrl.
5773     EVT EltVT = VT.getVectorElementType();
5774     ShAmt *= EltVT.getSizeInBits();
5775     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5776   }
5777
5778   bool Commuted = false;
5779   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
5780   // 1,1,1,1 -> v8i16 though.
5781   V1IsSplat = isSplatVector(V1.getNode());
5782   V2IsSplat = isSplatVector(V2.getNode());
5783
5784   // Canonicalize the splat or undef, if present, to be on the RHS.
5785   if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
5786     Op = CommuteVectorShuffle(SVOp, DAG);
5787     SVOp = cast<ShuffleVectorSDNode>(Op);
5788     V1 = SVOp->getOperand(0);
5789     V2 = SVOp->getOperand(1);
5790     std::swap(V1IsSplat, V2IsSplat);
5791     std::swap(V1IsUndef, V2IsUndef);
5792     Commuted = true;
5793   }
5794
5795   if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
5796     // Shuffling low element of v1 into undef, just return v1.
5797     if (V2IsUndef)
5798       return V1;
5799     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
5800     // the instruction selector will not match, so get a canonical MOVL with
5801     // swapped operands to undo the commute.
5802     return getMOVL(DAG, dl, VT, V2, V1);
5803   }
5804
5805   if (X86::isUNPCKLMask(SVOp))
5806     return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
5807                                 dl, VT, V1, V2, DAG);
5808
5809   if (X86::isUNPCKHMask(SVOp))
5810     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG);
5811
5812   if (V2IsSplat) {
5813     // Normalize mask so all entries that point to V2 points to its first
5814     // element then try to match unpck{h|l} again. If match, return a
5815     // new vector_shuffle with the corrected mask.
5816     SDValue NewMask = NormalizeMask(SVOp, DAG);
5817     ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
5818     if (NSVOp != SVOp) {
5819       if (X86::isUNPCKLMask(NSVOp, true)) {
5820         return NewMask;
5821       } else if (X86::isUNPCKHMask(NSVOp, true)) {
5822         return NewMask;
5823       }
5824     }
5825   }
5826
5827   if (Commuted) {
5828     // Commute is back and try unpck* again.
5829     // FIXME: this seems wrong.
5830     SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
5831     ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
5832
5833     if (X86::isUNPCKLMask(NewSVOp))
5834       return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
5835                                   dl, VT, V2, V1, DAG);
5836
5837     if (X86::isUNPCKHMask(NewSVOp))
5838       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG);
5839   }
5840
5841   // Normalize the node to match x86 shuffle ops if needed
5842   if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
5843     return CommuteVectorShuffle(SVOp, DAG);
5844
5845   // The checks below are all present in isShuffleMaskLegal, but they are
5846   // inlined here right now to enable us to directly emit target specific
5847   // nodes, and remove one by one until they don't return Op anymore.
5848   SmallVector<int, 16> M;
5849   SVOp->getMask(M);
5850
5851   if (isPALIGNRMask(M, VT, HasSSSE3))
5852     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
5853                                 X86::getShufflePALIGNRImmediate(SVOp),
5854                                 DAG);
5855
5856   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
5857       SVOp->getSplatIndex() == 0 && V2IsUndef) {
5858     if (VT == MVT::v2f64) {
5859       X86ISD::NodeType Opcode =
5860         getSubtarget()->hasAVX() ? X86ISD::VUNPCKLPD : X86ISD::UNPCKLPD;
5861       return getTargetShuffleNode(Opcode, dl, VT, V1, V1, DAG);
5862     }
5863     if (VT == MVT::v2i64)
5864       return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
5865   }
5866
5867   if (isPSHUFHWMask(M, VT))
5868     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
5869                                 X86::getShufflePSHUFHWImmediate(SVOp),
5870                                 DAG);
5871
5872   if (isPSHUFLWMask(M, VT))
5873     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
5874                                 X86::getShufflePSHUFLWImmediate(SVOp),
5875                                 DAG);
5876
5877   if (isSHUFPMask(M, VT)) {
5878     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5879     if (VT == MVT::v4f32 || VT == MVT::v4i32)
5880       return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V2,
5881                                   TargetMask, DAG);
5882     if (VT == MVT::v2f64 || VT == MVT::v2i64)
5883       return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V2,
5884                                   TargetMask, DAG);
5885   }
5886
5887   if (X86::isUNPCKL_v_undef_Mask(SVOp))
5888     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5889       return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
5890                                   dl, VT, V1, V1, DAG);
5891   if (X86::isUNPCKH_v_undef_Mask(SVOp))
5892     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5893       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5894
5895   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
5896   if (VT == MVT::v8i16) {
5897     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
5898     if (NewOp.getNode())
5899       return NewOp;
5900   }
5901
5902   if (VT == MVT::v16i8) {
5903     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
5904     if (NewOp.getNode())
5905       return NewOp;
5906   }
5907
5908   // Handle all 4 wide cases with a number of shuffles.
5909   if (NumElems == 4)
5910     return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
5911
5912   return SDValue();
5913 }
5914
5915 SDValue
5916 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
5917                                                 SelectionDAG &DAG) const {
5918   EVT VT = Op.getValueType();
5919   DebugLoc dl = Op.getDebugLoc();
5920   if (VT.getSizeInBits() == 8) {
5921     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
5922                                     Op.getOperand(0), Op.getOperand(1));
5923     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
5924                                     DAG.getValueType(VT));
5925     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5926   } else if (VT.getSizeInBits() == 16) {
5927     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5928     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
5929     if (Idx == 0)
5930       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
5931                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5932                                      DAG.getNode(ISD::BITCAST, dl,
5933                                                  MVT::v4i32,
5934                                                  Op.getOperand(0)),
5935                                      Op.getOperand(1)));
5936     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
5937                                     Op.getOperand(0), Op.getOperand(1));
5938     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
5939                                     DAG.getValueType(VT));
5940     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5941   } else if (VT == MVT::f32) {
5942     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
5943     // the result back to FR32 register. It's only worth matching if the
5944     // result has a single use which is a store or a bitcast to i32.  And in
5945     // the case of a store, it's not worth it if the index is a constant 0,
5946     // because a MOVSSmr can be used instead, which is smaller and faster.
5947     if (!Op.hasOneUse())
5948       return SDValue();
5949     SDNode *User = *Op.getNode()->use_begin();
5950     if ((User->getOpcode() != ISD::STORE ||
5951          (isa<ConstantSDNode>(Op.getOperand(1)) &&
5952           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
5953         (User->getOpcode() != ISD::BITCAST ||
5954          User->getValueType(0) != MVT::i32))
5955       return SDValue();
5956     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5957                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
5958                                               Op.getOperand(0)),
5959                                               Op.getOperand(1));
5960     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
5961   } else if (VT == MVT::i32) {
5962     // ExtractPS works with constant index.
5963     if (isa<ConstantSDNode>(Op.getOperand(1)))
5964       return Op;
5965   }
5966   return SDValue();
5967 }
5968
5969
5970 SDValue
5971 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
5972                                            SelectionDAG &DAG) const {
5973   if (!isa<ConstantSDNode>(Op.getOperand(1)))
5974     return SDValue();
5975
5976   SDValue Vec = Op.getOperand(0);
5977   EVT VecVT = Vec.getValueType();
5978
5979   // If this is a 256-bit vector result, first extract the 128-bit
5980   // vector and then extract from the 128-bit vector.
5981   if (VecVT.getSizeInBits() > 128) {
5982     DebugLoc dl = Op.getNode()->getDebugLoc();
5983     unsigned NumElems = VecVT.getVectorNumElements();
5984     SDValue Idx = Op.getOperand(1);
5985
5986     if (!isa<ConstantSDNode>(Idx))
5987       return SDValue();
5988
5989     unsigned ExtractNumElems = NumElems / (VecVT.getSizeInBits() / 128);
5990     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
5991
5992     // Get the 128-bit vector.
5993     bool Upper = IdxVal >= ExtractNumElems;
5994     Vec = Extract128BitVector(Vec, Idx, DAG, dl);
5995
5996     // Extract from it.
5997     SDValue ScaledIdx = Idx;
5998     if (Upper)
5999       ScaledIdx = DAG.getNode(ISD::SUB, dl, Idx.getValueType(), Idx,
6000                               DAG.getConstant(ExtractNumElems,
6001                                               Idx.getValueType()));
6002     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6003                        ScaledIdx);
6004   }
6005
6006   assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
6007
6008   if (Subtarget->hasSSE41()) {
6009     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6010     if (Res.getNode())
6011       return Res;
6012   }
6013
6014   EVT VT = Op.getValueType();
6015   DebugLoc dl = Op.getDebugLoc();
6016   // TODO: handle v16i8.
6017   if (VT.getSizeInBits() == 16) {
6018     SDValue Vec = Op.getOperand(0);
6019     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6020     if (Idx == 0)
6021       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6022                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6023                                      DAG.getNode(ISD::BITCAST, dl,
6024                                                  MVT::v4i32, Vec),
6025                                      Op.getOperand(1)));
6026     // Transform it so it match pextrw which produces a 32-bit result.
6027     EVT EltVT = MVT::i32;
6028     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6029                                     Op.getOperand(0), Op.getOperand(1));
6030     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6031                                     DAG.getValueType(VT));
6032     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6033   } else if (VT.getSizeInBits() == 32) {
6034     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6035     if (Idx == 0)
6036       return Op;
6037
6038     // SHUFPS the element to the lowest double word, then movss.
6039     int Mask[4] = { Idx, -1, -1, -1 };
6040     EVT VVT = Op.getOperand(0).getValueType();
6041     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6042                                        DAG.getUNDEF(VVT), Mask);
6043     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6044                        DAG.getIntPtrConstant(0));
6045   } else if (VT.getSizeInBits() == 64) {
6046     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6047     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6048     //        to match extract_elt for f64.
6049     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6050     if (Idx == 0)
6051       return Op;
6052
6053     // UNPCKHPD the element to the lowest double word, then movsd.
6054     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
6055     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
6056     int Mask[2] = { 1, -1 };
6057     EVT VVT = Op.getOperand(0).getValueType();
6058     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6059                                        DAG.getUNDEF(VVT), Mask);
6060     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6061                        DAG.getIntPtrConstant(0));
6062   }
6063
6064   return SDValue();
6065 }
6066
6067 SDValue
6068 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
6069                                                SelectionDAG &DAG) const {
6070   EVT VT = Op.getValueType();
6071   EVT EltVT = VT.getVectorElementType();
6072   DebugLoc dl = Op.getDebugLoc();
6073
6074   SDValue N0 = Op.getOperand(0);
6075   SDValue N1 = Op.getOperand(1);
6076   SDValue N2 = Op.getOperand(2);
6077
6078   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
6079       isa<ConstantSDNode>(N2)) {
6080     unsigned Opc;
6081     if (VT == MVT::v8i16)
6082       Opc = X86ISD::PINSRW;
6083     else if (VT == MVT::v16i8)
6084       Opc = X86ISD::PINSRB;
6085     else
6086       Opc = X86ISD::PINSRB;
6087
6088     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
6089     // argument.
6090     if (N1.getValueType() != MVT::i32)
6091       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6092     if (N2.getValueType() != MVT::i32)
6093       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6094     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
6095   } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
6096     // Bits [7:6] of the constant are the source select.  This will always be
6097     //  zero here.  The DAG Combiner may combine an extract_elt index into these
6098     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
6099     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
6100     // Bits [5:4] of the constant are the destination select.  This is the
6101     //  value of the incoming immediate.
6102     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
6103     //   combine either bitwise AND or insert of float 0.0 to set these bits.
6104     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
6105     // Create this as a scalar to vector..
6106     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
6107     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
6108   } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
6109     // PINSR* works with constant index.
6110     return Op;
6111   }
6112   return SDValue();
6113 }
6114
6115 SDValue
6116 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
6117   EVT VT = Op.getValueType();
6118   EVT EltVT = VT.getVectorElementType();
6119
6120   DebugLoc dl = Op.getDebugLoc();
6121   SDValue N0 = Op.getOperand(0);
6122   SDValue N1 = Op.getOperand(1);
6123   SDValue N2 = Op.getOperand(2);
6124
6125   // If this is a 256-bit vector result, first insert into a 128-bit
6126   // vector and then insert into the 256-bit vector.
6127   if (VT.getSizeInBits() > 128) {
6128     if (!isa<ConstantSDNode>(N2))
6129       return SDValue();
6130
6131     // Get the 128-bit vector.
6132     unsigned NumElems = VT.getVectorNumElements();
6133     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
6134     bool Upper = IdxVal >= NumElems / 2;
6135
6136     SDValue SubN0 = Extract128BitVector(N0, N2, DAG, dl);
6137
6138     // Insert into it.
6139     SDValue ScaledN2 = N2;
6140     if (Upper)
6141       ScaledN2 = DAG.getNode(ISD::SUB, dl, N2.getValueType(), N2,
6142                              DAG.getConstant(NumElems /
6143                                              (VT.getSizeInBits() / 128),
6144                                              N2.getValueType()));
6145     Op = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubN0.getValueType(), SubN0,
6146                      N1, ScaledN2);
6147
6148     // Insert the 128-bit vector
6149     // FIXME: Why UNDEF?
6150     return Insert128BitVector(N0, Op, N2, DAG, dl);
6151   }
6152
6153   if (Subtarget->hasSSE41())
6154     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
6155
6156   if (EltVT == MVT::i8)
6157     return SDValue();
6158
6159   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
6160     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
6161     // as its second argument.
6162     if (N1.getValueType() != MVT::i32)
6163       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6164     if (N2.getValueType() != MVT::i32)
6165       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6166     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
6167   }
6168   return SDValue();
6169 }
6170
6171 SDValue
6172 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6173   LLVMContext *Context = DAG.getContext();
6174   DebugLoc dl = Op.getDebugLoc();
6175   EVT OpVT = Op.getValueType();
6176
6177   // If this is a 256-bit vector result, first insert into a 128-bit
6178   // vector and then insert into the 256-bit vector.
6179   if (OpVT.getSizeInBits() > 128) {
6180     // Insert into a 128-bit vector.
6181     EVT VT128 = EVT::getVectorVT(*Context,
6182                                  OpVT.getVectorElementType(),
6183                                  OpVT.getVectorNumElements() / 2);
6184
6185     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
6186
6187     // Insert the 128-bit vector.
6188     return Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, OpVT), Op,
6189                               DAG.getConstant(0, MVT::i32),
6190                               DAG, dl);
6191   }
6192
6193   if (Op.getValueType() == MVT::v1i64 &&
6194       Op.getOperand(0).getValueType() == MVT::i64)
6195     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
6196
6197   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
6198   assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
6199          "Expected an SSE type!");
6200   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
6201                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
6202 }
6203
6204 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
6205 // a simple subregister reference or explicit instructions to grab
6206 // upper bits of a vector.
6207 SDValue
6208 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6209   if (Subtarget->hasAVX()) {
6210     DebugLoc dl = Op.getNode()->getDebugLoc();
6211     SDValue Vec = Op.getNode()->getOperand(0);
6212     SDValue Idx = Op.getNode()->getOperand(1);
6213
6214     if (Op.getNode()->getValueType(0).getSizeInBits() == 128
6215         && Vec.getNode()->getValueType(0).getSizeInBits() == 256) {
6216         return Extract128BitVector(Vec, Idx, DAG, dl);
6217     }
6218   }
6219   return SDValue();
6220 }
6221
6222 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
6223 // simple superregister reference or explicit instructions to insert
6224 // the upper bits of a vector.
6225 SDValue
6226 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6227   if (Subtarget->hasAVX()) {
6228     DebugLoc dl = Op.getNode()->getDebugLoc();
6229     SDValue Vec = Op.getNode()->getOperand(0);
6230     SDValue SubVec = Op.getNode()->getOperand(1);
6231     SDValue Idx = Op.getNode()->getOperand(2);
6232
6233     if (Op.getNode()->getValueType(0).getSizeInBits() == 256
6234         && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) {
6235       return Insert128BitVector(Vec, SubVec, Idx, DAG, dl);
6236     }
6237   }
6238   return SDValue();
6239 }
6240
6241 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
6242 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
6243 // one of the above mentioned nodes. It has to be wrapped because otherwise
6244 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
6245 // be used to form addressing mode. These wrapped nodes will be selected
6246 // into MOV32ri.
6247 SDValue
6248 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
6249   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
6250
6251   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6252   // global base reg.
6253   unsigned char OpFlag = 0;
6254   unsigned WrapperKind = X86ISD::Wrapper;
6255   CodeModel::Model M = getTargetMachine().getCodeModel();
6256
6257   if (Subtarget->isPICStyleRIPRel() &&
6258       (M == CodeModel::Small || M == CodeModel::Kernel))
6259     WrapperKind = X86ISD::WrapperRIP;
6260   else if (Subtarget->isPICStyleGOT())
6261     OpFlag = X86II::MO_GOTOFF;
6262   else if (Subtarget->isPICStyleStubPIC())
6263     OpFlag = X86II::MO_PIC_BASE_OFFSET;
6264
6265   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
6266                                              CP->getAlignment(),
6267                                              CP->getOffset(), OpFlag);
6268   DebugLoc DL = CP->getDebugLoc();
6269   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6270   // With PIC, the address is actually $g + Offset.
6271   if (OpFlag) {
6272     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6273                          DAG.getNode(X86ISD::GlobalBaseReg,
6274                                      DebugLoc(), getPointerTy()),
6275                          Result);
6276   }
6277
6278   return Result;
6279 }
6280
6281 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
6282   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
6283
6284   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6285   // global base reg.
6286   unsigned char OpFlag = 0;
6287   unsigned WrapperKind = X86ISD::Wrapper;
6288   CodeModel::Model M = getTargetMachine().getCodeModel();
6289
6290   if (Subtarget->isPICStyleRIPRel() &&
6291       (M == CodeModel::Small || M == CodeModel::Kernel))
6292     WrapperKind = X86ISD::WrapperRIP;
6293   else if (Subtarget->isPICStyleGOT())
6294     OpFlag = X86II::MO_GOTOFF;
6295   else if (Subtarget->isPICStyleStubPIC())
6296     OpFlag = X86II::MO_PIC_BASE_OFFSET;
6297
6298   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
6299                                           OpFlag);
6300   DebugLoc DL = JT->getDebugLoc();
6301   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6302
6303   // With PIC, the address is actually $g + Offset.
6304   if (OpFlag)
6305     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6306                          DAG.getNode(X86ISD::GlobalBaseReg,
6307                                      DebugLoc(), getPointerTy()),
6308                          Result);
6309
6310   return Result;
6311 }
6312
6313 SDValue
6314 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
6315   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
6316
6317   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6318   // global base reg.
6319   unsigned char OpFlag = 0;
6320   unsigned WrapperKind = X86ISD::Wrapper;
6321   CodeModel::Model M = getTargetMachine().getCodeModel();
6322
6323   if (Subtarget->isPICStyleRIPRel() &&
6324       (M == CodeModel::Small || M == CodeModel::Kernel))
6325     WrapperKind = X86ISD::WrapperRIP;
6326   else if (Subtarget->isPICStyleGOT())
6327     OpFlag = X86II::MO_GOTOFF;
6328   else if (Subtarget->isPICStyleStubPIC())
6329     OpFlag = X86II::MO_PIC_BASE_OFFSET;
6330
6331   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
6332
6333   DebugLoc DL = Op.getDebugLoc();
6334   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6335
6336
6337   // With PIC, the address is actually $g + Offset.
6338   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
6339       !Subtarget->is64Bit()) {
6340     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6341                          DAG.getNode(X86ISD::GlobalBaseReg,
6342                                      DebugLoc(), getPointerTy()),
6343                          Result);
6344   }
6345
6346   return Result;
6347 }
6348
6349 SDValue
6350 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
6351   // Create the TargetBlockAddressAddress node.
6352   unsigned char OpFlags =
6353     Subtarget->ClassifyBlockAddressReference();
6354   CodeModel::Model M = getTargetMachine().getCodeModel();
6355   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
6356   DebugLoc dl = Op.getDebugLoc();
6357   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
6358                                        /*isTarget=*/true, OpFlags);
6359
6360   if (Subtarget->isPICStyleRIPRel() &&
6361       (M == CodeModel::Small || M == CodeModel::Kernel))
6362     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6363   else
6364     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6365
6366   // With PIC, the address is actually $g + Offset.
6367   if (isGlobalRelativeToPICBase(OpFlags)) {
6368     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6369                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6370                          Result);
6371   }
6372
6373   return Result;
6374 }
6375
6376 SDValue
6377 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
6378                                       int64_t Offset,
6379                                       SelectionDAG &DAG) const {
6380   // Create the TargetGlobalAddress node, folding in the constant
6381   // offset if it is legal.
6382   unsigned char OpFlags =
6383     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
6384   CodeModel::Model M = getTargetMachine().getCodeModel();
6385   SDValue Result;
6386   if (OpFlags == X86II::MO_NO_FLAG &&
6387       X86::isOffsetSuitableForCodeModel(Offset, M)) {
6388     // A direct static reference to a global.
6389     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
6390     Offset = 0;
6391   } else {
6392     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
6393   }
6394
6395   if (Subtarget->isPICStyleRIPRel() &&
6396       (M == CodeModel::Small || M == CodeModel::Kernel))
6397     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6398   else
6399     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6400
6401   // With PIC, the address is actually $g + Offset.
6402   if (isGlobalRelativeToPICBase(OpFlags)) {
6403     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6404                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6405                          Result);
6406   }
6407
6408   // For globals that require a load from a stub to get the address, emit the
6409   // load.
6410   if (isGlobalStubReference(OpFlags))
6411     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
6412                          MachinePointerInfo::getGOT(), false, false, 0);
6413
6414   // If there was a non-zero offset that we didn't fold, create an explicit
6415   // addition for it.
6416   if (Offset != 0)
6417     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
6418                          DAG.getConstant(Offset, getPointerTy()));
6419
6420   return Result;
6421 }
6422
6423 SDValue
6424 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
6425   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
6426   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
6427   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
6428 }
6429
6430 static SDValue
6431 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
6432            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
6433            unsigned char OperandFlags) {
6434   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6435   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6436   DebugLoc dl = GA->getDebugLoc();
6437   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6438                                            GA->getValueType(0),
6439                                            GA->getOffset(),
6440                                            OperandFlags);
6441   if (InFlag) {
6442     SDValue Ops[] = { Chain,  TGA, *InFlag };
6443     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
6444   } else {
6445     SDValue Ops[]  = { Chain, TGA };
6446     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
6447   }
6448
6449   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
6450   MFI->setAdjustsStack(true);
6451
6452   SDValue Flag = Chain.getValue(1);
6453   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
6454 }
6455
6456 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
6457 static SDValue
6458 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6459                                 const EVT PtrVT) {
6460   SDValue InFlag;
6461   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
6462   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
6463                                      DAG.getNode(X86ISD::GlobalBaseReg,
6464                                                  DebugLoc(), PtrVT), InFlag);
6465   InFlag = Chain.getValue(1);
6466
6467   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
6468 }
6469
6470 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
6471 static SDValue
6472 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6473                                 const EVT PtrVT) {
6474   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
6475                     X86::RAX, X86II::MO_TLSGD);
6476 }
6477
6478 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
6479 // "local exec" model.
6480 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6481                                    const EVT PtrVT, TLSModel::Model model,
6482                                    bool is64Bit) {
6483   DebugLoc dl = GA->getDebugLoc();
6484
6485   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
6486   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
6487                                                          is64Bit ? 257 : 256));
6488
6489   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
6490                                       DAG.getIntPtrConstant(0),
6491                                       MachinePointerInfo(Ptr), false, false, 0);
6492
6493   unsigned char OperandFlags = 0;
6494   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
6495   // initialexec.
6496   unsigned WrapperKind = X86ISD::Wrapper;
6497   if (model == TLSModel::LocalExec) {
6498     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
6499   } else if (is64Bit) {
6500     assert(model == TLSModel::InitialExec);
6501     OperandFlags = X86II::MO_GOTTPOFF;
6502     WrapperKind = X86ISD::WrapperRIP;
6503   } else {
6504     assert(model == TLSModel::InitialExec);
6505     OperandFlags = X86II::MO_INDNTPOFF;
6506   }
6507
6508   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
6509   // exec)
6510   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6511                                            GA->getValueType(0),
6512                                            GA->getOffset(), OperandFlags);
6513   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
6514
6515   if (model == TLSModel::InitialExec)
6516     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
6517                          MachinePointerInfo::getGOT(), false, false, 0);
6518
6519   // The address of the thread local variable is the add of the thread
6520   // pointer with the offset of the variable.
6521   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
6522 }
6523
6524 SDValue
6525 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
6526
6527   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
6528   const GlobalValue *GV = GA->getGlobal();
6529
6530   if (Subtarget->isTargetELF()) {
6531     // TODO: implement the "local dynamic" model
6532     // TODO: implement the "initial exec"model for pic executables
6533
6534     // If GV is an alias then use the aliasee for determining
6535     // thread-localness.
6536     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
6537       GV = GA->resolveAliasedGlobal(false);
6538
6539     TLSModel::Model model
6540       = getTLSModel(GV, getTargetMachine().getRelocationModel());
6541
6542     switch (model) {
6543       case TLSModel::GeneralDynamic:
6544       case TLSModel::LocalDynamic: // not implemented
6545         if (Subtarget->is64Bit())
6546           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
6547         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
6548
6549       case TLSModel::InitialExec:
6550       case TLSModel::LocalExec:
6551         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
6552                                    Subtarget->is64Bit());
6553     }
6554   } else if (Subtarget->isTargetDarwin()) {
6555     // Darwin only has one model of TLS.  Lower to that.
6556     unsigned char OpFlag = 0;
6557     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
6558                            X86ISD::WrapperRIP : X86ISD::Wrapper;
6559
6560     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6561     // global base reg.
6562     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
6563                   !Subtarget->is64Bit();
6564     if (PIC32)
6565       OpFlag = X86II::MO_TLVP_PIC_BASE;
6566     else
6567       OpFlag = X86II::MO_TLVP;
6568     DebugLoc DL = Op.getDebugLoc();
6569     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
6570                                                 GA->getValueType(0),
6571                                                 GA->getOffset(), OpFlag);
6572     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6573
6574     // With PIC32, the address is actually $g + Offset.
6575     if (PIC32)
6576       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6577                            DAG.getNode(X86ISD::GlobalBaseReg,
6578                                        DebugLoc(), getPointerTy()),
6579                            Offset);
6580
6581     // Lowering the machine isd will make sure everything is in the right
6582     // location.
6583     SDValue Chain = DAG.getEntryNode();
6584     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6585     SDValue Args[] = { Chain, Offset };
6586     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
6587
6588     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
6589     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6590     MFI->setAdjustsStack(true);
6591
6592     // And our return value (tls address) is in the standard call return value
6593     // location.
6594     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
6595     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
6596   }
6597
6598   assert(false &&
6599          "TLS not implemented for this target.");
6600
6601   llvm_unreachable("Unreachable");
6602   return SDValue();
6603 }
6604
6605
6606 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
6607 /// take a 2 x i32 value to shift plus a shift amount.
6608 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
6609   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6610   EVT VT = Op.getValueType();
6611   unsigned VTBits = VT.getSizeInBits();
6612   DebugLoc dl = Op.getDebugLoc();
6613   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
6614   SDValue ShOpLo = Op.getOperand(0);
6615   SDValue ShOpHi = Op.getOperand(1);
6616   SDValue ShAmt  = Op.getOperand(2);
6617   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
6618                                      DAG.getConstant(VTBits - 1, MVT::i8))
6619                        : DAG.getConstant(0, VT);
6620
6621   SDValue Tmp2, Tmp3;
6622   if (Op.getOpcode() == ISD::SHL_PARTS) {
6623     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
6624     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
6625   } else {
6626     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
6627     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
6628   }
6629
6630   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
6631                                 DAG.getConstant(VTBits, MVT::i8));
6632   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
6633                              AndNode, DAG.getConstant(0, MVT::i8));
6634
6635   SDValue Hi, Lo;
6636   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6637   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
6638   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
6639
6640   if (Op.getOpcode() == ISD::SHL_PARTS) {
6641     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6642     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6643   } else {
6644     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6645     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6646   }
6647
6648   SDValue Ops[2] = { Lo, Hi };
6649   return DAG.getMergeValues(Ops, 2, dl);
6650 }
6651
6652 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
6653                                            SelectionDAG &DAG) const {
6654   EVT SrcVT = Op.getOperand(0).getValueType();
6655
6656   if (SrcVT.isVector())
6657     return SDValue();
6658
6659   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
6660          "Unknown SINT_TO_FP to lower!");
6661
6662   // These are really Legal; return the operand so the caller accepts it as
6663   // Legal.
6664   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
6665     return Op;
6666   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
6667       Subtarget->is64Bit()) {
6668     return Op;
6669   }
6670
6671   DebugLoc dl = Op.getDebugLoc();
6672   unsigned Size = SrcVT.getSizeInBits()/8;
6673   MachineFunction &MF = DAG.getMachineFunction();
6674   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
6675   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6676   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6677                                StackSlot,
6678                                MachinePointerInfo::getFixedStack(SSFI),
6679                                false, false, 0);
6680   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
6681 }
6682
6683 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
6684                                      SDValue StackSlot,
6685                                      SelectionDAG &DAG) const {
6686   // Build the FILD
6687   DebugLoc DL = Op.getDebugLoc();
6688   SDVTList Tys;
6689   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
6690   if (useSSE)
6691     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
6692   else
6693     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
6694
6695   unsigned ByteSize = SrcVT.getSizeInBits()/8;
6696
6697   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
6698   MachineMemOperand *MMO =
6699     DAG.getMachineFunction()
6700     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6701                           MachineMemOperand::MOLoad, ByteSize, ByteSize);
6702
6703   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
6704   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
6705                                            X86ISD::FILD, DL,
6706                                            Tys, Ops, array_lengthof(Ops),
6707                                            SrcVT, MMO);
6708
6709   if (useSSE) {
6710     Chain = Result.getValue(1);
6711     SDValue InFlag = Result.getValue(2);
6712
6713     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
6714     // shouldn't be necessary except that RFP cannot be live across
6715     // multiple blocks. When stackifier is fixed, they can be uncoupled.
6716     MachineFunction &MF = DAG.getMachineFunction();
6717     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
6718     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
6719     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6720     Tys = DAG.getVTList(MVT::Other);
6721     SDValue Ops[] = {
6722       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
6723     };
6724     MachineMemOperand *MMO =
6725       DAG.getMachineFunction()
6726       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6727                             MachineMemOperand::MOStore, SSFISize, SSFISize);
6728
6729     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
6730                                     Ops, array_lengthof(Ops),
6731                                     Op.getValueType(), MMO);
6732     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
6733                          MachinePointerInfo::getFixedStack(SSFI),
6734                          false, false, 0);
6735   }
6736
6737   return Result;
6738 }
6739
6740 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
6741 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
6742                                                SelectionDAG &DAG) const {
6743   // This algorithm is not obvious. Here it is in C code, more or less:
6744   /*
6745     double uint64_to_double( uint32_t hi, uint32_t lo ) {
6746       static const __m128i exp = { 0x4330000045300000ULL, 0 };
6747       static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
6748
6749       // Copy ints to xmm registers.
6750       __m128i xh = _mm_cvtsi32_si128( hi );
6751       __m128i xl = _mm_cvtsi32_si128( lo );
6752
6753       // Combine into low half of a single xmm register.
6754       __m128i x = _mm_unpacklo_epi32( xh, xl );
6755       __m128d d;
6756       double sd;
6757
6758       // Merge in appropriate exponents to give the integer bits the right
6759       // magnitude.
6760       x = _mm_unpacklo_epi32( x, exp );
6761
6762       // Subtract away the biases to deal with the IEEE-754 double precision
6763       // implicit 1.
6764       d = _mm_sub_pd( (__m128d) x, bias );
6765
6766       // All conversions up to here are exact. The correctly rounded result is
6767       // calculated using the current rounding mode using the following
6768       // horizontal add.
6769       d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
6770       _mm_store_sd( &sd, d );   // Because we are returning doubles in XMM, this
6771                                 // store doesn't really need to be here (except
6772                                 // maybe to zero the other double)
6773       return sd;
6774     }
6775   */
6776
6777   DebugLoc dl = Op.getDebugLoc();
6778   LLVMContext *Context = DAG.getContext();
6779
6780   // Build some magic constants.
6781   std::vector<Constant*> CV0;
6782   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
6783   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
6784   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6785   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6786   Constant *C0 = ConstantVector::get(CV0);
6787   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
6788
6789   std::vector<Constant*> CV1;
6790   CV1.push_back(
6791     ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
6792   CV1.push_back(
6793     ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
6794   Constant *C1 = ConstantVector::get(CV1);
6795   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
6796
6797   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6798                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6799                                         Op.getOperand(0),
6800                                         DAG.getIntPtrConstant(1)));
6801   SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6802                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6803                                         Op.getOperand(0),
6804                                         DAG.getIntPtrConstant(0)));
6805   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
6806   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
6807                               MachinePointerInfo::getConstantPool(),
6808                               false, false, 16);
6809   SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
6810   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
6811   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
6812                               MachinePointerInfo::getConstantPool(),
6813                               false, false, 16);
6814   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
6815
6816   // Add the halves; easiest way is to swap them into another reg first.
6817   int ShufMask[2] = { 1, -1 };
6818   SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
6819                                       DAG.getUNDEF(MVT::v2f64), ShufMask);
6820   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
6821   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
6822                      DAG.getIntPtrConstant(0));
6823 }
6824
6825 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
6826 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
6827                                                SelectionDAG &DAG) const {
6828   DebugLoc dl = Op.getDebugLoc();
6829   // FP constant to bias correct the final result.
6830   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
6831                                    MVT::f64);
6832
6833   // Load the 32-bit value into an XMM register.
6834   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6835                              DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6836                                          Op.getOperand(0),
6837                                          DAG.getIntPtrConstant(0)));
6838
6839   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6840                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
6841                      DAG.getIntPtrConstant(0));
6842
6843   // Or the load with the bias.
6844   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
6845                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6846                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6847                                                    MVT::v2f64, Load)),
6848                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6849                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6850                                                    MVT::v2f64, Bias)));
6851   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6852                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
6853                    DAG.getIntPtrConstant(0));
6854
6855   // Subtract the bias.
6856   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
6857
6858   // Handle final rounding.
6859   EVT DestVT = Op.getValueType();
6860
6861   if (DestVT.bitsLT(MVT::f64)) {
6862     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
6863                        DAG.getIntPtrConstant(0));
6864   } else if (DestVT.bitsGT(MVT::f64)) {
6865     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
6866   }
6867
6868   // Handle final rounding.
6869   return Sub;
6870 }
6871
6872 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
6873                                            SelectionDAG &DAG) const {
6874   SDValue N0 = Op.getOperand(0);
6875   DebugLoc dl = Op.getDebugLoc();
6876
6877   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
6878   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
6879   // the optimization here.
6880   if (DAG.SignBitIsZero(N0))
6881     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
6882
6883   EVT SrcVT = N0.getValueType();
6884   EVT DstVT = Op.getValueType();
6885   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
6886     return LowerUINT_TO_FP_i64(Op, DAG);
6887   else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
6888     return LowerUINT_TO_FP_i32(Op, DAG);
6889
6890   // Make a 64-bit buffer, and use it to build an FILD.
6891   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
6892   if (SrcVT == MVT::i32) {
6893     SDValue WordOff = DAG.getConstant(4, getPointerTy());
6894     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
6895                                      getPointerTy(), StackSlot, WordOff);
6896     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6897                                   StackSlot, MachinePointerInfo(),
6898                                   false, false, 0);
6899     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
6900                                   OffsetSlot, MachinePointerInfo(),
6901                                   false, false, 0);
6902     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
6903     return Fild;
6904   }
6905
6906   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
6907   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6908                                 StackSlot, MachinePointerInfo(),
6909                                false, false, 0);
6910   // For i64 source, we need to add the appropriate power of 2 if the input
6911   // was negative.  This is the same as the optimization in
6912   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
6913   // we must be careful to do the computation in x87 extended precision, not
6914   // in SSE. (The generic code can't know it's OK to do this, or how to.)
6915   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
6916   MachineMemOperand *MMO =
6917     DAG.getMachineFunction()
6918     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6919                           MachineMemOperand::MOLoad, 8, 8);
6920
6921   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
6922   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
6923   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
6924                                          MVT::i64, MMO);
6925
6926   APInt FF(32, 0x5F800000ULL);
6927
6928   // Check whether the sign bit is set.
6929   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
6930                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
6931                                  ISD::SETLT);
6932
6933   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
6934   SDValue FudgePtr = DAG.getConstantPool(
6935                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
6936                                          getPointerTy());
6937
6938   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
6939   SDValue Zero = DAG.getIntPtrConstant(0);
6940   SDValue Four = DAG.getIntPtrConstant(4);
6941   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
6942                                Zero, Four);
6943   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
6944
6945   // Load the value out, extending it from f32 to f80.
6946   // FIXME: Avoid the extend by constructing the right constant pool?
6947   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
6948                                  FudgePtr, MachinePointerInfo::getConstantPool(),
6949                                  MVT::f32, false, false, 4);
6950   // Extend everything to 80 bits to force it to be done on x87.
6951   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
6952   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
6953 }
6954
6955 std::pair<SDValue,SDValue> X86TargetLowering::
6956 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
6957   DebugLoc DL = Op.getDebugLoc();
6958
6959   EVT DstTy = Op.getValueType();
6960
6961   if (!IsSigned) {
6962     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
6963     DstTy = MVT::i64;
6964   }
6965
6966   assert(DstTy.getSimpleVT() <= MVT::i64 &&
6967          DstTy.getSimpleVT() >= MVT::i16 &&
6968          "Unknown FP_TO_SINT to lower!");
6969
6970   // These are really Legal.
6971   if (DstTy == MVT::i32 &&
6972       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
6973     return std::make_pair(SDValue(), SDValue());
6974   if (Subtarget->is64Bit() &&
6975       DstTy == MVT::i64 &&
6976       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
6977     return std::make_pair(SDValue(), SDValue());
6978
6979   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
6980   // stack slot.
6981   MachineFunction &MF = DAG.getMachineFunction();
6982   unsigned MemSize = DstTy.getSizeInBits()/8;
6983   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
6984   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6985
6986
6987
6988   unsigned Opc;
6989   switch (DstTy.getSimpleVT().SimpleTy) {
6990   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
6991   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
6992   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
6993   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
6994   }
6995
6996   SDValue Chain = DAG.getEntryNode();
6997   SDValue Value = Op.getOperand(0);
6998   EVT TheVT = Op.getOperand(0).getValueType();
6999   if (isScalarFPTypeInSSEReg(TheVT)) {
7000     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
7001     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
7002                          MachinePointerInfo::getFixedStack(SSFI),
7003                          false, false, 0);
7004     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
7005     SDValue Ops[] = {
7006       Chain, StackSlot, DAG.getValueType(TheVT)
7007     };
7008
7009     MachineMemOperand *MMO =
7010       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7011                               MachineMemOperand::MOLoad, MemSize, MemSize);
7012     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
7013                                     DstTy, MMO);
7014     Chain = Value.getValue(1);
7015     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7016     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7017   }
7018
7019   MachineMemOperand *MMO =
7020     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7021                             MachineMemOperand::MOStore, MemSize, MemSize);
7022
7023   // Build the FP_TO_INT*_IN_MEM
7024   SDValue Ops[] = { Chain, Value, StackSlot };
7025   SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
7026                                          Ops, 3, DstTy, MMO);
7027
7028   return std::make_pair(FIST, StackSlot);
7029 }
7030
7031 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
7032                                            SelectionDAG &DAG) const {
7033   if (Op.getValueType().isVector())
7034     return SDValue();
7035
7036   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
7037   SDValue FIST = Vals.first, StackSlot = Vals.second;
7038   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
7039   if (FIST.getNode() == 0) return Op;
7040
7041   // Load the result.
7042   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7043                      FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7044 }
7045
7046 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
7047                                            SelectionDAG &DAG) const {
7048   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
7049   SDValue FIST = Vals.first, StackSlot = Vals.second;
7050   assert(FIST.getNode() && "Unexpected failure");
7051
7052   // Load the result.
7053   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7054                      FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7055 }
7056
7057 SDValue X86TargetLowering::LowerFABS(SDValue Op,
7058                                      SelectionDAG &DAG) const {
7059   LLVMContext *Context = DAG.getContext();
7060   DebugLoc dl = Op.getDebugLoc();
7061   EVT VT = Op.getValueType();
7062   EVT EltVT = VT;
7063   if (VT.isVector())
7064     EltVT = VT.getVectorElementType();
7065   std::vector<Constant*> CV;
7066   if (EltVT == MVT::f64) {
7067     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
7068     CV.push_back(C);
7069     CV.push_back(C);
7070   } else {
7071     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
7072     CV.push_back(C);
7073     CV.push_back(C);
7074     CV.push_back(C);
7075     CV.push_back(C);
7076   }
7077   Constant *C = ConstantVector::get(CV);
7078   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7079   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7080                              MachinePointerInfo::getConstantPool(),
7081                              false, false, 16);
7082   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
7083 }
7084
7085 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
7086   LLVMContext *Context = DAG.getContext();
7087   DebugLoc dl = Op.getDebugLoc();
7088   EVT VT = Op.getValueType();
7089   EVT EltVT = VT;
7090   if (VT.isVector())
7091     EltVT = VT.getVectorElementType();
7092   std::vector<Constant*> CV;
7093   if (EltVT == MVT::f64) {
7094     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
7095     CV.push_back(C);
7096     CV.push_back(C);
7097   } else {
7098     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
7099     CV.push_back(C);
7100     CV.push_back(C);
7101     CV.push_back(C);
7102     CV.push_back(C);
7103   }
7104   Constant *C = ConstantVector::get(CV);
7105   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7106   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7107                              MachinePointerInfo::getConstantPool(),
7108                              false, false, 16);
7109   if (VT.isVector()) {
7110     return DAG.getNode(ISD::BITCAST, dl, VT,
7111                        DAG.getNode(ISD::XOR, dl, MVT::v2i64,
7112                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7113                                 Op.getOperand(0)),
7114                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask)));
7115   } else {
7116     return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
7117   }
7118 }
7119
7120 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
7121   LLVMContext *Context = DAG.getContext();
7122   SDValue Op0 = Op.getOperand(0);
7123   SDValue Op1 = Op.getOperand(1);
7124   DebugLoc dl = Op.getDebugLoc();
7125   EVT VT = Op.getValueType();
7126   EVT SrcVT = Op1.getValueType();
7127
7128   // If second operand is smaller, extend it first.
7129   if (SrcVT.bitsLT(VT)) {
7130     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
7131     SrcVT = VT;
7132   }
7133   // And if it is bigger, shrink it first.
7134   if (SrcVT.bitsGT(VT)) {
7135     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
7136     SrcVT = VT;
7137   }
7138
7139   // At this point the operands and the result should have the same
7140   // type, and that won't be f80 since that is not custom lowered.
7141
7142   // First get the sign bit of second operand.
7143   std::vector<Constant*> CV;
7144   if (SrcVT == MVT::f64) {
7145     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
7146     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7147   } else {
7148     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
7149     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7150     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7151     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7152   }
7153   Constant *C = ConstantVector::get(CV);
7154   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7155   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
7156                               MachinePointerInfo::getConstantPool(),
7157                               false, false, 16);
7158   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
7159
7160   // Shift sign bit right or left if the two operands have different types.
7161   if (SrcVT.bitsGT(VT)) {
7162     // Op0 is MVT::f32, Op1 is MVT::f64.
7163     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
7164     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
7165                           DAG.getConstant(32, MVT::i32));
7166     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
7167     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
7168                           DAG.getIntPtrConstant(0));
7169   }
7170
7171   // Clear first operand sign bit.
7172   CV.clear();
7173   if (VT == MVT::f64) {
7174     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
7175     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7176   } else {
7177     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
7178     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7179     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7180     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7181   }
7182   C = ConstantVector::get(CV);
7183   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7184   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7185                               MachinePointerInfo::getConstantPool(),
7186                               false, false, 16);
7187   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
7188
7189   // Or the value with the sign bit.
7190   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
7191 }
7192
7193 /// Emit nodes that will be selected as "test Op0,Op0", or something
7194 /// equivalent.
7195 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
7196                                     SelectionDAG &DAG) const {
7197   DebugLoc dl = Op.getDebugLoc();
7198
7199   // CF and OF aren't always set the way we want. Determine which
7200   // of these we need.
7201   bool NeedCF = false;
7202   bool NeedOF = false;
7203   switch (X86CC) {
7204   default: break;
7205   case X86::COND_A: case X86::COND_AE:
7206   case X86::COND_B: case X86::COND_BE:
7207     NeedCF = true;
7208     break;
7209   case X86::COND_G: case X86::COND_GE:
7210   case X86::COND_L: case X86::COND_LE:
7211   case X86::COND_O: case X86::COND_NO:
7212     NeedOF = true;
7213     break;
7214   }
7215
7216   // See if we can use the EFLAGS value from the operand instead of
7217   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
7218   // we prove that the arithmetic won't overflow, we can't use OF or CF.
7219   if (Op.getResNo() != 0 || NeedOF || NeedCF)
7220     // Emit a CMP with 0, which is the TEST pattern.
7221     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
7222                        DAG.getConstant(0, Op.getValueType()));
7223
7224   unsigned Opcode = 0;
7225   unsigned NumOperands = 0;
7226   switch (Op.getNode()->getOpcode()) {
7227   case ISD::ADD:
7228     // Due to an isel shortcoming, be conservative if this add is likely to be
7229     // selected as part of a load-modify-store instruction. When the root node
7230     // in a match is a store, isel doesn't know how to remap non-chain non-flag
7231     // uses of other nodes in the match, such as the ADD in this case. This
7232     // leads to the ADD being left around and reselected, with the result being
7233     // two adds in the output.  Alas, even if none our users are stores, that
7234     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
7235     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
7236     // climbing the DAG back to the root, and it doesn't seem to be worth the
7237     // effort.
7238     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7239            UE = Op.getNode()->use_end(); UI != UE; ++UI)
7240       if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
7241         goto default_case;
7242
7243     if (ConstantSDNode *C =
7244         dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
7245       // An add of one will be selected as an INC.
7246       if (C->getAPIntValue() == 1) {
7247         Opcode = X86ISD::INC;
7248         NumOperands = 1;
7249         break;
7250       }
7251
7252       // An add of negative one (subtract of one) will be selected as a DEC.
7253       if (C->getAPIntValue().isAllOnesValue()) {
7254         Opcode = X86ISD::DEC;
7255         NumOperands = 1;
7256         break;
7257       }
7258     }
7259
7260     // Otherwise use a regular EFLAGS-setting add.
7261     Opcode = X86ISD::ADD;
7262     NumOperands = 2;
7263     break;
7264   case ISD::AND: {
7265     // If the primary and result isn't used, don't bother using X86ISD::AND,
7266     // because a TEST instruction will be better.
7267     bool NonFlagUse = false;
7268     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7269            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
7270       SDNode *User = *UI;
7271       unsigned UOpNo = UI.getOperandNo();
7272       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
7273         // Look pass truncate.
7274         UOpNo = User->use_begin().getOperandNo();
7275         User = *User->use_begin();
7276       }
7277
7278       if (User->getOpcode() != ISD::BRCOND &&
7279           User->getOpcode() != ISD::SETCC &&
7280           (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
7281         NonFlagUse = true;
7282         break;
7283       }
7284     }
7285
7286     if (!NonFlagUse)
7287       break;
7288   }
7289     // FALL THROUGH
7290   case ISD::SUB:
7291   case ISD::OR:
7292   case ISD::XOR:
7293     // Due to the ISEL shortcoming noted above, be conservative if this op is
7294     // likely to be selected as part of a load-modify-store instruction.
7295     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7296            UE = Op.getNode()->use_end(); UI != UE; ++UI)
7297       if (UI->getOpcode() == ISD::STORE)
7298         goto default_case;
7299
7300     // Otherwise use a regular EFLAGS-setting instruction.
7301     switch (Op.getNode()->getOpcode()) {
7302     default: llvm_unreachable("unexpected operator!");
7303     case ISD::SUB: Opcode = X86ISD::SUB; break;
7304     case ISD::OR:  Opcode = X86ISD::OR;  break;
7305     case ISD::XOR: Opcode = X86ISD::XOR; break;
7306     case ISD::AND: Opcode = X86ISD::AND; break;
7307     }
7308
7309     NumOperands = 2;
7310     break;
7311   case X86ISD::ADD:
7312   case X86ISD::SUB:
7313   case X86ISD::INC:
7314   case X86ISD::DEC:
7315   case X86ISD::OR:
7316   case X86ISD::XOR:
7317   case X86ISD::AND:
7318     return SDValue(Op.getNode(), 1);
7319   default:
7320   default_case:
7321     break;
7322   }
7323
7324   if (Opcode == 0)
7325     // Emit a CMP with 0, which is the TEST pattern.
7326     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
7327                        DAG.getConstant(0, Op.getValueType()));
7328
7329   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
7330   SmallVector<SDValue, 4> Ops;
7331   for (unsigned i = 0; i != NumOperands; ++i)
7332     Ops.push_back(Op.getOperand(i));
7333
7334   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
7335   DAG.ReplaceAllUsesWith(Op, New);
7336   return SDValue(New.getNode(), 1);
7337 }
7338
7339 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
7340 /// equivalent.
7341 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
7342                                    SelectionDAG &DAG) const {
7343   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
7344     if (C->getAPIntValue() == 0)
7345       return EmitTest(Op0, X86CC, DAG);
7346
7347   DebugLoc dl = Op0.getDebugLoc();
7348   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
7349 }
7350
7351 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
7352 /// if it's possible.
7353 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
7354                                      DebugLoc dl, SelectionDAG &DAG) const {
7355   SDValue Op0 = And.getOperand(0);
7356   SDValue Op1 = And.getOperand(1);
7357   if (Op0.getOpcode() == ISD::TRUNCATE)
7358     Op0 = Op0.getOperand(0);
7359   if (Op1.getOpcode() == ISD::TRUNCATE)
7360     Op1 = Op1.getOperand(0);
7361
7362   SDValue LHS, RHS;
7363   if (Op1.getOpcode() == ISD::SHL)
7364     std::swap(Op0, Op1);
7365   if (Op0.getOpcode() == ISD::SHL) {
7366     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
7367       if (And00C->getZExtValue() == 1) {
7368         // If we looked past a truncate, check that it's only truncating away
7369         // known zeros.
7370         unsigned BitWidth = Op0.getValueSizeInBits();
7371         unsigned AndBitWidth = And.getValueSizeInBits();
7372         if (BitWidth > AndBitWidth) {
7373           APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
7374           DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
7375           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
7376             return SDValue();
7377         }
7378         LHS = Op1;
7379         RHS = Op0.getOperand(1);
7380       }
7381   } else if (Op1.getOpcode() == ISD::Constant) {
7382     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
7383     SDValue AndLHS = Op0;
7384     if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
7385       LHS = AndLHS.getOperand(0);
7386       RHS = AndLHS.getOperand(1);
7387     }
7388   }
7389
7390   if (LHS.getNode()) {
7391     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
7392     // instruction.  Since the shift amount is in-range-or-undefined, we know
7393     // that doing a bittest on the i32 value is ok.  We extend to i32 because
7394     // the encoding for the i16 version is larger than the i32 version.
7395     // Also promote i16 to i32 for performance / code size reason.
7396     if (LHS.getValueType() == MVT::i8 ||
7397         LHS.getValueType() == MVT::i16)
7398       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
7399
7400     // If the operand types disagree, extend the shift amount to match.  Since
7401     // BT ignores high bits (like shifts) we can use anyextend.
7402     if (LHS.getValueType() != RHS.getValueType())
7403       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
7404
7405     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
7406     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
7407     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7408                        DAG.getConstant(Cond, MVT::i8), BT);
7409   }
7410
7411   return SDValue();
7412 }
7413
7414 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
7415   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
7416   SDValue Op0 = Op.getOperand(0);
7417   SDValue Op1 = Op.getOperand(1);
7418   DebugLoc dl = Op.getDebugLoc();
7419   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7420
7421   // Optimize to BT if possible.
7422   // Lower (X & (1 << N)) == 0 to BT(X, N).
7423   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
7424   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
7425   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
7426       Op1.getOpcode() == ISD::Constant &&
7427       cast<ConstantSDNode>(Op1)->isNullValue() &&
7428       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7429     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
7430     if (NewSetCC.getNode())
7431       return NewSetCC;
7432   }
7433
7434   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
7435   // these.
7436   if (Op1.getOpcode() == ISD::Constant &&
7437       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
7438        cast<ConstantSDNode>(Op1)->isNullValue()) &&
7439       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7440
7441     // If the input is a setcc, then reuse the input setcc or use a new one with
7442     // the inverted condition.
7443     if (Op0.getOpcode() == X86ISD::SETCC) {
7444       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
7445       bool Invert = (CC == ISD::SETNE) ^
7446         cast<ConstantSDNode>(Op1)->isNullValue();
7447       if (!Invert) return Op0;
7448
7449       CCode = X86::GetOppositeBranchCondition(CCode);
7450       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7451                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
7452     }
7453   }
7454
7455   bool isFP = Op1.getValueType().isFloatingPoint();
7456   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
7457   if (X86CC == X86::COND_INVALID)
7458     return SDValue();
7459
7460   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
7461   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7462                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
7463 }
7464
7465 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
7466   SDValue Cond;
7467   SDValue Op0 = Op.getOperand(0);
7468   SDValue Op1 = Op.getOperand(1);
7469   SDValue CC = Op.getOperand(2);
7470   EVT VT = Op.getValueType();
7471   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
7472   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
7473   DebugLoc dl = Op.getDebugLoc();
7474
7475   if (isFP) {
7476     unsigned SSECC = 8;
7477     EVT VT0 = Op0.getValueType();
7478     assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
7479     unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
7480     bool Swap = false;
7481
7482     switch (SetCCOpcode) {
7483     default: break;
7484     case ISD::SETOEQ:
7485     case ISD::SETEQ:  SSECC = 0; break;
7486     case ISD::SETOGT:
7487     case ISD::SETGT: Swap = true; // Fallthrough
7488     case ISD::SETLT:
7489     case ISD::SETOLT: SSECC = 1; break;
7490     case ISD::SETOGE:
7491     case ISD::SETGE: Swap = true; // Fallthrough
7492     case ISD::SETLE:
7493     case ISD::SETOLE: SSECC = 2; break;
7494     case ISD::SETUO:  SSECC = 3; break;
7495     case ISD::SETUNE:
7496     case ISD::SETNE:  SSECC = 4; break;
7497     case ISD::SETULE: Swap = true;
7498     case ISD::SETUGE: SSECC = 5; break;
7499     case ISD::SETULT: Swap = true;
7500     case ISD::SETUGT: SSECC = 6; break;
7501     case ISD::SETO:   SSECC = 7; break;
7502     }
7503     if (Swap)
7504       std::swap(Op0, Op1);
7505
7506     // In the two special cases we can't handle, emit two comparisons.
7507     if (SSECC == 8) {
7508       if (SetCCOpcode == ISD::SETUEQ) {
7509         SDValue UNORD, EQ;
7510         UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
7511         EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
7512         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
7513       }
7514       else if (SetCCOpcode == ISD::SETONE) {
7515         SDValue ORD, NEQ;
7516         ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
7517         NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
7518         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
7519       }
7520       llvm_unreachable("Illegal FP comparison");
7521     }
7522     // Handle all other FP comparisons here.
7523     return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
7524   }
7525
7526   // We are handling one of the integer comparisons here.  Since SSE only has
7527   // GT and EQ comparisons for integer, swapping operands and multiple
7528   // operations may be required for some comparisons.
7529   unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
7530   bool Swap = false, Invert = false, FlipSigns = false;
7531
7532   switch (VT.getSimpleVT().SimpleTy) {
7533   default: break;
7534   case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
7535   case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
7536   case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
7537   case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
7538   }
7539
7540   switch (SetCCOpcode) {
7541   default: break;
7542   case ISD::SETNE:  Invert = true;
7543   case ISD::SETEQ:  Opc = EQOpc; break;
7544   case ISD::SETLT:  Swap = true;
7545   case ISD::SETGT:  Opc = GTOpc; break;
7546   case ISD::SETGE:  Swap = true;
7547   case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
7548   case ISD::SETULT: Swap = true;
7549   case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
7550   case ISD::SETUGE: Swap = true;
7551   case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
7552   }
7553   if (Swap)
7554     std::swap(Op0, Op1);
7555
7556   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
7557   // bits of the inputs before performing those operations.
7558   if (FlipSigns) {
7559     EVT EltVT = VT.getVectorElementType();
7560     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
7561                                       EltVT);
7562     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
7563     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
7564                                     SignBits.size());
7565     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
7566     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
7567   }
7568
7569   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
7570
7571   // If the logical-not of the result is required, perform that now.
7572   if (Invert)
7573     Result = DAG.getNOT(dl, Result, VT);
7574
7575   return Result;
7576 }
7577
7578 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
7579 static bool isX86LogicalCmp(SDValue Op) {
7580   unsigned Opc = Op.getNode()->getOpcode();
7581   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
7582     return true;
7583   if (Op.getResNo() == 1 &&
7584       (Opc == X86ISD::ADD ||
7585        Opc == X86ISD::SUB ||
7586        Opc == X86ISD::ADC ||
7587        Opc == X86ISD::SBB ||
7588        Opc == X86ISD::SMUL ||
7589        Opc == X86ISD::UMUL ||
7590        Opc == X86ISD::INC ||
7591        Opc == X86ISD::DEC ||
7592        Opc == X86ISD::OR ||
7593        Opc == X86ISD::XOR ||
7594        Opc == X86ISD::AND))
7595     return true;
7596
7597   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
7598     return true;
7599
7600   return false;
7601 }
7602
7603 static bool isZero(SDValue V) {
7604   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7605   return C && C->isNullValue();
7606 }
7607
7608 static bool isAllOnes(SDValue V) {
7609   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7610   return C && C->isAllOnesValue();
7611 }
7612
7613 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
7614   bool addTest = true;
7615   SDValue Cond  = Op.getOperand(0);
7616   SDValue Op1 = Op.getOperand(1);
7617   SDValue Op2 = Op.getOperand(2);
7618   DebugLoc DL = Op.getDebugLoc();
7619   SDValue CC;
7620
7621   if (Cond.getOpcode() == ISD::SETCC) {
7622     SDValue NewCond = LowerSETCC(Cond, DAG);
7623     if (NewCond.getNode())
7624       Cond = NewCond;
7625   }
7626
7627   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
7628   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
7629   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
7630   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
7631   if (Cond.getOpcode() == X86ISD::SETCC &&
7632       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
7633       isZero(Cond.getOperand(1).getOperand(1))) {
7634     SDValue Cmp = Cond.getOperand(1);
7635
7636     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
7637
7638     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
7639         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
7640       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
7641
7642       SDValue CmpOp0 = Cmp.getOperand(0);
7643       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
7644                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
7645
7646       SDValue Res =   // Res = 0 or -1.
7647         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7648                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
7649
7650       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
7651         Res = DAG.getNOT(DL, Res, Res.getValueType());
7652
7653       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
7654       if (N2C == 0 || !N2C->isNullValue())
7655         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
7656       return Res;
7657     }
7658   }
7659
7660   // Look past (and (setcc_carry (cmp ...)), 1).
7661   if (Cond.getOpcode() == ISD::AND &&
7662       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7663     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7664     if (C && C->getAPIntValue() == 1)
7665       Cond = Cond.getOperand(0);
7666   }
7667
7668   // If condition flag is set by a X86ISD::CMP, then use it as the condition
7669   // setting operand in place of the X86ISD::SETCC.
7670   if (Cond.getOpcode() == X86ISD::SETCC ||
7671       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7672     CC = Cond.getOperand(0);
7673
7674     SDValue Cmp = Cond.getOperand(1);
7675     unsigned Opc = Cmp.getOpcode();
7676     EVT VT = Op.getValueType();
7677
7678     bool IllegalFPCMov = false;
7679     if (VT.isFloatingPoint() && !VT.isVector() &&
7680         !isScalarFPTypeInSSEReg(VT))  // FPStack?
7681       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
7682
7683     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
7684         Opc == X86ISD::BT) { // FIXME
7685       Cond = Cmp;
7686       addTest = false;
7687     }
7688   }
7689
7690   if (addTest) {
7691     // Look pass the truncate.
7692     if (Cond.getOpcode() == ISD::TRUNCATE)
7693       Cond = Cond.getOperand(0);
7694
7695     // We know the result of AND is compared against zero. Try to match
7696     // it to BT.
7697     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7698       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
7699       if (NewSetCC.getNode()) {
7700         CC = NewSetCC.getOperand(0);
7701         Cond = NewSetCC.getOperand(1);
7702         addTest = false;
7703       }
7704     }
7705   }
7706
7707   if (addTest) {
7708     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7709     Cond = EmitTest(Cond, X86::COND_NE, DAG);
7710   }
7711
7712   // a <  b ? -1 :  0 -> RES = ~setcc_carry
7713   // a <  b ?  0 : -1 -> RES = setcc_carry
7714   // a >= b ? -1 :  0 -> RES = setcc_carry
7715   // a >= b ?  0 : -1 -> RES = ~setcc_carry
7716   if (Cond.getOpcode() == X86ISD::CMP) {
7717     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
7718
7719     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
7720         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
7721       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7722                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
7723       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
7724         return DAG.getNOT(DL, Res, Res.getValueType());
7725       return Res;
7726     }
7727   }
7728
7729   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
7730   // condition is true.
7731   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
7732   SDValue Ops[] = { Op2, Op1, CC, Cond };
7733   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
7734 }
7735
7736 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
7737 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
7738 // from the AND / OR.
7739 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
7740   Opc = Op.getOpcode();
7741   if (Opc != ISD::OR && Opc != ISD::AND)
7742     return false;
7743   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7744           Op.getOperand(0).hasOneUse() &&
7745           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
7746           Op.getOperand(1).hasOneUse());
7747 }
7748
7749 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
7750 // 1 and that the SETCC node has a single use.
7751 static bool isXor1OfSetCC(SDValue Op) {
7752   if (Op.getOpcode() != ISD::XOR)
7753     return false;
7754   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7755   if (N1C && N1C->getAPIntValue() == 1) {
7756     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7757       Op.getOperand(0).hasOneUse();
7758   }
7759   return false;
7760 }
7761
7762 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
7763   bool addTest = true;
7764   SDValue Chain = Op.getOperand(0);
7765   SDValue Cond  = Op.getOperand(1);
7766   SDValue Dest  = Op.getOperand(2);
7767   DebugLoc dl = Op.getDebugLoc();
7768   SDValue CC;
7769
7770   if (Cond.getOpcode() == ISD::SETCC) {
7771     SDValue NewCond = LowerSETCC(Cond, DAG);
7772     if (NewCond.getNode())
7773       Cond = NewCond;
7774   }
7775 #if 0
7776   // FIXME: LowerXALUO doesn't handle these!!
7777   else if (Cond.getOpcode() == X86ISD::ADD  ||
7778            Cond.getOpcode() == X86ISD::SUB  ||
7779            Cond.getOpcode() == X86ISD::SMUL ||
7780            Cond.getOpcode() == X86ISD::UMUL)
7781     Cond = LowerXALUO(Cond, DAG);
7782 #endif
7783
7784   // Look pass (and (setcc_carry (cmp ...)), 1).
7785   if (Cond.getOpcode() == ISD::AND &&
7786       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7787     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7788     if (C && C->getAPIntValue() == 1)
7789       Cond = Cond.getOperand(0);
7790   }
7791
7792   // If condition flag is set by a X86ISD::CMP, then use it as the condition
7793   // setting operand in place of the X86ISD::SETCC.
7794   if (Cond.getOpcode() == X86ISD::SETCC ||
7795       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7796     CC = Cond.getOperand(0);
7797
7798     SDValue Cmp = Cond.getOperand(1);
7799     unsigned Opc = Cmp.getOpcode();
7800     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
7801     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
7802       Cond = Cmp;
7803       addTest = false;
7804     } else {
7805       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
7806       default: break;
7807       case X86::COND_O:
7808       case X86::COND_B:
7809         // These can only come from an arithmetic instruction with overflow,
7810         // e.g. SADDO, UADDO.
7811         Cond = Cond.getNode()->getOperand(1);
7812         addTest = false;
7813         break;
7814       }
7815     }
7816   } else {
7817     unsigned CondOpc;
7818     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
7819       SDValue Cmp = Cond.getOperand(0).getOperand(1);
7820       if (CondOpc == ISD::OR) {
7821         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
7822         // two branches instead of an explicit OR instruction with a
7823         // separate test.
7824         if (Cmp == Cond.getOperand(1).getOperand(1) &&
7825             isX86LogicalCmp(Cmp)) {
7826           CC = Cond.getOperand(0).getOperand(0);
7827           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7828                               Chain, Dest, CC, Cmp);
7829           CC = Cond.getOperand(1).getOperand(0);
7830           Cond = Cmp;
7831           addTest = false;
7832         }
7833       } else { // ISD::AND
7834         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
7835         // two branches instead of an explicit AND instruction with a
7836         // separate test. However, we only do this if this block doesn't
7837         // have a fall-through edge, because this requires an explicit
7838         // jmp when the condition is false.
7839         if (Cmp == Cond.getOperand(1).getOperand(1) &&
7840             isX86LogicalCmp(Cmp) &&
7841             Op.getNode()->hasOneUse()) {
7842           X86::CondCode CCode =
7843             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7844           CCode = X86::GetOppositeBranchCondition(CCode);
7845           CC = DAG.getConstant(CCode, MVT::i8);
7846           SDNode *User = *Op.getNode()->use_begin();
7847           // Look for an unconditional branch following this conditional branch.
7848           // We need this because we need to reverse the successors in order
7849           // to implement FCMP_OEQ.
7850           if (User->getOpcode() == ISD::BR) {
7851             SDValue FalseBB = User->getOperand(1);
7852             SDNode *NewBR =
7853               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
7854             assert(NewBR == User);
7855             (void)NewBR;
7856             Dest = FalseBB;
7857
7858             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7859                                 Chain, Dest, CC, Cmp);
7860             X86::CondCode CCode =
7861               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
7862             CCode = X86::GetOppositeBranchCondition(CCode);
7863             CC = DAG.getConstant(CCode, MVT::i8);
7864             Cond = Cmp;
7865             addTest = false;
7866           }
7867         }
7868       }
7869     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
7870       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
7871       // It should be transformed during dag combiner except when the condition
7872       // is set by a arithmetics with overflow node.
7873       X86::CondCode CCode =
7874         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7875       CCode = X86::GetOppositeBranchCondition(CCode);
7876       CC = DAG.getConstant(CCode, MVT::i8);
7877       Cond = Cond.getOperand(0).getOperand(1);
7878       addTest = false;
7879     }
7880   }
7881
7882   if (addTest) {
7883     // Look pass the truncate.
7884     if (Cond.getOpcode() == ISD::TRUNCATE)
7885       Cond = Cond.getOperand(0);
7886
7887     // We know the result of AND is compared against zero. Try to match
7888     // it to BT.
7889     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7890       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
7891       if (NewSetCC.getNode()) {
7892         CC = NewSetCC.getOperand(0);
7893         Cond = NewSetCC.getOperand(1);
7894         addTest = false;
7895       }
7896     }
7897   }
7898
7899   if (addTest) {
7900     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7901     Cond = EmitTest(Cond, X86::COND_NE, DAG);
7902   }
7903   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7904                      Chain, Dest, CC, Cond);
7905 }
7906
7907
7908 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
7909 // Calls to _alloca is needed to probe the stack when allocating more than 4k
7910 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
7911 // that the guard pages used by the OS virtual memory manager are allocated in
7912 // correct sequence.
7913 SDValue
7914 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7915                                            SelectionDAG &DAG) const {
7916   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows()) &&
7917          "This should be used only on Windows targets");
7918   DebugLoc dl = Op.getDebugLoc();
7919
7920   // Get the inputs.
7921   SDValue Chain = Op.getOperand(0);
7922   SDValue Size  = Op.getOperand(1);
7923   // FIXME: Ensure alignment here
7924
7925   SDValue Flag;
7926
7927   EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
7928
7929   Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
7930   Flag = Chain.getValue(1);
7931
7932   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7933
7934   Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
7935   Flag = Chain.getValue(1);
7936
7937   Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
7938
7939   SDValue Ops1[2] = { Chain.getValue(0), Chain };
7940   return DAG.getMergeValues(Ops1, 2, dl);
7941 }
7942
7943 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
7944   MachineFunction &MF = DAG.getMachineFunction();
7945   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
7946
7947   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
7948   DebugLoc DL = Op.getDebugLoc();
7949
7950   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
7951     // vastart just stores the address of the VarArgsFrameIndex slot into the
7952     // memory location argument.
7953     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
7954                                    getPointerTy());
7955     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
7956                         MachinePointerInfo(SV), false, false, 0);
7957   }
7958
7959   // __va_list_tag:
7960   //   gp_offset         (0 - 6 * 8)
7961   //   fp_offset         (48 - 48 + 8 * 16)
7962   //   overflow_arg_area (point to parameters coming in memory).
7963   //   reg_save_area
7964   SmallVector<SDValue, 8> MemOps;
7965   SDValue FIN = Op.getOperand(1);
7966   // Store gp_offset
7967   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
7968                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
7969                                                MVT::i32),
7970                                FIN, MachinePointerInfo(SV), false, false, 0);
7971   MemOps.push_back(Store);
7972
7973   // Store fp_offset
7974   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7975                     FIN, DAG.getIntPtrConstant(4));
7976   Store = DAG.getStore(Op.getOperand(0), DL,
7977                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
7978                                        MVT::i32),
7979                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
7980   MemOps.push_back(Store);
7981
7982   // Store ptr to overflow_arg_area
7983   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7984                     FIN, DAG.getIntPtrConstant(4));
7985   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
7986                                     getPointerTy());
7987   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
7988                        MachinePointerInfo(SV, 8),
7989                        false, false, 0);
7990   MemOps.push_back(Store);
7991
7992   // Store ptr to reg_save_area.
7993   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7994                     FIN, DAG.getIntPtrConstant(8));
7995   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
7996                                     getPointerTy());
7997   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
7998                        MachinePointerInfo(SV, 16), false, false, 0);
7999   MemOps.push_back(Store);
8000   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
8001                      &MemOps[0], MemOps.size());
8002 }
8003
8004 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
8005   assert(Subtarget->is64Bit() &&
8006          "LowerVAARG only handles 64-bit va_arg!");
8007   assert((Subtarget->isTargetLinux() ||
8008           Subtarget->isTargetDarwin()) &&
8009           "Unhandled target in LowerVAARG");
8010   assert(Op.getNode()->getNumOperands() == 4);
8011   SDValue Chain = Op.getOperand(0);
8012   SDValue SrcPtr = Op.getOperand(1);
8013   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
8014   unsigned Align = Op.getConstantOperandVal(3);
8015   DebugLoc dl = Op.getDebugLoc();
8016
8017   EVT ArgVT = Op.getNode()->getValueType(0);
8018   const Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
8019   uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
8020   uint8_t ArgMode;
8021
8022   // Decide which area this value should be read from.
8023   // TODO: Implement the AMD64 ABI in its entirety. This simple
8024   // selection mechanism works only for the basic types.
8025   if (ArgVT == MVT::f80) {
8026     llvm_unreachable("va_arg for f80 not yet implemented");
8027   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
8028     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
8029   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
8030     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
8031   } else {
8032     llvm_unreachable("Unhandled argument type in LowerVAARG");
8033   }
8034
8035   if (ArgMode == 2) {
8036     // Sanity Check: Make sure using fp_offset makes sense.
8037     assert(!UseSoftFloat &&
8038            !(DAG.getMachineFunction()
8039                 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
8040            Subtarget->hasXMM());
8041   }
8042
8043   // Insert VAARG_64 node into the DAG
8044   // VAARG_64 returns two values: Variable Argument Address, Chain
8045   SmallVector<SDValue, 11> InstOps;
8046   InstOps.push_back(Chain);
8047   InstOps.push_back(SrcPtr);
8048   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
8049   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
8050   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
8051   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
8052   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
8053                                           VTs, &InstOps[0], InstOps.size(),
8054                                           MVT::i64,
8055                                           MachinePointerInfo(SV),
8056                                           /*Align=*/0,
8057                                           /*Volatile=*/false,
8058                                           /*ReadMem=*/true,
8059                                           /*WriteMem=*/true);
8060   Chain = VAARG.getValue(1);
8061
8062   // Load the next argument and return it
8063   return DAG.getLoad(ArgVT, dl,
8064                      Chain,
8065                      VAARG,
8066                      MachinePointerInfo(),
8067                      false, false, 0);
8068 }
8069
8070 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
8071   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
8072   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
8073   SDValue Chain = Op.getOperand(0);
8074   SDValue DstPtr = Op.getOperand(1);
8075   SDValue SrcPtr = Op.getOperand(2);
8076   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
8077   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8078   DebugLoc DL = Op.getDebugLoc();
8079
8080   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
8081                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
8082                        false,
8083                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
8084 }
8085
8086 SDValue
8087 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
8088   DebugLoc dl = Op.getDebugLoc();
8089   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8090   switch (IntNo) {
8091   default: return SDValue();    // Don't custom lower most intrinsics.
8092   // Comparison intrinsics.
8093   case Intrinsic::x86_sse_comieq_ss:
8094   case Intrinsic::x86_sse_comilt_ss:
8095   case Intrinsic::x86_sse_comile_ss:
8096   case Intrinsic::x86_sse_comigt_ss:
8097   case Intrinsic::x86_sse_comige_ss:
8098   case Intrinsic::x86_sse_comineq_ss:
8099   case Intrinsic::x86_sse_ucomieq_ss:
8100   case Intrinsic::x86_sse_ucomilt_ss:
8101   case Intrinsic::x86_sse_ucomile_ss:
8102   case Intrinsic::x86_sse_ucomigt_ss:
8103   case Intrinsic::x86_sse_ucomige_ss:
8104   case Intrinsic::x86_sse_ucomineq_ss:
8105   case Intrinsic::x86_sse2_comieq_sd:
8106   case Intrinsic::x86_sse2_comilt_sd:
8107   case Intrinsic::x86_sse2_comile_sd:
8108   case Intrinsic::x86_sse2_comigt_sd:
8109   case Intrinsic::x86_sse2_comige_sd:
8110   case Intrinsic::x86_sse2_comineq_sd:
8111   case Intrinsic::x86_sse2_ucomieq_sd:
8112   case Intrinsic::x86_sse2_ucomilt_sd:
8113   case Intrinsic::x86_sse2_ucomile_sd:
8114   case Intrinsic::x86_sse2_ucomigt_sd:
8115   case Intrinsic::x86_sse2_ucomige_sd:
8116   case Intrinsic::x86_sse2_ucomineq_sd: {
8117     unsigned Opc = 0;
8118     ISD::CondCode CC = ISD::SETCC_INVALID;
8119     switch (IntNo) {
8120     default: break;
8121     case Intrinsic::x86_sse_comieq_ss:
8122     case Intrinsic::x86_sse2_comieq_sd:
8123       Opc = X86ISD::COMI;
8124       CC = ISD::SETEQ;
8125       break;
8126     case Intrinsic::x86_sse_comilt_ss:
8127     case Intrinsic::x86_sse2_comilt_sd:
8128       Opc = X86ISD::COMI;
8129       CC = ISD::SETLT;
8130       break;
8131     case Intrinsic::x86_sse_comile_ss:
8132     case Intrinsic::x86_sse2_comile_sd:
8133       Opc = X86ISD::COMI;
8134       CC = ISD::SETLE;
8135       break;
8136     case Intrinsic::x86_sse_comigt_ss:
8137     case Intrinsic::x86_sse2_comigt_sd:
8138       Opc = X86ISD::COMI;
8139       CC = ISD::SETGT;
8140       break;
8141     case Intrinsic::x86_sse_comige_ss:
8142     case Intrinsic::x86_sse2_comige_sd:
8143       Opc = X86ISD::COMI;
8144       CC = ISD::SETGE;
8145       break;
8146     case Intrinsic::x86_sse_comineq_ss:
8147     case Intrinsic::x86_sse2_comineq_sd:
8148       Opc = X86ISD::COMI;
8149       CC = ISD::SETNE;
8150       break;
8151     case Intrinsic::x86_sse_ucomieq_ss:
8152     case Intrinsic::x86_sse2_ucomieq_sd:
8153       Opc = X86ISD::UCOMI;
8154       CC = ISD::SETEQ;
8155       break;
8156     case Intrinsic::x86_sse_ucomilt_ss:
8157     case Intrinsic::x86_sse2_ucomilt_sd:
8158       Opc = X86ISD::UCOMI;
8159       CC = ISD::SETLT;
8160       break;
8161     case Intrinsic::x86_sse_ucomile_ss:
8162     case Intrinsic::x86_sse2_ucomile_sd:
8163       Opc = X86ISD::UCOMI;
8164       CC = ISD::SETLE;
8165       break;
8166     case Intrinsic::x86_sse_ucomigt_ss:
8167     case Intrinsic::x86_sse2_ucomigt_sd:
8168       Opc = X86ISD::UCOMI;
8169       CC = ISD::SETGT;
8170       break;
8171     case Intrinsic::x86_sse_ucomige_ss:
8172     case Intrinsic::x86_sse2_ucomige_sd:
8173       Opc = X86ISD::UCOMI;
8174       CC = ISD::SETGE;
8175       break;
8176     case Intrinsic::x86_sse_ucomineq_ss:
8177     case Intrinsic::x86_sse2_ucomineq_sd:
8178       Opc = X86ISD::UCOMI;
8179       CC = ISD::SETNE;
8180       break;
8181     }
8182
8183     SDValue LHS = Op.getOperand(1);
8184     SDValue RHS = Op.getOperand(2);
8185     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
8186     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
8187     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
8188     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8189                                 DAG.getConstant(X86CC, MVT::i8), Cond);
8190     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
8191   }
8192   // ptest and testp intrinsics. The intrinsic these come from are designed to
8193   // return an integer value, not just an instruction so lower it to the ptest
8194   // or testp pattern and a setcc for the result.
8195   case Intrinsic::x86_sse41_ptestz:
8196   case Intrinsic::x86_sse41_ptestc:
8197   case Intrinsic::x86_sse41_ptestnzc:
8198   case Intrinsic::x86_avx_ptestz_256:
8199   case Intrinsic::x86_avx_ptestc_256:
8200   case Intrinsic::x86_avx_ptestnzc_256:
8201   case Intrinsic::x86_avx_vtestz_ps:
8202   case Intrinsic::x86_avx_vtestc_ps:
8203   case Intrinsic::x86_avx_vtestnzc_ps:
8204   case Intrinsic::x86_avx_vtestz_pd:
8205   case Intrinsic::x86_avx_vtestc_pd:
8206   case Intrinsic::x86_avx_vtestnzc_pd:
8207   case Intrinsic::x86_avx_vtestz_ps_256:
8208   case Intrinsic::x86_avx_vtestc_ps_256:
8209   case Intrinsic::x86_avx_vtestnzc_ps_256:
8210   case Intrinsic::x86_avx_vtestz_pd_256:
8211   case Intrinsic::x86_avx_vtestc_pd_256:
8212   case Intrinsic::x86_avx_vtestnzc_pd_256: {
8213     bool IsTestPacked = false;
8214     unsigned X86CC = 0;
8215     switch (IntNo) {
8216     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
8217     case Intrinsic::x86_avx_vtestz_ps:
8218     case Intrinsic::x86_avx_vtestz_pd:
8219     case Intrinsic::x86_avx_vtestz_ps_256:
8220     case Intrinsic::x86_avx_vtestz_pd_256:
8221       IsTestPacked = true; // Fallthrough
8222     case Intrinsic::x86_sse41_ptestz:
8223     case Intrinsic::x86_avx_ptestz_256:
8224       // ZF = 1
8225       X86CC = X86::COND_E;
8226       break;
8227     case Intrinsic::x86_avx_vtestc_ps:
8228     case Intrinsic::x86_avx_vtestc_pd:
8229     case Intrinsic::x86_avx_vtestc_ps_256:
8230     case Intrinsic::x86_avx_vtestc_pd_256:
8231       IsTestPacked = true; // Fallthrough
8232     case Intrinsic::x86_sse41_ptestc:
8233     case Intrinsic::x86_avx_ptestc_256:
8234       // CF = 1
8235       X86CC = X86::COND_B;
8236       break;
8237     case Intrinsic::x86_avx_vtestnzc_ps:
8238     case Intrinsic::x86_avx_vtestnzc_pd:
8239     case Intrinsic::x86_avx_vtestnzc_ps_256:
8240     case Intrinsic::x86_avx_vtestnzc_pd_256:
8241       IsTestPacked = true; // Fallthrough
8242     case Intrinsic::x86_sse41_ptestnzc:
8243     case Intrinsic::x86_avx_ptestnzc_256:
8244       // ZF and CF = 0
8245       X86CC = X86::COND_A;
8246       break;
8247     }
8248
8249     SDValue LHS = Op.getOperand(1);
8250     SDValue RHS = Op.getOperand(2);
8251     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
8252     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
8253     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
8254     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
8255     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
8256   }
8257
8258   // Fix vector shift instructions where the last operand is a non-immediate
8259   // i32 value.
8260   case Intrinsic::x86_sse2_pslli_w:
8261   case Intrinsic::x86_sse2_pslli_d:
8262   case Intrinsic::x86_sse2_pslli_q:
8263   case Intrinsic::x86_sse2_psrli_w:
8264   case Intrinsic::x86_sse2_psrli_d:
8265   case Intrinsic::x86_sse2_psrli_q:
8266   case Intrinsic::x86_sse2_psrai_w:
8267   case Intrinsic::x86_sse2_psrai_d:
8268   case Intrinsic::x86_mmx_pslli_w:
8269   case Intrinsic::x86_mmx_pslli_d:
8270   case Intrinsic::x86_mmx_pslli_q:
8271   case Intrinsic::x86_mmx_psrli_w:
8272   case Intrinsic::x86_mmx_psrli_d:
8273   case Intrinsic::x86_mmx_psrli_q:
8274   case Intrinsic::x86_mmx_psrai_w:
8275   case Intrinsic::x86_mmx_psrai_d: {
8276     SDValue ShAmt = Op.getOperand(2);
8277     if (isa<ConstantSDNode>(ShAmt))
8278       return SDValue();
8279
8280     unsigned NewIntNo = 0;
8281     EVT ShAmtVT = MVT::v4i32;
8282     switch (IntNo) {
8283     case Intrinsic::x86_sse2_pslli_w:
8284       NewIntNo = Intrinsic::x86_sse2_psll_w;
8285       break;
8286     case Intrinsic::x86_sse2_pslli_d:
8287       NewIntNo = Intrinsic::x86_sse2_psll_d;
8288       break;
8289     case Intrinsic::x86_sse2_pslli_q:
8290       NewIntNo = Intrinsic::x86_sse2_psll_q;
8291       break;
8292     case Intrinsic::x86_sse2_psrli_w:
8293       NewIntNo = Intrinsic::x86_sse2_psrl_w;
8294       break;
8295     case Intrinsic::x86_sse2_psrli_d:
8296       NewIntNo = Intrinsic::x86_sse2_psrl_d;
8297       break;
8298     case Intrinsic::x86_sse2_psrli_q:
8299       NewIntNo = Intrinsic::x86_sse2_psrl_q;
8300       break;
8301     case Intrinsic::x86_sse2_psrai_w:
8302       NewIntNo = Intrinsic::x86_sse2_psra_w;
8303       break;
8304     case Intrinsic::x86_sse2_psrai_d:
8305       NewIntNo = Intrinsic::x86_sse2_psra_d;
8306       break;
8307     default: {
8308       ShAmtVT = MVT::v2i32;
8309       switch (IntNo) {
8310       case Intrinsic::x86_mmx_pslli_w:
8311         NewIntNo = Intrinsic::x86_mmx_psll_w;
8312         break;
8313       case Intrinsic::x86_mmx_pslli_d:
8314         NewIntNo = Intrinsic::x86_mmx_psll_d;
8315         break;
8316       case Intrinsic::x86_mmx_pslli_q:
8317         NewIntNo = Intrinsic::x86_mmx_psll_q;
8318         break;
8319       case Intrinsic::x86_mmx_psrli_w:
8320         NewIntNo = Intrinsic::x86_mmx_psrl_w;
8321         break;
8322       case Intrinsic::x86_mmx_psrli_d:
8323         NewIntNo = Intrinsic::x86_mmx_psrl_d;
8324         break;
8325       case Intrinsic::x86_mmx_psrli_q:
8326         NewIntNo = Intrinsic::x86_mmx_psrl_q;
8327         break;
8328       case Intrinsic::x86_mmx_psrai_w:
8329         NewIntNo = Intrinsic::x86_mmx_psra_w;
8330         break;
8331       case Intrinsic::x86_mmx_psrai_d:
8332         NewIntNo = Intrinsic::x86_mmx_psra_d;
8333         break;
8334       default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
8335       }
8336       break;
8337     }
8338     }
8339
8340     // The vector shift intrinsics with scalars uses 32b shift amounts but
8341     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
8342     // to be zero.
8343     SDValue ShOps[4];
8344     ShOps[0] = ShAmt;
8345     ShOps[1] = DAG.getConstant(0, MVT::i32);
8346     if (ShAmtVT == MVT::v4i32) {
8347       ShOps[2] = DAG.getUNDEF(MVT::i32);
8348       ShOps[3] = DAG.getUNDEF(MVT::i32);
8349       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
8350     } else {
8351       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
8352 // FIXME this must be lowered to get rid of the invalid type.
8353     }
8354
8355     EVT VT = Op.getValueType();
8356     ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
8357     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8358                        DAG.getConstant(NewIntNo, MVT::i32),
8359                        Op.getOperand(1), ShAmt);
8360   }
8361   }
8362 }
8363
8364 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
8365                                            SelectionDAG &DAG) const {
8366   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8367   MFI->setReturnAddressIsTaken(true);
8368
8369   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8370   DebugLoc dl = Op.getDebugLoc();
8371
8372   if (Depth > 0) {
8373     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
8374     SDValue Offset =
8375       DAG.getConstant(TD->getPointerSize(),
8376                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
8377     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8378                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
8379                                    FrameAddr, Offset),
8380                        MachinePointerInfo(), false, false, 0);
8381   }
8382
8383   // Just load the return address.
8384   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
8385   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8386                      RetAddrFI, MachinePointerInfo(), false, false, 0);
8387 }
8388
8389 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
8390   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8391   MFI->setFrameAddressIsTaken(true);
8392
8393   EVT VT = Op.getValueType();
8394   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
8395   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8396   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
8397   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
8398   while (Depth--)
8399     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
8400                             MachinePointerInfo(),
8401                             false, false, 0);
8402   return FrameAddr;
8403 }
8404
8405 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
8406                                                      SelectionDAG &DAG) const {
8407   return DAG.getIntPtrConstant(2*TD->getPointerSize());
8408 }
8409
8410 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
8411   MachineFunction &MF = DAG.getMachineFunction();
8412   SDValue Chain     = Op.getOperand(0);
8413   SDValue Offset    = Op.getOperand(1);
8414   SDValue Handler   = Op.getOperand(2);
8415   DebugLoc dl       = Op.getDebugLoc();
8416
8417   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
8418                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
8419                                      getPointerTy());
8420   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
8421
8422   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
8423                                   DAG.getIntPtrConstant(TD->getPointerSize()));
8424   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
8425   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
8426                        false, false, 0);
8427   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
8428   MF.getRegInfo().addLiveOut(StoreAddrReg);
8429
8430   return DAG.getNode(X86ISD::EH_RETURN, dl,
8431                      MVT::Other,
8432                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
8433 }
8434
8435 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
8436                                              SelectionDAG &DAG) const {
8437   SDValue Root = Op.getOperand(0);
8438   SDValue Trmp = Op.getOperand(1); // trampoline
8439   SDValue FPtr = Op.getOperand(2); // nested function
8440   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
8441   DebugLoc dl  = Op.getDebugLoc();
8442
8443   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8444
8445   if (Subtarget->is64Bit()) {
8446     SDValue OutChains[6];
8447
8448     // Large code-model.
8449     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
8450     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
8451
8452     const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
8453     const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
8454
8455     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
8456
8457     // Load the pointer to the nested function into R11.
8458     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
8459     SDValue Addr = Trmp;
8460     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8461                                 Addr, MachinePointerInfo(TrmpAddr),
8462                                 false, false, 0);
8463
8464     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8465                        DAG.getConstant(2, MVT::i64));
8466     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
8467                                 MachinePointerInfo(TrmpAddr, 2),
8468                                 false, false, 2);
8469
8470     // Load the 'nest' parameter value into R10.
8471     // R10 is specified in X86CallingConv.td
8472     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
8473     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8474                        DAG.getConstant(10, MVT::i64));
8475     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8476                                 Addr, MachinePointerInfo(TrmpAddr, 10),
8477                                 false, false, 0);
8478
8479     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8480                        DAG.getConstant(12, MVT::i64));
8481     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
8482                                 MachinePointerInfo(TrmpAddr, 12),
8483                                 false, false, 2);
8484
8485     // Jump to the nested function.
8486     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
8487     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8488                        DAG.getConstant(20, MVT::i64));
8489     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8490                                 Addr, MachinePointerInfo(TrmpAddr, 20),
8491                                 false, false, 0);
8492
8493     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
8494     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8495                        DAG.getConstant(22, MVT::i64));
8496     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
8497                                 MachinePointerInfo(TrmpAddr, 22),
8498                                 false, false, 0);
8499
8500     SDValue Ops[] =
8501       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
8502     return DAG.getMergeValues(Ops, 2, dl);
8503   } else {
8504     const Function *Func =
8505       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
8506     CallingConv::ID CC = Func->getCallingConv();
8507     unsigned NestReg;
8508
8509     switch (CC) {
8510     default:
8511       llvm_unreachable("Unsupported calling convention");
8512     case CallingConv::C:
8513     case CallingConv::X86_StdCall: {
8514       // Pass 'nest' parameter in ECX.
8515       // Must be kept in sync with X86CallingConv.td
8516       NestReg = X86::ECX;
8517
8518       // Check that ECX wasn't needed by an 'inreg' parameter.
8519       const FunctionType *FTy = Func->getFunctionType();
8520       const AttrListPtr &Attrs = Func->getAttributes();
8521
8522       if (!Attrs.isEmpty() && !Func->isVarArg()) {
8523         unsigned InRegCount = 0;
8524         unsigned Idx = 1;
8525
8526         for (FunctionType::param_iterator I = FTy->param_begin(),
8527              E = FTy->param_end(); I != E; ++I, ++Idx)
8528           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
8529             // FIXME: should only count parameters that are lowered to integers.
8530             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
8531
8532         if (InRegCount > 2) {
8533           report_fatal_error("Nest register in use - reduce number of inreg"
8534                              " parameters!");
8535         }
8536       }
8537       break;
8538     }
8539     case CallingConv::X86_FastCall:
8540     case CallingConv::X86_ThisCall:
8541     case CallingConv::Fast:
8542       // Pass 'nest' parameter in EAX.
8543       // Must be kept in sync with X86CallingConv.td
8544       NestReg = X86::EAX;
8545       break;
8546     }
8547
8548     SDValue OutChains[4];
8549     SDValue Addr, Disp;
8550
8551     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8552                        DAG.getConstant(10, MVT::i32));
8553     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
8554
8555     // This is storing the opcode for MOV32ri.
8556     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
8557     const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
8558     OutChains[0] = DAG.getStore(Root, dl,
8559                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
8560                                 Trmp, MachinePointerInfo(TrmpAddr),
8561                                 false, false, 0);
8562
8563     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8564                        DAG.getConstant(1, MVT::i32));
8565     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
8566                                 MachinePointerInfo(TrmpAddr, 1),
8567                                 false, false, 1);
8568
8569     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
8570     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8571                        DAG.getConstant(5, MVT::i32));
8572     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
8573                                 MachinePointerInfo(TrmpAddr, 5),
8574                                 false, false, 1);
8575
8576     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8577                        DAG.getConstant(6, MVT::i32));
8578     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
8579                                 MachinePointerInfo(TrmpAddr, 6),
8580                                 false, false, 1);
8581
8582     SDValue Ops[] =
8583       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
8584     return DAG.getMergeValues(Ops, 2, dl);
8585   }
8586 }
8587
8588 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8589                                             SelectionDAG &DAG) const {
8590   /*
8591    The rounding mode is in bits 11:10 of FPSR, and has the following
8592    settings:
8593      00 Round to nearest
8594      01 Round to -inf
8595      10 Round to +inf
8596      11 Round to 0
8597
8598   FLT_ROUNDS, on the other hand, expects the following:
8599     -1 Undefined
8600      0 Round to 0
8601      1 Round to nearest
8602      2 Round to +inf
8603      3 Round to -inf
8604
8605   To perform the conversion, we do:
8606     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
8607   */
8608
8609   MachineFunction &MF = DAG.getMachineFunction();
8610   const TargetMachine &TM = MF.getTarget();
8611   const TargetFrameLowering &TFI = *TM.getFrameLowering();
8612   unsigned StackAlignment = TFI.getStackAlignment();
8613   EVT VT = Op.getValueType();
8614   DebugLoc DL = Op.getDebugLoc();
8615
8616   // Save FP Control Word to stack slot
8617   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
8618   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8619
8620
8621   MachineMemOperand *MMO =
8622    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8623                            MachineMemOperand::MOStore, 2, 2);
8624
8625   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
8626   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
8627                                           DAG.getVTList(MVT::Other),
8628                                           Ops, 2, MVT::i16, MMO);
8629
8630   // Load FP Control Word from stack slot
8631   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
8632                             MachinePointerInfo(), false, false, 0);
8633
8634   // Transform as necessary
8635   SDValue CWD1 =
8636     DAG.getNode(ISD::SRL, DL, MVT::i16,
8637                 DAG.getNode(ISD::AND, DL, MVT::i16,
8638                             CWD, DAG.getConstant(0x800, MVT::i16)),
8639                 DAG.getConstant(11, MVT::i8));
8640   SDValue CWD2 =
8641     DAG.getNode(ISD::SRL, DL, MVT::i16,
8642                 DAG.getNode(ISD::AND, DL, MVT::i16,
8643                             CWD, DAG.getConstant(0x400, MVT::i16)),
8644                 DAG.getConstant(9, MVT::i8));
8645
8646   SDValue RetVal =
8647     DAG.getNode(ISD::AND, DL, MVT::i16,
8648                 DAG.getNode(ISD::ADD, DL, MVT::i16,
8649                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
8650                             DAG.getConstant(1, MVT::i16)),
8651                 DAG.getConstant(3, MVT::i16));
8652
8653
8654   return DAG.getNode((VT.getSizeInBits() < 16 ?
8655                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
8656 }
8657
8658 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
8659   EVT VT = Op.getValueType();
8660   EVT OpVT = VT;
8661   unsigned NumBits = VT.getSizeInBits();
8662   DebugLoc dl = Op.getDebugLoc();
8663
8664   Op = Op.getOperand(0);
8665   if (VT == MVT::i8) {
8666     // Zero extend to i32 since there is not an i8 bsr.
8667     OpVT = MVT::i32;
8668     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8669   }
8670
8671   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
8672   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8673   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
8674
8675   // If src is zero (i.e. bsr sets ZF), returns NumBits.
8676   SDValue Ops[] = {
8677     Op,
8678     DAG.getConstant(NumBits+NumBits-1, OpVT),
8679     DAG.getConstant(X86::COND_E, MVT::i8),
8680     Op.getValue(1)
8681   };
8682   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8683
8684   // Finally xor with NumBits-1.
8685   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
8686
8687   if (VT == MVT::i8)
8688     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8689   return Op;
8690 }
8691
8692 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
8693   EVT VT = Op.getValueType();
8694   EVT OpVT = VT;
8695   unsigned NumBits = VT.getSizeInBits();
8696   DebugLoc dl = Op.getDebugLoc();
8697
8698   Op = Op.getOperand(0);
8699   if (VT == MVT::i8) {
8700     OpVT = MVT::i32;
8701     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8702   }
8703
8704   // Issue a bsf (scan bits forward) which also sets EFLAGS.
8705   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8706   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
8707
8708   // If src is zero (i.e. bsf sets ZF), returns NumBits.
8709   SDValue Ops[] = {
8710     Op,
8711     DAG.getConstant(NumBits, OpVT),
8712     DAG.getConstant(X86::COND_E, MVT::i8),
8713     Op.getValue(1)
8714   };
8715   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8716
8717   if (VT == MVT::i8)
8718     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8719   return Op;
8720 }
8721
8722 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) const {
8723   EVT VT = Op.getValueType();
8724   assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
8725   DebugLoc dl = Op.getDebugLoc();
8726
8727   //  ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
8728   //  ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
8729   //  ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
8730   //  ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
8731   //  ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
8732   //
8733   //  AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
8734   //  AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
8735   //  return AloBlo + AloBhi + AhiBlo;
8736
8737   SDValue A = Op.getOperand(0);
8738   SDValue B = Op.getOperand(1);
8739
8740   SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8741                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8742                        A, DAG.getConstant(32, MVT::i32));
8743   SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8744                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8745                        B, DAG.getConstant(32, MVT::i32));
8746   SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8747                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8748                        A, B);
8749   SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8750                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8751                        A, Bhi);
8752   SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8753                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8754                        Ahi, B);
8755   AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8756                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8757                        AloBhi, DAG.getConstant(32, MVT::i32));
8758   AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8759                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8760                        AhiBlo, DAG.getConstant(32, MVT::i32));
8761   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
8762   Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
8763   return Res;
8764 }
8765
8766 SDValue X86TargetLowering::LowerSHL(SDValue Op, SelectionDAG &DAG) const {
8767   EVT VT = Op.getValueType();
8768   DebugLoc dl = Op.getDebugLoc();
8769   SDValue R = Op.getOperand(0);
8770
8771   LLVMContext *Context = DAG.getContext();
8772
8773   assert(Subtarget->hasSSE41() && "Cannot lower SHL without SSE4.1 or later");
8774
8775   if (VT == MVT::v4i32) {
8776     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8777                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8778                      Op.getOperand(1), DAG.getConstant(23, MVT::i32));
8779
8780     ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
8781
8782     std::vector<Constant*> CV(4, CI);
8783     Constant *C = ConstantVector::get(CV);
8784     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8785     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8786                                  MachinePointerInfo::getConstantPool(),
8787                                  false, false, 16);
8788
8789     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
8790     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
8791     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
8792     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
8793   }
8794   if (VT == MVT::v16i8) {
8795     // a = a << 5;
8796     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8797                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8798                      Op.getOperand(1), DAG.getConstant(5, MVT::i32));
8799
8800     ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
8801     ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
8802
8803     std::vector<Constant*> CVM1(16, CM1);
8804     std::vector<Constant*> CVM2(16, CM2);
8805     Constant *C = ConstantVector::get(CVM1);
8806     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8807     SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8808                             MachinePointerInfo::getConstantPool(),
8809                             false, false, 16);
8810
8811     // r = pblendv(r, psllw(r & (char16)15, 4), a);
8812     M = DAG.getNode(ISD::AND, dl, VT, R, M);
8813     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8814                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8815                     DAG.getConstant(4, MVT::i32));
8816     R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
8817     // a += a
8818     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8819
8820     C = ConstantVector::get(CVM2);
8821     CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8822     M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8823                     MachinePointerInfo::getConstantPool(),
8824                     false, false, 16);
8825
8826     // r = pblendv(r, psllw(r & (char16)63, 2), a);
8827     M = DAG.getNode(ISD::AND, dl, VT, R, M);
8828     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8829                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8830                     DAG.getConstant(2, MVT::i32));
8831     R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
8832     // a += a
8833     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8834
8835     // return pblendv(r, r+r, a);
8836     R = DAG.getNode(X86ISD::PBLENDVB, dl, VT,
8837                     R, DAG.getNode(ISD::ADD, dl, VT, R, R), Op);
8838     return R;
8839   }
8840   return SDValue();
8841 }
8842
8843 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
8844   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
8845   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
8846   // looks for this combo and may remove the "setcc" instruction if the "setcc"
8847   // has only one use.
8848   SDNode *N = Op.getNode();
8849   SDValue LHS = N->getOperand(0);
8850   SDValue RHS = N->getOperand(1);
8851   unsigned BaseOp = 0;
8852   unsigned Cond = 0;
8853   DebugLoc DL = Op.getDebugLoc();
8854   switch (Op.getOpcode()) {
8855   default: llvm_unreachable("Unknown ovf instruction!");
8856   case ISD::SADDO:
8857     // A subtract of one will be selected as a INC. Note that INC doesn't
8858     // set CF, so we can't do this for UADDO.
8859     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
8860       if (C->isOne()) {
8861         BaseOp = X86ISD::INC;
8862         Cond = X86::COND_O;
8863         break;
8864       }
8865     BaseOp = X86ISD::ADD;
8866     Cond = X86::COND_O;
8867     break;
8868   case ISD::UADDO:
8869     BaseOp = X86ISD::ADD;
8870     Cond = X86::COND_B;
8871     break;
8872   case ISD::SSUBO:
8873     // A subtract of one will be selected as a DEC. Note that DEC doesn't
8874     // set CF, so we can't do this for USUBO.
8875     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
8876       if (C->isOne()) {
8877         BaseOp = X86ISD::DEC;
8878         Cond = X86::COND_O;
8879         break;
8880       }
8881     BaseOp = X86ISD::SUB;
8882     Cond = X86::COND_O;
8883     break;
8884   case ISD::USUBO:
8885     BaseOp = X86ISD::SUB;
8886     Cond = X86::COND_B;
8887     break;
8888   case ISD::SMULO:
8889     BaseOp = X86ISD::SMUL;
8890     Cond = X86::COND_O;
8891     break;
8892   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
8893     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
8894                                  MVT::i32);
8895     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
8896
8897     SDValue SetCC =
8898       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8899                   DAG.getConstant(X86::COND_O, MVT::i32),
8900                   SDValue(Sum.getNode(), 2));
8901
8902     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
8903     return Sum;
8904   }
8905   }
8906
8907   // Also sets EFLAGS.
8908   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
8909   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
8910
8911   SDValue SetCC =
8912     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
8913                 DAG.getConstant(Cond, MVT::i32),
8914                 SDValue(Sum.getNode(), 1));
8915
8916   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
8917   return Sum;
8918 }
8919
8920 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
8921   DebugLoc dl = Op.getDebugLoc();
8922
8923   if (!Subtarget->hasSSE2()) {
8924     SDValue Chain = Op.getOperand(0);
8925     SDValue Zero = DAG.getConstant(0,
8926                                    Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
8927     SDValue Ops[] = {
8928       DAG.getRegister(X86::ESP, MVT::i32), // Base
8929       DAG.getTargetConstant(1, MVT::i8),   // Scale
8930       DAG.getRegister(0, MVT::i32),        // Index
8931       DAG.getTargetConstant(0, MVT::i32),  // Disp
8932       DAG.getRegister(0, MVT::i32),        // Segment.
8933       Zero,
8934       Chain
8935     };
8936     SDNode *Res =
8937       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
8938                           array_lengthof(Ops));
8939     return SDValue(Res, 0);
8940   }
8941
8942   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
8943   if (!isDev)
8944     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
8945
8946   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8947   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
8948   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
8949   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
8950
8951   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
8952   if (!Op1 && !Op2 && !Op3 && Op4)
8953     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
8954
8955   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
8956   if (Op1 && !Op2 && !Op3 && !Op4)
8957     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
8958
8959   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
8960   //           (MFENCE)>;
8961   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
8962 }
8963
8964 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
8965   EVT T = Op.getValueType();
8966   DebugLoc DL = Op.getDebugLoc();
8967   unsigned Reg = 0;
8968   unsigned size = 0;
8969   switch(T.getSimpleVT().SimpleTy) {
8970   default:
8971     assert(false && "Invalid value type!");
8972   case MVT::i8:  Reg = X86::AL;  size = 1; break;
8973   case MVT::i16: Reg = X86::AX;  size = 2; break;
8974   case MVT::i32: Reg = X86::EAX; size = 4; break;
8975   case MVT::i64:
8976     assert(Subtarget->is64Bit() && "Node not type legal!");
8977     Reg = X86::RAX; size = 8;
8978     break;
8979   }
8980   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
8981                                     Op.getOperand(2), SDValue());
8982   SDValue Ops[] = { cpIn.getValue(0),
8983                     Op.getOperand(1),
8984                     Op.getOperand(3),
8985                     DAG.getTargetConstant(size, MVT::i8),
8986                     cpIn.getValue(1) };
8987   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
8988   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
8989   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
8990                                            Ops, 5, T, MMO);
8991   SDValue cpOut =
8992     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
8993   return cpOut;
8994 }
8995
8996 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
8997                                                  SelectionDAG &DAG) const {
8998   assert(Subtarget->is64Bit() && "Result not type legalized?");
8999   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9000   SDValue TheChain = Op.getOperand(0);
9001   DebugLoc dl = Op.getDebugLoc();
9002   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
9003   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
9004   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
9005                                    rax.getValue(2));
9006   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
9007                             DAG.getConstant(32, MVT::i8));
9008   SDValue Ops[] = {
9009     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
9010     rdx.getValue(1)
9011   };
9012   return DAG.getMergeValues(Ops, 2, dl);
9013 }
9014
9015 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
9016                                             SelectionDAG &DAG) const {
9017   EVT SrcVT = Op.getOperand(0).getValueType();
9018   EVT DstVT = Op.getValueType();
9019   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
9020          Subtarget->hasMMX() && "Unexpected custom BITCAST");
9021   assert((DstVT == MVT::i64 ||
9022           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
9023          "Unexpected custom BITCAST");
9024   // i64 <=> MMX conversions are Legal.
9025   if (SrcVT==MVT::i64 && DstVT.isVector())
9026     return Op;
9027   if (DstVT==MVT::i64 && SrcVT.isVector())
9028     return Op;
9029   // MMX <=> MMX conversions are Legal.
9030   if (SrcVT.isVector() && DstVT.isVector())
9031     return Op;
9032   // All other conversions need to be expanded.
9033   return SDValue();
9034 }
9035
9036 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
9037   SDNode *Node = Op.getNode();
9038   DebugLoc dl = Node->getDebugLoc();
9039   EVT T = Node->getValueType(0);
9040   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
9041                               DAG.getConstant(0, T), Node->getOperand(2));
9042   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
9043                        cast<AtomicSDNode>(Node)->getMemoryVT(),
9044                        Node->getOperand(0),
9045                        Node->getOperand(1), negOp,
9046                        cast<AtomicSDNode>(Node)->getSrcValue(),
9047                        cast<AtomicSDNode>(Node)->getAlignment());
9048 }
9049
9050 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
9051   EVT VT = Op.getNode()->getValueType(0);
9052
9053   // Let legalize expand this if it isn't a legal type yet.
9054   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9055     return SDValue();
9056
9057   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
9058
9059   unsigned Opc;
9060   bool ExtraOp = false;
9061   switch (Op.getOpcode()) {
9062   default: assert(0 && "Invalid code");
9063   case ISD::ADDC: Opc = X86ISD::ADD; break;
9064   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
9065   case ISD::SUBC: Opc = X86ISD::SUB; break;
9066   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
9067   }
9068
9069   if (!ExtraOp)
9070     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
9071                        Op.getOperand(1));
9072   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
9073                      Op.getOperand(1), Op.getOperand(2));
9074 }
9075
9076 /// LowerOperation - Provide custom lowering hooks for some operations.
9077 ///
9078 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9079   switch (Op.getOpcode()) {
9080   default: llvm_unreachable("Should not custom lower this!");
9081   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op,DAG);
9082   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
9083   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
9084   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
9085   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
9086   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
9087   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
9088   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
9089   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op, DAG);
9090   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, DAG);
9091   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
9092   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
9093   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
9094   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
9095   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
9096   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
9097   case ISD::SHL_PARTS:
9098   case ISD::SRA_PARTS:
9099   case ISD::SRL_PARTS:          return LowerShift(Op, DAG);
9100   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
9101   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
9102   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
9103   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
9104   case ISD::FABS:               return LowerFABS(Op, DAG);
9105   case ISD::FNEG:               return LowerFNEG(Op, DAG);
9106   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
9107   case ISD::SETCC:              return LowerSETCC(Op, DAG);
9108   case ISD::VSETCC:             return LowerVSETCC(Op, DAG);
9109   case ISD::SELECT:             return LowerSELECT(Op, DAG);
9110   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
9111   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
9112   case ISD::VASTART:            return LowerVASTART(Op, DAG);
9113   case ISD::VAARG:              return LowerVAARG(Op, DAG);
9114   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
9115   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
9116   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
9117   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
9118   case ISD::FRAME_TO_ARGS_OFFSET:
9119                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
9120   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
9121   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
9122   case ISD::TRAMPOLINE:         return LowerTRAMPOLINE(Op, DAG);
9123   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
9124   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
9125   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
9126   case ISD::MUL:                return LowerMUL_V2I64(Op, DAG);
9127   case ISD::SHL:                return LowerSHL(Op, DAG);
9128   case ISD::SADDO:
9129   case ISD::UADDO:
9130   case ISD::SSUBO:
9131   case ISD::USUBO:
9132   case ISD::SMULO:
9133   case ISD::UMULO:              return LowerXALUO(Op, DAG);
9134   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
9135   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
9136   case ISD::ADDC:
9137   case ISD::ADDE:
9138   case ISD::SUBC:
9139   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
9140   }
9141 }
9142
9143 void X86TargetLowering::
9144 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
9145                         SelectionDAG &DAG, unsigned NewOp) const {
9146   EVT T = Node->getValueType(0);
9147   DebugLoc dl = Node->getDebugLoc();
9148   assert (T == MVT::i64 && "Only know how to expand i64 atomics");
9149
9150   SDValue Chain = Node->getOperand(0);
9151   SDValue In1 = Node->getOperand(1);
9152   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9153                              Node->getOperand(2), DAG.getIntPtrConstant(0));
9154   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9155                              Node->getOperand(2), DAG.getIntPtrConstant(1));
9156   SDValue Ops[] = { Chain, In1, In2L, In2H };
9157   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
9158   SDValue Result =
9159     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
9160                             cast<MemSDNode>(Node)->getMemOperand());
9161   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
9162   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
9163   Results.push_back(Result.getValue(2));
9164 }
9165
9166 /// ReplaceNodeResults - Replace a node with an illegal result type
9167 /// with a new node built out of custom code.
9168 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
9169                                            SmallVectorImpl<SDValue>&Results,
9170                                            SelectionDAG &DAG) const {
9171   DebugLoc dl = N->getDebugLoc();
9172   switch (N->getOpcode()) {
9173   default:
9174     assert(false && "Do not know how to custom type legalize this operation!");
9175     return;
9176   case ISD::ADDC:
9177   case ISD::ADDE:
9178   case ISD::SUBC:
9179   case ISD::SUBE:
9180     // We don't want to expand or promote these.
9181     return;
9182   case ISD::FP_TO_SINT: {
9183     std::pair<SDValue,SDValue> Vals =
9184         FP_TO_INTHelper(SDValue(N, 0), DAG, true);
9185     SDValue FIST = Vals.first, StackSlot = Vals.second;
9186     if (FIST.getNode() != 0) {
9187       EVT VT = N->getValueType(0);
9188       // Return a load from the stack slot.
9189       Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
9190                                     MachinePointerInfo(), false, false, 0));
9191     }
9192     return;
9193   }
9194   case ISD::READCYCLECOUNTER: {
9195     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9196     SDValue TheChain = N->getOperand(0);
9197     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
9198     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
9199                                      rd.getValue(1));
9200     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
9201                                      eax.getValue(2));
9202     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
9203     SDValue Ops[] = { eax, edx };
9204     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
9205     Results.push_back(edx.getValue(1));
9206     return;
9207   }
9208   case ISD::ATOMIC_CMP_SWAP: {
9209     EVT T = N->getValueType(0);
9210     assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
9211     SDValue cpInL, cpInH;
9212     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
9213                         DAG.getConstant(0, MVT::i32));
9214     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
9215                         DAG.getConstant(1, MVT::i32));
9216     cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
9217     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
9218                              cpInL.getValue(1));
9219     SDValue swapInL, swapInH;
9220     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
9221                           DAG.getConstant(0, MVT::i32));
9222     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
9223                           DAG.getConstant(1, MVT::i32));
9224     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
9225                                cpInH.getValue(1));
9226     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
9227                                swapInL.getValue(1));
9228     SDValue Ops[] = { swapInH.getValue(0),
9229                       N->getOperand(1),
9230                       swapInH.getValue(1) };
9231     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9232     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
9233     SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG8_DAG, dl, Tys,
9234                                              Ops, 3, T, MMO);
9235     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
9236                                         MVT::i32, Result.getValue(1));
9237     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
9238                                         MVT::i32, cpOutL.getValue(2));
9239     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
9240     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
9241     Results.push_back(cpOutH.getValue(1));
9242     return;
9243   }
9244   case ISD::ATOMIC_LOAD_ADD:
9245     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
9246     return;
9247   case ISD::ATOMIC_LOAD_AND:
9248     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
9249     return;
9250   case ISD::ATOMIC_LOAD_NAND:
9251     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
9252     return;
9253   case ISD::ATOMIC_LOAD_OR:
9254     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
9255     return;
9256   case ISD::ATOMIC_LOAD_SUB:
9257     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
9258     return;
9259   case ISD::ATOMIC_LOAD_XOR:
9260     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
9261     return;
9262   case ISD::ATOMIC_SWAP:
9263     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
9264     return;
9265   }
9266 }
9267
9268 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
9269   switch (Opcode) {
9270   default: return NULL;
9271   case X86ISD::BSF:                return "X86ISD::BSF";
9272   case X86ISD::BSR:                return "X86ISD::BSR";
9273   case X86ISD::SHLD:               return "X86ISD::SHLD";
9274   case X86ISD::SHRD:               return "X86ISD::SHRD";
9275   case X86ISD::FAND:               return "X86ISD::FAND";
9276   case X86ISD::FOR:                return "X86ISD::FOR";
9277   case X86ISD::FXOR:               return "X86ISD::FXOR";
9278   case X86ISD::FSRL:               return "X86ISD::FSRL";
9279   case X86ISD::FILD:               return "X86ISD::FILD";
9280   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
9281   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
9282   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
9283   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
9284   case X86ISD::FLD:                return "X86ISD::FLD";
9285   case X86ISD::FST:                return "X86ISD::FST";
9286   case X86ISD::CALL:               return "X86ISD::CALL";
9287   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
9288   case X86ISD::BT:                 return "X86ISD::BT";
9289   case X86ISD::CMP:                return "X86ISD::CMP";
9290   case X86ISD::COMI:               return "X86ISD::COMI";
9291   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
9292   case X86ISD::SETCC:              return "X86ISD::SETCC";
9293   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
9294   case X86ISD::CMOV:               return "X86ISD::CMOV";
9295   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
9296   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
9297   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
9298   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
9299   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
9300   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
9301   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
9302   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
9303   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
9304   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
9305   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
9306   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
9307   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
9308   case X86ISD::PANDN:              return "X86ISD::PANDN";
9309   case X86ISD::PSIGNB:             return "X86ISD::PSIGNB";
9310   case X86ISD::PSIGNW:             return "X86ISD::PSIGNW";
9311   case X86ISD::PSIGND:             return "X86ISD::PSIGND";
9312   case X86ISD::PBLENDVB:           return "X86ISD::PBLENDVB";
9313   case X86ISD::FMAX:               return "X86ISD::FMAX";
9314   case X86ISD::FMIN:               return "X86ISD::FMIN";
9315   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
9316   case X86ISD::FRCP:               return "X86ISD::FRCP";
9317   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
9318   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
9319   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
9320   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
9321   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
9322   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
9323   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
9324   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
9325   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
9326   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
9327   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
9328   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
9329   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
9330   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
9331   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
9332   case X86ISD::VSHL:               return "X86ISD::VSHL";
9333   case X86ISD::VSRL:               return "X86ISD::VSRL";
9334   case X86ISD::CMPPD:              return "X86ISD::CMPPD";
9335   case X86ISD::CMPPS:              return "X86ISD::CMPPS";
9336   case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
9337   case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
9338   case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
9339   case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
9340   case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
9341   case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
9342   case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
9343   case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
9344   case X86ISD::ADD:                return "X86ISD::ADD";
9345   case X86ISD::SUB:                return "X86ISD::SUB";
9346   case X86ISD::ADC:                return "X86ISD::ADC";
9347   case X86ISD::SBB:                return "X86ISD::SBB";
9348   case X86ISD::SMUL:               return "X86ISD::SMUL";
9349   case X86ISD::UMUL:               return "X86ISD::UMUL";
9350   case X86ISD::INC:                return "X86ISD::INC";
9351   case X86ISD::DEC:                return "X86ISD::DEC";
9352   case X86ISD::OR:                 return "X86ISD::OR";
9353   case X86ISD::XOR:                return "X86ISD::XOR";
9354   case X86ISD::AND:                return "X86ISD::AND";
9355   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
9356   case X86ISD::PTEST:              return "X86ISD::PTEST";
9357   case X86ISD::TESTP:              return "X86ISD::TESTP";
9358   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
9359   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
9360   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
9361   case X86ISD::PSHUFHW_LD:         return "X86ISD::PSHUFHW_LD";
9362   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
9363   case X86ISD::PSHUFLW_LD:         return "X86ISD::PSHUFLW_LD";
9364   case X86ISD::SHUFPS:             return "X86ISD::SHUFPS";
9365   case X86ISD::SHUFPD:             return "X86ISD::SHUFPD";
9366   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
9367   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
9368   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
9369   case X86ISD::MOVHLPD:            return "X86ISD::MOVHLPD";
9370   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
9371   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
9372   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
9373   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
9374   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
9375   case X86ISD::MOVSHDUP_LD:        return "X86ISD::MOVSHDUP_LD";
9376   case X86ISD::MOVSLDUP_LD:        return "X86ISD::MOVSLDUP_LD";
9377   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
9378   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
9379   case X86ISD::UNPCKLPS:           return "X86ISD::UNPCKLPS";
9380   case X86ISD::UNPCKLPD:           return "X86ISD::UNPCKLPD";
9381   case X86ISD::VUNPCKLPS:          return "X86ISD::VUNPCKLPS";
9382   case X86ISD::VUNPCKLPD:          return "X86ISD::VUNPCKLPD";
9383   case X86ISD::VUNPCKLPSY:         return "X86ISD::VUNPCKLPSY";
9384   case X86ISD::VUNPCKLPDY:         return "X86ISD::VUNPCKLPDY";
9385   case X86ISD::UNPCKHPS:           return "X86ISD::UNPCKHPS";
9386   case X86ISD::UNPCKHPD:           return "X86ISD::UNPCKHPD";
9387   case X86ISD::PUNPCKLBW:          return "X86ISD::PUNPCKLBW";
9388   case X86ISD::PUNPCKLWD:          return "X86ISD::PUNPCKLWD";
9389   case X86ISD::PUNPCKLDQ:          return "X86ISD::PUNPCKLDQ";
9390   case X86ISD::PUNPCKLQDQ:         return "X86ISD::PUNPCKLQDQ";
9391   case X86ISD::PUNPCKHBW:          return "X86ISD::PUNPCKHBW";
9392   case X86ISD::PUNPCKHWD:          return "X86ISD::PUNPCKHWD";
9393   case X86ISD::PUNPCKHDQ:          return "X86ISD::PUNPCKHDQ";
9394   case X86ISD::PUNPCKHQDQ:         return "X86ISD::PUNPCKHQDQ";
9395   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
9396   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
9397   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
9398   }
9399 }
9400
9401 // isLegalAddressingMode - Return true if the addressing mode represented
9402 // by AM is legal for this target, for a load/store of the specified type.
9403 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
9404                                               const Type *Ty) const {
9405   // X86 supports extremely general addressing modes.
9406   CodeModel::Model M = getTargetMachine().getCodeModel();
9407   Reloc::Model R = getTargetMachine().getRelocationModel();
9408
9409   // X86 allows a sign-extended 32-bit immediate field as a displacement.
9410   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
9411     return false;
9412
9413   if (AM.BaseGV) {
9414     unsigned GVFlags =
9415       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
9416
9417     // If a reference to this global requires an extra load, we can't fold it.
9418     if (isGlobalStubReference(GVFlags))
9419       return false;
9420
9421     // If BaseGV requires a register for the PIC base, we cannot also have a
9422     // BaseReg specified.
9423     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
9424       return false;
9425
9426     // If lower 4G is not available, then we must use rip-relative addressing.
9427     if ((M != CodeModel::Small || R != Reloc::Static) &&
9428         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
9429       return false;
9430   }
9431
9432   switch (AM.Scale) {
9433   case 0:
9434   case 1:
9435   case 2:
9436   case 4:
9437   case 8:
9438     // These scales always work.
9439     break;
9440   case 3:
9441   case 5:
9442   case 9:
9443     // These scales are formed with basereg+scalereg.  Only accept if there is
9444     // no basereg yet.
9445     if (AM.HasBaseReg)
9446       return false;
9447     break;
9448   default:  // Other stuff never works.
9449     return false;
9450   }
9451
9452   return true;
9453 }
9454
9455
9456 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
9457   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9458     return false;
9459   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
9460   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
9461   if (NumBits1 <= NumBits2)
9462     return false;
9463   return true;
9464 }
9465
9466 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
9467   if (!VT1.isInteger() || !VT2.isInteger())
9468     return false;
9469   unsigned NumBits1 = VT1.getSizeInBits();
9470   unsigned NumBits2 = VT2.getSizeInBits();
9471   if (NumBits1 <= NumBits2)
9472     return false;
9473   return true;
9474 }
9475
9476 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
9477   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9478   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
9479 }
9480
9481 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
9482   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9483   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
9484 }
9485
9486 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
9487   // i16 instructions are longer (0x66 prefix) and potentially slower.
9488   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
9489 }
9490
9491 /// isShuffleMaskLegal - Targets can use this to indicate that they only
9492 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
9493 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
9494 /// are assumed to be legal.
9495 bool
9496 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
9497                                       EVT VT) const {
9498   // Very little shuffling can be done for 64-bit vectors right now.
9499   if (VT.getSizeInBits() == 64)
9500     return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
9501
9502   // FIXME: pshufb, blends, shifts.
9503   return (VT.getVectorNumElements() == 2 ||
9504           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
9505           isMOVLMask(M, VT) ||
9506           isSHUFPMask(M, VT) ||
9507           isPSHUFDMask(M, VT) ||
9508           isPSHUFHWMask(M, VT) ||
9509           isPSHUFLWMask(M, VT) ||
9510           isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
9511           isUNPCKLMask(M, VT) ||
9512           isUNPCKHMask(M, VT) ||
9513           isUNPCKL_v_undef_Mask(M, VT) ||
9514           isUNPCKH_v_undef_Mask(M, VT));
9515 }
9516
9517 bool
9518 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
9519                                           EVT VT) const {
9520   unsigned NumElts = VT.getVectorNumElements();
9521   // FIXME: This collection of masks seems suspect.
9522   if (NumElts == 2)
9523     return true;
9524   if (NumElts == 4 && VT.getSizeInBits() == 128) {
9525     return (isMOVLMask(Mask, VT)  ||
9526             isCommutedMOVLMask(Mask, VT, true) ||
9527             isSHUFPMask(Mask, VT) ||
9528             isCommutedSHUFPMask(Mask, VT));
9529   }
9530   return false;
9531 }
9532
9533 //===----------------------------------------------------------------------===//
9534 //                           X86 Scheduler Hooks
9535 //===----------------------------------------------------------------------===//
9536
9537 // private utility function
9538 MachineBasicBlock *
9539 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
9540                                                        MachineBasicBlock *MBB,
9541                                                        unsigned regOpc,
9542                                                        unsigned immOpc,
9543                                                        unsigned LoadOpc,
9544                                                        unsigned CXchgOpc,
9545                                                        unsigned notOpc,
9546                                                        unsigned EAXreg,
9547                                                        TargetRegisterClass *RC,
9548                                                        bool invSrc) const {
9549   // For the atomic bitwise operator, we generate
9550   //   thisMBB:
9551   //   newMBB:
9552   //     ld  t1 = [bitinstr.addr]
9553   //     op  t2 = t1, [bitinstr.val]
9554   //     mov EAX = t1
9555   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
9556   //     bz  newMBB
9557   //     fallthrough -->nextMBB
9558   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9559   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9560   MachineFunction::iterator MBBIter = MBB;
9561   ++MBBIter;
9562
9563   /// First build the CFG
9564   MachineFunction *F = MBB->getParent();
9565   MachineBasicBlock *thisMBB = MBB;
9566   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9567   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9568   F->insert(MBBIter, newMBB);
9569   F->insert(MBBIter, nextMBB);
9570
9571   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9572   nextMBB->splice(nextMBB->begin(), thisMBB,
9573                   llvm::next(MachineBasicBlock::iterator(bInstr)),
9574                   thisMBB->end());
9575   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9576
9577   // Update thisMBB to fall through to newMBB
9578   thisMBB->addSuccessor(newMBB);
9579
9580   // newMBB jumps to itself and fall through to nextMBB
9581   newMBB->addSuccessor(nextMBB);
9582   newMBB->addSuccessor(newMBB);
9583
9584   // Insert instructions into newMBB based on incoming instruction
9585   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9586          "unexpected number of operands");
9587   DebugLoc dl = bInstr->getDebugLoc();
9588   MachineOperand& destOper = bInstr->getOperand(0);
9589   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9590   int numArgs = bInstr->getNumOperands() - 1;
9591   for (int i=0; i < numArgs; ++i)
9592     argOpers[i] = &bInstr->getOperand(i+1);
9593
9594   // x86 address has 4 operands: base, index, scale, and displacement
9595   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9596   int valArgIndx = lastAddrIndx + 1;
9597
9598   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9599   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
9600   for (int i=0; i <= lastAddrIndx; ++i)
9601     (*MIB).addOperand(*argOpers[i]);
9602
9603   unsigned tt = F->getRegInfo().createVirtualRegister(RC);
9604   if (invSrc) {
9605     MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
9606   }
9607   else
9608     tt = t1;
9609
9610   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9611   assert((argOpers[valArgIndx]->isReg() ||
9612           argOpers[valArgIndx]->isImm()) &&
9613          "invalid operand");
9614   if (argOpers[valArgIndx]->isReg())
9615     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
9616   else
9617     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
9618   MIB.addReg(tt);
9619   (*MIB).addOperand(*argOpers[valArgIndx]);
9620
9621   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
9622   MIB.addReg(t1);
9623
9624   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
9625   for (int i=0; i <= lastAddrIndx; ++i)
9626     (*MIB).addOperand(*argOpers[i]);
9627   MIB.addReg(t2);
9628   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9629   (*MIB).setMemRefs(bInstr->memoperands_begin(),
9630                     bInstr->memoperands_end());
9631
9632   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9633   MIB.addReg(EAXreg);
9634
9635   // insert branch
9636   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9637
9638   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
9639   return nextMBB;
9640 }
9641
9642 // private utility function:  64 bit atomics on 32 bit host.
9643 MachineBasicBlock *
9644 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
9645                                                        MachineBasicBlock *MBB,
9646                                                        unsigned regOpcL,
9647                                                        unsigned regOpcH,
9648                                                        unsigned immOpcL,
9649                                                        unsigned immOpcH,
9650                                                        bool invSrc) const {
9651   // For the atomic bitwise operator, we generate
9652   //   thisMBB (instructions are in pairs, except cmpxchg8b)
9653   //     ld t1,t2 = [bitinstr.addr]
9654   //   newMBB:
9655   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
9656   //     op  t5, t6 <- out1, out2, [bitinstr.val]
9657   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
9658   //     mov ECX, EBX <- t5, t6
9659   //     mov EAX, EDX <- t1, t2
9660   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
9661   //     mov t3, t4 <- EAX, EDX
9662   //     bz  newMBB
9663   //     result in out1, out2
9664   //     fallthrough -->nextMBB
9665
9666   const TargetRegisterClass *RC = X86::GR32RegisterClass;
9667   const unsigned LoadOpc = X86::MOV32rm;
9668   const unsigned NotOpc = X86::NOT32r;
9669   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9670   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9671   MachineFunction::iterator MBBIter = MBB;
9672   ++MBBIter;
9673
9674   /// First build the CFG
9675   MachineFunction *F = MBB->getParent();
9676   MachineBasicBlock *thisMBB = MBB;
9677   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9678   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9679   F->insert(MBBIter, newMBB);
9680   F->insert(MBBIter, nextMBB);
9681
9682   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9683   nextMBB->splice(nextMBB->begin(), thisMBB,
9684                   llvm::next(MachineBasicBlock::iterator(bInstr)),
9685                   thisMBB->end());
9686   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9687
9688   // Update thisMBB to fall through to newMBB
9689   thisMBB->addSuccessor(newMBB);
9690
9691   // newMBB jumps to itself and fall through to nextMBB
9692   newMBB->addSuccessor(nextMBB);
9693   newMBB->addSuccessor(newMBB);
9694
9695   DebugLoc dl = bInstr->getDebugLoc();
9696   // Insert instructions into newMBB based on incoming instruction
9697   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
9698   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
9699          "unexpected number of operands");
9700   MachineOperand& dest1Oper = bInstr->getOperand(0);
9701   MachineOperand& dest2Oper = bInstr->getOperand(1);
9702   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9703   for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
9704     argOpers[i] = &bInstr->getOperand(i+2);
9705
9706     // We use some of the operands multiple times, so conservatively just
9707     // clear any kill flags that might be present.
9708     if (argOpers[i]->isReg() && argOpers[i]->isUse())
9709       argOpers[i]->setIsKill(false);
9710   }
9711
9712   // x86 address has 5 operands: base, index, scale, displacement, and segment.
9713   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9714
9715   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9716   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
9717   for (int i=0; i <= lastAddrIndx; ++i)
9718     (*MIB).addOperand(*argOpers[i]);
9719   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9720   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
9721   // add 4 to displacement.
9722   for (int i=0; i <= lastAddrIndx-2; ++i)
9723     (*MIB).addOperand(*argOpers[i]);
9724   MachineOperand newOp3 = *(argOpers[3]);
9725   if (newOp3.isImm())
9726     newOp3.setImm(newOp3.getImm()+4);
9727   else
9728     newOp3.setOffset(newOp3.getOffset()+4);
9729   (*MIB).addOperand(newOp3);
9730   (*MIB).addOperand(*argOpers[lastAddrIndx]);
9731
9732   // t3/4 are defined later, at the bottom of the loop
9733   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
9734   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
9735   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
9736     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
9737   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
9738     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
9739
9740   // The subsequent operations should be using the destination registers of
9741   //the PHI instructions.
9742   if (invSrc) {
9743     t1 = F->getRegInfo().createVirtualRegister(RC);
9744     t2 = F->getRegInfo().createVirtualRegister(RC);
9745     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
9746     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
9747   } else {
9748     t1 = dest1Oper.getReg();
9749     t2 = dest2Oper.getReg();
9750   }
9751
9752   int valArgIndx = lastAddrIndx + 1;
9753   assert((argOpers[valArgIndx]->isReg() ||
9754           argOpers[valArgIndx]->isImm()) &&
9755          "invalid operand");
9756   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
9757   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
9758   if (argOpers[valArgIndx]->isReg())
9759     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
9760   else
9761     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
9762   if (regOpcL != X86::MOV32rr)
9763     MIB.addReg(t1);
9764   (*MIB).addOperand(*argOpers[valArgIndx]);
9765   assert(argOpers[valArgIndx + 1]->isReg() ==
9766          argOpers[valArgIndx]->isReg());
9767   assert(argOpers[valArgIndx + 1]->isImm() ==
9768          argOpers[valArgIndx]->isImm());
9769   if (argOpers[valArgIndx + 1]->isReg())
9770     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
9771   else
9772     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
9773   if (regOpcH != X86::MOV32rr)
9774     MIB.addReg(t2);
9775   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
9776
9777   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9778   MIB.addReg(t1);
9779   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
9780   MIB.addReg(t2);
9781
9782   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
9783   MIB.addReg(t5);
9784   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
9785   MIB.addReg(t6);
9786
9787   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
9788   for (int i=0; i <= lastAddrIndx; ++i)
9789     (*MIB).addOperand(*argOpers[i]);
9790
9791   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9792   (*MIB).setMemRefs(bInstr->memoperands_begin(),
9793                     bInstr->memoperands_end());
9794
9795   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
9796   MIB.addReg(X86::EAX);
9797   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
9798   MIB.addReg(X86::EDX);
9799
9800   // insert branch
9801   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9802
9803   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
9804   return nextMBB;
9805 }
9806
9807 // private utility function
9808 MachineBasicBlock *
9809 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
9810                                                       MachineBasicBlock *MBB,
9811                                                       unsigned cmovOpc) const {
9812   // For the atomic min/max operator, we generate
9813   //   thisMBB:
9814   //   newMBB:
9815   //     ld t1 = [min/max.addr]
9816   //     mov t2 = [min/max.val]
9817   //     cmp  t1, t2
9818   //     cmov[cond] t2 = t1
9819   //     mov EAX = t1
9820   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
9821   //     bz   newMBB
9822   //     fallthrough -->nextMBB
9823   //
9824   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9825   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9826   MachineFunction::iterator MBBIter = MBB;
9827   ++MBBIter;
9828
9829   /// First build the CFG
9830   MachineFunction *F = MBB->getParent();
9831   MachineBasicBlock *thisMBB = MBB;
9832   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9833   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9834   F->insert(MBBIter, newMBB);
9835   F->insert(MBBIter, nextMBB);
9836
9837   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9838   nextMBB->splice(nextMBB->begin(), thisMBB,
9839                   llvm::next(MachineBasicBlock::iterator(mInstr)),
9840                   thisMBB->end());
9841   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9842
9843   // Update thisMBB to fall through to newMBB
9844   thisMBB->addSuccessor(newMBB);
9845
9846   // newMBB jumps to newMBB and fall through to nextMBB
9847   newMBB->addSuccessor(nextMBB);
9848   newMBB->addSuccessor(newMBB);
9849
9850   DebugLoc dl = mInstr->getDebugLoc();
9851   // Insert instructions into newMBB based on incoming instruction
9852   assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9853          "unexpected number of operands");
9854   MachineOperand& destOper = mInstr->getOperand(0);
9855   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9856   int numArgs = mInstr->getNumOperands() - 1;
9857   for (int i=0; i < numArgs; ++i)
9858     argOpers[i] = &mInstr->getOperand(i+1);
9859
9860   // x86 address has 4 operands: base, index, scale, and displacement
9861   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9862   int valArgIndx = lastAddrIndx + 1;
9863
9864   unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9865   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
9866   for (int i=0; i <= lastAddrIndx; ++i)
9867     (*MIB).addOperand(*argOpers[i]);
9868
9869   // We only support register and immediate values
9870   assert((argOpers[valArgIndx]->isReg() ||
9871           argOpers[valArgIndx]->isImm()) &&
9872          "invalid operand");
9873
9874   unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9875   if (argOpers[valArgIndx]->isReg())
9876     MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
9877   else
9878     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
9879   (*MIB).addOperand(*argOpers[valArgIndx]);
9880
9881   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9882   MIB.addReg(t1);
9883
9884   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
9885   MIB.addReg(t1);
9886   MIB.addReg(t2);
9887
9888   // Generate movc
9889   unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9890   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
9891   MIB.addReg(t2);
9892   MIB.addReg(t1);
9893
9894   // Cmp and exchange if none has modified the memory location
9895   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
9896   for (int i=0; i <= lastAddrIndx; ++i)
9897     (*MIB).addOperand(*argOpers[i]);
9898   MIB.addReg(t3);
9899   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9900   (*MIB).setMemRefs(mInstr->memoperands_begin(),
9901                     mInstr->memoperands_end());
9902
9903   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9904   MIB.addReg(X86::EAX);
9905
9906   // insert branch
9907   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9908
9909   mInstr->eraseFromParent();   // The pseudo instruction is gone now.
9910   return nextMBB;
9911 }
9912
9913 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
9914 // or XMM0_V32I8 in AVX all of this code can be replaced with that
9915 // in the .td file.
9916 MachineBasicBlock *
9917 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
9918                             unsigned numArgs, bool memArg) const {
9919   assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
9920          "Target must have SSE4.2 or AVX features enabled");
9921
9922   DebugLoc dl = MI->getDebugLoc();
9923   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9924   unsigned Opc;
9925   if (!Subtarget->hasAVX()) {
9926     if (memArg)
9927       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
9928     else
9929       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
9930   } else {
9931     if (memArg)
9932       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
9933     else
9934       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
9935   }
9936
9937   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
9938   for (unsigned i = 0; i < numArgs; ++i) {
9939     MachineOperand &Op = MI->getOperand(i+1);
9940     if (!(Op.isReg() && Op.isImplicit()))
9941       MIB.addOperand(Op);
9942   }
9943   BuildMI(*BB, MI, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
9944     .addReg(X86::XMM0);
9945
9946   MI->eraseFromParent();
9947   return BB;
9948 }
9949
9950 MachineBasicBlock *
9951 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
9952   DebugLoc dl = MI->getDebugLoc();
9953   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9954
9955   // Address into RAX/EAX, other two args into ECX, EDX.
9956   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
9957   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
9958   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
9959   for (int i = 0; i < X86::AddrNumOperands; ++i)
9960     MIB.addOperand(MI->getOperand(i));
9961
9962   unsigned ValOps = X86::AddrNumOperands;
9963   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
9964     .addReg(MI->getOperand(ValOps).getReg());
9965   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
9966     .addReg(MI->getOperand(ValOps+1).getReg());
9967
9968   // The instruction doesn't actually take any operands though.
9969   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
9970
9971   MI->eraseFromParent(); // The pseudo is gone now.
9972   return BB;
9973 }
9974
9975 MachineBasicBlock *
9976 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
9977   DebugLoc dl = MI->getDebugLoc();
9978   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9979
9980   // First arg in ECX, the second in EAX.
9981   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
9982     .addReg(MI->getOperand(0).getReg());
9983   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
9984     .addReg(MI->getOperand(1).getReg());
9985
9986   // The instruction doesn't actually take any operands though.
9987   BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
9988
9989   MI->eraseFromParent(); // The pseudo is gone now.
9990   return BB;
9991 }
9992
9993 MachineBasicBlock *
9994 X86TargetLowering::EmitVAARG64WithCustomInserter(
9995                    MachineInstr *MI,
9996                    MachineBasicBlock *MBB) const {
9997   // Emit va_arg instruction on X86-64.
9998
9999   // Operands to this pseudo-instruction:
10000   // 0  ) Output        : destination address (reg)
10001   // 1-5) Input         : va_list address (addr, i64mem)
10002   // 6  ) ArgSize       : Size (in bytes) of vararg type
10003   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
10004   // 8  ) Align         : Alignment of type
10005   // 9  ) EFLAGS (implicit-def)
10006
10007   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
10008   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
10009
10010   unsigned DestReg = MI->getOperand(0).getReg();
10011   MachineOperand &Base = MI->getOperand(1);
10012   MachineOperand &Scale = MI->getOperand(2);
10013   MachineOperand &Index = MI->getOperand(3);
10014   MachineOperand &Disp = MI->getOperand(4);
10015   MachineOperand &Segment = MI->getOperand(5);
10016   unsigned ArgSize = MI->getOperand(6).getImm();
10017   unsigned ArgMode = MI->getOperand(7).getImm();
10018   unsigned Align = MI->getOperand(8).getImm();
10019
10020   // Memory Reference
10021   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
10022   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
10023   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
10024
10025   // Machine Information
10026   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10027   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
10028   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
10029   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
10030   DebugLoc DL = MI->getDebugLoc();
10031
10032   // struct va_list {
10033   //   i32   gp_offset
10034   //   i32   fp_offset
10035   //   i64   overflow_area (address)
10036   //   i64   reg_save_area (address)
10037   // }
10038   // sizeof(va_list) = 24
10039   // alignment(va_list) = 8
10040
10041   unsigned TotalNumIntRegs = 6;
10042   unsigned TotalNumXMMRegs = 8;
10043   bool UseGPOffset = (ArgMode == 1);
10044   bool UseFPOffset = (ArgMode == 2);
10045   unsigned MaxOffset = TotalNumIntRegs * 8 +
10046                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
10047
10048   /* Align ArgSize to a multiple of 8 */
10049   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
10050   bool NeedsAlign = (Align > 8);
10051
10052   MachineBasicBlock *thisMBB = MBB;
10053   MachineBasicBlock *overflowMBB;
10054   MachineBasicBlock *offsetMBB;
10055   MachineBasicBlock *endMBB;
10056
10057   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
10058   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
10059   unsigned OffsetReg = 0;
10060
10061   if (!UseGPOffset && !UseFPOffset) {
10062     // If we only pull from the overflow region, we don't create a branch.
10063     // We don't need to alter control flow.
10064     OffsetDestReg = 0; // unused
10065     OverflowDestReg = DestReg;
10066
10067     offsetMBB = NULL;
10068     overflowMBB = thisMBB;
10069     endMBB = thisMBB;
10070   } else {
10071     // First emit code to check if gp_offset (or fp_offset) is below the bound.
10072     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
10073     // If not, pull from overflow_area. (branch to overflowMBB)
10074     //
10075     //       thisMBB
10076     //         |     .
10077     //         |        .
10078     //     offsetMBB   overflowMBB
10079     //         |        .
10080     //         |     .
10081     //        endMBB
10082
10083     // Registers for the PHI in endMBB
10084     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
10085     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
10086
10087     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10088     MachineFunction *MF = MBB->getParent();
10089     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10090     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10091     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10092
10093     MachineFunction::iterator MBBIter = MBB;
10094     ++MBBIter;
10095
10096     // Insert the new basic blocks
10097     MF->insert(MBBIter, offsetMBB);
10098     MF->insert(MBBIter, overflowMBB);
10099     MF->insert(MBBIter, endMBB);
10100
10101     // Transfer the remainder of MBB and its successor edges to endMBB.
10102     endMBB->splice(endMBB->begin(), thisMBB,
10103                     llvm::next(MachineBasicBlock::iterator(MI)),
10104                     thisMBB->end());
10105     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
10106
10107     // Make offsetMBB and overflowMBB successors of thisMBB
10108     thisMBB->addSuccessor(offsetMBB);
10109     thisMBB->addSuccessor(overflowMBB);
10110
10111     // endMBB is a successor of both offsetMBB and overflowMBB
10112     offsetMBB->addSuccessor(endMBB);
10113     overflowMBB->addSuccessor(endMBB);
10114
10115     // Load the offset value into a register
10116     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
10117     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
10118       .addOperand(Base)
10119       .addOperand(Scale)
10120       .addOperand(Index)
10121       .addDisp(Disp, UseFPOffset ? 4 : 0)
10122       .addOperand(Segment)
10123       .setMemRefs(MMOBegin, MMOEnd);
10124
10125     // Check if there is enough room left to pull this argument.
10126     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
10127       .addReg(OffsetReg)
10128       .addImm(MaxOffset + 8 - ArgSizeA8);
10129
10130     // Branch to "overflowMBB" if offset >= max
10131     // Fall through to "offsetMBB" otherwise
10132     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
10133       .addMBB(overflowMBB);
10134   }
10135
10136   // In offsetMBB, emit code to use the reg_save_area.
10137   if (offsetMBB) {
10138     assert(OffsetReg != 0);
10139
10140     // Read the reg_save_area address.
10141     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
10142     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
10143       .addOperand(Base)
10144       .addOperand(Scale)
10145       .addOperand(Index)
10146       .addDisp(Disp, 16)
10147       .addOperand(Segment)
10148       .setMemRefs(MMOBegin, MMOEnd);
10149
10150     // Zero-extend the offset
10151     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
10152       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
10153         .addImm(0)
10154         .addReg(OffsetReg)
10155         .addImm(X86::sub_32bit);
10156
10157     // Add the offset to the reg_save_area to get the final address.
10158     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
10159       .addReg(OffsetReg64)
10160       .addReg(RegSaveReg);
10161
10162     // Compute the offset for the next argument
10163     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
10164     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
10165       .addReg(OffsetReg)
10166       .addImm(UseFPOffset ? 16 : 8);
10167
10168     // Store it back into the va_list.
10169     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
10170       .addOperand(Base)
10171       .addOperand(Scale)
10172       .addOperand(Index)
10173       .addDisp(Disp, UseFPOffset ? 4 : 0)
10174       .addOperand(Segment)
10175       .addReg(NextOffsetReg)
10176       .setMemRefs(MMOBegin, MMOEnd);
10177
10178     // Jump to endMBB
10179     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
10180       .addMBB(endMBB);
10181   }
10182
10183   //
10184   // Emit code to use overflow area
10185   //
10186
10187   // Load the overflow_area address into a register.
10188   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
10189   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
10190     .addOperand(Base)
10191     .addOperand(Scale)
10192     .addOperand(Index)
10193     .addDisp(Disp, 8)
10194     .addOperand(Segment)
10195     .setMemRefs(MMOBegin, MMOEnd);
10196
10197   // If we need to align it, do so. Otherwise, just copy the address
10198   // to OverflowDestReg.
10199   if (NeedsAlign) {
10200     // Align the overflow address
10201     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
10202     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
10203
10204     // aligned_addr = (addr + (align-1)) & ~(align-1)
10205     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
10206       .addReg(OverflowAddrReg)
10207       .addImm(Align-1);
10208
10209     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
10210       .addReg(TmpReg)
10211       .addImm(~(uint64_t)(Align-1));
10212   } else {
10213     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
10214       .addReg(OverflowAddrReg);
10215   }
10216
10217   // Compute the next overflow address after this argument.
10218   // (the overflow address should be kept 8-byte aligned)
10219   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
10220   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
10221     .addReg(OverflowDestReg)
10222     .addImm(ArgSizeA8);
10223
10224   // Store the new overflow address.
10225   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
10226     .addOperand(Base)
10227     .addOperand(Scale)
10228     .addOperand(Index)
10229     .addDisp(Disp, 8)
10230     .addOperand(Segment)
10231     .addReg(NextAddrReg)
10232     .setMemRefs(MMOBegin, MMOEnd);
10233
10234   // If we branched, emit the PHI to the front of endMBB.
10235   if (offsetMBB) {
10236     BuildMI(*endMBB, endMBB->begin(), DL,
10237             TII->get(X86::PHI), DestReg)
10238       .addReg(OffsetDestReg).addMBB(offsetMBB)
10239       .addReg(OverflowDestReg).addMBB(overflowMBB);
10240   }
10241
10242   // Erase the pseudo instruction
10243   MI->eraseFromParent();
10244
10245   return endMBB;
10246 }
10247
10248 MachineBasicBlock *
10249 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
10250                                                  MachineInstr *MI,
10251                                                  MachineBasicBlock *MBB) const {
10252   // Emit code to save XMM registers to the stack. The ABI says that the
10253   // number of registers to save is given in %al, so it's theoretically
10254   // possible to do an indirect jump trick to avoid saving all of them,
10255   // however this code takes a simpler approach and just executes all
10256   // of the stores if %al is non-zero. It's less code, and it's probably
10257   // easier on the hardware branch predictor, and stores aren't all that
10258   // expensive anyway.
10259
10260   // Create the new basic blocks. One block contains all the XMM stores,
10261   // and one block is the final destination regardless of whether any
10262   // stores were performed.
10263   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10264   MachineFunction *F = MBB->getParent();
10265   MachineFunction::iterator MBBIter = MBB;
10266   ++MBBIter;
10267   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
10268   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
10269   F->insert(MBBIter, XMMSaveMBB);
10270   F->insert(MBBIter, EndMBB);
10271
10272   // Transfer the remainder of MBB and its successor edges to EndMBB.
10273   EndMBB->splice(EndMBB->begin(), MBB,
10274                  llvm::next(MachineBasicBlock::iterator(MI)),
10275                  MBB->end());
10276   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
10277
10278   // The original block will now fall through to the XMM save block.
10279   MBB->addSuccessor(XMMSaveMBB);
10280   // The XMMSaveMBB will fall through to the end block.
10281   XMMSaveMBB->addSuccessor(EndMBB);
10282
10283   // Now add the instructions.
10284   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10285   DebugLoc DL = MI->getDebugLoc();
10286
10287   unsigned CountReg = MI->getOperand(0).getReg();
10288   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
10289   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
10290
10291   if (!Subtarget->isTargetWin64()) {
10292     // If %al is 0, branch around the XMM save block.
10293     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
10294     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
10295     MBB->addSuccessor(EndMBB);
10296   }
10297
10298   // In the XMM save block, save all the XMM argument registers.
10299   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
10300     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
10301     MachineMemOperand *MMO =
10302       F->getMachineMemOperand(
10303           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
10304         MachineMemOperand::MOStore,
10305         /*Size=*/16, /*Align=*/16);
10306     BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
10307       .addFrameIndex(RegSaveFrameIndex)
10308       .addImm(/*Scale=*/1)
10309       .addReg(/*IndexReg=*/0)
10310       .addImm(/*Disp=*/Offset)
10311       .addReg(/*Segment=*/0)
10312       .addReg(MI->getOperand(i).getReg())
10313       .addMemOperand(MMO);
10314   }
10315
10316   MI->eraseFromParent();   // The pseudo instruction is gone now.
10317
10318   return EndMBB;
10319 }
10320
10321 MachineBasicBlock *
10322 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
10323                                      MachineBasicBlock *BB) const {
10324   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10325   DebugLoc DL = MI->getDebugLoc();
10326
10327   // To "insert" a SELECT_CC instruction, we actually have to insert the
10328   // diamond control-flow pattern.  The incoming instruction knows the
10329   // destination vreg to set, the condition code register to branch on, the
10330   // true/false values to select between, and a branch opcode to use.
10331   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10332   MachineFunction::iterator It = BB;
10333   ++It;
10334
10335   //  thisMBB:
10336   //  ...
10337   //   TrueVal = ...
10338   //   cmpTY ccX, r1, r2
10339   //   bCC copy1MBB
10340   //   fallthrough --> copy0MBB
10341   MachineBasicBlock *thisMBB = BB;
10342   MachineFunction *F = BB->getParent();
10343   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
10344   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
10345   F->insert(It, copy0MBB);
10346   F->insert(It, sinkMBB);
10347
10348   // If the EFLAGS register isn't dead in the terminator, then claim that it's
10349   // live into the sink and copy blocks.
10350   const MachineFunction *MF = BB->getParent();
10351   const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
10352   BitVector ReservedRegs = TRI->getReservedRegs(*MF);
10353
10354   for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
10355     const MachineOperand &MO = MI->getOperand(I);
10356     if (!MO.isReg() || !MO.isUse() || MO.isKill()) continue;
10357     unsigned Reg = MO.getReg();
10358     if (Reg != X86::EFLAGS) continue;
10359     copy0MBB->addLiveIn(Reg);
10360     sinkMBB->addLiveIn(Reg);
10361   }
10362
10363   // Transfer the remainder of BB and its successor edges to sinkMBB.
10364   sinkMBB->splice(sinkMBB->begin(), BB,
10365                   llvm::next(MachineBasicBlock::iterator(MI)),
10366                   BB->end());
10367   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
10368
10369   // Add the true and fallthrough blocks as its successors.
10370   BB->addSuccessor(copy0MBB);
10371   BB->addSuccessor(sinkMBB);
10372
10373   // Create the conditional branch instruction.
10374   unsigned Opc =
10375     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
10376   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
10377
10378   //  copy0MBB:
10379   //   %FalseValue = ...
10380   //   # fallthrough to sinkMBB
10381   copy0MBB->addSuccessor(sinkMBB);
10382
10383   //  sinkMBB:
10384   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
10385   //  ...
10386   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
10387           TII->get(X86::PHI), MI->getOperand(0).getReg())
10388     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
10389     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
10390
10391   MI->eraseFromParent();   // The pseudo instruction is gone now.
10392   return sinkMBB;
10393 }
10394
10395 MachineBasicBlock *
10396 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
10397                                           MachineBasicBlock *BB) const {
10398   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10399   DebugLoc DL = MI->getDebugLoc();
10400
10401   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
10402   // non-trivial part is impdef of ESP.
10403   // FIXME: The code should be tweaked as soon as we'll try to do codegen for
10404   // mingw-w64.
10405
10406   const char *StackProbeSymbol =
10407       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
10408
10409   BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
10410     .addExternalSymbol(StackProbeSymbol)
10411     .addReg(X86::EAX, RegState::Implicit)
10412     .addReg(X86::ESP, RegState::Implicit)
10413     .addReg(X86::EAX, RegState::Define | RegState::Implicit)
10414     .addReg(X86::ESP, RegState::Define | RegState::Implicit)
10415     .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10416
10417   MI->eraseFromParent();   // The pseudo instruction is gone now.
10418   return BB;
10419 }
10420
10421 MachineBasicBlock *
10422 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
10423                                       MachineBasicBlock *BB) const {
10424   // This is pretty easy.  We're taking the value that we received from
10425   // our load from the relocation, sticking it in either RDI (x86-64)
10426   // or EAX and doing an indirect call.  The return value will then
10427   // be in the normal return register.
10428   const X86InstrInfo *TII
10429     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
10430   DebugLoc DL = MI->getDebugLoc();
10431   MachineFunction *F = BB->getParent();
10432
10433   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
10434   assert(MI->getOperand(3).isGlobal() && "This should be a global");
10435
10436   if (Subtarget->is64Bit()) {
10437     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10438                                       TII->get(X86::MOV64rm), X86::RDI)
10439     .addReg(X86::RIP)
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::CALL64m));
10445     addDirectMem(MIB, X86::RDI);
10446   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
10447     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10448                                       TII->get(X86::MOV32rm), X86::EAX)
10449     .addReg(0)
10450     .addImm(0).addReg(0)
10451     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10452                       MI->getOperand(3).getTargetFlags())
10453     .addReg(0);
10454     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10455     addDirectMem(MIB, X86::EAX);
10456   } else {
10457     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10458                                       TII->get(X86::MOV32rm), X86::EAX)
10459     .addReg(TII->getGlobalBaseReg(F))
10460     .addImm(0).addReg(0)
10461     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10462                       MI->getOperand(3).getTargetFlags())
10463     .addReg(0);
10464     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10465     addDirectMem(MIB, X86::EAX);
10466   }
10467
10468   MI->eraseFromParent(); // The pseudo instruction is gone now.
10469   return BB;
10470 }
10471
10472 MachineBasicBlock *
10473 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
10474                                                MachineBasicBlock *BB) const {
10475   switch (MI->getOpcode()) {
10476   default: assert(false && "Unexpected instr type to insert");
10477   case X86::TAILJMPd64:
10478   case X86::TAILJMPr64:
10479   case X86::TAILJMPm64:
10480     assert(!"TAILJMP64 would not be touched here.");
10481   case X86::TCRETURNdi64:
10482   case X86::TCRETURNri64:
10483   case X86::TCRETURNmi64:
10484     // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset.
10485     // On AMD64, additional defs should be added before register allocation.
10486     if (!Subtarget->isTargetWin64()) {
10487       MI->addRegisterDefined(X86::RSI);
10488       MI->addRegisterDefined(X86::RDI);
10489       MI->addRegisterDefined(X86::XMM6);
10490       MI->addRegisterDefined(X86::XMM7);
10491       MI->addRegisterDefined(X86::XMM8);
10492       MI->addRegisterDefined(X86::XMM9);
10493       MI->addRegisterDefined(X86::XMM10);
10494       MI->addRegisterDefined(X86::XMM11);
10495       MI->addRegisterDefined(X86::XMM12);
10496       MI->addRegisterDefined(X86::XMM13);
10497       MI->addRegisterDefined(X86::XMM14);
10498       MI->addRegisterDefined(X86::XMM15);
10499     }
10500     return BB;
10501   case X86::WIN_ALLOCA:
10502     return EmitLoweredWinAlloca(MI, BB);
10503   case X86::TLSCall_32:
10504   case X86::TLSCall_64:
10505     return EmitLoweredTLSCall(MI, BB);
10506   case X86::CMOV_GR8:
10507   case X86::CMOV_FR32:
10508   case X86::CMOV_FR64:
10509   case X86::CMOV_V4F32:
10510   case X86::CMOV_V2F64:
10511   case X86::CMOV_V2I64:
10512   case X86::CMOV_GR16:
10513   case X86::CMOV_GR32:
10514   case X86::CMOV_RFP32:
10515   case X86::CMOV_RFP64:
10516   case X86::CMOV_RFP80:
10517     return EmitLoweredSelect(MI, BB);
10518
10519   case X86::FP32_TO_INT16_IN_MEM:
10520   case X86::FP32_TO_INT32_IN_MEM:
10521   case X86::FP32_TO_INT64_IN_MEM:
10522   case X86::FP64_TO_INT16_IN_MEM:
10523   case X86::FP64_TO_INT32_IN_MEM:
10524   case X86::FP64_TO_INT64_IN_MEM:
10525   case X86::FP80_TO_INT16_IN_MEM:
10526   case X86::FP80_TO_INT32_IN_MEM:
10527   case X86::FP80_TO_INT64_IN_MEM: {
10528     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10529     DebugLoc DL = MI->getDebugLoc();
10530
10531     // Change the floating point control register to use "round towards zero"
10532     // mode when truncating to an integer value.
10533     MachineFunction *F = BB->getParent();
10534     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
10535     addFrameReference(BuildMI(*BB, MI, DL,
10536                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
10537
10538     // Load the old value of the high byte of the control word...
10539     unsigned OldCW =
10540       F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
10541     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
10542                       CWFrameIdx);
10543
10544     // Set the high part to be round to zero...
10545     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
10546       .addImm(0xC7F);
10547
10548     // Reload the modified control word now...
10549     addFrameReference(BuildMI(*BB, MI, DL,
10550                               TII->get(X86::FLDCW16m)), CWFrameIdx);
10551
10552     // Restore the memory image of control word to original value
10553     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
10554       .addReg(OldCW);
10555
10556     // Get the X86 opcode to use.
10557     unsigned Opc;
10558     switch (MI->getOpcode()) {
10559     default: llvm_unreachable("illegal opcode!");
10560     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
10561     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
10562     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
10563     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
10564     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
10565     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
10566     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
10567     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
10568     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
10569     }
10570
10571     X86AddressMode AM;
10572     MachineOperand &Op = MI->getOperand(0);
10573     if (Op.isReg()) {
10574       AM.BaseType = X86AddressMode::RegBase;
10575       AM.Base.Reg = Op.getReg();
10576     } else {
10577       AM.BaseType = X86AddressMode::FrameIndexBase;
10578       AM.Base.FrameIndex = Op.getIndex();
10579     }
10580     Op = MI->getOperand(1);
10581     if (Op.isImm())
10582       AM.Scale = Op.getImm();
10583     Op = MI->getOperand(2);
10584     if (Op.isImm())
10585       AM.IndexReg = Op.getImm();
10586     Op = MI->getOperand(3);
10587     if (Op.isGlobal()) {
10588       AM.GV = Op.getGlobal();
10589     } else {
10590       AM.Disp = Op.getImm();
10591     }
10592     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
10593                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
10594
10595     // Reload the original control word now.
10596     addFrameReference(BuildMI(*BB, MI, DL,
10597                               TII->get(X86::FLDCW16m)), CWFrameIdx);
10598
10599     MI->eraseFromParent();   // The pseudo instruction is gone now.
10600     return BB;
10601   }
10602     // String/text processing lowering.
10603   case X86::PCMPISTRM128REG:
10604   case X86::VPCMPISTRM128REG:
10605     return EmitPCMP(MI, BB, 3, false /* in-mem */);
10606   case X86::PCMPISTRM128MEM:
10607   case X86::VPCMPISTRM128MEM:
10608     return EmitPCMP(MI, BB, 3, true /* in-mem */);
10609   case X86::PCMPESTRM128REG:
10610   case X86::VPCMPESTRM128REG:
10611     return EmitPCMP(MI, BB, 5, false /* in mem */);
10612   case X86::PCMPESTRM128MEM:
10613   case X86::VPCMPESTRM128MEM:
10614     return EmitPCMP(MI, BB, 5, true /* in mem */);
10615
10616     // Thread synchronization.
10617   case X86::MONITOR:
10618     return EmitMonitor(MI, BB);
10619   case X86::MWAIT:
10620     return EmitMwait(MI, BB);
10621
10622     // Atomic Lowering.
10623   case X86::ATOMAND32:
10624     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10625                                                X86::AND32ri, X86::MOV32rm,
10626                                                X86::LCMPXCHG32,
10627                                                X86::NOT32r, X86::EAX,
10628                                                X86::GR32RegisterClass);
10629   case X86::ATOMOR32:
10630     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
10631                                                X86::OR32ri, X86::MOV32rm,
10632                                                X86::LCMPXCHG32,
10633                                                X86::NOT32r, X86::EAX,
10634                                                X86::GR32RegisterClass);
10635   case X86::ATOMXOR32:
10636     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
10637                                                X86::XOR32ri, X86::MOV32rm,
10638                                                X86::LCMPXCHG32,
10639                                                X86::NOT32r, X86::EAX,
10640                                                X86::GR32RegisterClass);
10641   case X86::ATOMNAND32:
10642     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10643                                                X86::AND32ri, X86::MOV32rm,
10644                                                X86::LCMPXCHG32,
10645                                                X86::NOT32r, X86::EAX,
10646                                                X86::GR32RegisterClass, true);
10647   case X86::ATOMMIN32:
10648     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
10649   case X86::ATOMMAX32:
10650     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
10651   case X86::ATOMUMIN32:
10652     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
10653   case X86::ATOMUMAX32:
10654     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
10655
10656   case X86::ATOMAND16:
10657     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10658                                                X86::AND16ri, X86::MOV16rm,
10659                                                X86::LCMPXCHG16,
10660                                                X86::NOT16r, X86::AX,
10661                                                X86::GR16RegisterClass);
10662   case X86::ATOMOR16:
10663     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
10664                                                X86::OR16ri, X86::MOV16rm,
10665                                                X86::LCMPXCHG16,
10666                                                X86::NOT16r, X86::AX,
10667                                                X86::GR16RegisterClass);
10668   case X86::ATOMXOR16:
10669     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
10670                                                X86::XOR16ri, X86::MOV16rm,
10671                                                X86::LCMPXCHG16,
10672                                                X86::NOT16r, X86::AX,
10673                                                X86::GR16RegisterClass);
10674   case X86::ATOMNAND16:
10675     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10676                                                X86::AND16ri, X86::MOV16rm,
10677                                                X86::LCMPXCHG16,
10678                                                X86::NOT16r, X86::AX,
10679                                                X86::GR16RegisterClass, true);
10680   case X86::ATOMMIN16:
10681     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
10682   case X86::ATOMMAX16:
10683     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
10684   case X86::ATOMUMIN16:
10685     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
10686   case X86::ATOMUMAX16:
10687     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
10688
10689   case X86::ATOMAND8:
10690     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10691                                                X86::AND8ri, X86::MOV8rm,
10692                                                X86::LCMPXCHG8,
10693                                                X86::NOT8r, X86::AL,
10694                                                X86::GR8RegisterClass);
10695   case X86::ATOMOR8:
10696     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
10697                                                X86::OR8ri, X86::MOV8rm,
10698                                                X86::LCMPXCHG8,
10699                                                X86::NOT8r, X86::AL,
10700                                                X86::GR8RegisterClass);
10701   case X86::ATOMXOR8:
10702     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
10703                                                X86::XOR8ri, X86::MOV8rm,
10704                                                X86::LCMPXCHG8,
10705                                                X86::NOT8r, X86::AL,
10706                                                X86::GR8RegisterClass);
10707   case X86::ATOMNAND8:
10708     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10709                                                X86::AND8ri, X86::MOV8rm,
10710                                                X86::LCMPXCHG8,
10711                                                X86::NOT8r, X86::AL,
10712                                                X86::GR8RegisterClass, true);
10713   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
10714   // This group is for 64-bit host.
10715   case X86::ATOMAND64:
10716     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10717                                                X86::AND64ri32, X86::MOV64rm,
10718                                                X86::LCMPXCHG64,
10719                                                X86::NOT64r, X86::RAX,
10720                                                X86::GR64RegisterClass);
10721   case X86::ATOMOR64:
10722     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
10723                                                X86::OR64ri32, X86::MOV64rm,
10724                                                X86::LCMPXCHG64,
10725                                                X86::NOT64r, X86::RAX,
10726                                                X86::GR64RegisterClass);
10727   case X86::ATOMXOR64:
10728     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
10729                                                X86::XOR64ri32, X86::MOV64rm,
10730                                                X86::LCMPXCHG64,
10731                                                X86::NOT64r, X86::RAX,
10732                                                X86::GR64RegisterClass);
10733   case X86::ATOMNAND64:
10734     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10735                                                X86::AND64ri32, X86::MOV64rm,
10736                                                X86::LCMPXCHG64,
10737                                                X86::NOT64r, X86::RAX,
10738                                                X86::GR64RegisterClass, true);
10739   case X86::ATOMMIN64:
10740     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
10741   case X86::ATOMMAX64:
10742     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
10743   case X86::ATOMUMIN64:
10744     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
10745   case X86::ATOMUMAX64:
10746     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
10747
10748   // This group does 64-bit operations on a 32-bit host.
10749   case X86::ATOMAND6432:
10750     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10751                                                X86::AND32rr, X86::AND32rr,
10752                                                X86::AND32ri, X86::AND32ri,
10753                                                false);
10754   case X86::ATOMOR6432:
10755     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10756                                                X86::OR32rr, X86::OR32rr,
10757                                                X86::OR32ri, X86::OR32ri,
10758                                                false);
10759   case X86::ATOMXOR6432:
10760     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10761                                                X86::XOR32rr, X86::XOR32rr,
10762                                                X86::XOR32ri, X86::XOR32ri,
10763                                                false);
10764   case X86::ATOMNAND6432:
10765     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10766                                                X86::AND32rr, X86::AND32rr,
10767                                                X86::AND32ri, X86::AND32ri,
10768                                                true);
10769   case X86::ATOMADD6432:
10770     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10771                                                X86::ADD32rr, X86::ADC32rr,
10772                                                X86::ADD32ri, X86::ADC32ri,
10773                                                false);
10774   case X86::ATOMSUB6432:
10775     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10776                                                X86::SUB32rr, X86::SBB32rr,
10777                                                X86::SUB32ri, X86::SBB32ri,
10778                                                false);
10779   case X86::ATOMSWAP6432:
10780     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10781                                                X86::MOV32rr, X86::MOV32rr,
10782                                                X86::MOV32ri, X86::MOV32ri,
10783                                                false);
10784   case X86::VASTART_SAVE_XMM_REGS:
10785     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
10786
10787   case X86::VAARG_64:
10788     return EmitVAARG64WithCustomInserter(MI, BB);
10789   }
10790 }
10791
10792 //===----------------------------------------------------------------------===//
10793 //                           X86 Optimization Hooks
10794 //===----------------------------------------------------------------------===//
10795
10796 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
10797                                                        const APInt &Mask,
10798                                                        APInt &KnownZero,
10799                                                        APInt &KnownOne,
10800                                                        const SelectionDAG &DAG,
10801                                                        unsigned Depth) const {
10802   unsigned Opc = Op.getOpcode();
10803   assert((Opc >= ISD::BUILTIN_OP_END ||
10804           Opc == ISD::INTRINSIC_WO_CHAIN ||
10805           Opc == ISD::INTRINSIC_W_CHAIN ||
10806           Opc == ISD::INTRINSIC_VOID) &&
10807          "Should use MaskedValueIsZero if you don't know whether Op"
10808          " is a target node!");
10809
10810   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
10811   switch (Opc) {
10812   default: break;
10813   case X86ISD::ADD:
10814   case X86ISD::SUB:
10815   case X86ISD::ADC:
10816   case X86ISD::SBB:
10817   case X86ISD::SMUL:
10818   case X86ISD::UMUL:
10819   case X86ISD::INC:
10820   case X86ISD::DEC:
10821   case X86ISD::OR:
10822   case X86ISD::XOR:
10823   case X86ISD::AND:
10824     // These nodes' second result is a boolean.
10825     if (Op.getResNo() == 0)
10826       break;
10827     // Fallthrough
10828   case X86ISD::SETCC:
10829     KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
10830                                        Mask.getBitWidth() - 1);
10831     break;
10832   }
10833 }
10834
10835 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
10836                                                          unsigned Depth) const {
10837   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
10838   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
10839     return Op.getValueType().getScalarType().getSizeInBits();
10840
10841   // Fallback case.
10842   return 1;
10843 }
10844
10845 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
10846 /// node is a GlobalAddress + offset.
10847 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
10848                                        const GlobalValue* &GA,
10849                                        int64_t &Offset) const {
10850   if (N->getOpcode() == X86ISD::Wrapper) {
10851     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
10852       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
10853       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
10854       return true;
10855     }
10856   }
10857   return TargetLowering::isGAPlusOffset(N, GA, Offset);
10858 }
10859
10860 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
10861 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
10862 /// if the load addresses are consecutive, non-overlapping, and in the right
10863 /// order.
10864 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
10865                                      TargetLowering::DAGCombinerInfo &DCI) {
10866   DebugLoc dl = N->getDebugLoc();
10867   EVT VT = N->getValueType(0);
10868
10869   if (VT.getSizeInBits() != 128)
10870     return SDValue();
10871
10872   // Don't create instructions with illegal types after legalize types has run.
10873   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10874   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
10875     return SDValue();
10876
10877   SmallVector<SDValue, 16> Elts;
10878   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
10879     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
10880
10881   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
10882 }
10883
10884 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
10885 /// generation and convert it from being a bunch of shuffles and extracts
10886 /// to a simple store and scalar loads to extract the elements.
10887 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
10888                                                 const TargetLowering &TLI) {
10889   SDValue InputVector = N->getOperand(0);
10890
10891   // Only operate on vectors of 4 elements, where the alternative shuffling
10892   // gets to be more expensive.
10893   if (InputVector.getValueType() != MVT::v4i32)
10894     return SDValue();
10895
10896   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
10897   // single use which is a sign-extend or zero-extend, and all elements are
10898   // used.
10899   SmallVector<SDNode *, 4> Uses;
10900   unsigned ExtractedElements = 0;
10901   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
10902        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
10903     if (UI.getUse().getResNo() != InputVector.getResNo())
10904       return SDValue();
10905
10906     SDNode *Extract = *UI;
10907     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10908       return SDValue();
10909
10910     if (Extract->getValueType(0) != MVT::i32)
10911       return SDValue();
10912     if (!Extract->hasOneUse())
10913       return SDValue();
10914     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
10915         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
10916       return SDValue();
10917     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
10918       return SDValue();
10919
10920     // Record which element was extracted.
10921     ExtractedElements |=
10922       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
10923
10924     Uses.push_back(Extract);
10925   }
10926
10927   // If not all the elements were used, this may not be worthwhile.
10928   if (ExtractedElements != 15)
10929     return SDValue();
10930
10931   // Ok, we've now decided to do the transformation.
10932   DebugLoc dl = InputVector.getDebugLoc();
10933
10934   // Store the value to a temporary stack slot.
10935   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
10936   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
10937                             MachinePointerInfo(), false, false, 0);
10938
10939   // Replace each use (extract) with a load of the appropriate element.
10940   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
10941        UE = Uses.end(); UI != UE; ++UI) {
10942     SDNode *Extract = *UI;
10943
10944     // Compute the element's address.
10945     SDValue Idx = Extract->getOperand(1);
10946     unsigned EltSize =
10947         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
10948     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
10949     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
10950
10951     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(),
10952                                      StackPtr, OffsetVal);
10953
10954     // Load the scalar.
10955     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
10956                                      ScalarAddr, MachinePointerInfo(),
10957                                      false, false, 0);
10958
10959     // Replace the exact with the load.
10960     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
10961   }
10962
10963   // The replacement was made in place; don't return anything.
10964   return SDValue();
10965 }
10966
10967 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
10968 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
10969                                     const X86Subtarget *Subtarget) {
10970   DebugLoc DL = N->getDebugLoc();
10971   SDValue Cond = N->getOperand(0);
10972   // Get the LHS/RHS of the select.
10973   SDValue LHS = N->getOperand(1);
10974   SDValue RHS = N->getOperand(2);
10975
10976   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
10977   // instructions match the semantics of the common C idiom x<y?x:y but not
10978   // x<=y?x:y, because of how they handle negative zero (which can be
10979   // ignored in unsafe-math mode).
10980   if (Subtarget->hasSSE2() &&
10981       (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
10982       Cond.getOpcode() == ISD::SETCC) {
10983     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
10984
10985     unsigned Opcode = 0;
10986     // Check for x CC y ? x : y.
10987     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
10988         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
10989       switch (CC) {
10990       default: break;
10991       case ISD::SETULT:
10992         // Converting this to a min would handle NaNs incorrectly, and swapping
10993         // the operands would cause it to handle comparisons between positive
10994         // and negative zero incorrectly.
10995         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
10996           if (!UnsafeFPMath &&
10997               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10998             break;
10999           std::swap(LHS, RHS);
11000         }
11001         Opcode = X86ISD::FMIN;
11002         break;
11003       case ISD::SETOLE:
11004         // Converting this to a min would handle comparisons between positive
11005         // and negative zero incorrectly.
11006         if (!UnsafeFPMath &&
11007             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
11008           break;
11009         Opcode = X86ISD::FMIN;
11010         break;
11011       case ISD::SETULE:
11012         // Converting this to a min would handle both negative zeros and NaNs
11013         // incorrectly, but we can swap the operands to fix both.
11014         std::swap(LHS, RHS);
11015       case ISD::SETOLT:
11016       case ISD::SETLT:
11017       case ISD::SETLE:
11018         Opcode = X86ISD::FMIN;
11019         break;
11020
11021       case ISD::SETOGE:
11022         // Converting this to a max would handle comparisons between positive
11023         // and negative zero incorrectly.
11024         if (!UnsafeFPMath &&
11025             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS))
11026           break;
11027         Opcode = X86ISD::FMAX;
11028         break;
11029       case ISD::SETUGT:
11030         // Converting this to a max would handle NaNs incorrectly, and swapping
11031         // the operands would cause it to handle comparisons between positive
11032         // and negative zero incorrectly.
11033         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
11034           if (!UnsafeFPMath &&
11035               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
11036             break;
11037           std::swap(LHS, RHS);
11038         }
11039         Opcode = X86ISD::FMAX;
11040         break;
11041       case ISD::SETUGE:
11042         // Converting this to a max would handle both negative zeros and NaNs
11043         // incorrectly, but we can swap the operands to fix both.
11044         std::swap(LHS, RHS);
11045       case ISD::SETOGT:
11046       case ISD::SETGT:
11047       case ISD::SETGE:
11048         Opcode = X86ISD::FMAX;
11049         break;
11050       }
11051     // Check for x CC y ? y : x -- a min/max with reversed arms.
11052     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
11053                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
11054       switch (CC) {
11055       default: break;
11056       case ISD::SETOGE:
11057         // Converting this to a min would handle comparisons between positive
11058         // and negative zero incorrectly, and swapping the operands would
11059         // cause it to handle NaNs incorrectly.
11060         if (!UnsafeFPMath &&
11061             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
11062           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11063             break;
11064           std::swap(LHS, RHS);
11065         }
11066         Opcode = X86ISD::FMIN;
11067         break;
11068       case ISD::SETUGT:
11069         // Converting this to a min would handle NaNs incorrectly.
11070         if (!UnsafeFPMath &&
11071             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
11072           break;
11073         Opcode = X86ISD::FMIN;
11074         break;
11075       case ISD::SETUGE:
11076         // Converting this to a min would handle both negative zeros and NaNs
11077         // incorrectly, but we can swap the operands to fix both.
11078         std::swap(LHS, RHS);
11079       case ISD::SETOGT:
11080       case ISD::SETGT:
11081       case ISD::SETGE:
11082         Opcode = X86ISD::FMIN;
11083         break;
11084
11085       case ISD::SETULT:
11086         // Converting this to a max would handle NaNs incorrectly.
11087         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11088           break;
11089         Opcode = X86ISD::FMAX;
11090         break;
11091       case ISD::SETOLE:
11092         // Converting this to a max would handle comparisons between positive
11093         // and negative zero incorrectly, and swapping the operands would
11094         // cause it to handle NaNs incorrectly.
11095         if (!UnsafeFPMath &&
11096             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
11097           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11098             break;
11099           std::swap(LHS, RHS);
11100         }
11101         Opcode = X86ISD::FMAX;
11102         break;
11103       case ISD::SETULE:
11104         // Converting this to a max would handle both negative zeros and NaNs
11105         // incorrectly, but we can swap the operands to fix both.
11106         std::swap(LHS, RHS);
11107       case ISD::SETOLT:
11108       case ISD::SETLT:
11109       case ISD::SETLE:
11110         Opcode = X86ISD::FMAX;
11111         break;
11112       }
11113     }
11114
11115     if (Opcode)
11116       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
11117   }
11118
11119   // If this is a select between two integer constants, try to do some
11120   // optimizations.
11121   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
11122     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
11123       // Don't do this for crazy integer types.
11124       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
11125         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
11126         // so that TrueC (the true value) is larger than FalseC.
11127         bool NeedsCondInvert = false;
11128
11129         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
11130             // Efficiently invertible.
11131             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
11132              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
11133               isa<ConstantSDNode>(Cond.getOperand(1))))) {
11134           NeedsCondInvert = true;
11135           std::swap(TrueC, FalseC);
11136         }
11137
11138         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
11139         if (FalseC->getAPIntValue() == 0 &&
11140             TrueC->getAPIntValue().isPowerOf2()) {
11141           if (NeedsCondInvert) // Invert the condition if needed.
11142             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11143                                DAG.getConstant(1, Cond.getValueType()));
11144
11145           // Zero extend the condition if needed.
11146           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
11147
11148           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
11149           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
11150                              DAG.getConstant(ShAmt, MVT::i8));
11151         }
11152
11153         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
11154         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
11155           if (NeedsCondInvert) // Invert the condition if needed.
11156             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11157                                DAG.getConstant(1, Cond.getValueType()));
11158
11159           // Zero extend the condition if needed.
11160           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
11161                              FalseC->getValueType(0), Cond);
11162           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11163                              SDValue(FalseC, 0));
11164         }
11165
11166         // Optimize cases that will turn into an LEA instruction.  This requires
11167         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
11168         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
11169           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
11170           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
11171
11172           bool isFastMultiplier = false;
11173           if (Diff < 10) {
11174             switch ((unsigned char)Diff) {
11175               default: break;
11176               case 1:  // result = add base, cond
11177               case 2:  // result = lea base(    , cond*2)
11178               case 3:  // result = lea base(cond, cond*2)
11179               case 4:  // result = lea base(    , cond*4)
11180               case 5:  // result = lea base(cond, cond*4)
11181               case 8:  // result = lea base(    , cond*8)
11182               case 9:  // result = lea base(cond, cond*8)
11183                 isFastMultiplier = true;
11184                 break;
11185             }
11186           }
11187
11188           if (isFastMultiplier) {
11189             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
11190             if (NeedsCondInvert) // Invert the condition if needed.
11191               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11192                                  DAG.getConstant(1, Cond.getValueType()));
11193
11194             // Zero extend the condition if needed.
11195             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
11196                                Cond);
11197             // Scale the condition by the difference.
11198             if (Diff != 1)
11199               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
11200                                  DAG.getConstant(Diff, Cond.getValueType()));
11201
11202             // Add the base if non-zero.
11203             if (FalseC->getAPIntValue() != 0)
11204               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11205                                  SDValue(FalseC, 0));
11206             return Cond;
11207           }
11208         }
11209       }
11210   }
11211
11212   return SDValue();
11213 }
11214
11215 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
11216 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
11217                                   TargetLowering::DAGCombinerInfo &DCI) {
11218   DebugLoc DL = N->getDebugLoc();
11219
11220   // If the flag operand isn't dead, don't touch this CMOV.
11221   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
11222     return SDValue();
11223
11224   // If this is a select between two integer constants, try to do some
11225   // optimizations.  Note that the operands are ordered the opposite of SELECT
11226   // operands.
11227   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
11228     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
11229       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
11230       // larger than FalseC (the false value).
11231       X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
11232
11233       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
11234         CC = X86::GetOppositeBranchCondition(CC);
11235         std::swap(TrueC, FalseC);
11236       }
11237
11238       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
11239       // This is efficient for any integer data type (including i8/i16) and
11240       // shift amount.
11241       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
11242         SDValue Cond = N->getOperand(3);
11243         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11244                            DAG.getConstant(CC, MVT::i8), Cond);
11245
11246         // Zero extend the condition if needed.
11247         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
11248
11249         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
11250         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
11251                            DAG.getConstant(ShAmt, MVT::i8));
11252         if (N->getNumValues() == 2)  // Dead flag value?
11253           return DCI.CombineTo(N, Cond, SDValue());
11254         return Cond;
11255       }
11256
11257       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
11258       // for any integer data type, including i8/i16.
11259       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
11260         SDValue Cond = N->getOperand(3);
11261         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11262                            DAG.getConstant(CC, MVT::i8), Cond);
11263
11264         // Zero extend the condition if needed.
11265         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
11266                            FalseC->getValueType(0), Cond);
11267         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11268                            SDValue(FalseC, 0));
11269
11270         if (N->getNumValues() == 2)  // Dead flag value?
11271           return DCI.CombineTo(N, Cond, SDValue());
11272         return Cond;
11273       }
11274
11275       // Optimize cases that will turn into an LEA instruction.  This requires
11276       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
11277       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
11278         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
11279         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
11280
11281         bool isFastMultiplier = false;
11282         if (Diff < 10) {
11283           switch ((unsigned char)Diff) {
11284           default: break;
11285           case 1:  // result = add base, cond
11286           case 2:  // result = lea base(    , cond*2)
11287           case 3:  // result = lea base(cond, cond*2)
11288           case 4:  // result = lea base(    , cond*4)
11289           case 5:  // result = lea base(cond, cond*4)
11290           case 8:  // result = lea base(    , cond*8)
11291           case 9:  // result = lea base(cond, cond*8)
11292             isFastMultiplier = true;
11293             break;
11294           }
11295         }
11296
11297         if (isFastMultiplier) {
11298           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
11299           SDValue Cond = N->getOperand(3);
11300           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11301                              DAG.getConstant(CC, MVT::i8), Cond);
11302           // Zero extend the condition if needed.
11303           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
11304                              Cond);
11305           // Scale the condition by the difference.
11306           if (Diff != 1)
11307             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
11308                                DAG.getConstant(Diff, Cond.getValueType()));
11309
11310           // Add the base if non-zero.
11311           if (FalseC->getAPIntValue() != 0)
11312             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11313                                SDValue(FalseC, 0));
11314           if (N->getNumValues() == 2)  // Dead flag value?
11315             return DCI.CombineTo(N, Cond, SDValue());
11316           return Cond;
11317         }
11318       }
11319     }
11320   }
11321   return SDValue();
11322 }
11323
11324
11325 /// PerformMulCombine - Optimize a single multiply with constant into two
11326 /// in order to implement it with two cheaper instructions, e.g.
11327 /// LEA + SHL, LEA + LEA.
11328 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
11329                                  TargetLowering::DAGCombinerInfo &DCI) {
11330   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11331     return SDValue();
11332
11333   EVT VT = N->getValueType(0);
11334   if (VT != MVT::i64)
11335     return SDValue();
11336
11337   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
11338   if (!C)
11339     return SDValue();
11340   uint64_t MulAmt = C->getZExtValue();
11341   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
11342     return SDValue();
11343
11344   uint64_t MulAmt1 = 0;
11345   uint64_t MulAmt2 = 0;
11346   if ((MulAmt % 9) == 0) {
11347     MulAmt1 = 9;
11348     MulAmt2 = MulAmt / 9;
11349   } else if ((MulAmt % 5) == 0) {
11350     MulAmt1 = 5;
11351     MulAmt2 = MulAmt / 5;
11352   } else if ((MulAmt % 3) == 0) {
11353     MulAmt1 = 3;
11354     MulAmt2 = MulAmt / 3;
11355   }
11356   if (MulAmt2 &&
11357       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
11358     DebugLoc DL = N->getDebugLoc();
11359
11360     if (isPowerOf2_64(MulAmt2) &&
11361         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
11362       // If second multiplifer is pow2, issue it first. We want the multiply by
11363       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
11364       // is an add.
11365       std::swap(MulAmt1, MulAmt2);
11366
11367     SDValue NewMul;
11368     if (isPowerOf2_64(MulAmt1))
11369       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
11370                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
11371     else
11372       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
11373                            DAG.getConstant(MulAmt1, VT));
11374
11375     if (isPowerOf2_64(MulAmt2))
11376       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
11377                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
11378     else
11379       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
11380                            DAG.getConstant(MulAmt2, VT));
11381
11382     // Do not add new nodes to DAG combiner worklist.
11383     DCI.CombineTo(N, NewMul, false);
11384   }
11385   return SDValue();
11386 }
11387
11388 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
11389   SDValue N0 = N->getOperand(0);
11390   SDValue N1 = N->getOperand(1);
11391   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
11392   EVT VT = N0.getValueType();
11393
11394   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
11395   // since the result of setcc_c is all zero's or all ones.
11396   if (N1C && N0.getOpcode() == ISD::AND &&
11397       N0.getOperand(1).getOpcode() == ISD::Constant) {
11398     SDValue N00 = N0.getOperand(0);
11399     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
11400         ((N00.getOpcode() == ISD::ANY_EXTEND ||
11401           N00.getOpcode() == ISD::ZERO_EXTEND) &&
11402          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
11403       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
11404       APInt ShAmt = N1C->getAPIntValue();
11405       Mask = Mask.shl(ShAmt);
11406       if (Mask != 0)
11407         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
11408                            N00, DAG.getConstant(Mask, VT));
11409     }
11410   }
11411
11412   return SDValue();
11413 }
11414
11415 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
11416 ///                       when possible.
11417 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
11418                                    const X86Subtarget *Subtarget) {
11419   EVT VT = N->getValueType(0);
11420   if (!VT.isVector() && VT.isInteger() &&
11421       N->getOpcode() == ISD::SHL)
11422     return PerformSHLCombine(N, DAG);
11423
11424   // On X86 with SSE2 support, we can transform this to a vector shift if
11425   // all elements are shifted by the same amount.  We can't do this in legalize
11426   // because the a constant vector is typically transformed to a constant pool
11427   // so we have no knowledge of the shift amount.
11428   if (!Subtarget->hasSSE2())
11429     return SDValue();
11430
11431   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
11432     return SDValue();
11433
11434   SDValue ShAmtOp = N->getOperand(1);
11435   EVT EltVT = VT.getVectorElementType();
11436   DebugLoc DL = N->getDebugLoc();
11437   SDValue BaseShAmt = SDValue();
11438   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
11439     unsigned NumElts = VT.getVectorNumElements();
11440     unsigned i = 0;
11441     for (; i != NumElts; ++i) {
11442       SDValue Arg = ShAmtOp.getOperand(i);
11443       if (Arg.getOpcode() == ISD::UNDEF) continue;
11444       BaseShAmt = Arg;
11445       break;
11446     }
11447     for (; i != NumElts; ++i) {
11448       SDValue Arg = ShAmtOp.getOperand(i);
11449       if (Arg.getOpcode() == ISD::UNDEF) continue;
11450       if (Arg != BaseShAmt) {
11451         return SDValue();
11452       }
11453     }
11454   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
11455              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
11456     SDValue InVec = ShAmtOp.getOperand(0);
11457     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
11458       unsigned NumElts = InVec.getValueType().getVectorNumElements();
11459       unsigned i = 0;
11460       for (; i != NumElts; ++i) {
11461         SDValue Arg = InVec.getOperand(i);
11462         if (Arg.getOpcode() == ISD::UNDEF) continue;
11463         BaseShAmt = Arg;
11464         break;
11465       }
11466     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
11467        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
11468          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
11469          if (C->getZExtValue() == SplatIdx)
11470            BaseShAmt = InVec.getOperand(1);
11471        }
11472     }
11473     if (BaseShAmt.getNode() == 0)
11474       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
11475                               DAG.getIntPtrConstant(0));
11476   } else
11477     return SDValue();
11478
11479   // The shift amount is an i32.
11480   if (EltVT.bitsGT(MVT::i32))
11481     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
11482   else if (EltVT.bitsLT(MVT::i32))
11483     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
11484
11485   // The shift amount is identical so we can do a vector shift.
11486   SDValue  ValOp = N->getOperand(0);
11487   switch (N->getOpcode()) {
11488   default:
11489     llvm_unreachable("Unknown shift opcode!");
11490     break;
11491   case ISD::SHL:
11492     if (VT == MVT::v2i64)
11493       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11494                          DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
11495                          ValOp, BaseShAmt);
11496     if (VT == MVT::v4i32)
11497       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11498                          DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
11499                          ValOp, BaseShAmt);
11500     if (VT == MVT::v8i16)
11501       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11502                          DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
11503                          ValOp, BaseShAmt);
11504     break;
11505   case ISD::SRA:
11506     if (VT == MVT::v4i32)
11507       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11508                          DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
11509                          ValOp, BaseShAmt);
11510     if (VT == MVT::v8i16)
11511       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11512                          DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
11513                          ValOp, BaseShAmt);
11514     break;
11515   case ISD::SRL:
11516     if (VT == MVT::v2i64)
11517       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11518                          DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
11519                          ValOp, BaseShAmt);
11520     if (VT == MVT::v4i32)
11521       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11522                          DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
11523                          ValOp, BaseShAmt);
11524     if (VT ==  MVT::v8i16)
11525       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11526                          DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
11527                          ValOp, BaseShAmt);
11528     break;
11529   }
11530   return SDValue();
11531 }
11532
11533
11534 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
11535                                  TargetLowering::DAGCombinerInfo &DCI,
11536                                  const X86Subtarget *Subtarget) {
11537   if (DCI.isBeforeLegalizeOps())
11538     return SDValue();
11539
11540   // Want to form PANDN nodes, in the hopes of then easily combining them with
11541   // OR and AND nodes to form PBLEND/PSIGN.
11542   EVT VT = N->getValueType(0);
11543   if (VT != MVT::v2i64)
11544     return SDValue();
11545
11546   SDValue N0 = N->getOperand(0);
11547   SDValue N1 = N->getOperand(1);
11548   DebugLoc DL = N->getDebugLoc();
11549
11550   // Check LHS for vnot
11551   if (N0.getOpcode() == ISD::XOR &&
11552       ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
11553     return DAG.getNode(X86ISD::PANDN, DL, VT, N0.getOperand(0), N1);
11554
11555   // Check RHS for vnot
11556   if (N1.getOpcode() == ISD::XOR &&
11557       ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
11558     return DAG.getNode(X86ISD::PANDN, DL, VT, N1.getOperand(0), N0);
11559
11560   return SDValue();
11561 }
11562
11563 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
11564                                 TargetLowering::DAGCombinerInfo &DCI,
11565                                 const X86Subtarget *Subtarget) {
11566   if (DCI.isBeforeLegalizeOps())
11567     return SDValue();
11568
11569   EVT VT = N->getValueType(0);
11570   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64 && VT != MVT::v2i64)
11571     return SDValue();
11572
11573   SDValue N0 = N->getOperand(0);
11574   SDValue N1 = N->getOperand(1);
11575
11576   // look for psign/blend
11577   if (Subtarget->hasSSSE3()) {
11578     if (VT == MVT::v2i64) {
11579       // Canonicalize pandn to RHS
11580       if (N0.getOpcode() == X86ISD::PANDN)
11581         std::swap(N0, N1);
11582       // or (and (m, x), (pandn m, y))
11583       if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::PANDN) {
11584         SDValue Mask = N1.getOperand(0);
11585         SDValue X    = N1.getOperand(1);
11586         SDValue Y;
11587         if (N0.getOperand(0) == Mask)
11588           Y = N0.getOperand(1);
11589         if (N0.getOperand(1) == Mask)
11590           Y = N0.getOperand(0);
11591
11592         // Check to see if the mask appeared in both the AND and PANDN and
11593         if (!Y.getNode())
11594           return SDValue();
11595
11596         // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
11597         if (Mask.getOpcode() != ISD::BITCAST ||
11598             X.getOpcode() != ISD::BITCAST ||
11599             Y.getOpcode() != ISD::BITCAST)
11600           return SDValue();
11601
11602         // Look through mask bitcast.
11603         Mask = Mask.getOperand(0);
11604         EVT MaskVT = Mask.getValueType();
11605
11606         // Validate that the Mask operand is a vector sra node.  The sra node
11607         // will be an intrinsic.
11608         if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
11609           return SDValue();
11610
11611         // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
11612         // there is no psrai.b
11613         switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
11614         case Intrinsic::x86_sse2_psrai_w:
11615         case Intrinsic::x86_sse2_psrai_d:
11616           break;
11617         default: return SDValue();
11618         }
11619
11620         // Check that the SRA is all signbits.
11621         SDValue SraC = Mask.getOperand(2);
11622         unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
11623         unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
11624         if ((SraAmt + 1) != EltBits)
11625           return SDValue();
11626
11627         DebugLoc DL = N->getDebugLoc();
11628
11629         // Now we know we at least have a plendvb with the mask val.  See if
11630         // we can form a psignb/w/d.
11631         // psign = x.type == y.type == mask.type && y = sub(0, x);
11632         X = X.getOperand(0);
11633         Y = Y.getOperand(0);
11634         if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
11635             ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
11636             X.getValueType() == MaskVT && X.getValueType() == Y.getValueType()){
11637           unsigned Opc = 0;
11638           switch (EltBits) {
11639           case 8: Opc = X86ISD::PSIGNB; break;
11640           case 16: Opc = X86ISD::PSIGNW; break;
11641           case 32: Opc = X86ISD::PSIGND; break;
11642           default: break;
11643           }
11644           if (Opc) {
11645             SDValue Sign = DAG.getNode(Opc, DL, MaskVT, X, Mask.getOperand(1));
11646             return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Sign);
11647           }
11648         }
11649         // PBLENDVB only available on SSE 4.1
11650         if (!Subtarget->hasSSE41())
11651           return SDValue();
11652
11653         X = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, X);
11654         Y = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Y);
11655         Mask = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Mask);
11656         Mask = DAG.getNode(X86ISD::PBLENDVB, DL, MVT::v16i8, X, Y, Mask);
11657         return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Mask);
11658       }
11659     }
11660   }
11661
11662   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
11663   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
11664     std::swap(N0, N1);
11665   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
11666     return SDValue();
11667   if (!N0.hasOneUse() || !N1.hasOneUse())
11668     return SDValue();
11669
11670   SDValue ShAmt0 = N0.getOperand(1);
11671   if (ShAmt0.getValueType() != MVT::i8)
11672     return SDValue();
11673   SDValue ShAmt1 = N1.getOperand(1);
11674   if (ShAmt1.getValueType() != MVT::i8)
11675     return SDValue();
11676   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
11677     ShAmt0 = ShAmt0.getOperand(0);
11678   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
11679     ShAmt1 = ShAmt1.getOperand(0);
11680
11681   DebugLoc DL = N->getDebugLoc();
11682   unsigned Opc = X86ISD::SHLD;
11683   SDValue Op0 = N0.getOperand(0);
11684   SDValue Op1 = N1.getOperand(0);
11685   if (ShAmt0.getOpcode() == ISD::SUB) {
11686     Opc = X86ISD::SHRD;
11687     std::swap(Op0, Op1);
11688     std::swap(ShAmt0, ShAmt1);
11689   }
11690
11691   unsigned Bits = VT.getSizeInBits();
11692   if (ShAmt1.getOpcode() == ISD::SUB) {
11693     SDValue Sum = ShAmt1.getOperand(0);
11694     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
11695       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
11696       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
11697         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
11698       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
11699         return DAG.getNode(Opc, DL, VT,
11700                            Op0, Op1,
11701                            DAG.getNode(ISD::TRUNCATE, DL,
11702                                        MVT::i8, ShAmt0));
11703     }
11704   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
11705     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
11706     if (ShAmt0C &&
11707         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
11708       return DAG.getNode(Opc, DL, VT,
11709                          N0.getOperand(0), N1.getOperand(0),
11710                          DAG.getNode(ISD::TRUNCATE, DL,
11711                                        MVT::i8, ShAmt0));
11712   }
11713
11714   return SDValue();
11715 }
11716
11717 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
11718 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
11719                                    const X86Subtarget *Subtarget) {
11720   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
11721   // the FP state in cases where an emms may be missing.
11722   // A preferable solution to the general problem is to figure out the right
11723   // places to insert EMMS.  This qualifies as a quick hack.
11724
11725   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
11726   StoreSDNode *St = cast<StoreSDNode>(N);
11727   EVT VT = St->getValue().getValueType();
11728   if (VT.getSizeInBits() != 64)
11729     return SDValue();
11730
11731   const Function *F = DAG.getMachineFunction().getFunction();
11732   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
11733   bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
11734     && Subtarget->hasSSE2();
11735   if ((VT.isVector() ||
11736        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
11737       isa<LoadSDNode>(St->getValue()) &&
11738       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
11739       St->getChain().hasOneUse() && !St->isVolatile()) {
11740     SDNode* LdVal = St->getValue().getNode();
11741     LoadSDNode *Ld = 0;
11742     int TokenFactorIndex = -1;
11743     SmallVector<SDValue, 8> Ops;
11744     SDNode* ChainVal = St->getChain().getNode();
11745     // Must be a store of a load.  We currently handle two cases:  the load
11746     // is a direct child, and it's under an intervening TokenFactor.  It is
11747     // possible to dig deeper under nested TokenFactors.
11748     if (ChainVal == LdVal)
11749       Ld = cast<LoadSDNode>(St->getChain());
11750     else if (St->getValue().hasOneUse() &&
11751              ChainVal->getOpcode() == ISD::TokenFactor) {
11752       for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
11753         if (ChainVal->getOperand(i).getNode() == LdVal) {
11754           TokenFactorIndex = i;
11755           Ld = cast<LoadSDNode>(St->getValue());
11756         } else
11757           Ops.push_back(ChainVal->getOperand(i));
11758       }
11759     }
11760
11761     if (!Ld || !ISD::isNormalLoad(Ld))
11762       return SDValue();
11763
11764     // If this is not the MMX case, i.e. we are just turning i64 load/store
11765     // into f64 load/store, avoid the transformation if there are multiple
11766     // uses of the loaded value.
11767     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
11768       return SDValue();
11769
11770     DebugLoc LdDL = Ld->getDebugLoc();
11771     DebugLoc StDL = N->getDebugLoc();
11772     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
11773     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
11774     // pair instead.
11775     if (Subtarget->is64Bit() || F64IsLegal) {
11776       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
11777       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
11778                                   Ld->getPointerInfo(), Ld->isVolatile(),
11779                                   Ld->isNonTemporal(), Ld->getAlignment());
11780       SDValue NewChain = NewLd.getValue(1);
11781       if (TokenFactorIndex != -1) {
11782         Ops.push_back(NewChain);
11783         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
11784                                Ops.size());
11785       }
11786       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
11787                           St->getPointerInfo(),
11788                           St->isVolatile(), St->isNonTemporal(),
11789                           St->getAlignment());
11790     }
11791
11792     // Otherwise, lower to two pairs of 32-bit loads / stores.
11793     SDValue LoAddr = Ld->getBasePtr();
11794     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
11795                                  DAG.getConstant(4, MVT::i32));
11796
11797     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
11798                                Ld->getPointerInfo(),
11799                                Ld->isVolatile(), Ld->isNonTemporal(),
11800                                Ld->getAlignment());
11801     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
11802                                Ld->getPointerInfo().getWithOffset(4),
11803                                Ld->isVolatile(), Ld->isNonTemporal(),
11804                                MinAlign(Ld->getAlignment(), 4));
11805
11806     SDValue NewChain = LoLd.getValue(1);
11807     if (TokenFactorIndex != -1) {
11808       Ops.push_back(LoLd);
11809       Ops.push_back(HiLd);
11810       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
11811                              Ops.size());
11812     }
11813
11814     LoAddr = St->getBasePtr();
11815     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
11816                          DAG.getConstant(4, MVT::i32));
11817
11818     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
11819                                 St->getPointerInfo(),
11820                                 St->isVolatile(), St->isNonTemporal(),
11821                                 St->getAlignment());
11822     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
11823                                 St->getPointerInfo().getWithOffset(4),
11824                                 St->isVolatile(),
11825                                 St->isNonTemporal(),
11826                                 MinAlign(St->getAlignment(), 4));
11827     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
11828   }
11829   return SDValue();
11830 }
11831
11832 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
11833 /// X86ISD::FXOR nodes.
11834 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
11835   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
11836   // F[X]OR(0.0, x) -> x
11837   // F[X]OR(x, 0.0) -> x
11838   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
11839     if (C->getValueAPF().isPosZero())
11840       return N->getOperand(1);
11841   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
11842     if (C->getValueAPF().isPosZero())
11843       return N->getOperand(0);
11844   return SDValue();
11845 }
11846
11847 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
11848 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
11849   // FAND(0.0, x) -> 0.0
11850   // FAND(x, 0.0) -> 0.0
11851   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
11852     if (C->getValueAPF().isPosZero())
11853       return N->getOperand(0);
11854   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
11855     if (C->getValueAPF().isPosZero())
11856       return N->getOperand(1);
11857   return SDValue();
11858 }
11859
11860 static SDValue PerformBTCombine(SDNode *N,
11861                                 SelectionDAG &DAG,
11862                                 TargetLowering::DAGCombinerInfo &DCI) {
11863   // BT ignores high bits in the bit index operand.
11864   SDValue Op1 = N->getOperand(1);
11865   if (Op1.hasOneUse()) {
11866     unsigned BitWidth = Op1.getValueSizeInBits();
11867     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
11868     APInt KnownZero, KnownOne;
11869     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
11870                                           !DCI.isBeforeLegalizeOps());
11871     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11872     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
11873         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
11874       DCI.CommitTargetLoweringOpt(TLO);
11875   }
11876   return SDValue();
11877 }
11878
11879 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
11880   SDValue Op = N->getOperand(0);
11881   if (Op.getOpcode() == ISD::BITCAST)
11882     Op = Op.getOperand(0);
11883   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
11884   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
11885       VT.getVectorElementType().getSizeInBits() ==
11886       OpVT.getVectorElementType().getSizeInBits()) {
11887     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
11888   }
11889   return SDValue();
11890 }
11891
11892 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
11893   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
11894   //           (and (i32 x86isd::setcc_carry), 1)
11895   // This eliminates the zext. This transformation is necessary because
11896   // ISD::SETCC is always legalized to i8.
11897   DebugLoc dl = N->getDebugLoc();
11898   SDValue N0 = N->getOperand(0);
11899   EVT VT = N->getValueType(0);
11900   if (N0.getOpcode() == ISD::AND &&
11901       N0.hasOneUse() &&
11902       N0.getOperand(0).hasOneUse()) {
11903     SDValue N00 = N0.getOperand(0);
11904     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
11905       return SDValue();
11906     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
11907     if (!C || C->getZExtValue() != 1)
11908       return SDValue();
11909     return DAG.getNode(ISD::AND, dl, VT,
11910                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
11911                                    N00.getOperand(0), N00.getOperand(1)),
11912                        DAG.getConstant(1, VT));
11913   }
11914
11915   return SDValue();
11916 }
11917
11918 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
11919 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
11920   unsigned X86CC = N->getConstantOperandVal(0);
11921   SDValue EFLAG = N->getOperand(1);
11922   DebugLoc DL = N->getDebugLoc();
11923
11924   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
11925   // a zext and produces an all-ones bit which is more useful than 0/1 in some
11926   // cases.
11927   if (X86CC == X86::COND_B)
11928     return DAG.getNode(ISD::AND, DL, MVT::i8,
11929                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
11930                                    DAG.getConstant(X86CC, MVT::i8), EFLAG),
11931                        DAG.getConstant(1, MVT::i8));
11932
11933   return SDValue();
11934 }
11935
11936 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
11937 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
11938                                  X86TargetLowering::DAGCombinerInfo &DCI) {
11939   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
11940   // the result is either zero or one (depending on the input carry bit).
11941   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
11942   if (X86::isZeroNode(N->getOperand(0)) &&
11943       X86::isZeroNode(N->getOperand(1)) &&
11944       // We don't have a good way to replace an EFLAGS use, so only do this when
11945       // dead right now.
11946       SDValue(N, 1).use_empty()) {
11947     DebugLoc DL = N->getDebugLoc();
11948     EVT VT = N->getValueType(0);
11949     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
11950     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
11951                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
11952                                            DAG.getConstant(X86::COND_B,MVT::i8),
11953                                            N->getOperand(2)),
11954                                DAG.getConstant(1, VT));
11955     return DCI.CombineTo(N, Res1, CarryOut);
11956   }
11957
11958   return SDValue();
11959 }
11960
11961 // fold (add Y, (sete  X, 0)) -> adc  0, Y
11962 //      (add Y, (setne X, 0)) -> sbb -1, Y
11963 //      (sub (sete  X, 0), Y) -> sbb  0, Y
11964 //      (sub (setne X, 0), Y) -> adc -1, Y
11965 static SDValue OptimizeConditonalInDecrement(SDNode *N, SelectionDAG &DAG) {
11966   DebugLoc DL = N->getDebugLoc();
11967
11968   // Look through ZExts.
11969   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
11970   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
11971     return SDValue();
11972
11973   SDValue SetCC = Ext.getOperand(0);
11974   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
11975     return SDValue();
11976
11977   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
11978   if (CC != X86::COND_E && CC != X86::COND_NE)
11979     return SDValue();
11980
11981   SDValue Cmp = SetCC.getOperand(1);
11982   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
11983       !X86::isZeroNode(Cmp.getOperand(1)) ||
11984       !Cmp.getOperand(0).getValueType().isInteger())
11985     return SDValue();
11986
11987   SDValue CmpOp0 = Cmp.getOperand(0);
11988   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
11989                                DAG.getConstant(1, CmpOp0.getValueType()));
11990
11991   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
11992   if (CC == X86::COND_NE)
11993     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
11994                        DL, OtherVal.getValueType(), OtherVal,
11995                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
11996   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
11997                      DL, OtherVal.getValueType(), OtherVal,
11998                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
11999 }
12000
12001 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
12002                                              DAGCombinerInfo &DCI) const {
12003   SelectionDAG &DAG = DCI.DAG;
12004   switch (N->getOpcode()) {
12005   default: break;
12006   case ISD::EXTRACT_VECTOR_ELT:
12007     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
12008   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
12009   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
12010   case ISD::ADD:
12011   case ISD::SUB:            return OptimizeConditonalInDecrement(N, DAG);
12012   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
12013   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
12014   case ISD::SHL:
12015   case ISD::SRA:
12016   case ISD::SRL:            return PerformShiftCombine(N, DAG, Subtarget);
12017   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
12018   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
12019   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
12020   case X86ISD::FXOR:
12021   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
12022   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
12023   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
12024   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
12025   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG);
12026   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG);
12027   case X86ISD::SHUFPS:      // Handle all target specific shuffles
12028   case X86ISD::SHUFPD:
12029   case X86ISD::PALIGN:
12030   case X86ISD::PUNPCKHBW:
12031   case X86ISD::PUNPCKHWD:
12032   case X86ISD::PUNPCKHDQ:
12033   case X86ISD::PUNPCKHQDQ:
12034   case X86ISD::UNPCKHPS:
12035   case X86ISD::UNPCKHPD:
12036   case X86ISD::PUNPCKLBW:
12037   case X86ISD::PUNPCKLWD:
12038   case X86ISD::PUNPCKLDQ:
12039   case X86ISD::PUNPCKLQDQ:
12040   case X86ISD::UNPCKLPS:
12041   case X86ISD::UNPCKLPD:
12042   case X86ISD::VUNPCKLPS:
12043   case X86ISD::VUNPCKLPD:
12044   case X86ISD::VUNPCKLPSY:
12045   case X86ISD::VUNPCKLPDY:
12046   case X86ISD::MOVHLPS:
12047   case X86ISD::MOVLHPS:
12048   case X86ISD::PSHUFD:
12049   case X86ISD::PSHUFHW:
12050   case X86ISD::PSHUFLW:
12051   case X86ISD::MOVSS:
12052   case X86ISD::MOVSD:
12053   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI);
12054   }
12055
12056   return SDValue();
12057 }
12058
12059 /// isTypeDesirableForOp - Return true if the target has native support for
12060 /// the specified value type and it is 'desirable' to use the type for the
12061 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
12062 /// instruction encodings are longer and some i16 instructions are slow.
12063 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
12064   if (!isTypeLegal(VT))
12065     return false;
12066   if (VT != MVT::i16)
12067     return true;
12068
12069   switch (Opc) {
12070   default:
12071     return true;
12072   case ISD::LOAD:
12073   case ISD::SIGN_EXTEND:
12074   case ISD::ZERO_EXTEND:
12075   case ISD::ANY_EXTEND:
12076   case ISD::SHL:
12077   case ISD::SRL:
12078   case ISD::SUB:
12079   case ISD::ADD:
12080   case ISD::MUL:
12081   case ISD::AND:
12082   case ISD::OR:
12083   case ISD::XOR:
12084     return false;
12085   }
12086 }
12087
12088 /// IsDesirableToPromoteOp - This method query the target whether it is
12089 /// beneficial for dag combiner to promote the specified node. If true, it
12090 /// should return the desired promotion type by reference.
12091 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
12092   EVT VT = Op.getValueType();
12093   if (VT != MVT::i16)
12094     return false;
12095
12096   bool Promote = false;
12097   bool Commute = false;
12098   switch (Op.getOpcode()) {
12099   default: break;
12100   case ISD::LOAD: {
12101     LoadSDNode *LD = cast<LoadSDNode>(Op);
12102     // If the non-extending load has a single use and it's not live out, then it
12103     // might be folded.
12104     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
12105                                                      Op.hasOneUse()*/) {
12106       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12107              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
12108         // The only case where we'd want to promote LOAD (rather then it being
12109         // promoted as an operand is when it's only use is liveout.
12110         if (UI->getOpcode() != ISD::CopyToReg)
12111           return false;
12112       }
12113     }
12114     Promote = true;
12115     break;
12116   }
12117   case ISD::SIGN_EXTEND:
12118   case ISD::ZERO_EXTEND:
12119   case ISD::ANY_EXTEND:
12120     Promote = true;
12121     break;
12122   case ISD::SHL:
12123   case ISD::SRL: {
12124     SDValue N0 = Op.getOperand(0);
12125     // Look out for (store (shl (load), x)).
12126     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
12127       return false;
12128     Promote = true;
12129     break;
12130   }
12131   case ISD::ADD:
12132   case ISD::MUL:
12133   case ISD::AND:
12134   case ISD::OR:
12135   case ISD::XOR:
12136     Commute = true;
12137     // fallthrough
12138   case ISD::SUB: {
12139     SDValue N0 = Op.getOperand(0);
12140     SDValue N1 = Op.getOperand(1);
12141     if (!Commute && MayFoldLoad(N1))
12142       return false;
12143     // Avoid disabling potential load folding opportunities.
12144     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
12145       return false;
12146     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
12147       return false;
12148     Promote = true;
12149   }
12150   }
12151
12152   PVT = MVT::i32;
12153   return Promote;
12154 }
12155
12156 //===----------------------------------------------------------------------===//
12157 //                           X86 Inline Assembly Support
12158 //===----------------------------------------------------------------------===//
12159
12160 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
12161   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
12162
12163   std::string AsmStr = IA->getAsmString();
12164
12165   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
12166   SmallVector<StringRef, 4> AsmPieces;
12167   SplitString(AsmStr, AsmPieces, ";\n");
12168
12169   switch (AsmPieces.size()) {
12170   default: return false;
12171   case 1:
12172     AsmStr = AsmPieces[0];
12173     AsmPieces.clear();
12174     SplitString(AsmStr, AsmPieces, " \t");  // Split with whitespace.
12175
12176     // FIXME: this should verify that we are targetting a 486 or better.  If not,
12177     // we will turn this bswap into something that will be lowered to logical ops
12178     // instead of emitting the bswap asm.  For now, we don't support 486 or lower
12179     // so don't worry about this.
12180     // bswap $0
12181     if (AsmPieces.size() == 2 &&
12182         (AsmPieces[0] == "bswap" ||
12183          AsmPieces[0] == "bswapq" ||
12184          AsmPieces[0] == "bswapl") &&
12185         (AsmPieces[1] == "$0" ||
12186          AsmPieces[1] == "${0:q}")) {
12187       // No need to check constraints, nothing other than the equivalent of
12188       // "=r,0" would be valid here.
12189       const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12190       if (!Ty || Ty->getBitWidth() % 16 != 0)
12191         return false;
12192       return IntrinsicLowering::LowerToByteSwap(CI);
12193     }
12194     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
12195     if (CI->getType()->isIntegerTy(16) &&
12196         AsmPieces.size() == 3 &&
12197         (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
12198         AsmPieces[1] == "$$8," &&
12199         AsmPieces[2] == "${0:w}" &&
12200         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
12201       AsmPieces.clear();
12202       const std::string &ConstraintsStr = IA->getConstraintString();
12203       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
12204       std::sort(AsmPieces.begin(), AsmPieces.end());
12205       if (AsmPieces.size() == 4 &&
12206           AsmPieces[0] == "~{cc}" &&
12207           AsmPieces[1] == "~{dirflag}" &&
12208           AsmPieces[2] == "~{flags}" &&
12209           AsmPieces[3] == "~{fpsr}") {
12210         const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12211         if (!Ty || Ty->getBitWidth() % 16 != 0)
12212           return false;
12213         return IntrinsicLowering::LowerToByteSwap(CI);
12214       }
12215     }
12216     break;
12217   case 3:
12218     if (CI->getType()->isIntegerTy(32) &&
12219         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
12220       SmallVector<StringRef, 4> Words;
12221       SplitString(AsmPieces[0], Words, " \t,");
12222       if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
12223           Words[2] == "${0:w}") {
12224         Words.clear();
12225         SplitString(AsmPieces[1], Words, " \t,");
12226         if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" &&
12227             Words[2] == "$0") {
12228           Words.clear();
12229           SplitString(AsmPieces[2], Words, " \t,");
12230           if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
12231               Words[2] == "${0:w}") {
12232             AsmPieces.clear();
12233             const std::string &ConstraintsStr = IA->getConstraintString();
12234             SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
12235             std::sort(AsmPieces.begin(), AsmPieces.end());
12236             if (AsmPieces.size() == 4 &&
12237                 AsmPieces[0] == "~{cc}" &&
12238                 AsmPieces[1] == "~{dirflag}" &&
12239                 AsmPieces[2] == "~{flags}" &&
12240                 AsmPieces[3] == "~{fpsr}") {
12241               const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12242               if (!Ty || Ty->getBitWidth() % 16 != 0)
12243                 return false;
12244               return IntrinsicLowering::LowerToByteSwap(CI);
12245             }
12246           }
12247         }
12248       }
12249     }
12250
12251     if (CI->getType()->isIntegerTy(64)) {
12252       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
12253       if (Constraints.size() >= 2 &&
12254           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
12255           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
12256         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
12257         SmallVector<StringRef, 4> Words;
12258         SplitString(AsmPieces[0], Words, " \t");
12259         if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
12260           Words.clear();
12261           SplitString(AsmPieces[1], Words, " \t");
12262           if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
12263             Words.clear();
12264             SplitString(AsmPieces[2], Words, " \t,");
12265             if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
12266                 Words[2] == "%edx") {
12267               const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12268               if (!Ty || Ty->getBitWidth() % 16 != 0)
12269                 return false;
12270               return IntrinsicLowering::LowerToByteSwap(CI);
12271             }
12272           }
12273         }
12274       }
12275     }
12276     break;
12277   }
12278   return false;
12279 }
12280
12281
12282
12283 /// getConstraintType - Given a constraint letter, return the type of
12284 /// constraint it is for this target.
12285 X86TargetLowering::ConstraintType
12286 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
12287   if (Constraint.size() == 1) {
12288     switch (Constraint[0]) {
12289     case 'R':
12290     case 'q':
12291     case 'Q':
12292     case 'f':
12293     case 't':
12294     case 'u':
12295     case 'y':
12296     case 'x':
12297     case 'Y':
12298       return C_RegisterClass;
12299     case 'a':
12300     case 'b':
12301     case 'c':
12302     case 'd':
12303     case 'S':
12304     case 'D':
12305     case 'A':
12306       return C_Register;
12307     case 'I':
12308     case 'J':
12309     case 'K':
12310     case 'L':
12311     case 'M':
12312     case 'N':
12313     case 'G':
12314     case 'C':
12315     case 'e':
12316     case 'Z':
12317       return C_Other;
12318     default:
12319       break;
12320     }
12321   }
12322   return TargetLowering::getConstraintType(Constraint);
12323 }
12324
12325 /// Examine constraint type and operand type and determine a weight value.
12326 /// This object must already have been set up with the operand type
12327 /// and the current alternative constraint selected.
12328 TargetLowering::ConstraintWeight
12329   X86TargetLowering::getSingleConstraintMatchWeight(
12330     AsmOperandInfo &info, const char *constraint) const {
12331   ConstraintWeight weight = CW_Invalid;
12332   Value *CallOperandVal = info.CallOperandVal;
12333     // If we don't have a value, we can't do a match,
12334     // but allow it at the lowest weight.
12335   if (CallOperandVal == NULL)
12336     return CW_Default;
12337   const Type *type = CallOperandVal->getType();
12338   // Look at the constraint type.
12339   switch (*constraint) {
12340   default:
12341     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
12342   case 'R':
12343   case 'q':
12344   case 'Q':
12345   case 'a':
12346   case 'b':
12347   case 'c':
12348   case 'd':
12349   case 'S':
12350   case 'D':
12351   case 'A':
12352     if (CallOperandVal->getType()->isIntegerTy())
12353       weight = CW_SpecificReg;
12354     break;
12355   case 'f':
12356   case 't':
12357   case 'u':
12358       if (type->isFloatingPointTy())
12359         weight = CW_SpecificReg;
12360       break;
12361   case 'y':
12362       if (type->isX86_MMXTy() && Subtarget->hasMMX())
12363         weight = CW_SpecificReg;
12364       break;
12365   case 'x':
12366   case 'Y':
12367     if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
12368       weight = CW_Register;
12369     break;
12370   case 'I':
12371     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
12372       if (C->getZExtValue() <= 31)
12373         weight = CW_Constant;
12374     }
12375     break;
12376   case 'J':
12377     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12378       if (C->getZExtValue() <= 63)
12379         weight = CW_Constant;
12380     }
12381     break;
12382   case 'K':
12383     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12384       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
12385         weight = CW_Constant;
12386     }
12387     break;
12388   case 'L':
12389     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12390       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
12391         weight = CW_Constant;
12392     }
12393     break;
12394   case 'M':
12395     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12396       if (C->getZExtValue() <= 3)
12397         weight = CW_Constant;
12398     }
12399     break;
12400   case 'N':
12401     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12402       if (C->getZExtValue() <= 0xff)
12403         weight = CW_Constant;
12404     }
12405     break;
12406   case 'G':
12407   case 'C':
12408     if (dyn_cast<ConstantFP>(CallOperandVal)) {
12409       weight = CW_Constant;
12410     }
12411     break;
12412   case 'e':
12413     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12414       if ((C->getSExtValue() >= -0x80000000LL) &&
12415           (C->getSExtValue() <= 0x7fffffffLL))
12416         weight = CW_Constant;
12417     }
12418     break;
12419   case 'Z':
12420     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12421       if (C->getZExtValue() <= 0xffffffff)
12422         weight = CW_Constant;
12423     }
12424     break;
12425   }
12426   return weight;
12427 }
12428
12429 /// LowerXConstraint - try to replace an X constraint, which matches anything,
12430 /// with another that has more specific requirements based on the type of the
12431 /// corresponding operand.
12432 const char *X86TargetLowering::
12433 LowerXConstraint(EVT ConstraintVT) const {
12434   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
12435   // 'f' like normal targets.
12436   if (ConstraintVT.isFloatingPoint()) {
12437     if (Subtarget->hasXMMInt())
12438       return "Y";
12439     if (Subtarget->hasXMM())
12440       return "x";
12441   }
12442
12443   return TargetLowering::LowerXConstraint(ConstraintVT);
12444 }
12445
12446 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
12447 /// vector.  If it is invalid, don't add anything to Ops.
12448 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
12449                                                      char Constraint,
12450                                                      std::vector<SDValue>&Ops,
12451                                                      SelectionDAG &DAG) const {
12452   SDValue Result(0, 0);
12453
12454   switch (Constraint) {
12455   default: break;
12456   case 'I':
12457     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12458       if (C->getZExtValue() <= 31) {
12459         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12460         break;
12461       }
12462     }
12463     return;
12464   case 'J':
12465     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12466       if (C->getZExtValue() <= 63) {
12467         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12468         break;
12469       }
12470     }
12471     return;
12472   case 'K':
12473     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12474       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
12475         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12476         break;
12477       }
12478     }
12479     return;
12480   case 'N':
12481     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12482       if (C->getZExtValue() <= 255) {
12483         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12484         break;
12485       }
12486     }
12487     return;
12488   case 'e': {
12489     // 32-bit signed value
12490     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12491       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
12492                                            C->getSExtValue())) {
12493         // Widen to 64 bits here to get it sign extended.
12494         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
12495         break;
12496       }
12497     // FIXME gcc accepts some relocatable values here too, but only in certain
12498     // memory models; it's complicated.
12499     }
12500     return;
12501   }
12502   case 'Z': {
12503     // 32-bit unsigned value
12504     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12505       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
12506                                            C->getZExtValue())) {
12507         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12508         break;
12509       }
12510     }
12511     // FIXME gcc accepts some relocatable values here too, but only in certain
12512     // memory models; it's complicated.
12513     return;
12514   }
12515   case 'i': {
12516     // Literal immediates are always ok.
12517     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
12518       // Widen to 64 bits here to get it sign extended.
12519       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
12520       break;
12521     }
12522
12523     // In any sort of PIC mode addresses need to be computed at runtime by
12524     // adding in a register or some sort of table lookup.  These can't
12525     // be used as immediates.
12526     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
12527       return;
12528
12529     // If we are in non-pic codegen mode, we allow the address of a global (with
12530     // an optional displacement) to be used with 'i'.
12531     GlobalAddressSDNode *GA = 0;
12532     int64_t Offset = 0;
12533
12534     // Match either (GA), (GA+C), (GA+C1+C2), etc.
12535     while (1) {
12536       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
12537         Offset += GA->getOffset();
12538         break;
12539       } else if (Op.getOpcode() == ISD::ADD) {
12540         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
12541           Offset += C->getZExtValue();
12542           Op = Op.getOperand(0);
12543           continue;
12544         }
12545       } else if (Op.getOpcode() == ISD::SUB) {
12546         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
12547           Offset += -C->getZExtValue();
12548           Op = Op.getOperand(0);
12549           continue;
12550         }
12551       }
12552
12553       // Otherwise, this isn't something we can handle, reject it.
12554       return;
12555     }
12556
12557     const GlobalValue *GV = GA->getGlobal();
12558     // If we require an extra load to get this address, as in PIC mode, we
12559     // can't accept it.
12560     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
12561                                                         getTargetMachine())))
12562       return;
12563
12564     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
12565                                         GA->getValueType(0), Offset);
12566     break;
12567   }
12568   }
12569
12570   if (Result.getNode()) {
12571     Ops.push_back(Result);
12572     return;
12573   }
12574   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
12575 }
12576
12577 std::vector<unsigned> X86TargetLowering::
12578 getRegClassForInlineAsmConstraint(const std::string &Constraint,
12579                                   EVT VT) const {
12580   if (Constraint.size() == 1) {
12581     // FIXME: not handling fp-stack yet!
12582     switch (Constraint[0]) {      // GCC X86 Constraint Letters
12583     default: break;  // Unknown constraint letter
12584     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
12585       if (Subtarget->is64Bit()) {
12586         if (VT == MVT::i32)
12587           return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
12588                                        X86::ESI, X86::EDI, X86::R8D, X86::R9D,
12589                                        X86::R10D,X86::R11D,X86::R12D,
12590                                        X86::R13D,X86::R14D,X86::R15D,
12591                                        X86::EBP, X86::ESP, 0);
12592         else if (VT == MVT::i16)
12593           return make_vector<unsigned>(X86::AX,  X86::DX,  X86::CX, X86::BX,
12594                                        X86::SI,  X86::DI,  X86::R8W,X86::R9W,
12595                                        X86::R10W,X86::R11W,X86::R12W,
12596                                        X86::R13W,X86::R14W,X86::R15W,
12597                                        X86::BP,  X86::SP, 0);
12598         else if (VT == MVT::i8)
12599           return make_vector<unsigned>(X86::AL,  X86::DL,  X86::CL, X86::BL,
12600                                        X86::SIL, X86::DIL, X86::R8B,X86::R9B,
12601                                        X86::R10B,X86::R11B,X86::R12B,
12602                                        X86::R13B,X86::R14B,X86::R15B,
12603                                        X86::BPL, X86::SPL, 0);
12604
12605         else if (VT == MVT::i64)
12606           return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
12607                                        X86::RSI, X86::RDI, X86::R8,  X86::R9,
12608                                        X86::R10, X86::R11, X86::R12,
12609                                        X86::R13, X86::R14, X86::R15,
12610                                        X86::RBP, X86::RSP, 0);
12611
12612         break;
12613       }
12614       // 32-bit fallthrough
12615     case 'Q':   // Q_REGS
12616       if (VT == MVT::i32)
12617         return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
12618       else if (VT == MVT::i16)
12619         return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
12620       else if (VT == MVT::i8)
12621         return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
12622       else if (VT == MVT::i64)
12623         return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
12624       break;
12625     }
12626   }
12627
12628   return std::vector<unsigned>();
12629 }
12630
12631 std::pair<unsigned, const TargetRegisterClass*>
12632 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
12633                                                 EVT VT) const {
12634   // First, see if this is a constraint that directly corresponds to an LLVM
12635   // register class.
12636   if (Constraint.size() == 1) {
12637     // GCC Constraint Letters
12638     switch (Constraint[0]) {
12639     default: break;
12640     case 'r':   // GENERAL_REGS
12641     case 'l':   // INDEX_REGS
12642       if (VT == MVT::i8)
12643         return std::make_pair(0U, X86::GR8RegisterClass);
12644       if (VT == MVT::i16)
12645         return std::make_pair(0U, X86::GR16RegisterClass);
12646       if (VT == MVT::i32 || !Subtarget->is64Bit())
12647         return std::make_pair(0U, X86::GR32RegisterClass);
12648       return std::make_pair(0U, X86::GR64RegisterClass);
12649     case 'R':   // LEGACY_REGS
12650       if (VT == MVT::i8)
12651         return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
12652       if (VT == MVT::i16)
12653         return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
12654       if (VT == MVT::i32 || !Subtarget->is64Bit())
12655         return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
12656       return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
12657     case 'f':  // FP Stack registers.
12658       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
12659       // value to the correct fpstack register class.
12660       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
12661         return std::make_pair(0U, X86::RFP32RegisterClass);
12662       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
12663         return std::make_pair(0U, X86::RFP64RegisterClass);
12664       return std::make_pair(0U, X86::RFP80RegisterClass);
12665     case 'y':   // MMX_REGS if MMX allowed.
12666       if (!Subtarget->hasMMX()) break;
12667       return std::make_pair(0U, X86::VR64RegisterClass);
12668     case 'Y':   // SSE_REGS if SSE2 allowed
12669       if (!Subtarget->hasXMMInt()) break;
12670       // FALL THROUGH.
12671     case 'x':   // SSE_REGS if SSE1 allowed
12672       if (!Subtarget->hasXMM()) break;
12673
12674       switch (VT.getSimpleVT().SimpleTy) {
12675       default: break;
12676       // Scalar SSE types.
12677       case MVT::f32:
12678       case MVT::i32:
12679         return std::make_pair(0U, X86::FR32RegisterClass);
12680       case MVT::f64:
12681       case MVT::i64:
12682         return std::make_pair(0U, X86::FR64RegisterClass);
12683       // Vector types.
12684       case MVT::v16i8:
12685       case MVT::v8i16:
12686       case MVT::v4i32:
12687       case MVT::v2i64:
12688       case MVT::v4f32:
12689       case MVT::v2f64:
12690         return std::make_pair(0U, X86::VR128RegisterClass);
12691       }
12692       break;
12693     }
12694   }
12695
12696   // Use the default implementation in TargetLowering to convert the register
12697   // constraint into a member of a register class.
12698   std::pair<unsigned, const TargetRegisterClass*> Res;
12699   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
12700
12701   // Not found as a standard register?
12702   if (Res.second == 0) {
12703     // Map st(0) -> st(7) -> ST0
12704     if (Constraint.size() == 7 && Constraint[0] == '{' &&
12705         tolower(Constraint[1]) == 's' &&
12706         tolower(Constraint[2]) == 't' &&
12707         Constraint[3] == '(' &&
12708         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
12709         Constraint[5] == ')' &&
12710         Constraint[6] == '}') {
12711
12712       Res.first = X86::ST0+Constraint[4]-'0';
12713       Res.second = X86::RFP80RegisterClass;
12714       return Res;
12715     }
12716
12717     // GCC allows "st(0)" to be called just plain "st".
12718     if (StringRef("{st}").equals_lower(Constraint)) {
12719       Res.first = X86::ST0;
12720       Res.second = X86::RFP80RegisterClass;
12721       return Res;
12722     }
12723
12724     // flags -> EFLAGS
12725     if (StringRef("{flags}").equals_lower(Constraint)) {
12726       Res.first = X86::EFLAGS;
12727       Res.second = X86::CCRRegisterClass;
12728       return Res;
12729     }
12730
12731     // 'A' means EAX + EDX.
12732     if (Constraint == "A") {
12733       Res.first = X86::EAX;
12734       Res.second = X86::GR32_ADRegisterClass;
12735       return Res;
12736     }
12737     return Res;
12738   }
12739
12740   // Otherwise, check to see if this is a register class of the wrong value
12741   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
12742   // turn into {ax},{dx}.
12743   if (Res.second->hasType(VT))
12744     return Res;   // Correct type already, nothing to do.
12745
12746   // All of the single-register GCC register classes map their values onto
12747   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
12748   // really want an 8-bit or 32-bit register, map to the appropriate register
12749   // class and return the appropriate register.
12750   if (Res.second == X86::GR16RegisterClass) {
12751     if (VT == MVT::i8) {
12752       unsigned DestReg = 0;
12753       switch (Res.first) {
12754       default: break;
12755       case X86::AX: DestReg = X86::AL; break;
12756       case X86::DX: DestReg = X86::DL; break;
12757       case X86::CX: DestReg = X86::CL; break;
12758       case X86::BX: DestReg = X86::BL; break;
12759       }
12760       if (DestReg) {
12761         Res.first = DestReg;
12762         Res.second = X86::GR8RegisterClass;
12763       }
12764     } else if (VT == MVT::i32) {
12765       unsigned DestReg = 0;
12766       switch (Res.first) {
12767       default: break;
12768       case X86::AX: DestReg = X86::EAX; break;
12769       case X86::DX: DestReg = X86::EDX; break;
12770       case X86::CX: DestReg = X86::ECX; break;
12771       case X86::BX: DestReg = X86::EBX; break;
12772       case X86::SI: DestReg = X86::ESI; break;
12773       case X86::DI: DestReg = X86::EDI; break;
12774       case X86::BP: DestReg = X86::EBP; break;
12775       case X86::SP: DestReg = X86::ESP; break;
12776       }
12777       if (DestReg) {
12778         Res.first = DestReg;
12779         Res.second = X86::GR32RegisterClass;
12780       }
12781     } else if (VT == MVT::i64) {
12782       unsigned DestReg = 0;
12783       switch (Res.first) {
12784       default: break;
12785       case X86::AX: DestReg = X86::RAX; break;
12786       case X86::DX: DestReg = X86::RDX; break;
12787       case X86::CX: DestReg = X86::RCX; break;
12788       case X86::BX: DestReg = X86::RBX; break;
12789       case X86::SI: DestReg = X86::RSI; break;
12790       case X86::DI: DestReg = X86::RDI; break;
12791       case X86::BP: DestReg = X86::RBP; break;
12792       case X86::SP: DestReg = X86::RSP; break;
12793       }
12794       if (DestReg) {
12795         Res.first = DestReg;
12796         Res.second = X86::GR64RegisterClass;
12797       }
12798     }
12799   } else if (Res.second == X86::FR32RegisterClass ||
12800              Res.second == X86::FR64RegisterClass ||
12801              Res.second == X86::VR128RegisterClass) {
12802     // Handle references to XMM physical registers that got mapped into the
12803     // wrong class.  This can happen with constraints like {xmm0} where the
12804     // target independent register mapper will just pick the first match it can
12805     // find, ignoring the required type.
12806     if (VT == MVT::f32)
12807       Res.second = X86::FR32RegisterClass;
12808     else if (VT == MVT::f64)
12809       Res.second = X86::FR64RegisterClass;
12810     else if (X86::VR128RegisterClass->hasType(VT))
12811       Res.second = X86::VR128RegisterClass;
12812   }
12813
12814   return Res;
12815 }