Unneeded include's.
[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 #include "X86.h"
16 #include "X86InstrBuilder.h"
17 #include "X86ISelLowering.h"
18 #include "X86MachineFunctionInfo.h"
19 #include "X86TargetMachine.h"
20 #include "llvm/CallingConv.h"
21 #include "llvm/Constants.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/GlobalVariable.h"
24 #include "llvm/Function.h"
25 #include "llvm/Intrinsics.h"
26 #include "llvm/ADT/BitVector.h"
27 #include "llvm/ADT/VectorExtras.h"
28 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
29 #include "llvm/CodeGen/CallingConvLower.h"
30 #include "llvm/CodeGen/MachineFrameInfo.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineModuleInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/PseudoSourceValue.h"
36 #include "llvm/CodeGen/SelectionDAG.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Target/TargetOptions.h"
40 #include "llvm/ADT/SmallSet.h"
41 #include "llvm/ADT/StringExtras.h"
42 using namespace llvm;
43
44 // Forward declarations.
45 static SDOperand getMOVLMask(unsigned NumElems, SelectionDAG &DAG);
46
47 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
48   : TargetLowering(TM) {
49   Subtarget = &TM.getSubtarget<X86Subtarget>();
50   X86ScalarSSEf64 = Subtarget->hasSSE2();
51   X86ScalarSSEf32 = Subtarget->hasSSE1();
52   X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
53   
54   bool Fast = false;
55
56   RegInfo = TM.getRegisterInfo();
57
58   // Set up the TargetLowering object.
59
60   // X86 is weird, it always uses i8 for shift amounts and setcc results.
61   setShiftAmountType(MVT::i8);
62   setSetCCResultContents(ZeroOrOneSetCCResult);
63   setSchedulingPreference(SchedulingForRegPressure);
64   setShiftAmountFlavor(Mask);   // shl X, 32 == shl X, 0
65   setStackPointerRegisterToSaveRestore(X86StackPtr);
66
67   if (Subtarget->isTargetDarwin()) {
68     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
69     setUseUnderscoreSetJmp(false);
70     setUseUnderscoreLongJmp(false);
71   } else if (Subtarget->isTargetMingw()) {
72     // MS runtime is weird: it exports _setjmp, but longjmp!
73     setUseUnderscoreSetJmp(true);
74     setUseUnderscoreLongJmp(false);
75   } else {
76     setUseUnderscoreSetJmp(true);
77     setUseUnderscoreLongJmp(true);
78   }
79   
80   // Set up the register classes.
81   addRegisterClass(MVT::i8, X86::GR8RegisterClass);
82   addRegisterClass(MVT::i16, X86::GR16RegisterClass);
83   addRegisterClass(MVT::i32, X86::GR32RegisterClass);
84   if (Subtarget->is64Bit())
85     addRegisterClass(MVT::i64, X86::GR64RegisterClass);
86
87   setLoadXAction(ISD::SEXTLOAD, MVT::i1, Promote);
88
89   // We don't accept any truncstore of integer registers.  
90   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
91   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
92   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
93   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
94   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
95   setTruncStoreAction(MVT::i16, MVT::i8, Expand);
96
97   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
98   // operation.
99   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
100   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
101   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
102
103   if (Subtarget->is64Bit()) {
104     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Expand);
105     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
106   } else {
107     if (X86ScalarSSEf64)
108       // If SSE i64 SINT_TO_FP is not available, expand i32 UINT_TO_FP.
109       setOperationAction(ISD::UINT_TO_FP   , MVT::i32  , Expand);
110     else
111       setOperationAction(ISD::UINT_TO_FP   , MVT::i32  , Promote);
112   }
113
114   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
115   // this operation.
116   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
117   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
118   // SSE has no i16 to fp conversion, only i32
119   if (X86ScalarSSEf32) {
120     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
121     // f32 and f64 cases are Legal, f80 case is not
122     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
123   } else {
124     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
125     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
126   }
127
128   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
129   // are Legal, f80 is custom lowered.
130   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
131   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
132
133   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
134   // this operation.
135   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
136   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
137
138   if (X86ScalarSSEf32) {
139     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
140     // f32 and f64 cases are Legal, f80 case is not
141     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
142   } else {
143     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
144     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
145   }
146
147   // Handle FP_TO_UINT by promoting the destination to a larger signed
148   // conversion.
149   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
150   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
151   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
152
153   if (Subtarget->is64Bit()) {
154     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
155     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
156   } else {
157     if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
158       // Expand FP_TO_UINT into a select.
159       // FIXME: We would like to use a Custom expander here eventually to do
160       // the optimal thing for SSE vs. the default expansion in the legalizer.
161       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
162     else
163       // With SSE3 we can use fisttpll to convert to a signed i64.
164       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Promote);
165   }
166
167   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
168   if (!X86ScalarSSEf64) {
169     setOperationAction(ISD::BIT_CONVERT      , MVT::f32  , Expand);
170     setOperationAction(ISD::BIT_CONVERT      , MVT::i32  , Expand);
171   }
172
173   // Scalar integer divide and remainder are lowered to use operations that
174   // produce two results, to match the available instructions. This exposes
175   // the two-result form to trivial CSE, which is able to combine x/y and x%y
176   // into a single instruction.
177   //
178   // Scalar integer multiply-high is also lowered to use two-result
179   // operations, to match the available instructions. However, plain multiply
180   // (low) operations are left as Legal, as there are single-result
181   // instructions for this in x86. Using the two-result multiply instructions
182   // when both high and low results are needed must be arranged by dagcombine.
183   setOperationAction(ISD::MULHS           , MVT::i8    , Expand);
184   setOperationAction(ISD::MULHU           , MVT::i8    , Expand);
185   setOperationAction(ISD::SDIV            , MVT::i8    , Expand);
186   setOperationAction(ISD::UDIV            , MVT::i8    , Expand);
187   setOperationAction(ISD::SREM            , MVT::i8    , Expand);
188   setOperationAction(ISD::UREM            , MVT::i8    , Expand);
189   setOperationAction(ISD::MULHS           , MVT::i16   , Expand);
190   setOperationAction(ISD::MULHU           , MVT::i16   , Expand);
191   setOperationAction(ISD::SDIV            , MVT::i16   , Expand);
192   setOperationAction(ISD::UDIV            , MVT::i16   , Expand);
193   setOperationAction(ISD::SREM            , MVT::i16   , Expand);
194   setOperationAction(ISD::UREM            , MVT::i16   , Expand);
195   setOperationAction(ISD::MULHS           , MVT::i32   , Expand);
196   setOperationAction(ISD::MULHU           , MVT::i32   , Expand);
197   setOperationAction(ISD::SDIV            , MVT::i32   , Expand);
198   setOperationAction(ISD::UDIV            , MVT::i32   , Expand);
199   setOperationAction(ISD::SREM            , MVT::i32   , Expand);
200   setOperationAction(ISD::UREM            , MVT::i32   , Expand);
201   setOperationAction(ISD::MULHS           , MVT::i64   , Expand);
202   setOperationAction(ISD::MULHU           , MVT::i64   , Expand);
203   setOperationAction(ISD::SDIV            , MVT::i64   , Expand);
204   setOperationAction(ISD::UDIV            , MVT::i64   , Expand);
205   setOperationAction(ISD::SREM            , MVT::i64   , Expand);
206   setOperationAction(ISD::UREM            , MVT::i64   , Expand);
207
208   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
209   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
210   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
211   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
212   if (Subtarget->is64Bit())
213     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
214   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
215   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
216   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
217   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
218   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
219   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
220   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
221   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
222   
223   setOperationAction(ISD::CTPOP            , MVT::i8   , Expand);
224   setOperationAction(ISD::CTTZ             , MVT::i8   , Custom);
225   setOperationAction(ISD::CTLZ             , MVT::i8   , Custom);
226   setOperationAction(ISD::CTPOP            , MVT::i16  , Expand);
227   setOperationAction(ISD::CTTZ             , MVT::i16  , Custom);
228   setOperationAction(ISD::CTLZ             , MVT::i16  , Custom);
229   setOperationAction(ISD::CTPOP            , MVT::i32  , Expand);
230   setOperationAction(ISD::CTTZ             , MVT::i32  , Custom);
231   setOperationAction(ISD::CTLZ             , MVT::i32  , Custom);
232   if (Subtarget->is64Bit()) {
233     setOperationAction(ISD::CTPOP          , MVT::i64  , Expand);
234     setOperationAction(ISD::CTTZ           , MVT::i64  , Custom);
235     setOperationAction(ISD::CTLZ           , MVT::i64  , Custom);
236   }
237
238   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
239   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
240
241   // These should be promoted to a larger select which is supported.
242   setOperationAction(ISD::SELECT           , MVT::i1   , Promote);
243   setOperationAction(ISD::SELECT           , MVT::i8   , Promote);
244   // X86 wants to expand cmov itself.
245   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
246   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
247   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
248   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
249   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
250   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
251   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
252   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
253   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
254   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
255   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
256   if (Subtarget->is64Bit()) {
257     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
258     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
259   }
260   // X86 ret instruction may pop stack.
261   setOperationAction(ISD::RET             , MVT::Other, Custom);
262   if (!Subtarget->is64Bit())
263     setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
264
265   // Darwin ABI issue.
266   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
267   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
268   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
269   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
270   if (Subtarget->is64Bit())
271     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
272   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
273   if (Subtarget->is64Bit()) {
274     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
275     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
276     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
277     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
278   }
279   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
280   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
281   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
282   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
283   if (Subtarget->is64Bit()) {
284     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
285     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
286     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
287   }
288
289   if (Subtarget->hasSSE1())
290     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
291
292   if (!Subtarget->hasSSE2())
293     setOperationAction(ISD::MEMBARRIER    , MVT::Other, Expand);
294
295   // Expand certain atomics
296   setOperationAction(ISD::ATOMIC_LCS     , MVT::i8, Custom);
297   setOperationAction(ISD::ATOMIC_LCS     , MVT::i16, Custom);
298   setOperationAction(ISD::ATOMIC_LCS     , MVT::i32, Custom);
299   setOperationAction(ISD::ATOMIC_LCS     , MVT::i64, Custom);
300   setOperationAction(ISD::ATOMIC_LSS     , MVT::i32, Expand);
301
302   // Use the default ISD::LOCATION, ISD::DECLARE expansion.
303   setOperationAction(ISD::LOCATION, MVT::Other, Expand);
304   // FIXME - use subtarget debug flags
305   if (!Subtarget->isTargetDarwin() &&
306       !Subtarget->isTargetELF() &&
307       !Subtarget->isTargetCygMing())
308     setOperationAction(ISD::LABEL, MVT::Other, Expand);
309
310   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
311   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
312   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
313   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
314   if (Subtarget->is64Bit()) {
315     // FIXME: Verify
316     setExceptionPointerRegister(X86::RAX);
317     setExceptionSelectorRegister(X86::RDX);
318   } else {
319     setExceptionPointerRegister(X86::EAX);
320     setExceptionSelectorRegister(X86::EDX);
321   }
322   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
323   
324   setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
325
326   setOperationAction(ISD::TRAP, MVT::Other, Legal);
327
328   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
329   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
330   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
331   if (Subtarget->is64Bit()) {
332     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
333     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
334   } else {
335     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
336     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
337   }
338
339   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
340   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
341   if (Subtarget->is64Bit())
342     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
343   if (Subtarget->isTargetCygMing())
344     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
345   else
346     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
347
348   if (X86ScalarSSEf64) {
349     // f32 and f64 use SSE.
350     // Set up the FP register classes.
351     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
352     addRegisterClass(MVT::f64, X86::FR64RegisterClass);
353
354     // Use ANDPD to simulate FABS.
355     setOperationAction(ISD::FABS , MVT::f64, Custom);
356     setOperationAction(ISD::FABS , MVT::f32, Custom);
357
358     // Use XORP to simulate FNEG.
359     setOperationAction(ISD::FNEG , MVT::f64, Custom);
360     setOperationAction(ISD::FNEG , MVT::f32, Custom);
361
362     // Use ANDPD and ORPD to simulate FCOPYSIGN.
363     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
364     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
365
366     // We don't support sin/cos/fmod
367     setOperationAction(ISD::FSIN , MVT::f64, Expand);
368     setOperationAction(ISD::FCOS , MVT::f64, Expand);
369     setOperationAction(ISD::FSIN , MVT::f32, Expand);
370     setOperationAction(ISD::FCOS , MVT::f32, Expand);
371
372     // Expand FP immediates into loads from the stack, except for the special
373     // cases we handle.
374     addLegalFPImmediate(APFloat(+0.0)); // xorpd
375     addLegalFPImmediate(APFloat(+0.0f)); // xorps
376
377     // Floating truncations from f80 and extensions to f80 go through memory.
378     // If optimizing, we lie about this though and handle it in
379     // InstructionSelectPreprocess so that dagcombine2 can hack on these.
380     if (Fast) {
381       setConvertAction(MVT::f32, MVT::f80, Expand);
382       setConvertAction(MVT::f64, MVT::f80, Expand);
383       setConvertAction(MVT::f80, MVT::f32, Expand);
384       setConvertAction(MVT::f80, MVT::f64, Expand);
385     }
386   } else if (X86ScalarSSEf32) {
387     // Use SSE for f32, x87 for f64.
388     // Set up the FP register classes.
389     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
390     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
391
392     // Use ANDPS to simulate FABS.
393     setOperationAction(ISD::FABS , MVT::f32, Custom);
394
395     // Use XORP to simulate FNEG.
396     setOperationAction(ISD::FNEG , MVT::f32, Custom);
397
398     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
399
400     // Use ANDPS and ORPS to simulate FCOPYSIGN.
401     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
402     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
403
404     // We don't support sin/cos/fmod
405     setOperationAction(ISD::FSIN , MVT::f32, Expand);
406     setOperationAction(ISD::FCOS , MVT::f32, Expand);
407
408     // Special cases we handle for FP constants.
409     addLegalFPImmediate(APFloat(+0.0f)); // xorps
410     addLegalFPImmediate(APFloat(+0.0)); // FLD0
411     addLegalFPImmediate(APFloat(+1.0)); // FLD1
412     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
413     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
414
415     // SSE <-> X87 conversions go through memory.  If optimizing, we lie about
416     // this though and handle it in InstructionSelectPreprocess so that
417     // dagcombine2 can hack on these.
418     if (Fast) {
419       setConvertAction(MVT::f32, MVT::f64, Expand);
420       setConvertAction(MVT::f32, MVT::f80, Expand);
421       setConvertAction(MVT::f80, MVT::f32, Expand);    
422       setConvertAction(MVT::f64, MVT::f32, Expand);
423       // And x87->x87 truncations also.
424       setConvertAction(MVT::f80, MVT::f64, Expand);
425     }
426
427     if (!UnsafeFPMath) {
428       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
429       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
430     }
431   } else {
432     // f32 and f64 in x87.
433     // Set up the FP register classes.
434     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
435     addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
436
437     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
438     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
439     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
440     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
441
442     // Floating truncations go through memory.  If optimizing, we lie about
443     // this though and handle it in InstructionSelectPreprocess so that
444     // dagcombine2 can hack on these.
445     if (Fast) {
446       setConvertAction(MVT::f80, MVT::f32, Expand);    
447       setConvertAction(MVT::f64, MVT::f32, Expand);
448       setConvertAction(MVT::f80, MVT::f64, Expand);
449     }
450
451     if (!UnsafeFPMath) {
452       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
453       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
454     }
455     addLegalFPImmediate(APFloat(+0.0)); // FLD0
456     addLegalFPImmediate(APFloat(+1.0)); // FLD1
457     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
458     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
459     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
460     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
461     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
462     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
463   }
464
465   // Long double always uses X87.
466   addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
467   setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
468   setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
469   {
470     APFloat TmpFlt(+0.0);
471     TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven);
472     addLegalFPImmediate(TmpFlt);  // FLD0
473     TmpFlt.changeSign();
474     addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
475     APFloat TmpFlt2(+1.0);
476     TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven);
477     addLegalFPImmediate(TmpFlt2);  // FLD1
478     TmpFlt2.changeSign();
479     addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
480   }
481     
482   if (!UnsafeFPMath) {
483     setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
484     setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
485   }
486
487   // Always use a library call for pow.
488   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
489   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
490   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
491
492   // First set operation action for all vector types to expand. Then we
493   // will selectively turn on ones that can be effectively codegen'd.
494   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
495        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
496     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
497     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
498     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
499     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
500     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
501     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
502     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
503     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
504     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
505     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
506     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
507     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
508     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
509     setOperationAction(ISD::VECTOR_SHUFFLE,     (MVT::SimpleValueType)VT, Expand);
510     setOperationAction(ISD::EXTRACT_VECTOR_ELT, (MVT::SimpleValueType)VT, Expand);
511     setOperationAction(ISD::INSERT_VECTOR_ELT,  (MVT::SimpleValueType)VT, Expand);
512     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
513     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
514     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
515     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
516     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
517     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
518     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
519     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
520     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
521     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
522     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
523     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
524     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
525     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
526     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
527     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
528     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
529     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
530     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
531     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
532     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
533     setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
534   }
535
536   if (Subtarget->hasMMX()) {
537     addRegisterClass(MVT::v8i8,  X86::VR64RegisterClass);
538     addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
539     addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
540     addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
541
542     // FIXME: add MMX packed arithmetics
543
544     setOperationAction(ISD::ADD,                MVT::v8i8,  Legal);
545     setOperationAction(ISD::ADD,                MVT::v4i16, Legal);
546     setOperationAction(ISD::ADD,                MVT::v2i32, Legal);
547     setOperationAction(ISD::ADD,                MVT::v1i64, Legal);
548
549     setOperationAction(ISD::SUB,                MVT::v8i8,  Legal);
550     setOperationAction(ISD::SUB,                MVT::v4i16, Legal);
551     setOperationAction(ISD::SUB,                MVT::v2i32, Legal);
552     setOperationAction(ISD::SUB,                MVT::v1i64, Legal);
553
554     setOperationAction(ISD::MULHS,              MVT::v4i16, Legal);
555     setOperationAction(ISD::MUL,                MVT::v4i16, Legal);
556
557     setOperationAction(ISD::AND,                MVT::v8i8,  Promote);
558     AddPromotedToType (ISD::AND,                MVT::v8i8,  MVT::v1i64);
559     setOperationAction(ISD::AND,                MVT::v4i16, Promote);
560     AddPromotedToType (ISD::AND,                MVT::v4i16, MVT::v1i64);
561     setOperationAction(ISD::AND,                MVT::v2i32, Promote);
562     AddPromotedToType (ISD::AND,                MVT::v2i32, MVT::v1i64);
563     setOperationAction(ISD::AND,                MVT::v1i64, Legal);
564
565     setOperationAction(ISD::OR,                 MVT::v8i8,  Promote);
566     AddPromotedToType (ISD::OR,                 MVT::v8i8,  MVT::v1i64);
567     setOperationAction(ISD::OR,                 MVT::v4i16, Promote);
568     AddPromotedToType (ISD::OR,                 MVT::v4i16, MVT::v1i64);
569     setOperationAction(ISD::OR,                 MVT::v2i32, Promote);
570     AddPromotedToType (ISD::OR,                 MVT::v2i32, MVT::v1i64);
571     setOperationAction(ISD::OR,                 MVT::v1i64, Legal);
572
573     setOperationAction(ISD::XOR,                MVT::v8i8,  Promote);
574     AddPromotedToType (ISD::XOR,                MVT::v8i8,  MVT::v1i64);
575     setOperationAction(ISD::XOR,                MVT::v4i16, Promote);
576     AddPromotedToType (ISD::XOR,                MVT::v4i16, MVT::v1i64);
577     setOperationAction(ISD::XOR,                MVT::v2i32, Promote);
578     AddPromotedToType (ISD::XOR,                MVT::v2i32, MVT::v1i64);
579     setOperationAction(ISD::XOR,                MVT::v1i64, Legal);
580
581     setOperationAction(ISD::LOAD,               MVT::v8i8,  Promote);
582     AddPromotedToType (ISD::LOAD,               MVT::v8i8,  MVT::v1i64);
583     setOperationAction(ISD::LOAD,               MVT::v4i16, Promote);
584     AddPromotedToType (ISD::LOAD,               MVT::v4i16, MVT::v1i64);
585     setOperationAction(ISD::LOAD,               MVT::v2i32, Promote);
586     AddPromotedToType (ISD::LOAD,               MVT::v2i32, MVT::v1i64);
587     setOperationAction(ISD::LOAD,               MVT::v1i64, Legal);
588
589     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i8,  Custom);
590     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i16, Custom);
591     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i32, Custom);
592     setOperationAction(ISD::BUILD_VECTOR,       MVT::v1i64, Custom);
593
594     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8i8,  Custom);
595     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i16, Custom);
596     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i32, Custom);
597     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v1i64, Custom);
598
599     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Custom);
600     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Custom);
601     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Custom);
602   }
603
604   if (Subtarget->hasSSE1()) {
605     addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
606
607     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
608     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
609     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
610     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
611     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
612     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
613     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
614     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
615     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
616     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
617     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
618     setOperationAction(ISD::VSETCC,             MVT::v4f32, Legal);
619   }
620
621   if (Subtarget->hasSSE2()) {
622     addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
623     addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
624     addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
625     addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
626     addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
627
628     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
629     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
630     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
631     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
632     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
633     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
634     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
635     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
636     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
637     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
638     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
639     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
640     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
641     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
642     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
643
644     setOperationAction(ISD::VSETCC,             MVT::v2f64, Legal);
645     setOperationAction(ISD::VSETCC,             MVT::v16i8, Legal);
646     setOperationAction(ISD::VSETCC,             MVT::v8i16, Legal);
647     setOperationAction(ISD::VSETCC,             MVT::v4i32, Legal);
648     setOperationAction(ISD::VSETCC,             MVT::v2i64, Legal);
649
650     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
651     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
652     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
653     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
654     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
655
656     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
657     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
658       MVT VT = (MVT::SimpleValueType)i;
659       // Do not attempt to custom lower non-power-of-2 vectors
660       if (!isPowerOf2_32(VT.getVectorNumElements()))
661         continue;
662       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
663       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
664       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
665     }
666     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
667     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
668     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
669     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
670     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
671     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
672     if (Subtarget->is64Bit()) {
673       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
674       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
675     }
676
677     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
678     for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
679       setOperationAction(ISD::AND,    (MVT::SimpleValueType)VT, Promote);
680       AddPromotedToType (ISD::AND,    (MVT::SimpleValueType)VT, MVT::v2i64);
681       setOperationAction(ISD::OR,     (MVT::SimpleValueType)VT, Promote);
682       AddPromotedToType (ISD::OR,     (MVT::SimpleValueType)VT, MVT::v2i64);
683       setOperationAction(ISD::XOR,    (MVT::SimpleValueType)VT, Promote);
684       AddPromotedToType (ISD::XOR,    (MVT::SimpleValueType)VT, MVT::v2i64);
685       setOperationAction(ISD::LOAD,   (MVT::SimpleValueType)VT, Promote);
686       AddPromotedToType (ISD::LOAD,   (MVT::SimpleValueType)VT, MVT::v2i64);
687       setOperationAction(ISD::SELECT, (MVT::SimpleValueType)VT, Promote);
688       AddPromotedToType (ISD::SELECT, (MVT::SimpleValueType)VT, MVT::v2i64);
689     }
690
691     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
692
693     // Custom lower v2i64 and v2f64 selects.
694     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
695     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
696     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
697     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
698     
699   }
700   
701   if (Subtarget->hasSSE41()) {
702     // FIXME: Do we need to handle scalar-to-vector here?
703     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
704     setOperationAction(ISD::MUL,                MVT::v2i64, Legal);
705
706     // i8 and i16 vectors are custom , because the source register and source
707     // source memory operand types are not the same width.  f32 vectors are
708     // custom since the immediate controlling the insert encodes additional
709     // information.
710     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
711     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
712     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Legal);
713     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
714
715     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
716     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
717     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
718     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
719
720     if (Subtarget->is64Bit()) {
721       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Legal);
722       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
723     }
724   }
725
726   // We want to custom lower some of our intrinsics.
727   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
728
729   // We have target-specific dag combine patterns for the following nodes:
730   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
731   setTargetDAGCombine(ISD::BUILD_VECTOR);
732   setTargetDAGCombine(ISD::SELECT);
733   setTargetDAGCombine(ISD::STORE);
734
735   computeRegisterProperties();
736
737   // FIXME: These should be based on subtarget info. Plus, the values should
738   // be smaller when we are in optimizing for size mode.
739   maxStoresPerMemset = 16; // For %llvm.memset -> sequence of stores
740   maxStoresPerMemcpy = 16; // For %llvm.memcpy -> sequence of stores
741   maxStoresPerMemmove = 3; // For %llvm.memmove -> sequence of stores
742   allowUnalignedMemoryAccesses = true; // x86 supports it!
743   setPrefLoopAlignment(16);
744 }
745
746
747 MVT X86TargetLowering::getSetCCResultType(const SDOperand &) const {
748   return MVT::i8;
749 }
750
751
752 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
753 /// the desired ByVal argument alignment.
754 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
755   if (MaxAlign == 16)
756     return;
757   if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
758     if (VTy->getBitWidth() == 128)
759       MaxAlign = 16;
760   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
761     unsigned EltAlign = 0;
762     getMaxByValAlign(ATy->getElementType(), EltAlign);
763     if (EltAlign > MaxAlign)
764       MaxAlign = EltAlign;
765   } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
766     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
767       unsigned EltAlign = 0;
768       getMaxByValAlign(STy->getElementType(i), EltAlign);
769       if (EltAlign > MaxAlign)
770         MaxAlign = EltAlign;
771       if (MaxAlign == 16)
772         break;
773     }
774   }
775   return;
776 }
777
778 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
779 /// function arguments in the caller parameter area. For X86, aggregates
780 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
781 /// are at 4-byte boundaries.
782 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
783   if (Subtarget->is64Bit())
784     return getTargetData()->getABITypeAlignment(Ty);
785   unsigned Align = 4;
786   if (Subtarget->hasSSE1())
787     getMaxByValAlign(Ty, Align);
788   return Align;
789 }
790
791 /// getOptimalMemOpType - Returns the target specific optimal type for load
792 /// and store operations as a result of memset, memcpy, and memmove
793 /// lowering. It returns MVT::iAny if SelectionDAG should be responsible for
794 /// determining it.
795 MVT
796 X86TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned Align,
797                                        bool isSrcConst, bool isSrcStr) const {
798   if ((isSrcConst || isSrcStr) && Subtarget->hasSSE2() && Size >= 16)
799     return MVT::v4i32;
800   if ((isSrcConst || isSrcStr) && Subtarget->hasSSE1() && Size >= 16)
801     return MVT::v4f32;
802   if (Subtarget->is64Bit() && Size >= 8)
803     return MVT::i64;
804   return MVT::i32;
805 }
806
807
808 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
809 /// jumptable.
810 SDOperand X86TargetLowering::getPICJumpTableRelocBase(SDOperand Table,
811                                                       SelectionDAG &DAG) const {
812   if (usesGlobalOffsetTable())
813     return DAG.getNode(ISD::GLOBAL_OFFSET_TABLE, getPointerTy());
814   if (!Subtarget->isPICStyleRIPRel())
815     return DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy());
816   return Table;
817 }
818
819 //===----------------------------------------------------------------------===//
820 //               Return Value Calling Convention Implementation
821 //===----------------------------------------------------------------------===//
822
823 #include "X86GenCallingConv.inc"
824
825 /// LowerRET - Lower an ISD::RET node.
826 SDOperand X86TargetLowering::LowerRET(SDOperand Op, SelectionDAG &DAG) {
827   assert((Op.getNumOperands() & 1) == 1 && "ISD::RET should have odd # args");
828   
829   SmallVector<CCValAssign, 16> RVLocs;
830   unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
831   bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
832   CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs);
833   CCInfo.AnalyzeReturn(Op.Val, RetCC_X86);
834     
835   // If this is the first return lowered for this function, add the regs to the
836   // liveout set for the function.
837   if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
838     for (unsigned i = 0; i != RVLocs.size(); ++i)
839       if (RVLocs[i].isRegLoc())
840         DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
841   }
842   SDOperand Chain = Op.getOperand(0);
843   
844   // Handle tail call return.
845   Chain = GetPossiblePreceedingTailCall(Chain, X86ISD::TAILCALL);
846   if (Chain.getOpcode() == X86ISD::TAILCALL) {
847     SDOperand TailCall = Chain;
848     SDOperand TargetAddress = TailCall.getOperand(1);
849     SDOperand StackAdjustment = TailCall.getOperand(2);
850     assert(((TargetAddress.getOpcode() == ISD::Register &&
851                (cast<RegisterSDNode>(TargetAddress)->getReg() == X86::ECX ||
852                 cast<RegisterSDNode>(TargetAddress)->getReg() == X86::R9)) ||
853               TargetAddress.getOpcode() == ISD::TargetExternalSymbol ||
854               TargetAddress.getOpcode() == ISD::TargetGlobalAddress) && 
855              "Expecting an global address, external symbol, or register");
856     assert(StackAdjustment.getOpcode() == ISD::Constant &&
857            "Expecting a const value");
858
859     SmallVector<SDOperand,8> Operands;
860     Operands.push_back(Chain.getOperand(0));
861     Operands.push_back(TargetAddress);
862     Operands.push_back(StackAdjustment);
863     // Copy registers used by the call. Last operand is a flag so it is not
864     // copied.
865     for (unsigned i=3; i < TailCall.getNumOperands()-1; i++) {
866       Operands.push_back(Chain.getOperand(i));
867     }
868     return DAG.getNode(X86ISD::TC_RETURN, MVT::Other, &Operands[0], 
869                        Operands.size());
870   }
871   
872   // Regular return.
873   SDOperand Flag;
874
875   SmallVector<SDOperand, 6> RetOps;
876   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
877   // Operand #1 = Bytes To Pop
878   RetOps.push_back(DAG.getConstant(getBytesToPopOnReturn(), MVT::i16));
879   
880   // Copy the result values into the output registers.
881   for (unsigned i = 0; i != RVLocs.size(); ++i) {
882     CCValAssign &VA = RVLocs[i];
883     assert(VA.isRegLoc() && "Can only return in registers!");
884     SDOperand ValToCopy = Op.getOperand(i*2+1);
885     
886     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
887     // the RET instruction and handled by the FP Stackifier.
888     if (RVLocs[i].getLocReg() == X86::ST0 ||
889         RVLocs[i].getLocReg() == X86::ST1) {
890       // If this is a copy from an xmm register to ST(0), use an FPExtend to
891       // change the value to the FP stack register class.
892       if (isScalarFPTypeInSSEReg(RVLocs[i].getValVT()))
893         ValToCopy = DAG.getNode(ISD::FP_EXTEND, MVT::f80, ValToCopy);
894       RetOps.push_back(ValToCopy);
895       // Don't emit a copytoreg.
896       continue;
897     }
898     
899     Chain = DAG.getCopyToReg(Chain, VA.getLocReg(), ValToCopy, Flag);
900     Flag = Chain.getValue(1);
901   }
902
903   // The x86-64 ABI for returning structs by value requires that we copy
904   // the sret argument into %rax for the return. We saved the argument into
905   // a virtual register in the entry block, so now we copy the value out
906   // and into %rax.
907   if (Subtarget->is64Bit() &&
908       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
909     MachineFunction &MF = DAG.getMachineFunction();
910     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
911     unsigned Reg = FuncInfo->getSRetReturnReg();
912     if (!Reg) {
913       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
914       FuncInfo->setSRetReturnReg(Reg);
915     }
916     SDOperand Val = DAG.getCopyFromReg(Chain, Reg, getPointerTy());
917
918     Chain = DAG.getCopyToReg(Chain, X86::RAX, Val, Flag);
919     Flag = Chain.getValue(1);
920   }
921   
922   RetOps[0] = Chain;  // Update chain.
923
924   // Add the flag if we have it.
925   if (Flag.Val)
926     RetOps.push_back(Flag);
927   
928   return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, &RetOps[0], RetOps.size());
929 }
930
931
932 /// LowerCallResult - Lower the result values of an ISD::CALL into the
933 /// appropriate copies out of appropriate physical registers.  This assumes that
934 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
935 /// being lowered.  The returns a SDNode with the same number of values as the
936 /// ISD::CALL.
937 SDNode *X86TargetLowering::
938 LowerCallResult(SDOperand Chain, SDOperand InFlag, SDNode *TheCall, 
939                 unsigned CallingConv, SelectionDAG &DAG) {
940   
941   // Assign locations to each value returned by this call.
942   SmallVector<CCValAssign, 16> RVLocs;
943   bool isVarArg = cast<ConstantSDNode>(TheCall->getOperand(2))->getValue() != 0;
944   CCState CCInfo(CallingConv, isVarArg, getTargetMachine(), RVLocs);
945   CCInfo.AnalyzeCallResult(TheCall, RetCC_X86);
946
947   SmallVector<SDOperand, 8> ResultVals;
948   
949   // Copy all of the result registers out of their specified physreg.
950   for (unsigned i = 0; i != RVLocs.size(); ++i) {
951     MVT CopyVT = RVLocs[i].getValVT();
952     
953     // If this is a call to a function that returns an fp value on the floating
954     // point stack, but where we prefer to use the value in xmm registers, copy
955     // it out as F80 and use a truncate to move it from fp stack reg to xmm reg.
956     if (RVLocs[i].getLocReg() == X86::ST0 &&
957         isScalarFPTypeInSSEReg(RVLocs[i].getValVT())) {
958       CopyVT = MVT::f80;
959     }
960     
961     Chain = DAG.getCopyFromReg(Chain, RVLocs[i].getLocReg(),
962                                CopyVT, InFlag).getValue(1);
963     SDOperand Val = Chain.getValue(0);
964     InFlag = Chain.getValue(2);
965
966     if (CopyVT != RVLocs[i].getValVT()) {
967       // Round the F80 the right size, which also moves to the appropriate xmm
968       // register.
969       Val = DAG.getNode(ISD::FP_ROUND, RVLocs[i].getValVT(), Val,
970                         // This truncation won't change the value.
971                         DAG.getIntPtrConstant(1));
972     }
973     
974     ResultVals.push_back(Val);
975   }
976   
977   // Merge everything together with a MERGE_VALUES node.
978   ResultVals.push_back(Chain);
979   return DAG.getNode(ISD::MERGE_VALUES, TheCall->getVTList(),
980                      &ResultVals[0], ResultVals.size()).Val;
981 }
982
983
984 //===----------------------------------------------------------------------===//
985 //                C & StdCall & Fast Calling Convention implementation
986 //===----------------------------------------------------------------------===//
987 //  StdCall calling convention seems to be standard for many Windows' API
988 //  routines and around. It differs from C calling convention just a little:
989 //  callee should clean up the stack, not caller. Symbols should be also
990 //  decorated in some fancy way :) It doesn't support any vector arguments.
991 //  For info on fast calling convention see Fast Calling Convention (tail call)
992 //  implementation LowerX86_32FastCCCallTo.
993
994 /// AddLiveIn - This helper function adds the specified physical register to the
995 /// MachineFunction as a live in value.  It also creates a corresponding virtual
996 /// register for it.
997 static unsigned AddLiveIn(MachineFunction &MF, unsigned PReg,
998                           const TargetRegisterClass *RC) {
999   assert(RC->contains(PReg) && "Not the correct regclass!");
1000   unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
1001   MF.getRegInfo().addLiveIn(PReg, VReg);
1002   return VReg;
1003 }
1004
1005 /// CallIsStructReturn - Determines whether a CALL node uses struct return
1006 /// semantics.
1007 static bool CallIsStructReturn(SDOperand Op) {
1008   unsigned NumOps = (Op.getNumOperands() - 5) / 2;
1009   if (!NumOps)
1010     return false;
1011
1012   return cast<ARG_FLAGSSDNode>(Op.getOperand(6))->getArgFlags().isSRet();
1013 }
1014
1015 /// ArgsAreStructReturn - Determines whether a FORMAL_ARGUMENTS node uses struct
1016 /// return semantics.
1017 static bool ArgsAreStructReturn(SDOperand Op) {
1018   unsigned NumArgs = Op.Val->getNumValues() - 1;
1019   if (!NumArgs)
1020     return false;
1021
1022   return cast<ARG_FLAGSSDNode>(Op.getOperand(3))->getArgFlags().isSRet();
1023 }
1024
1025 /// IsCalleePop - Determines whether a CALL or FORMAL_ARGUMENTS node requires
1026 /// the callee to pop its own arguments. Callee pop is necessary to support tail
1027 /// calls.
1028 bool X86TargetLowering::IsCalleePop(SDOperand Op) {
1029   bool IsVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1030   if (IsVarArg)
1031     return false;
1032
1033   switch (cast<ConstantSDNode>(Op.getOperand(1))->getValue()) {
1034   default:
1035     return false;
1036   case CallingConv::X86_StdCall:
1037     return !Subtarget->is64Bit();
1038   case CallingConv::X86_FastCall:
1039     return !Subtarget->is64Bit();
1040   case CallingConv::Fast:
1041     return PerformTailCallOpt;
1042   }
1043 }
1044
1045 /// CCAssignFnForNode - Selects the correct CCAssignFn for a CALL or
1046 /// FORMAL_ARGUMENTS node.
1047 CCAssignFn *X86TargetLowering::CCAssignFnForNode(SDOperand Op) const {
1048   unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
1049   
1050   if (Subtarget->is64Bit()) {
1051     if (Subtarget->isTargetWin64())
1052       return CC_X86_Win64_C;
1053     else {
1054       if (CC == CallingConv::Fast && PerformTailCallOpt)
1055         return CC_X86_64_TailCall;
1056       else
1057         return CC_X86_64_C;
1058     }
1059   }
1060
1061   if (CC == CallingConv::X86_FastCall)
1062     return CC_X86_32_FastCall;
1063   else if (CC == CallingConv::Fast && PerformTailCallOpt)
1064     return CC_X86_32_TailCall;
1065   else
1066     return CC_X86_32_C;
1067 }
1068
1069 /// NameDecorationForFORMAL_ARGUMENTS - Selects the appropriate decoration to
1070 /// apply to a MachineFunction containing a given FORMAL_ARGUMENTS node.
1071 NameDecorationStyle
1072 X86TargetLowering::NameDecorationForFORMAL_ARGUMENTS(SDOperand Op) {
1073   unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
1074   if (CC == CallingConv::X86_FastCall)
1075     return FastCall;
1076   else if (CC == CallingConv::X86_StdCall)
1077     return StdCall;
1078   return None;
1079 }
1080
1081
1082 /// CallRequiresGOTInRegister - Check whether the call requires the GOT pointer
1083 /// in a register before calling.
1084 bool X86TargetLowering::CallRequiresGOTPtrInReg(bool Is64Bit, bool IsTailCall) {
1085   return !IsTailCall && !Is64Bit &&
1086     getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1087     Subtarget->isPICStyleGOT();
1088 }
1089
1090 /// CallRequiresFnAddressInReg - Check whether the call requires the function
1091 /// address to be loaded in a register.
1092 bool 
1093 X86TargetLowering::CallRequiresFnAddressInReg(bool Is64Bit, bool IsTailCall) {
1094   return !Is64Bit && IsTailCall &&  
1095     getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1096     Subtarget->isPICStyleGOT();
1097 }
1098
1099 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1100 /// by "Src" to address "Dst" with size and alignment information specified by
1101 /// the specific parameter attribute. The copy will be passed as a byval
1102 /// function parameter.
1103 static SDOperand 
1104 CreateCopyOfByValArgument(SDOperand Src, SDOperand Dst, SDOperand Chain,
1105                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG) {
1106   SDOperand SizeNode     = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1107   return DAG.getMemcpy(Chain, Dst, Src, SizeNode, Flags.getByValAlign(),
1108                        /*AlwaysInline=*/true, NULL, 0, NULL, 0);
1109 }
1110
1111 SDOperand X86TargetLowering::LowerMemArgument(SDOperand Op, SelectionDAG &DAG,
1112                                               const CCValAssign &VA,
1113                                               MachineFrameInfo *MFI,
1114                                               unsigned CC,
1115                                               SDOperand Root, unsigned i) {
1116   // Create the nodes corresponding to a load from this parameter slot.
1117   ISD::ArgFlagsTy Flags =
1118     cast<ARG_FLAGSSDNode>(Op.getOperand(3 + i))->getArgFlags();
1119   bool AlwaysUseMutable = (CC==CallingConv::Fast) && PerformTailCallOpt;
1120   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1121
1122   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1123   // changed with more analysis.  
1124   // In case of tail call optimization mark all arguments mutable. Since they
1125   // could be overwritten by lowering of arguments in case of a tail call.
1126   int FI = MFI->CreateFixedObject(VA.getValVT().getSizeInBits()/8,
1127                                   VA.getLocMemOffset(), isImmutable);
1128   SDOperand FIN = DAG.getFrameIndex(FI, getPointerTy());
1129   if (Flags.isByVal())
1130     return FIN;
1131   return DAG.getLoad(VA.getValVT(), Root, FIN,
1132                      PseudoSourceValue::getFixedStack(), FI);
1133 }
1134
1135 SDOperand
1136 X86TargetLowering::LowerFORMAL_ARGUMENTS(SDOperand Op, SelectionDAG &DAG) {
1137   MachineFunction &MF = DAG.getMachineFunction();
1138   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1139   
1140   const Function* Fn = MF.getFunction();
1141   if (Fn->hasExternalLinkage() &&
1142       Subtarget->isTargetCygMing() &&
1143       Fn->getName() == "main")
1144     FuncInfo->setForceFramePointer(true);
1145
1146   // Decorate the function name.
1147   FuncInfo->setDecorationStyle(NameDecorationForFORMAL_ARGUMENTS(Op));
1148   
1149   MachineFrameInfo *MFI = MF.getFrameInfo();
1150   SDOperand Root = Op.getOperand(0);
1151   bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1152   unsigned CC = MF.getFunction()->getCallingConv();
1153   bool Is64Bit = Subtarget->is64Bit();
1154   bool IsWin64 = Subtarget->isTargetWin64();
1155
1156   assert(!(isVarArg && CC == CallingConv::Fast) &&
1157          "Var args not supported with calling convention fastcc");
1158
1159   // Assign locations to all of the incoming arguments.
1160   SmallVector<CCValAssign, 16> ArgLocs;
1161   CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1162   CCInfo.AnalyzeFormalArguments(Op.Val, CCAssignFnForNode(Op));
1163   
1164   SmallVector<SDOperand, 8> ArgValues;
1165   unsigned LastVal = ~0U;
1166   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1167     CCValAssign &VA = ArgLocs[i];
1168     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1169     // places.
1170     assert(VA.getValNo() != LastVal &&
1171            "Don't support value assigned to multiple locs yet");
1172     LastVal = VA.getValNo();
1173     
1174     if (VA.isRegLoc()) {
1175       MVT RegVT = VA.getLocVT();
1176       TargetRegisterClass *RC;
1177       if (RegVT == MVT::i32)
1178         RC = X86::GR32RegisterClass;
1179       else if (Is64Bit && RegVT == MVT::i64)
1180         RC = X86::GR64RegisterClass;
1181       else if (RegVT == MVT::f32)
1182         RC = X86::FR32RegisterClass;
1183       else if (RegVT == MVT::f64)
1184         RC = X86::FR64RegisterClass;
1185       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1186         RC = X86::VR128RegisterClass;
1187       else if (RegVT.isVector()) {
1188         assert(RegVT.getSizeInBits() == 64);
1189         if (!Is64Bit)
1190           RC = X86::VR64RegisterClass;     // MMX values are passed in MMXs.
1191         else {
1192           // Darwin calling convention passes MMX values in either GPRs or
1193           // XMMs in x86-64. Other targets pass them in memory.
1194           if (RegVT != MVT::v1i64 && Subtarget->hasSSE2()) {
1195             RC = X86::VR128RegisterClass;  // MMX values are passed in XMMs.
1196             RegVT = MVT::v2i64;
1197           } else {
1198             RC = X86::GR64RegisterClass;   // v1i64 values are passed in GPRs.
1199             RegVT = MVT::i64;
1200           }
1201         }
1202       } else {
1203         assert(0 && "Unknown argument type!");
1204       }
1205
1206       unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
1207       SDOperand ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
1208       
1209       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1210       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1211       // right size.
1212       if (VA.getLocInfo() == CCValAssign::SExt)
1213         ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
1214                                DAG.getValueType(VA.getValVT()));
1215       else if (VA.getLocInfo() == CCValAssign::ZExt)
1216         ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
1217                                DAG.getValueType(VA.getValVT()));
1218       
1219       if (VA.getLocInfo() != CCValAssign::Full)
1220         ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
1221       
1222       // Handle MMX values passed in GPRs.
1223       if (Is64Bit && RegVT != VA.getLocVT()) {
1224         if (RegVT.getSizeInBits() == 64 && RC == X86::GR64RegisterClass)
1225           ArgValue = DAG.getNode(ISD::BIT_CONVERT, VA.getLocVT(), ArgValue);
1226         else if (RC == X86::VR128RegisterClass) {
1227           ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i64, ArgValue,
1228                                  DAG.getConstant(0, MVT::i64));
1229           ArgValue = DAG.getNode(ISD::BIT_CONVERT, VA.getLocVT(), ArgValue);
1230         }
1231       }
1232       
1233       ArgValues.push_back(ArgValue);
1234     } else {
1235       assert(VA.isMemLoc());
1236       ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, CC, Root, i));
1237     }
1238   }
1239
1240   // The x86-64 ABI for returning structs by value requires that we copy
1241   // the sret argument into %rax for the return. Save the argument into
1242   // a virtual register so that we can access it from the return points.
1243   if (Is64Bit && DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1244     MachineFunction &MF = DAG.getMachineFunction();
1245     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1246     unsigned Reg = FuncInfo->getSRetReturnReg();
1247     if (!Reg) {
1248       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1249       FuncInfo->setSRetReturnReg(Reg);
1250     }
1251     SDOperand Copy = DAG.getCopyToReg(DAG.getEntryNode(), Reg, ArgValues[0]);
1252     Root = DAG.getNode(ISD::TokenFactor, MVT::Other, Copy, Root);
1253   }
1254
1255   unsigned StackSize = CCInfo.getNextStackOffset();
1256   // align stack specially for tail calls
1257   if (CC == CallingConv::Fast)
1258     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1259
1260   // If the function takes variable number of arguments, make a frame index for
1261   // the start of the first vararg value... for expansion of llvm.va_start.
1262   if (isVarArg) {
1263     if (Is64Bit || CC != CallingConv::X86_FastCall) {
1264       VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
1265     }
1266     if (Is64Bit) {
1267       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1268
1269       // FIXME: We should really autogenerate these arrays
1270       static const unsigned GPR64ArgRegsWin64[] = {
1271         X86::RCX, X86::RDX, X86::R8,  X86::R9
1272       };
1273       static const unsigned XMMArgRegsWin64[] = {
1274         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1275       };
1276       static const unsigned GPR64ArgRegs64Bit[] = {
1277         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1278       };
1279       static const unsigned XMMArgRegs64Bit[] = {
1280         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1281         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1282       };
1283       const unsigned *GPR64ArgRegs, *XMMArgRegs;
1284
1285       if (IsWin64) {
1286         TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1287         GPR64ArgRegs = GPR64ArgRegsWin64;
1288         XMMArgRegs = XMMArgRegsWin64;
1289       } else {
1290         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1291         GPR64ArgRegs = GPR64ArgRegs64Bit;
1292         XMMArgRegs = XMMArgRegs64Bit;
1293       }
1294       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1295                                                        TotalNumIntRegs);
1296       unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1297                                                        TotalNumXMMRegs);
1298
1299       // For X86-64, if there are vararg parameters that are passed via
1300       // registers, then we must store them to their spots on the stack so they
1301       // may be loaded by deferencing the result of va_next.
1302       VarArgsGPOffset = NumIntRegs * 8;
1303       VarArgsFPOffset = TotalNumIntRegs * 8 + NumXMMRegs * 16;
1304       RegSaveFrameIndex = MFI->CreateStackObject(TotalNumIntRegs * 8 +
1305                                                  TotalNumXMMRegs * 16, 16);
1306
1307       // Store the integer parameter registers.
1308       SmallVector<SDOperand, 8> MemOps;
1309       SDOperand RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1310       SDOperand FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1311                                   DAG.getIntPtrConstant(VarArgsGPOffset));
1312       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1313         unsigned VReg = AddLiveIn(MF, GPR64ArgRegs[NumIntRegs],
1314                                   X86::GR64RegisterClass);
1315         SDOperand Val = DAG.getCopyFromReg(Root, VReg, MVT::i64);
1316         SDOperand Store =
1317           DAG.getStore(Val.getValue(1), Val, FIN,
1318                        PseudoSourceValue::getFixedStack(),
1319                        RegSaveFrameIndex);
1320         MemOps.push_back(Store);
1321         FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1322                           DAG.getIntPtrConstant(8));
1323       }
1324
1325       // Now store the XMM (fp + vector) parameter registers.
1326       FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1327                         DAG.getIntPtrConstant(VarArgsFPOffset));
1328       for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1329         unsigned VReg = AddLiveIn(MF, XMMArgRegs[NumXMMRegs],
1330                                   X86::VR128RegisterClass);
1331         SDOperand Val = DAG.getCopyFromReg(Root, VReg, MVT::v4f32);
1332         SDOperand Store =
1333           DAG.getStore(Val.getValue(1), Val, FIN,
1334                        PseudoSourceValue::getFixedStack(),
1335                        RegSaveFrameIndex);
1336         MemOps.push_back(Store);
1337         FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1338                           DAG.getIntPtrConstant(16));
1339       }
1340       if (!MemOps.empty())
1341           Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
1342                              &MemOps[0], MemOps.size());
1343     }
1344   }
1345   
1346   // Make sure the instruction takes 8n+4 bytes to make sure the start of the
1347   // arguments and the arguments after the retaddr has been pushed are
1348   // aligned.
1349   if (!Is64Bit && CC == CallingConv::X86_FastCall &&
1350       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWindows() &&
1351       (StackSize & 7) == 0)
1352     StackSize += 4;
1353
1354   ArgValues.push_back(Root);
1355
1356   // Some CCs need callee pop.
1357   if (IsCalleePop(Op)) {
1358     BytesToPopOnReturn  = StackSize; // Callee pops everything.
1359     BytesCallerReserves = 0;
1360   } else {
1361     BytesToPopOnReturn  = 0; // Callee pops nothing.
1362     // If this is an sret function, the return should pop the hidden pointer.
1363     if (!Is64Bit && ArgsAreStructReturn(Op))
1364       BytesToPopOnReturn = 4;  
1365     BytesCallerReserves = StackSize;
1366   }
1367
1368   if (!Is64Bit) {
1369     RegSaveFrameIndex = 0xAAAAAAA;   // RegSaveFrameIndex is X86-64 only.
1370     if (CC == CallingConv::X86_FastCall)
1371       VarArgsFrameIndex = 0xAAAAAAA;   // fastcc functions can't have varargs.
1372   }
1373
1374   FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1375
1376   // Return the new list of results.
1377   return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(),
1378                      &ArgValues[0], ArgValues.size()).getValue(Op.ResNo);
1379 }
1380
1381 SDOperand
1382 X86TargetLowering::LowerMemOpCallTo(SDOperand Op, SelectionDAG &DAG,
1383                                     const SDOperand &StackPtr,
1384                                     const CCValAssign &VA,
1385                                     SDOperand Chain,
1386                                     SDOperand Arg) {
1387   unsigned LocMemOffset = VA.getLocMemOffset();
1388   SDOperand PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1389   PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
1390   ISD::ArgFlagsTy Flags =
1391     cast<ARG_FLAGSSDNode>(Op.getOperand(6+2*VA.getValNo()))->getArgFlags();
1392   if (Flags.isByVal()) {
1393     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG);
1394   }
1395   return DAG.getStore(Chain, Arg, PtrOff,
1396                       PseudoSourceValue::getStack(), LocMemOffset);
1397 }
1398
1399 /// EmitTailCallLoadRetAddr - Emit a load of return adress if tail call
1400 /// optimization is performed and it is required.
1401 SDOperand 
1402 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG, 
1403                                            SDOperand &OutRetAddr,
1404                                            SDOperand Chain, 
1405                                            bool IsTailCall, 
1406                                            bool Is64Bit, 
1407                                            int FPDiff) {
1408   if (!IsTailCall || FPDiff==0) return Chain;
1409
1410   // Adjust the Return address stack slot.
1411   MVT VT = getPointerTy();
1412   OutRetAddr = getReturnAddressFrameIndex(DAG);
1413   // Load the "old" Return address.
1414   OutRetAddr = DAG.getLoad(VT, Chain,OutRetAddr, NULL, 0);
1415   return SDOperand(OutRetAddr.Val, 1);
1416 }
1417
1418 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1419 /// optimization is performed and it is required (FPDiff!=0).
1420 static SDOperand 
1421 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF, 
1422                          SDOperand Chain, SDOperand RetAddrFrIdx,
1423                          bool Is64Bit, int FPDiff) {
1424   // Store the return address to the appropriate stack slot.
1425   if (!FPDiff) return Chain;
1426   // Calculate the new stack slot for the return address.
1427   int SlotSize = Is64Bit ? 8 : 4;
1428   int NewReturnAddrFI = 
1429     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize);
1430   MVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1431   SDOperand NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1432   Chain = DAG.getStore(Chain, RetAddrFrIdx, NewRetAddrFrIdx, 
1433                        PseudoSourceValue::getFixedStack(), NewReturnAddrFI);
1434   return Chain;
1435 }
1436
1437 SDOperand X86TargetLowering::LowerCALL(SDOperand Op, SelectionDAG &DAG) {
1438   MachineFunction &MF = DAG.getMachineFunction();
1439   SDOperand Chain     = Op.getOperand(0);
1440   unsigned CC         = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
1441   bool isVarArg       = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1442   bool IsTailCall     = cast<ConstantSDNode>(Op.getOperand(3))->getValue() != 0
1443                         && CC == CallingConv::Fast && PerformTailCallOpt;
1444   SDOperand Callee    = Op.getOperand(4);
1445   bool Is64Bit        = Subtarget->is64Bit();
1446   bool IsStructRet    = CallIsStructReturn(Op);
1447
1448   assert(!(isVarArg && CC == CallingConv::Fast) &&
1449          "Var args not supported with calling convention fastcc");
1450
1451   // Analyze operands of the call, assigning locations to each operand.
1452   SmallVector<CCValAssign, 16> ArgLocs;
1453   CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1454   CCInfo.AnalyzeCallOperands(Op.Val, CCAssignFnForNode(Op));
1455   
1456   // Get a count of how many bytes are to be pushed on the stack.
1457   unsigned NumBytes = CCInfo.getNextStackOffset();
1458   if (CC == CallingConv::Fast)
1459     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1460
1461   // Make sure the instruction takes 8n+4 bytes to make sure the start of the
1462   // arguments and the arguments after the retaddr has been pushed are aligned.
1463   if (!Is64Bit && CC == CallingConv::X86_FastCall &&
1464       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWindows() &&
1465       (NumBytes & 7) == 0)
1466     NumBytes += 4;
1467
1468   int FPDiff = 0;
1469   if (IsTailCall) {
1470     // Lower arguments at fp - stackoffset + fpdiff.
1471     unsigned NumBytesCallerPushed = 
1472       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1473     FPDiff = NumBytesCallerPushed - NumBytes;
1474
1475     // Set the delta of movement of the returnaddr stackslot.
1476     // But only set if delta is greater than previous delta.
1477     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1478       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1479   }
1480
1481   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes));
1482
1483   SDOperand RetAddrFrIdx;
1484   // Load return adress for tail calls.
1485   Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, IsTailCall, Is64Bit,
1486                                   FPDiff);
1487
1488   SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
1489   SmallVector<SDOperand, 8> MemOpChains;
1490   SDOperand StackPtr;
1491
1492   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1493   // of tail call optimization arguments are handle later.
1494   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1495     CCValAssign &VA = ArgLocs[i];
1496     SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1497     bool isByVal = cast<ARG_FLAGSSDNode>(Op.getOperand(6+2*VA.getValNo()))->
1498       getArgFlags().isByVal();
1499   
1500     // Promote the value if needed.
1501     switch (VA.getLocInfo()) {
1502     default: assert(0 && "Unknown loc info!");
1503     case CCValAssign::Full: break;
1504     case CCValAssign::SExt:
1505       Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1506       break;
1507     case CCValAssign::ZExt:
1508       Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1509       break;
1510     case CCValAssign::AExt:
1511       Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1512       break;
1513     }
1514     
1515     if (VA.isRegLoc()) {
1516       if (Is64Bit) {
1517         MVT RegVT = VA.getLocVT();
1518         if (RegVT.isVector() && RegVT.getSizeInBits() == 64)
1519           switch (VA.getLocReg()) {
1520           default:
1521             break;
1522           case X86::RDI: case X86::RSI: case X86::RDX: case X86::RCX:
1523           case X86::R8: {
1524             // Special case: passing MMX values in GPR registers.
1525             Arg = DAG.getNode(ISD::BIT_CONVERT, MVT::i64, Arg);
1526             break;
1527           }
1528           case X86::XMM0: case X86::XMM1: case X86::XMM2: case X86::XMM3:
1529           case X86::XMM4: case X86::XMM5: case X86::XMM6: case X86::XMM7: {
1530             // Special case: passing MMX values in XMM registers.
1531             Arg = DAG.getNode(ISD::BIT_CONVERT, MVT::i64, Arg);
1532             Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Arg);
1533             Arg = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v2i64,
1534                               DAG.getNode(ISD::UNDEF, MVT::v2i64), Arg,
1535                               getMOVLMask(2, DAG));
1536             break;
1537           }
1538           }
1539       }
1540       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1541     } else {
1542       if (!IsTailCall || (IsTailCall && isByVal)) {
1543         assert(VA.isMemLoc());
1544         if (StackPtr.Val == 0)
1545           StackPtr = DAG.getCopyFromReg(Chain, X86StackPtr, getPointerTy());
1546         
1547         MemOpChains.push_back(LowerMemOpCallTo(Op, DAG, StackPtr, VA, Chain,
1548                                                Arg));
1549       }
1550     }
1551   }
1552   
1553   if (!MemOpChains.empty())
1554     Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1555                         &MemOpChains[0], MemOpChains.size());
1556
1557   // Build a sequence of copy-to-reg nodes chained together with token chain
1558   // and flag operands which copy the outgoing args into registers.
1559   SDOperand InFlag;
1560   // Tail call byval lowering might overwrite argument registers so in case of
1561   // tail call optimization the copies to registers are lowered later.
1562   if (!IsTailCall)
1563     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1564       Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1565                                InFlag);
1566       InFlag = Chain.getValue(1);
1567     }
1568
1569   // ELF / PIC requires GOT in the EBX register before function calls via PLT
1570   // GOT pointer.  
1571   if (CallRequiresGOTPtrInReg(Is64Bit, IsTailCall)) {
1572     Chain = DAG.getCopyToReg(Chain, X86::EBX,
1573                              DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
1574                              InFlag);
1575     InFlag = Chain.getValue(1);
1576   }
1577   // If we are tail calling and generating PIC/GOT style code load the address
1578   // of the callee into ecx. The value in ecx is used as target of the tail
1579   // jump. This is done to circumvent the ebx/callee-saved problem for tail
1580   // calls on PIC/GOT architectures. Normally we would just put the address of
1581   // GOT into ebx and then call target@PLT. But for tail callss ebx would be
1582   // restored (since ebx is callee saved) before jumping to the target@PLT.
1583   if (CallRequiresFnAddressInReg(Is64Bit, IsTailCall)) {
1584     // Note: The actual moving to ecx is done further down.
1585     GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1586     if (G &&  !G->getGlobal()->hasHiddenVisibility() &&
1587         !G->getGlobal()->hasProtectedVisibility())
1588       Callee =  LowerGlobalAddress(Callee, DAG);
1589     else if (isa<ExternalSymbolSDNode>(Callee))
1590       Callee = LowerExternalSymbol(Callee,DAG);
1591   }
1592
1593   if (Is64Bit && isVarArg) {
1594     // From AMD64 ABI document:
1595     // For calls that may call functions that use varargs or stdargs
1596     // (prototype-less calls or calls to functions containing ellipsis (...) in
1597     // the declaration) %al is used as hidden argument to specify the number
1598     // of SSE registers used. The contents of %al do not need to match exactly
1599     // the number of registers, but must be an ubound on the number of SSE
1600     // registers used and is in the range 0 - 8 inclusive.
1601
1602     // FIXME: Verify this on Win64
1603     // Count the number of XMM registers allocated.
1604     static const unsigned XMMArgRegs[] = {
1605       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1606       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1607     };
1608     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1609     
1610     Chain = DAG.getCopyToReg(Chain, X86::AL,
1611                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1612     InFlag = Chain.getValue(1);
1613   }
1614
1615
1616   // For tail calls lower the arguments to the 'real' stack slot.
1617   if (IsTailCall) {
1618     SmallVector<SDOperand, 8> MemOpChains2;
1619     SDOperand FIN;
1620     int FI = 0;
1621     // Do not flag preceeding copytoreg stuff together with the following stuff.
1622     InFlag = SDOperand();
1623     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1624       CCValAssign &VA = ArgLocs[i];
1625       if (!VA.isRegLoc()) {
1626         assert(VA.isMemLoc());
1627         SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1628         SDOperand FlagsOp = Op.getOperand(6+2*VA.getValNo());
1629         ISD::ArgFlagsTy Flags =
1630           cast<ARG_FLAGSSDNode>(FlagsOp)->getArgFlags();
1631         // Create frame index.
1632         int32_t Offset = VA.getLocMemOffset()+FPDiff;
1633         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
1634         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset);
1635         FIN = DAG.getFrameIndex(FI, getPointerTy());
1636
1637         if (Flags.isByVal()) {
1638           // Copy relative to framepointer.
1639           SDOperand Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
1640           if (StackPtr.Val == 0)
1641             StackPtr = DAG.getCopyFromReg(Chain, X86StackPtr, getPointerTy());
1642           Source = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, Source);
1643
1644           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN, Chain,
1645                                                            Flags, DAG));
1646         } else {
1647           // Store relative to framepointer.
1648           MemOpChains2.push_back(
1649             DAG.getStore(Chain, Arg, FIN,
1650                          PseudoSourceValue::getFixedStack(), FI));
1651         }            
1652       }
1653     }
1654
1655     if (!MemOpChains2.empty())
1656       Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1657                           &MemOpChains2[0], MemOpChains2.size());
1658
1659     // Copy arguments to their registers.
1660     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1661       Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1662                                InFlag);
1663       InFlag = Chain.getValue(1);
1664     }
1665     InFlag =SDOperand();
1666
1667     // Store the return address to the appropriate stack slot.
1668     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
1669                                      FPDiff);
1670   }
1671
1672   // If the callee is a GlobalAddress node (quite common, every direct call is)
1673   // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1674   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1675     // We should use extra load for direct calls to dllimported functions in
1676     // non-JIT mode.
1677     if ((IsTailCall || !Is64Bit ||
1678          getTargetMachine().getCodeModel() != CodeModel::Large)
1679         && !Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1680                                            getTargetMachine(), true))
1681       Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1682   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1683     if (IsTailCall || !Is64Bit ||
1684         getTargetMachine().getCodeModel() != CodeModel::Large)
1685       Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1686   } else if (IsTailCall) {
1687     unsigned Opc = Is64Bit ? X86::R9 : X86::ECX;
1688
1689     Chain = DAG.getCopyToReg(Chain, 
1690                              DAG.getRegister(Opc, getPointerTy()), 
1691                              Callee,InFlag);
1692     Callee = DAG.getRegister(Opc, getPointerTy());
1693     // Add register as live out.
1694     DAG.getMachineFunction().getRegInfo().addLiveOut(Opc);
1695   }
1696  
1697   // Returns a chain & a flag for retval copy to use.
1698   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1699   SmallVector<SDOperand, 8> Ops;
1700
1701   if (IsTailCall) {
1702     Ops.push_back(Chain);
1703     Ops.push_back(DAG.getIntPtrConstant(NumBytes));
1704     Ops.push_back(DAG.getIntPtrConstant(0));
1705     if (InFlag.Val)
1706       Ops.push_back(InFlag);
1707     Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
1708     InFlag = Chain.getValue(1);
1709  
1710     // Returns a chain & a flag for retval copy to use.
1711     NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1712     Ops.clear();
1713   }
1714   
1715   Ops.push_back(Chain);
1716   Ops.push_back(Callee);
1717
1718   if (IsTailCall)
1719     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
1720
1721   // Add argument registers to the end of the list so that they are known live
1722   // into the call.
1723   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1724     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1725                                   RegsToPass[i].second.getValueType()));
1726   
1727   // Add an implicit use GOT pointer in EBX.
1728   if (!IsTailCall && !Is64Bit &&
1729       getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1730       Subtarget->isPICStyleGOT())
1731     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1732
1733   // Add an implicit use of AL for x86 vararg functions.
1734   if (Is64Bit && isVarArg)
1735     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
1736
1737   if (InFlag.Val)
1738     Ops.push_back(InFlag);
1739
1740   if (IsTailCall) {
1741     assert(InFlag.Val && 
1742            "Flag must be set. Depend on flag being set in LowerRET");
1743     Chain = DAG.getNode(X86ISD::TAILCALL,
1744                         Op.Val->getVTList(), &Ops[0], Ops.size());
1745       
1746     return SDOperand(Chain.Val, Op.ResNo);
1747   }
1748
1749   Chain = DAG.getNode(X86ISD::CALL, NodeTys, &Ops[0], Ops.size());
1750   InFlag = Chain.getValue(1);
1751
1752   // Create the CALLSEQ_END node.
1753   unsigned NumBytesForCalleeToPush;
1754   if (IsCalleePop(Op))
1755     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
1756   else if (!Is64Bit && IsStructRet)
1757     // If this is is a call to a struct-return function, the callee
1758     // pops the hidden struct pointer, so we have to push it back.
1759     // This is common for Darwin/X86, Linux & Mingw32 targets.
1760     NumBytesForCalleeToPush = 4;
1761   else
1762     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
1763   
1764   // Returns a flag for retval copy to use.
1765   Chain = DAG.getCALLSEQ_END(Chain,
1766                              DAG.getIntPtrConstant(NumBytes),
1767                              DAG.getIntPtrConstant(NumBytesForCalleeToPush),
1768                              InFlag);
1769   InFlag = Chain.getValue(1);
1770
1771   // Handle result values, copying them out of physregs into vregs that we
1772   // return.
1773   return SDOperand(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
1774 }
1775
1776
1777 //===----------------------------------------------------------------------===//
1778 //                Fast Calling Convention (tail call) implementation
1779 //===----------------------------------------------------------------------===//
1780
1781 //  Like std call, callee cleans arguments, convention except that ECX is
1782 //  reserved for storing the tail called function address. Only 2 registers are
1783 //  free for argument passing (inreg). Tail call optimization is performed
1784 //  provided:
1785 //                * tailcallopt is enabled
1786 //                * caller/callee are fastcc
1787 //  On X86_64 architecture with GOT-style position independent code only local
1788 //  (within module) calls are supported at the moment.
1789 //  To keep the stack aligned according to platform abi the function
1790 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
1791 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
1792 //  If a tail called function callee has more arguments than the caller the
1793 //  caller needs to make sure that there is room to move the RETADDR to. This is
1794 //  achieved by reserving an area the size of the argument delta right after the
1795 //  original REtADDR, but before the saved framepointer or the spilled registers
1796 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
1797 //  stack layout:
1798 //    arg1
1799 //    arg2
1800 //    RETADDR
1801 //    [ new RETADDR 
1802 //      move area ]
1803 //    (possible EBP)
1804 //    ESI
1805 //    EDI
1806 //    local1 ..
1807
1808 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
1809 /// for a 16 byte align requirement.
1810 unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize, 
1811                                                         SelectionDAG& DAG) {
1812   if (PerformTailCallOpt) {
1813     MachineFunction &MF = DAG.getMachineFunction();
1814     const TargetMachine &TM = MF.getTarget();
1815     const TargetFrameInfo &TFI = *TM.getFrameInfo();
1816     unsigned StackAlignment = TFI.getStackAlignment();
1817     uint64_t AlignMask = StackAlignment - 1; 
1818     int64_t Offset = StackSize;
1819     unsigned SlotSize = Subtarget->is64Bit() ? 8 : 4;
1820     if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
1821       // Number smaller than 12 so just add the difference.
1822       Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
1823     } else {
1824       // Mask out lower bits, add stackalignment once plus the 12 bytes.
1825       Offset = ((~AlignMask) & Offset) + StackAlignment + 
1826         (StackAlignment-SlotSize);
1827     }
1828     StackSize = Offset;
1829   }
1830   return StackSize;
1831 }
1832
1833 /// IsEligibleForTailCallElimination - Check to see whether the next instruction
1834 /// following the call is a return. A function is eligible if caller/callee
1835 /// calling conventions match, currently only fastcc supports tail calls, and
1836 /// the function CALL is immediatly followed by a RET.
1837 bool X86TargetLowering::IsEligibleForTailCallOptimization(SDOperand Call,
1838                                                       SDOperand Ret,
1839                                                       SelectionDAG& DAG) const {
1840   if (!PerformTailCallOpt)
1841     return false;
1842
1843   if (CheckTailCallReturnConstraints(Call, Ret)) {
1844     MachineFunction &MF = DAG.getMachineFunction();
1845     unsigned CallerCC = MF.getFunction()->getCallingConv();
1846     unsigned CalleeCC = cast<ConstantSDNode>(Call.getOperand(1))->getValue();
1847     if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
1848       SDOperand Callee = Call.getOperand(4);
1849       // On x86/32Bit PIC/GOT  tail calls are supported.
1850       if (getTargetMachine().getRelocationModel() != Reloc::PIC_ ||
1851           !Subtarget->isPICStyleGOT()|| !Subtarget->is64Bit())
1852         return true;
1853
1854       // Can only do local tail calls (in same module, hidden or protected) on
1855       // x86_64 PIC/GOT at the moment.
1856       if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1857         return G->getGlobal()->hasHiddenVisibility()
1858             || G->getGlobal()->hasProtectedVisibility();
1859     }
1860   }
1861
1862   return false;
1863 }
1864
1865 //===----------------------------------------------------------------------===//
1866 //                           Other Lowering Hooks
1867 //===----------------------------------------------------------------------===//
1868
1869
1870 SDOperand X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
1871   MachineFunction &MF = DAG.getMachineFunction();
1872   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1873   int ReturnAddrIndex = FuncInfo->getRAIndex();
1874
1875   if (ReturnAddrIndex == 0) {
1876     // Set up a frame object for the return address.
1877     if (Subtarget->is64Bit())
1878       ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(8, -8);
1879     else
1880       ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(4, -4);
1881
1882     FuncInfo->setRAIndex(ReturnAddrIndex);
1883   }
1884
1885   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
1886 }
1887
1888
1889
1890 /// translateX86CC - do a one to one translation of a ISD::CondCode to the X86
1891 /// specific condition code. It returns a false if it cannot do a direct
1892 /// translation. X86CC is the translated CondCode.  LHS/RHS are modified as
1893 /// needed.
1894 static bool translateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
1895                            unsigned &X86CC, SDOperand &LHS, SDOperand &RHS,
1896                            SelectionDAG &DAG) {
1897   X86CC = X86::COND_INVALID;
1898   if (!isFP) {
1899     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
1900       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
1901         // X > -1   -> X == 0, jump !sign.
1902         RHS = DAG.getConstant(0, RHS.getValueType());
1903         X86CC = X86::COND_NS;
1904         return true;
1905       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
1906         // X < 0   -> X == 0, jump on sign.
1907         X86CC = X86::COND_S;
1908         return true;
1909       } else if (SetCCOpcode == ISD::SETLT && RHSC->getValue() == 1) {
1910         // X < 1   -> X <= 0
1911         RHS = DAG.getConstant(0, RHS.getValueType());
1912         X86CC = X86::COND_LE;
1913         return true;
1914       }
1915     }
1916
1917     switch (SetCCOpcode) {
1918     default: break;
1919     case ISD::SETEQ:  X86CC = X86::COND_E;  break;
1920     case ISD::SETGT:  X86CC = X86::COND_G;  break;
1921     case ISD::SETGE:  X86CC = X86::COND_GE; break;
1922     case ISD::SETLT:  X86CC = X86::COND_L;  break;
1923     case ISD::SETLE:  X86CC = X86::COND_LE; break;
1924     case ISD::SETNE:  X86CC = X86::COND_NE; break;
1925     case ISD::SETULT: X86CC = X86::COND_B;  break;
1926     case ISD::SETUGT: X86CC = X86::COND_A;  break;
1927     case ISD::SETULE: X86CC = X86::COND_BE; break;
1928     case ISD::SETUGE: X86CC = X86::COND_AE; break;
1929     }
1930   } else {
1931     // On a floating point condition, the flags are set as follows:
1932     // ZF  PF  CF   op
1933     //  0 | 0 | 0 | X > Y
1934     //  0 | 0 | 1 | X < Y
1935     //  1 | 0 | 0 | X == Y
1936     //  1 | 1 | 1 | unordered
1937     bool Flip = false;
1938     switch (SetCCOpcode) {
1939     default: break;
1940     case ISD::SETUEQ:
1941     case ISD::SETEQ: X86CC = X86::COND_E;  break;
1942     case ISD::SETOLT: Flip = true; // Fallthrough
1943     case ISD::SETOGT:
1944     case ISD::SETGT: X86CC = X86::COND_A;  break;
1945     case ISD::SETOLE: Flip = true; // Fallthrough
1946     case ISD::SETOGE:
1947     case ISD::SETGE: X86CC = X86::COND_AE; break;
1948     case ISD::SETUGT: Flip = true; // Fallthrough
1949     case ISD::SETULT:
1950     case ISD::SETLT: X86CC = X86::COND_B;  break;
1951     case ISD::SETUGE: Flip = true; // Fallthrough
1952     case ISD::SETULE:
1953     case ISD::SETLE: X86CC = X86::COND_BE; break;
1954     case ISD::SETONE:
1955     case ISD::SETNE: X86CC = X86::COND_NE; break;
1956     case ISD::SETUO: X86CC = X86::COND_P;  break;
1957     case ISD::SETO:  X86CC = X86::COND_NP; break;
1958     }
1959     if (Flip)
1960       std::swap(LHS, RHS);
1961   }
1962
1963   return X86CC != X86::COND_INVALID;
1964 }
1965
1966 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
1967 /// code. Current x86 isa includes the following FP cmov instructions:
1968 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
1969 static bool hasFPCMov(unsigned X86CC) {
1970   switch (X86CC) {
1971   default:
1972     return false;
1973   case X86::COND_B:
1974   case X86::COND_BE:
1975   case X86::COND_E:
1976   case X86::COND_P:
1977   case X86::COND_A:
1978   case X86::COND_AE:
1979   case X86::COND_NE:
1980   case X86::COND_NP:
1981     return true;
1982   }
1983 }
1984
1985 /// isUndefOrInRange - Op is either an undef node or a ConstantSDNode.  Return
1986 /// true if Op is undef or if its value falls within the specified range (L, H].
1987 static bool isUndefOrInRange(SDOperand Op, unsigned Low, unsigned Hi) {
1988   if (Op.getOpcode() == ISD::UNDEF)
1989     return true;
1990
1991   unsigned Val = cast<ConstantSDNode>(Op)->getValue();
1992   return (Val >= Low && Val < Hi);
1993 }
1994
1995 /// isUndefOrEqual - Op is either an undef node or a ConstantSDNode.  Return
1996 /// true if Op is undef or if its value equal to the specified value.
1997 static bool isUndefOrEqual(SDOperand Op, unsigned Val) {
1998   if (Op.getOpcode() == ISD::UNDEF)
1999     return true;
2000   return cast<ConstantSDNode>(Op)->getValue() == Val;
2001 }
2002
2003 /// isPSHUFDMask - Return true if the specified VECTOR_SHUFFLE operand
2004 /// specifies a shuffle of elements that is suitable for input to PSHUFD.
2005 bool X86::isPSHUFDMask(SDNode *N) {
2006   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2007
2008   if (N->getNumOperands() != 2 && N->getNumOperands() != 4)
2009     return false;
2010
2011   // Check if the value doesn't reference the second vector.
2012   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2013     SDOperand Arg = N->getOperand(i);
2014     if (Arg.getOpcode() == ISD::UNDEF) continue;
2015     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2016     if (cast<ConstantSDNode>(Arg)->getValue() >= e)
2017       return false;
2018   }
2019
2020   return true;
2021 }
2022
2023 /// isPSHUFHWMask - Return true if the specified VECTOR_SHUFFLE operand
2024 /// specifies a shuffle of elements that is suitable for input to PSHUFHW.
2025 bool X86::isPSHUFHWMask(SDNode *N) {
2026   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2027
2028   if (N->getNumOperands() != 8)
2029     return false;
2030
2031   // Lower quadword copied in order.
2032   for (unsigned i = 0; i != 4; ++i) {
2033     SDOperand Arg = N->getOperand(i);
2034     if (Arg.getOpcode() == ISD::UNDEF) continue;
2035     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2036     if (cast<ConstantSDNode>(Arg)->getValue() != i)
2037       return false;
2038   }
2039
2040   // Upper quadword shuffled.
2041   for (unsigned i = 4; i != 8; ++i) {
2042     SDOperand Arg = N->getOperand(i);
2043     if (Arg.getOpcode() == ISD::UNDEF) continue;
2044     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2045     unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2046     if (Val < 4 || Val > 7)
2047       return false;
2048   }
2049
2050   return true;
2051 }
2052
2053 /// isPSHUFLWMask - Return true if the specified VECTOR_SHUFFLE operand
2054 /// specifies a shuffle of elements that is suitable for input to PSHUFLW.
2055 bool X86::isPSHUFLWMask(SDNode *N) {
2056   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2057
2058   if (N->getNumOperands() != 8)
2059     return false;
2060
2061   // Upper quadword copied in order.
2062   for (unsigned i = 4; i != 8; ++i)
2063     if (!isUndefOrEqual(N->getOperand(i), i))
2064       return false;
2065
2066   // Lower quadword shuffled.
2067   for (unsigned i = 0; i != 4; ++i)
2068     if (!isUndefOrInRange(N->getOperand(i), 0, 4))
2069       return false;
2070
2071   return true;
2072 }
2073
2074 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2075 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2076 static bool isSHUFPMask(SDOperandPtr Elems, unsigned NumElems) {
2077   if (NumElems != 2 && NumElems != 4) return false;
2078
2079   unsigned Half = NumElems / 2;
2080   for (unsigned i = 0; i < Half; ++i)
2081     if (!isUndefOrInRange(Elems[i], 0, NumElems))
2082       return false;
2083   for (unsigned i = Half; i < NumElems; ++i)
2084     if (!isUndefOrInRange(Elems[i], NumElems, NumElems*2))
2085       return false;
2086
2087   return true;
2088 }
2089
2090 bool X86::isSHUFPMask(SDNode *N) {
2091   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2092   return ::isSHUFPMask(N->op_begin(), N->getNumOperands());
2093 }
2094
2095 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2096 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2097 /// half elements to come from vector 1 (which would equal the dest.) and
2098 /// the upper half to come from vector 2.
2099 static bool isCommutedSHUFP(SDOperandPtr Ops, unsigned NumOps) {
2100   if (NumOps != 2 && NumOps != 4) return false;
2101
2102   unsigned Half = NumOps / 2;
2103   for (unsigned i = 0; i < Half; ++i)
2104     if (!isUndefOrInRange(Ops[i], NumOps, NumOps*2))
2105       return false;
2106   for (unsigned i = Half; i < NumOps; ++i)
2107     if (!isUndefOrInRange(Ops[i], 0, NumOps))
2108       return false;
2109   return true;
2110 }
2111
2112 static bool isCommutedSHUFP(SDNode *N) {
2113   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2114   return isCommutedSHUFP(N->op_begin(), N->getNumOperands());
2115 }
2116
2117 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2118 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2119 bool X86::isMOVHLPSMask(SDNode *N) {
2120   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2121
2122   if (N->getNumOperands() != 4)
2123     return false;
2124
2125   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2126   return isUndefOrEqual(N->getOperand(0), 6) &&
2127          isUndefOrEqual(N->getOperand(1), 7) &&
2128          isUndefOrEqual(N->getOperand(2), 2) &&
2129          isUndefOrEqual(N->getOperand(3), 3);
2130 }
2131
2132 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2133 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2134 /// <2, 3, 2, 3>
2135 bool X86::isMOVHLPS_v_undef_Mask(SDNode *N) {
2136   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2137
2138   if (N->getNumOperands() != 4)
2139     return false;
2140
2141   // Expect bit0 == 2, bit1 == 3, bit2 == 2, bit3 == 3
2142   return isUndefOrEqual(N->getOperand(0), 2) &&
2143          isUndefOrEqual(N->getOperand(1), 3) &&
2144          isUndefOrEqual(N->getOperand(2), 2) &&
2145          isUndefOrEqual(N->getOperand(3), 3);
2146 }
2147
2148 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2149 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2150 bool X86::isMOVLPMask(SDNode *N) {
2151   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2152
2153   unsigned NumElems = N->getNumOperands();
2154   if (NumElems != 2 && NumElems != 4)
2155     return false;
2156
2157   for (unsigned i = 0; i < NumElems/2; ++i)
2158     if (!isUndefOrEqual(N->getOperand(i), i + NumElems))
2159       return false;
2160
2161   for (unsigned i = NumElems/2; i < NumElems; ++i)
2162     if (!isUndefOrEqual(N->getOperand(i), i))
2163       return false;
2164
2165   return true;
2166 }
2167
2168 /// isMOVHPMask - Return true if the specified VECTOR_SHUFFLE operand
2169 /// specifies a shuffle of elements that is suitable for input to MOVHP{S|D}
2170 /// and MOVLHPS.
2171 bool X86::isMOVHPMask(SDNode *N) {
2172   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2173
2174   unsigned NumElems = N->getNumOperands();
2175   if (NumElems != 2 && NumElems != 4)
2176     return false;
2177
2178   for (unsigned i = 0; i < NumElems/2; ++i)
2179     if (!isUndefOrEqual(N->getOperand(i), i))
2180       return false;
2181
2182   for (unsigned i = 0; i < NumElems/2; ++i) {
2183     SDOperand Arg = N->getOperand(i + NumElems/2);
2184     if (!isUndefOrEqual(Arg, i + NumElems))
2185       return false;
2186   }
2187
2188   return true;
2189 }
2190
2191 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2192 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2193 bool static isUNPCKLMask(SDOperandPtr Elts, unsigned NumElts,
2194                          bool V2IsSplat = false) {
2195   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2196     return false;
2197
2198   for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2199     SDOperand BitI  = Elts[i];
2200     SDOperand BitI1 = Elts[i+1];
2201     if (!isUndefOrEqual(BitI, j))
2202       return false;
2203     if (V2IsSplat) {
2204       if (isUndefOrEqual(BitI1, NumElts))
2205         return false;
2206     } else {
2207       if (!isUndefOrEqual(BitI1, j + NumElts))
2208         return false;
2209     }
2210   }
2211
2212   return true;
2213 }
2214
2215 bool X86::isUNPCKLMask(SDNode *N, bool V2IsSplat) {
2216   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2217   return ::isUNPCKLMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2218 }
2219
2220 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2221 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2222 bool static isUNPCKHMask(SDOperandPtr Elts, unsigned NumElts,
2223                          bool V2IsSplat = false) {
2224   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2225     return false;
2226
2227   for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2228     SDOperand BitI  = Elts[i];
2229     SDOperand BitI1 = Elts[i+1];
2230     if (!isUndefOrEqual(BitI, j + NumElts/2))
2231       return false;
2232     if (V2IsSplat) {
2233       if (isUndefOrEqual(BitI1, NumElts))
2234         return false;
2235     } else {
2236       if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2237         return false;
2238     }
2239   }
2240
2241   return true;
2242 }
2243
2244 bool X86::isUNPCKHMask(SDNode *N, bool V2IsSplat) {
2245   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2246   return ::isUNPCKHMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2247 }
2248
2249 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2250 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2251 /// <0, 0, 1, 1>
2252 bool X86::isUNPCKL_v_undef_Mask(SDNode *N) {
2253   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2254
2255   unsigned NumElems = N->getNumOperands();
2256   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2257     return false;
2258
2259   for (unsigned i = 0, j = 0; i != NumElems; i += 2, ++j) {
2260     SDOperand BitI  = N->getOperand(i);
2261     SDOperand BitI1 = N->getOperand(i+1);
2262
2263     if (!isUndefOrEqual(BitI, j))
2264       return false;
2265     if (!isUndefOrEqual(BitI1, j))
2266       return false;
2267   }
2268
2269   return true;
2270 }
2271
2272 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2273 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2274 /// <2, 2, 3, 3>
2275 bool X86::isUNPCKH_v_undef_Mask(SDNode *N) {
2276   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2277
2278   unsigned NumElems = N->getNumOperands();
2279   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2280     return false;
2281
2282   for (unsigned i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2283     SDOperand BitI  = N->getOperand(i);
2284     SDOperand BitI1 = N->getOperand(i + 1);
2285
2286     if (!isUndefOrEqual(BitI, j))
2287       return false;
2288     if (!isUndefOrEqual(BitI1, j))
2289       return false;
2290   }
2291
2292   return true;
2293 }
2294
2295 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2296 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2297 /// MOVSD, and MOVD, i.e. setting the lowest element.
2298 static bool isMOVLMask(SDOperandPtr Elts, unsigned NumElts) {
2299   if (NumElts != 2 && NumElts != 4)
2300     return false;
2301
2302   if (!isUndefOrEqual(Elts[0], NumElts))
2303     return false;
2304
2305   for (unsigned i = 1; i < NumElts; ++i) {
2306     if (!isUndefOrEqual(Elts[i], i))
2307       return false;
2308   }
2309
2310   return true;
2311 }
2312
2313 bool X86::isMOVLMask(SDNode *N) {
2314   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2315   return ::isMOVLMask(N->op_begin(), N->getNumOperands());
2316 }
2317
2318 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2319 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
2320 /// element of vector 2 and the other elements to come from vector 1 in order.
2321 static bool isCommutedMOVL(SDOperandPtr Ops, unsigned NumOps,
2322                            bool V2IsSplat = false,
2323                            bool V2IsUndef = false) {
2324   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2325     return false;
2326
2327   if (!isUndefOrEqual(Ops[0], 0))
2328     return false;
2329
2330   for (unsigned i = 1; i < NumOps; ++i) {
2331     SDOperand Arg = Ops[i];
2332     if (!(isUndefOrEqual(Arg, i+NumOps) ||
2333           (V2IsUndef && isUndefOrInRange(Arg, NumOps, NumOps*2)) ||
2334           (V2IsSplat && isUndefOrEqual(Arg, NumOps))))
2335       return false;
2336   }
2337
2338   return true;
2339 }
2340
2341 static bool isCommutedMOVL(SDNode *N, bool V2IsSplat = false,
2342                            bool V2IsUndef = false) {
2343   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2344   return isCommutedMOVL(N->op_begin(), N->getNumOperands(),
2345                         V2IsSplat, V2IsUndef);
2346 }
2347
2348 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2349 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2350 bool X86::isMOVSHDUPMask(SDNode *N) {
2351   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2352
2353   if (N->getNumOperands() != 4)
2354     return false;
2355
2356   // Expect 1, 1, 3, 3
2357   for (unsigned i = 0; i < 2; ++i) {
2358     SDOperand Arg = N->getOperand(i);
2359     if (Arg.getOpcode() == ISD::UNDEF) continue;
2360     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2361     unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2362     if (Val != 1) return false;
2363   }
2364
2365   bool HasHi = false;
2366   for (unsigned i = 2; i < 4; ++i) {
2367     SDOperand Arg = N->getOperand(i);
2368     if (Arg.getOpcode() == ISD::UNDEF) continue;
2369     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2370     unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2371     if (Val != 3) return false;
2372     HasHi = true;
2373   }
2374
2375   // Don't use movshdup if it can be done with a shufps.
2376   return HasHi;
2377 }
2378
2379 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2380 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2381 bool X86::isMOVSLDUPMask(SDNode *N) {
2382   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2383
2384   if (N->getNumOperands() != 4)
2385     return false;
2386
2387   // Expect 0, 0, 2, 2
2388   for (unsigned i = 0; i < 2; ++i) {
2389     SDOperand Arg = N->getOperand(i);
2390     if (Arg.getOpcode() == ISD::UNDEF) continue;
2391     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2392     unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2393     if (Val != 0) return false;
2394   }
2395
2396   bool HasHi = false;
2397   for (unsigned i = 2; i < 4; ++i) {
2398     SDOperand Arg = N->getOperand(i);
2399     if (Arg.getOpcode() == ISD::UNDEF) continue;
2400     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2401     unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2402     if (Val != 2) return false;
2403     HasHi = true;
2404   }
2405
2406   // Don't use movshdup if it can be done with a shufps.
2407   return HasHi;
2408 }
2409
2410 /// isIdentityMask - Return true if the specified VECTOR_SHUFFLE operand
2411 /// specifies a identity operation on the LHS or RHS.
2412 static bool isIdentityMask(SDNode *N, bool RHS = false) {
2413   unsigned NumElems = N->getNumOperands();
2414   for (unsigned i = 0; i < NumElems; ++i)
2415     if (!isUndefOrEqual(N->getOperand(i), i + (RHS ? NumElems : 0)))
2416       return false;
2417   return true;
2418 }
2419
2420 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2421 /// a splat of a single element.
2422 static bool isSplatMask(SDNode *N) {
2423   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2424
2425   // This is a splat operation if each element of the permute is the same, and
2426   // if the value doesn't reference the second vector.
2427   unsigned NumElems = N->getNumOperands();
2428   SDOperand ElementBase;
2429   unsigned i = 0;
2430   for (; i != NumElems; ++i) {
2431     SDOperand Elt = N->getOperand(i);
2432     if (isa<ConstantSDNode>(Elt)) {
2433       ElementBase = Elt;
2434       break;
2435     }
2436   }
2437
2438   if (!ElementBase.Val)
2439     return false;
2440
2441   for (; i != NumElems; ++i) {
2442     SDOperand Arg = N->getOperand(i);
2443     if (Arg.getOpcode() == ISD::UNDEF) continue;
2444     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2445     if (Arg != ElementBase) return false;
2446   }
2447
2448   // Make sure it is a splat of the first vector operand.
2449   return cast<ConstantSDNode>(ElementBase)->getValue() < NumElems;
2450 }
2451
2452 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2453 /// a splat of a single element and it's a 2 or 4 element mask.
2454 bool X86::isSplatMask(SDNode *N) {
2455   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2456
2457   // We can only splat 64-bit, and 32-bit quantities with a single instruction.
2458   if (N->getNumOperands() != 4 && N->getNumOperands() != 2)
2459     return false;
2460   return ::isSplatMask(N);
2461 }
2462
2463 /// isSplatLoMask - Return true if the specified VECTOR_SHUFFLE operand
2464 /// specifies a splat of zero element.
2465 bool X86::isSplatLoMask(SDNode *N) {
2466   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2467
2468   for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i)
2469     if (!isUndefOrEqual(N->getOperand(i), 0))
2470       return false;
2471   return true;
2472 }
2473
2474 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2475 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUF* and SHUFP*
2476 /// instructions.
2477 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2478   unsigned NumOperands = N->getNumOperands();
2479   unsigned Shift = (NumOperands == 4) ? 2 : 1;
2480   unsigned Mask = 0;
2481   for (unsigned i = 0; i < NumOperands; ++i) {
2482     unsigned Val = 0;
2483     SDOperand Arg = N->getOperand(NumOperands-i-1);
2484     if (Arg.getOpcode() != ISD::UNDEF)
2485       Val = cast<ConstantSDNode>(Arg)->getValue();
2486     if (Val >= NumOperands) Val -= NumOperands;
2487     Mask |= Val;
2488     if (i != NumOperands - 1)
2489       Mask <<= Shift;
2490   }
2491
2492   return Mask;
2493 }
2494
2495 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2496 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFHW
2497 /// instructions.
2498 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2499   unsigned Mask = 0;
2500   // 8 nodes, but we only care about the last 4.
2501   for (unsigned i = 7; i >= 4; --i) {
2502     unsigned Val = 0;
2503     SDOperand Arg = N->getOperand(i);
2504     if (Arg.getOpcode() != ISD::UNDEF)
2505       Val = cast<ConstantSDNode>(Arg)->getValue();
2506     Mask |= (Val - 4);
2507     if (i != 4)
2508       Mask <<= 2;
2509   }
2510
2511   return Mask;
2512 }
2513
2514 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2515 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFLW
2516 /// instructions.
2517 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2518   unsigned Mask = 0;
2519   // 8 nodes, but we only care about the first 4.
2520   for (int i = 3; i >= 0; --i) {
2521     unsigned Val = 0;
2522     SDOperand Arg = N->getOperand(i);
2523     if (Arg.getOpcode() != ISD::UNDEF)
2524       Val = cast<ConstantSDNode>(Arg)->getValue();
2525     Mask |= Val;
2526     if (i != 0)
2527       Mask <<= 2;
2528   }
2529
2530   return Mask;
2531 }
2532
2533 /// isPSHUFHW_PSHUFLWMask - true if the specified VECTOR_SHUFFLE operand
2534 /// specifies a 8 element shuffle that can be broken into a pair of
2535 /// PSHUFHW and PSHUFLW.
2536 static bool isPSHUFHW_PSHUFLWMask(SDNode *N) {
2537   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2538
2539   if (N->getNumOperands() != 8)
2540     return false;
2541
2542   // Lower quadword shuffled.
2543   for (unsigned i = 0; i != 4; ++i) {
2544     SDOperand Arg = N->getOperand(i);
2545     if (Arg.getOpcode() == ISD::UNDEF) continue;
2546     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2547     unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2548     if (Val >= 4)
2549       return false;
2550   }
2551
2552   // Upper quadword shuffled.
2553   for (unsigned i = 4; i != 8; ++i) {
2554     SDOperand Arg = N->getOperand(i);
2555     if (Arg.getOpcode() == ISD::UNDEF) continue;
2556     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2557     unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2558     if (Val < 4 || Val > 7)
2559       return false;
2560   }
2561
2562   return true;
2563 }
2564
2565 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as
2566 /// values in ther permute mask.
2567 static SDOperand CommuteVectorShuffle(SDOperand Op, SDOperand &V1,
2568                                       SDOperand &V2, SDOperand &Mask,
2569                                       SelectionDAG &DAG) {
2570   MVT VT = Op.getValueType();
2571   MVT MaskVT = Mask.getValueType();
2572   MVT EltVT = MaskVT.getVectorElementType();
2573   unsigned NumElems = Mask.getNumOperands();
2574   SmallVector<SDOperand, 8> MaskVec;
2575
2576   for (unsigned i = 0; i != NumElems; ++i) {
2577     SDOperand Arg = Mask.getOperand(i);
2578     if (Arg.getOpcode() == ISD::UNDEF) {
2579       MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2580       continue;
2581     }
2582     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2583     unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2584     if (Val < NumElems)
2585       MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2586     else
2587       MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2588   }
2589
2590   std::swap(V1, V2);
2591   Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
2592   return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2593 }
2594
2595 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
2596 /// the two vector operands have swapped position.
2597 static
2598 SDOperand CommuteVectorShuffleMask(SDOperand Mask, SelectionDAG &DAG) {
2599   MVT MaskVT = Mask.getValueType();
2600   MVT EltVT = MaskVT.getVectorElementType();
2601   unsigned NumElems = Mask.getNumOperands();
2602   SmallVector<SDOperand, 8> MaskVec;
2603   for (unsigned i = 0; i != NumElems; ++i) {
2604     SDOperand Arg = Mask.getOperand(i);
2605     if (Arg.getOpcode() == ISD::UNDEF) {
2606       MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2607       continue;
2608     }
2609     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2610     unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2611     if (Val < NumElems)
2612       MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2613     else
2614       MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2615   }
2616   return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
2617 }
2618
2619
2620 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2621 /// match movhlps. The lower half elements should come from upper half of
2622 /// V1 (and in order), and the upper half elements should come from the upper
2623 /// half of V2 (and in order).
2624 static bool ShouldXformToMOVHLPS(SDNode *Mask) {
2625   unsigned NumElems = Mask->getNumOperands();
2626   if (NumElems != 4)
2627     return false;
2628   for (unsigned i = 0, e = 2; i != e; ++i)
2629     if (!isUndefOrEqual(Mask->getOperand(i), i+2))
2630       return false;
2631   for (unsigned i = 2; i != 4; ++i)
2632     if (!isUndefOrEqual(Mask->getOperand(i), i+4))
2633       return false;
2634   return true;
2635 }
2636
2637 /// isScalarLoadToVector - Returns true if the node is a scalar load that
2638 /// is promoted to a vector. It also returns the LoadSDNode by reference if
2639 /// required.
2640 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
2641   if (N->getOpcode() == ISD::SCALAR_TO_VECTOR) {
2642     N = N->getOperand(0).Val;
2643     if (ISD::isNON_EXTLoad(N)) {
2644       if (LD)
2645         *LD = cast<LoadSDNode>(N);
2646       return true;
2647     }
2648   }
2649   return false;
2650 }
2651
2652 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
2653 /// match movlp{s|d}. The lower half elements should come from lower half of
2654 /// V1 (and in order), and the upper half elements should come from the upper
2655 /// half of V2 (and in order). And since V1 will become the source of the
2656 /// MOVLP, it must be either a vector load or a scalar load to vector.
2657 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2, SDNode *Mask) {
2658   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
2659     return false;
2660   // Is V2 is a vector load, don't do this transformation. We will try to use
2661   // load folding shufps op.
2662   if (ISD::isNON_EXTLoad(V2))
2663     return false;
2664
2665   unsigned NumElems = Mask->getNumOperands();
2666   if (NumElems != 2 && NumElems != 4)
2667     return false;
2668   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
2669     if (!isUndefOrEqual(Mask->getOperand(i), i))
2670       return false;
2671   for (unsigned i = NumElems/2; i != NumElems; ++i)
2672     if (!isUndefOrEqual(Mask->getOperand(i), i+NumElems))
2673       return false;
2674   return true;
2675 }
2676
2677 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
2678 /// all the same.
2679 static bool isSplatVector(SDNode *N) {
2680   if (N->getOpcode() != ISD::BUILD_VECTOR)
2681     return false;
2682
2683   SDOperand SplatValue = N->getOperand(0);
2684   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
2685     if (N->getOperand(i) != SplatValue)
2686       return false;
2687   return true;
2688 }
2689
2690 /// isUndefShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2691 /// to an undef.
2692 static bool isUndefShuffle(SDNode *N) {
2693   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2694     return false;
2695
2696   SDOperand V1 = N->getOperand(0);
2697   SDOperand V2 = N->getOperand(1);
2698   SDOperand Mask = N->getOperand(2);
2699   unsigned NumElems = Mask.getNumOperands();
2700   for (unsigned i = 0; i != NumElems; ++i) {
2701     SDOperand Arg = Mask.getOperand(i);
2702     if (Arg.getOpcode() != ISD::UNDEF) {
2703       unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2704       if (Val < NumElems && V1.getOpcode() != ISD::UNDEF)
2705         return false;
2706       else if (Val >= NumElems && V2.getOpcode() != ISD::UNDEF)
2707         return false;
2708     }
2709   }
2710   return true;
2711 }
2712
2713 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
2714 /// constant +0.0.
2715 static inline bool isZeroNode(SDOperand Elt) {
2716   return ((isa<ConstantSDNode>(Elt) &&
2717            cast<ConstantSDNode>(Elt)->getValue() == 0) ||
2718           (isa<ConstantFPSDNode>(Elt) &&
2719            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
2720 }
2721
2722 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2723 /// to an zero vector.
2724 static bool isZeroShuffle(SDNode *N) {
2725   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2726     return false;
2727
2728   SDOperand V1 = N->getOperand(0);
2729   SDOperand V2 = N->getOperand(1);
2730   SDOperand Mask = N->getOperand(2);
2731   unsigned NumElems = Mask.getNumOperands();
2732   for (unsigned i = 0; i != NumElems; ++i) {
2733     SDOperand Arg = Mask.getOperand(i);
2734     if (Arg.getOpcode() == ISD::UNDEF)
2735       continue;
2736     
2737     unsigned Idx = cast<ConstantSDNode>(Arg)->getValue();
2738     if (Idx < NumElems) {
2739       unsigned Opc = V1.Val->getOpcode();
2740       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.Val))
2741         continue;
2742       if (Opc != ISD::BUILD_VECTOR ||
2743           !isZeroNode(V1.Val->getOperand(Idx)))
2744         return false;
2745     } else if (Idx >= NumElems) {
2746       unsigned Opc = V2.Val->getOpcode();
2747       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.Val))
2748         continue;
2749       if (Opc != ISD::BUILD_VECTOR ||
2750           !isZeroNode(V2.Val->getOperand(Idx - NumElems)))
2751         return false;
2752     }
2753   }
2754   return true;
2755 }
2756
2757 /// getZeroVector - Returns a vector of specified type with all zero elements.
2758 ///
2759 static SDOperand getZeroVector(MVT VT, bool HasSSE2, SelectionDAG &DAG) {
2760   assert(VT.isVector() && "Expected a vector type");
2761   
2762   // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2763   // type.  This ensures they get CSE'd.
2764   SDOperand Vec;
2765   if (VT.getSizeInBits() == 64) { // MMX
2766     SDOperand Cst = DAG.getTargetConstant(0, MVT::i32);
2767     Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
2768   } else if (HasSSE2) {  // SSE2
2769     SDOperand Cst = DAG.getTargetConstant(0, MVT::i32);
2770     Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
2771   } else { // SSE1
2772     SDOperand Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
2773     Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4f32, Cst, Cst, Cst, Cst);
2774   }
2775   return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
2776 }
2777
2778 /// getOnesVector - Returns a vector of specified type with all bits set.
2779 ///
2780 static SDOperand getOnesVector(MVT VT, SelectionDAG &DAG) {
2781   assert(VT.isVector() && "Expected a vector type");
2782   
2783   // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2784   // type.  This ensures they get CSE'd.
2785   SDOperand Cst = DAG.getTargetConstant(~0U, MVT::i32);
2786   SDOperand Vec;
2787   if (VT.getSizeInBits() == 64)  // MMX
2788     Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
2789   else                                              // SSE
2790     Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
2791   return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
2792 }
2793
2794
2795 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
2796 /// that point to V2 points to its first element.
2797 static SDOperand NormalizeMask(SDOperand Mask, SelectionDAG &DAG) {
2798   assert(Mask.getOpcode() == ISD::BUILD_VECTOR);
2799
2800   bool Changed = false;
2801   SmallVector<SDOperand, 8> MaskVec;
2802   unsigned NumElems = Mask.getNumOperands();
2803   for (unsigned i = 0; i != NumElems; ++i) {
2804     SDOperand Arg = Mask.getOperand(i);
2805     if (Arg.getOpcode() != ISD::UNDEF) {
2806       unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2807       if (Val > NumElems) {
2808         Arg = DAG.getConstant(NumElems, Arg.getValueType());
2809         Changed = true;
2810       }
2811     }
2812     MaskVec.push_back(Arg);
2813   }
2814
2815   if (Changed)
2816     Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getValueType(),
2817                        &MaskVec[0], MaskVec.size());
2818   return Mask;
2819 }
2820
2821 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
2822 /// operation of specified width.
2823 static SDOperand getMOVLMask(unsigned NumElems, SelectionDAG &DAG) {
2824   MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2825   MVT BaseVT = MaskVT.getVectorElementType();
2826
2827   SmallVector<SDOperand, 8> MaskVec;
2828   MaskVec.push_back(DAG.getConstant(NumElems, BaseVT));
2829   for (unsigned i = 1; i != NumElems; ++i)
2830     MaskVec.push_back(DAG.getConstant(i, BaseVT));
2831   return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2832 }
2833
2834 /// getUnpacklMask - Returns a vector_shuffle mask for an unpackl operation
2835 /// of specified width.
2836 static SDOperand getUnpacklMask(unsigned NumElems, SelectionDAG &DAG) {
2837   MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2838   MVT BaseVT = MaskVT.getVectorElementType();
2839   SmallVector<SDOperand, 8> MaskVec;
2840   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
2841     MaskVec.push_back(DAG.getConstant(i,            BaseVT));
2842     MaskVec.push_back(DAG.getConstant(i + NumElems, BaseVT));
2843   }
2844   return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2845 }
2846
2847 /// getUnpackhMask - Returns a vector_shuffle mask for an unpackh operation
2848 /// of specified width.
2849 static SDOperand getUnpackhMask(unsigned NumElems, SelectionDAG &DAG) {
2850   MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2851   MVT BaseVT = MaskVT.getVectorElementType();
2852   unsigned Half = NumElems/2;
2853   SmallVector<SDOperand, 8> MaskVec;
2854   for (unsigned i = 0; i != Half; ++i) {
2855     MaskVec.push_back(DAG.getConstant(i + Half,            BaseVT));
2856     MaskVec.push_back(DAG.getConstant(i + NumElems + Half, BaseVT));
2857   }
2858   return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2859 }
2860
2861 /// getSwapEltZeroMask - Returns a vector_shuffle mask for a shuffle that swaps
2862 /// element #0 of a vector with the specified index, leaving the rest of the
2863 /// elements in place.
2864 static SDOperand getSwapEltZeroMask(unsigned NumElems, unsigned DestElt,
2865                                    SelectionDAG &DAG) {
2866   MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2867   MVT BaseVT = MaskVT.getVectorElementType();
2868   SmallVector<SDOperand, 8> MaskVec;
2869   // Element #0 of the result gets the elt we are replacing.
2870   MaskVec.push_back(DAG.getConstant(DestElt, BaseVT));
2871   for (unsigned i = 1; i != NumElems; ++i)
2872     MaskVec.push_back(DAG.getConstant(i == DestElt ? 0 : i, BaseVT));
2873   return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2874 }
2875
2876 /// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
2877 static SDOperand PromoteSplat(SDOperand Op, SelectionDAG &DAG, bool HasSSE2) {
2878   MVT PVT = HasSSE2 ? MVT::v4i32 : MVT::v4f32;
2879   MVT VT = Op.getValueType();
2880   if (PVT == VT)
2881     return Op;
2882   SDOperand V1 = Op.getOperand(0);
2883   SDOperand Mask = Op.getOperand(2);
2884   unsigned NumElems = Mask.getNumOperands();
2885   // Special handling of v4f32 -> v4i32.
2886   if (VT != MVT::v4f32) {
2887     Mask = getUnpacklMask(NumElems, DAG);
2888     while (NumElems > 4) {
2889       V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1, Mask);
2890       NumElems >>= 1;
2891     }
2892     Mask = getZeroVector(MVT::v4i32, true, DAG);
2893   }
2894
2895   V1 = DAG.getNode(ISD::BIT_CONVERT, PVT, V1);
2896   SDOperand Shuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, PVT, V1,
2897                                   DAG.getNode(ISD::UNDEF, PVT), Mask);
2898   return DAG.getNode(ISD::BIT_CONVERT, VT, Shuffle);
2899 }
2900
2901 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
2902 /// vector of zero or undef vector.  This produces a shuffle where the low
2903 /// element of V2 is swizzled into the zero/undef vector, landing at element
2904 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
2905 static SDOperand getShuffleVectorZeroOrUndef(SDOperand V2, unsigned Idx,
2906                                              bool isZero, bool HasSSE2,
2907                                              SelectionDAG &DAG) {
2908   MVT VT = V2.getValueType();
2909   SDOperand V1 = isZero
2910     ? getZeroVector(VT, HasSSE2, DAG) : DAG.getNode(ISD::UNDEF, VT);
2911   unsigned NumElems = V2.getValueType().getVectorNumElements();
2912   MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2913   MVT EVT = MaskVT.getVectorElementType();
2914   SmallVector<SDOperand, 16> MaskVec;
2915   for (unsigned i = 0; i != NumElems; ++i)
2916     if (i == Idx)  // If this is the insertion idx, put the low elt of V2 here.
2917       MaskVec.push_back(DAG.getConstant(NumElems, EVT));
2918     else
2919       MaskVec.push_back(DAG.getConstant(i, EVT));
2920   SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2921                                &MaskVec[0], MaskVec.size());
2922   return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2923 }
2924
2925 /// getNumOfConsecutiveZeros - Return the number of elements in a result of
2926 /// a shuffle that is zero.
2927 static
2928 unsigned getNumOfConsecutiveZeros(SDOperand Op, SDOperand Mask,
2929                                   unsigned NumElems, bool Low,
2930                                   SelectionDAG &DAG) {
2931   unsigned NumZeros = 0;
2932   for (unsigned i = 0; i < NumElems; ++i) {
2933     SDOperand Idx = Mask.getOperand(Low ? i : NumElems-i-1);
2934     if (Idx.getOpcode() == ISD::UNDEF) {
2935       ++NumZeros;
2936       continue;
2937     }
2938     unsigned Index = cast<ConstantSDNode>(Idx)->getValue();
2939     SDOperand Elt = DAG.getShuffleScalarElt(Op.Val, Index);
2940     if (Elt.Val && isZeroNode(Elt))
2941       ++NumZeros;
2942     else
2943       break;
2944   }
2945   return NumZeros;
2946 }
2947
2948 /// isVectorShift - Returns true if the shuffle can be implemented as a
2949 /// logical left or right shift of a vector.
2950 static bool isVectorShift(SDOperand Op, SDOperand Mask, SelectionDAG &DAG,
2951                           bool &isLeft, SDOperand &ShVal, unsigned &ShAmt) {
2952   unsigned NumElems = Mask.getNumOperands();
2953
2954   isLeft = true;
2955   unsigned NumZeros= getNumOfConsecutiveZeros(Op, Mask, NumElems, true, DAG);
2956   if (!NumZeros) {
2957     isLeft = false;
2958     NumZeros = getNumOfConsecutiveZeros(Op, Mask, NumElems, false, DAG);
2959     if (!NumZeros)
2960       return false;
2961   }
2962
2963   bool SeenV1 = false;
2964   bool SeenV2 = false;
2965   for (unsigned i = NumZeros; i < NumElems; ++i) {
2966     unsigned Val = isLeft ? (i - NumZeros) : i;
2967     SDOperand Idx = Mask.getOperand(isLeft ? i : (i - NumZeros));
2968     if (Idx.getOpcode() == ISD::UNDEF)
2969       continue;
2970     unsigned Index = cast<ConstantSDNode>(Idx)->getValue();
2971     if (Index < NumElems)
2972       SeenV1 = true;
2973     else {
2974       Index -= NumElems;
2975       SeenV2 = true;
2976     }
2977     if (Index != Val)
2978       return false;
2979   }
2980   if (SeenV1 && SeenV2)
2981     return false;
2982
2983   ShVal = SeenV1 ? Op.getOperand(0) : Op.getOperand(1);
2984   ShAmt = NumZeros;
2985   return true;
2986 }
2987
2988
2989 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
2990 ///
2991 static SDOperand LowerBuildVectorv16i8(SDOperand Op, unsigned NonZeros,
2992                                        unsigned NumNonZero, unsigned NumZero,
2993                                        SelectionDAG &DAG, TargetLowering &TLI) {
2994   if (NumNonZero > 8)
2995     return SDOperand();
2996
2997   SDOperand V(0, 0);
2998   bool First = true;
2999   for (unsigned i = 0; i < 16; ++i) {
3000     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3001     if (ThisIsNonZero && First) {
3002       if (NumZero)
3003         V = getZeroVector(MVT::v8i16, true, DAG);
3004       else
3005         V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
3006       First = false;
3007     }
3008
3009     if ((i & 1) != 0) {
3010       SDOperand ThisElt(0, 0), LastElt(0, 0);
3011       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3012       if (LastIsNonZero) {
3013         LastElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i-1));
3014       }
3015       if (ThisIsNonZero) {
3016         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i));
3017         ThisElt = DAG.getNode(ISD::SHL, MVT::i16,
3018                               ThisElt, DAG.getConstant(8, MVT::i8));
3019         if (LastIsNonZero)
3020           ThisElt = DAG.getNode(ISD::OR, MVT::i16, ThisElt, LastElt);
3021       } else
3022         ThisElt = LastElt;
3023
3024       if (ThisElt.Val)
3025         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, ThisElt,
3026                         DAG.getIntPtrConstant(i/2));
3027     }
3028   }
3029
3030   return DAG.getNode(ISD::BIT_CONVERT, MVT::v16i8, V);
3031 }
3032
3033 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3034 ///
3035 static SDOperand LowerBuildVectorv8i16(SDOperand Op, unsigned NonZeros,
3036                                        unsigned NumNonZero, unsigned NumZero,
3037                                        SelectionDAG &DAG, TargetLowering &TLI) {
3038   if (NumNonZero > 4)
3039     return SDOperand();
3040
3041   SDOperand V(0, 0);
3042   bool First = true;
3043   for (unsigned i = 0; i < 8; ++i) {
3044     bool isNonZero = (NonZeros & (1 << i)) != 0;
3045     if (isNonZero) {
3046       if (First) {
3047         if (NumZero)
3048           V = getZeroVector(MVT::v8i16, true, DAG);
3049         else
3050           V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
3051         First = false;
3052       }
3053       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, Op.getOperand(i),
3054                       DAG.getIntPtrConstant(i));
3055     }
3056   }
3057
3058   return V;
3059 }
3060
3061 /// getVShift - Return a vector logical shift node.
3062 ///
3063 static SDOperand getVShift(bool isLeft, MVT VT, SDOperand SrcOp,
3064                            unsigned NumBits, SelectionDAG &DAG,
3065                            const TargetLowering &TLI) {
3066   bool isMMX = VT.getSizeInBits() == 64;
3067   MVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
3068   unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3069   SrcOp = DAG.getNode(ISD::BIT_CONVERT, ShVT, SrcOp);
3070   return DAG.getNode(ISD::BIT_CONVERT, VT,
3071                      DAG.getNode(Opc, ShVT, SrcOp,
3072                               DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3073 }
3074
3075 SDOperand
3076 X86TargetLowering::LowerBUILD_VECTOR(SDOperand Op, SelectionDAG &DAG) {
3077   // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3078   if (ISD::isBuildVectorAllZeros(Op.Val) || ISD::isBuildVectorAllOnes(Op.Val)) {
3079     // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3080     // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3081     // eliminated on x86-32 hosts.
3082     if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3083       return Op;
3084
3085     if (ISD::isBuildVectorAllOnes(Op.Val))
3086       return getOnesVector(Op.getValueType(), DAG);
3087     return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG);
3088   }
3089
3090   MVT VT = Op.getValueType();
3091   MVT EVT = VT.getVectorElementType();
3092   unsigned EVTBits = EVT.getSizeInBits();
3093
3094   unsigned NumElems = Op.getNumOperands();
3095   unsigned NumZero  = 0;
3096   unsigned NumNonZero = 0;
3097   unsigned NonZeros = 0;
3098   bool IsAllConstants = true;
3099   SmallSet<SDOperand, 8> Values;
3100   for (unsigned i = 0; i < NumElems; ++i) {
3101     SDOperand Elt = Op.getOperand(i);
3102     if (Elt.getOpcode() == ISD::UNDEF)
3103       continue;
3104     Values.insert(Elt);
3105     if (Elt.getOpcode() != ISD::Constant &&
3106         Elt.getOpcode() != ISD::ConstantFP)
3107       IsAllConstants = false;
3108     if (isZeroNode(Elt))
3109       NumZero++;
3110     else {
3111       NonZeros |= (1 << i);
3112       NumNonZero++;
3113     }
3114   }
3115
3116   if (NumNonZero == 0) {
3117     // All undef vector. Return an UNDEF.  All zero vectors were handled above.
3118     return DAG.getNode(ISD::UNDEF, VT);
3119   }
3120
3121   // Special case for single non-zero, non-undef, element.
3122   if (NumNonZero == 1 && NumElems <= 4) {
3123     unsigned Idx = CountTrailingZeros_32(NonZeros);
3124     SDOperand Item = Op.getOperand(Idx);
3125     
3126     // If this is an insertion of an i64 value on x86-32, and if the top bits of
3127     // the value are obviously zero, truncate the value to i32 and do the
3128     // insertion that way.  Only do this if the value is non-constant or if the
3129     // value is a constant being inserted into element 0.  It is cheaper to do
3130     // a constant pool load than it is to do a movd + shuffle.
3131     if (EVT == MVT::i64 && !Subtarget->is64Bit() &&
3132         (!IsAllConstants || Idx == 0)) {
3133       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3134         // Handle MMX and SSE both.
3135         MVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3136         unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
3137         
3138         // Truncate the value (which may itself be a constant) to i32, and
3139         // convert it to a vector with movd (S2V+shuffle to zero extend).
3140         Item = DAG.getNode(ISD::TRUNCATE, MVT::i32, Item);
3141         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VecVT, Item);
3142         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3143                                            Subtarget->hasSSE2(), DAG);
3144         
3145         // Now we have our 32-bit value zero extended in the low element of
3146         // a vector.  If Idx != 0, swizzle it into place.
3147         if (Idx != 0) {
3148           SDOperand Ops[] = { 
3149             Item, DAG.getNode(ISD::UNDEF, Item.getValueType()),
3150             getSwapEltZeroMask(VecElts, Idx, DAG)
3151           };
3152           Item = DAG.getNode(ISD::VECTOR_SHUFFLE, VecVT, Ops, 3);
3153         }
3154         return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(), Item);
3155       }
3156     }
3157     
3158     // If we have a constant or non-constant insertion into the low element of
3159     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3160     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
3161     // depending on what the source datatype is.  Because we can only get here
3162     // when NumElems <= 4, this only needs to handle i32/f32/i64/f64.
3163     if (Idx == 0 &&
3164         // Don't do this for i64 values on x86-32.
3165         (EVT != MVT::i64 || Subtarget->is64Bit())) {
3166       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
3167       // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3168       return getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3169                                          Subtarget->hasSSE2(), DAG);
3170     }
3171
3172     // Is it a vector logical left shift?
3173     if (NumElems == 2 && Idx == 1 &&
3174         isZeroNode(Op.getOperand(0)) && !isZeroNode(Op.getOperand(1))) {
3175       unsigned NumBits = VT.getSizeInBits();
3176       return getVShift(true, VT,
3177                        DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(1)),
3178                        NumBits/2, DAG, *this);
3179     }
3180     
3181     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3182       return SDOperand();
3183
3184     // Otherwise, if this is a vector with i32 or f32 elements, and the element
3185     // is a non-constant being inserted into an element other than the low one,
3186     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
3187     // movd/movss) to move this into the low element, then shuffle it into
3188     // place.
3189     if (EVTBits == 32) {
3190       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
3191       
3192       // Turn it into a shuffle of zero and zero-extended scalar to vector.
3193       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3194                                          Subtarget->hasSSE2(), DAG);
3195       MVT MaskVT  = MVT::getIntVectorWithNumElements(NumElems);
3196       MVT MaskEVT = MaskVT.getVectorElementType();
3197       SmallVector<SDOperand, 8> MaskVec;
3198       for (unsigned i = 0; i < NumElems; i++)
3199         MaskVec.push_back(DAG.getConstant((i == Idx) ? 0 : 1, MaskEVT));
3200       SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3201                                    &MaskVec[0], MaskVec.size());
3202       return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Item,
3203                          DAG.getNode(ISD::UNDEF, VT), Mask);
3204     }
3205   }
3206
3207   // Splat is obviously ok. Let legalizer expand it to a shuffle.
3208   if (Values.size() == 1)
3209     return SDOperand();
3210   
3211   // A vector full of immediates; various special cases are already
3212   // handled, so this is best done with a single constant-pool load.
3213   if (IsAllConstants)
3214     return SDOperand();
3215
3216   // Let legalizer expand 2-wide build_vectors.
3217   if (EVTBits == 64) {
3218     if (NumNonZero == 1) {
3219       // One half is zero or undef.
3220       unsigned Idx = CountTrailingZeros_32(NonZeros);
3221       SDOperand V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT,
3222                                  Op.getOperand(Idx));
3223       return getShuffleVectorZeroOrUndef(V2, Idx, true,
3224                                          Subtarget->hasSSE2(), DAG);
3225     }
3226     return SDOperand();
3227   }
3228
3229   // If element VT is < 32 bits, convert it to inserts into a zero vector.
3230   if (EVTBits == 8 && NumElems == 16) {
3231     SDOperand V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3232                                         *this);
3233     if (V.Val) return V;
3234   }
3235
3236   if (EVTBits == 16 && NumElems == 8) {
3237     SDOperand V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3238                                         *this);
3239     if (V.Val) return V;
3240   }
3241
3242   // If element VT is == 32 bits, turn it into a number of shuffles.
3243   SmallVector<SDOperand, 8> V;
3244   V.resize(NumElems);
3245   if (NumElems == 4 && NumZero > 0) {
3246     for (unsigned i = 0; i < 4; ++i) {
3247       bool isZero = !(NonZeros & (1 << i));
3248       if (isZero)
3249         V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG);
3250       else
3251         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3252     }
3253
3254     for (unsigned i = 0; i < 2; ++i) {
3255       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3256         default: break;
3257         case 0:
3258           V[i] = V[i*2];  // Must be a zero vector.
3259           break;
3260         case 1:
3261           V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2+1], V[i*2],
3262                              getMOVLMask(NumElems, DAG));
3263           break;
3264         case 2:
3265           V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3266                              getMOVLMask(NumElems, DAG));
3267           break;
3268         case 3:
3269           V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3270                              getUnpacklMask(NumElems, DAG));
3271           break;
3272       }
3273     }
3274
3275     MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3276     MVT EVT = MaskVT.getVectorElementType();
3277     SmallVector<SDOperand, 8> MaskVec;
3278     bool Reverse = (NonZeros & 0x3) == 2;
3279     for (unsigned i = 0; i < 2; ++i)
3280       if (Reverse)
3281         MaskVec.push_back(DAG.getConstant(1-i, EVT));
3282       else
3283         MaskVec.push_back(DAG.getConstant(i, EVT));
3284     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3285     for (unsigned i = 0; i < 2; ++i)
3286       if (Reverse)
3287         MaskVec.push_back(DAG.getConstant(1-i+NumElems, EVT));
3288       else
3289         MaskVec.push_back(DAG.getConstant(i+NumElems, EVT));
3290     SDOperand ShufMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3291                                      &MaskVec[0], MaskVec.size());
3292     return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[0], V[1], ShufMask);
3293   }
3294
3295   if (Values.size() > 2) {
3296     // Expand into a number of unpckl*.
3297     // e.g. for v4f32
3298     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3299     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3300     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
3301     SDOperand UnpckMask = getUnpacklMask(NumElems, DAG);
3302     for (unsigned i = 0; i < NumElems; ++i)
3303       V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3304     NumElems >>= 1;
3305     while (NumElems != 0) {
3306       for (unsigned i = 0; i < NumElems; ++i)
3307         V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i], V[i + NumElems],
3308                            UnpckMask);
3309       NumElems >>= 1;
3310     }
3311     return V[0];
3312   }
3313
3314   return SDOperand();
3315 }
3316
3317 static
3318 SDOperand LowerVECTOR_SHUFFLEv8i16(SDOperand V1, SDOperand V2,
3319                                    SDOperand PermMask, SelectionDAG &DAG,
3320                                    TargetLowering &TLI) {
3321   SDOperand NewV;
3322   MVT MaskVT = MVT::getIntVectorWithNumElements(8);
3323   MVT MaskEVT = MaskVT.getVectorElementType();
3324   MVT PtrVT = TLI.getPointerTy();
3325   SmallVector<SDOperand, 8> MaskElts(PermMask.Val->op_begin(),
3326                                      PermMask.Val->op_end());
3327
3328   // First record which half of which vector the low elements come from.
3329   SmallVector<unsigned, 4> LowQuad(4);
3330   for (unsigned i = 0; i < 4; ++i) {
3331     SDOperand Elt = MaskElts[i];
3332     if (Elt.getOpcode() == ISD::UNDEF)
3333       continue;
3334     unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3335     int QuadIdx = EltIdx / 4;
3336     ++LowQuad[QuadIdx];
3337   }
3338   int BestLowQuad = -1;
3339   unsigned MaxQuad = 1;
3340   for (unsigned i = 0; i < 4; ++i) {
3341     if (LowQuad[i] > MaxQuad) {
3342       BestLowQuad = i;
3343       MaxQuad = LowQuad[i];
3344     }
3345   }
3346
3347   // Record which half of which vector the high elements come from.
3348   SmallVector<unsigned, 4> HighQuad(4);
3349   for (unsigned i = 4; i < 8; ++i) {
3350     SDOperand Elt = MaskElts[i];
3351     if (Elt.getOpcode() == ISD::UNDEF)
3352       continue;
3353     unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3354     int QuadIdx = EltIdx / 4;
3355     ++HighQuad[QuadIdx];
3356   }
3357   int BestHighQuad = -1;
3358   MaxQuad = 1;
3359   for (unsigned i = 0; i < 4; ++i) {
3360     if (HighQuad[i] > MaxQuad) {
3361       BestHighQuad = i;
3362       MaxQuad = HighQuad[i];
3363     }
3364   }
3365
3366   // If it's possible to sort parts of either half with PSHUF{H|L}W, then do it.
3367   if (BestLowQuad != -1 || BestHighQuad != -1) {
3368     // First sort the 4 chunks in order using shufpd.
3369     SmallVector<SDOperand, 8> MaskVec;
3370     if (BestLowQuad != -1)
3371       MaskVec.push_back(DAG.getConstant(BestLowQuad, MVT::i32));
3372     else
3373       MaskVec.push_back(DAG.getConstant(0, MVT::i32));
3374     if (BestHighQuad != -1)
3375       MaskVec.push_back(DAG.getConstant(BestHighQuad, MVT::i32));
3376     else
3377       MaskVec.push_back(DAG.getConstant(1, MVT::i32));
3378     SDOperand Mask= DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, &MaskVec[0],2);
3379     NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v2i64,
3380                        DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V1),
3381                        DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V2), Mask);
3382     NewV = DAG.getNode(ISD::BIT_CONVERT, MVT::v8i16, NewV);
3383
3384     // Now sort high and low parts separately.
3385     BitVector InOrder(8);
3386     if (BestLowQuad != -1) {
3387       // Sort lower half in order using PSHUFLW.
3388       MaskVec.clear();
3389       bool AnyOutOrder = false;
3390       for (unsigned i = 0; i != 4; ++i) {
3391         SDOperand Elt = MaskElts[i];
3392         if (Elt.getOpcode() == ISD::UNDEF) {
3393           MaskVec.push_back(Elt);
3394           InOrder.set(i);
3395         } else {
3396           unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3397           if (EltIdx != i)
3398             AnyOutOrder = true;
3399           MaskVec.push_back(DAG.getConstant(EltIdx % 4, MaskEVT));
3400           // If this element is in the right place after this shuffle, then
3401           // remember it.
3402           if ((int)(EltIdx / 4) == BestLowQuad)
3403             InOrder.set(i);
3404         }
3405       }
3406       if (AnyOutOrder) {
3407         for (unsigned i = 4; i != 8; ++i)
3408           MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3409         SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3410         NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
3411       }
3412     }
3413
3414     if (BestHighQuad != -1) {
3415       // Sort high half in order using PSHUFHW if possible.
3416       MaskVec.clear();
3417       for (unsigned i = 0; i != 4; ++i)
3418         MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3419       bool AnyOutOrder = false;
3420       for (unsigned i = 4; i != 8; ++i) {
3421         SDOperand Elt = MaskElts[i];
3422         if (Elt.getOpcode() == ISD::UNDEF) {
3423           MaskVec.push_back(Elt);
3424           InOrder.set(i);
3425         } else {
3426           unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3427           if (EltIdx != i)
3428             AnyOutOrder = true;
3429           MaskVec.push_back(DAG.getConstant((EltIdx % 4) + 4, MaskEVT));
3430           // If this element is in the right place after this shuffle, then
3431           // remember it.
3432           if ((int)(EltIdx / 4) == BestHighQuad)
3433             InOrder.set(i);
3434         }
3435       }
3436       if (AnyOutOrder) {
3437         SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3438         NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
3439       }
3440     }
3441
3442     // The other elements are put in the right place using pextrw and pinsrw.
3443     for (unsigned i = 0; i != 8; ++i) {
3444       if (InOrder[i])
3445         continue;
3446       SDOperand Elt = MaskElts[i];
3447       unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3448       if (EltIdx == i)
3449         continue;
3450       SDOperand ExtOp = (EltIdx < 8)
3451         ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
3452                       DAG.getConstant(EltIdx, PtrVT))
3453         : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3454                       DAG.getConstant(EltIdx - 8, PtrVT));
3455       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3456                          DAG.getConstant(i, PtrVT));
3457     }
3458     return NewV;
3459   }
3460
3461   // PSHUF{H|L}W are not used. Lower into extracts and inserts but try to use
3462   ///as few as possible.
3463   // First, let's find out how many elements are already in the right order.
3464   unsigned V1InOrder = 0;
3465   unsigned V1FromV1 = 0;
3466   unsigned V2InOrder = 0;
3467   unsigned V2FromV2 = 0;
3468   SmallVector<SDOperand, 8> V1Elts;
3469   SmallVector<SDOperand, 8> V2Elts;
3470   for (unsigned i = 0; i < 8; ++i) {
3471     SDOperand Elt = MaskElts[i];
3472     if (Elt.getOpcode() == ISD::UNDEF) {
3473       V1Elts.push_back(Elt);
3474       V2Elts.push_back(Elt);
3475       ++V1InOrder;
3476       ++V2InOrder;
3477       continue;
3478     }
3479     unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3480     if (EltIdx == i) {
3481       V1Elts.push_back(Elt);
3482       V2Elts.push_back(DAG.getConstant(i+8, MaskEVT));
3483       ++V1InOrder;
3484     } else if (EltIdx == i+8) {
3485       V1Elts.push_back(Elt);
3486       V2Elts.push_back(DAG.getConstant(i, MaskEVT));
3487       ++V2InOrder;
3488     } else if (EltIdx < 8) {
3489       V1Elts.push_back(Elt);
3490       ++V1FromV1;
3491     } else {
3492       V2Elts.push_back(DAG.getConstant(EltIdx-8, MaskEVT));
3493       ++V2FromV2;
3494     }
3495   }
3496
3497   if (V2InOrder > V1InOrder) {
3498     PermMask = CommuteVectorShuffleMask(PermMask, DAG);
3499     std::swap(V1, V2);
3500     std::swap(V1Elts, V2Elts);
3501     std::swap(V1FromV1, V2FromV2);
3502   }
3503
3504   if ((V1FromV1 + V1InOrder) != 8) {
3505     // Some elements are from V2.
3506     if (V1FromV1) {
3507       // If there are elements that are from V1 but out of place,
3508       // then first sort them in place
3509       SmallVector<SDOperand, 8> MaskVec;
3510       for (unsigned i = 0; i < 8; ++i) {
3511         SDOperand Elt = V1Elts[i];
3512         if (Elt.getOpcode() == ISD::UNDEF) {
3513           MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3514           continue;
3515         }
3516         unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3517         if (EltIdx >= 8)
3518           MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3519         else
3520           MaskVec.push_back(DAG.getConstant(EltIdx, MaskEVT));
3521       }
3522       SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3523       V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, V1, V1, Mask);
3524     }
3525
3526     NewV = V1;
3527     for (unsigned i = 0; i < 8; ++i) {
3528       SDOperand Elt = V1Elts[i];
3529       if (Elt.getOpcode() == ISD::UNDEF)
3530         continue;
3531       unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3532       if (EltIdx < 8)
3533         continue;
3534       SDOperand ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3535                                     DAG.getConstant(EltIdx - 8, PtrVT));
3536       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3537                          DAG.getConstant(i, PtrVT));
3538     }
3539     return NewV;
3540   } else {
3541     // All elements are from V1.
3542     NewV = V1;
3543     for (unsigned i = 0; i < 8; ++i) {
3544       SDOperand Elt = V1Elts[i];
3545       if (Elt.getOpcode() == ISD::UNDEF)
3546         continue;
3547       unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3548       SDOperand ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
3549                                     DAG.getConstant(EltIdx, PtrVT));
3550       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3551                          DAG.getConstant(i, PtrVT));
3552     }
3553     return NewV;
3554   }
3555 }
3556
3557 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
3558 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
3559 /// done when every pair / quad of shuffle mask elements point to elements in
3560 /// the right sequence. e.g.
3561 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
3562 static
3563 SDOperand RewriteAsNarrowerShuffle(SDOperand V1, SDOperand V2,
3564                                 MVT VT,
3565                                 SDOperand PermMask, SelectionDAG &DAG,
3566                                 TargetLowering &TLI) {
3567   unsigned NumElems = PermMask.getNumOperands();
3568   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
3569   MVT MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
3570   MVT NewVT = MaskVT;
3571   switch (VT.getSimpleVT()) {
3572   default: assert(false && "Unexpected!");
3573   case MVT::v4f32: NewVT = MVT::v2f64; break;
3574   case MVT::v4i32: NewVT = MVT::v2i64; break;
3575   case MVT::v8i16: NewVT = MVT::v4i32; break;
3576   case MVT::v16i8: NewVT = MVT::v4i32; break;
3577   }
3578
3579   if (NewWidth == 2) {
3580     if (VT.isInteger())
3581       NewVT = MVT::v2i64;
3582     else
3583       NewVT = MVT::v2f64;
3584   }
3585   unsigned Scale = NumElems / NewWidth;
3586   SmallVector<SDOperand, 8> MaskVec;
3587   for (unsigned i = 0; i < NumElems; i += Scale) {
3588     unsigned StartIdx = ~0U;
3589     for (unsigned j = 0; j < Scale; ++j) {
3590       SDOperand Elt = PermMask.getOperand(i+j);
3591       if (Elt.getOpcode() == ISD::UNDEF)
3592         continue;
3593       unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3594       if (StartIdx == ~0U)
3595         StartIdx = EltIdx - (EltIdx % Scale);
3596       if (EltIdx != StartIdx + j)
3597         return SDOperand();
3598     }
3599     if (StartIdx == ~0U)
3600       MaskVec.push_back(DAG.getNode(ISD::UNDEF, MVT::i32));
3601     else
3602       MaskVec.push_back(DAG.getConstant(StartIdx / Scale, MVT::i32));
3603   }
3604
3605   V1 = DAG.getNode(ISD::BIT_CONVERT, NewVT, V1);
3606   V2 = DAG.getNode(ISD::BIT_CONVERT, NewVT, V2);
3607   return DAG.getNode(ISD::VECTOR_SHUFFLE, NewVT, V1, V2,
3608                      DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3609                                  &MaskVec[0], MaskVec.size()));
3610 }
3611
3612 /// getVZextMovL - Return a zero-extending vector move low node.
3613 ///
3614 static SDOperand getVZextMovL(MVT VT, MVT OpVT,
3615                               SDOperand SrcOp, SelectionDAG &DAG,
3616                               const X86Subtarget *Subtarget) {
3617   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
3618     LoadSDNode *LD = NULL;
3619     if (!isScalarLoadToVector(SrcOp.Val, &LD))
3620       LD = dyn_cast<LoadSDNode>(SrcOp);
3621     if (!LD) {
3622       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
3623       // instead.
3624       MVT EVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
3625       if ((EVT != MVT::i64 || Subtarget->is64Bit()) &&
3626           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
3627           SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
3628           SrcOp.getOperand(0).getOperand(0).getValueType() == EVT) {
3629         // PR2108
3630         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
3631         return DAG.getNode(ISD::BIT_CONVERT, VT,
3632                            DAG.getNode(X86ISD::VZEXT_MOVL, OpVT,
3633                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, OpVT,
3634                                                    SrcOp.getOperand(0).getOperand(0))));
3635       }
3636     }
3637   }
3638
3639   return DAG.getNode(ISD::BIT_CONVERT, VT,
3640                      DAG.getNode(X86ISD::VZEXT_MOVL, OpVT,
3641                                  DAG.getNode(ISD::BIT_CONVERT, OpVT, SrcOp)));
3642 }
3643
3644 SDOperand
3645 X86TargetLowering::LowerVECTOR_SHUFFLE(SDOperand Op, SelectionDAG &DAG) {
3646   SDOperand V1 = Op.getOperand(0);
3647   SDOperand V2 = Op.getOperand(1);
3648   SDOperand PermMask = Op.getOperand(2);
3649   MVT VT = Op.getValueType();
3650   unsigned NumElems = PermMask.getNumOperands();
3651   bool isMMX = VT.getSizeInBits() == 64;
3652   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
3653   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
3654   bool V1IsSplat = false;
3655   bool V2IsSplat = false;
3656
3657   if (isUndefShuffle(Op.Val))
3658     return DAG.getNode(ISD::UNDEF, VT);
3659
3660   if (isZeroShuffle(Op.Val))
3661     return getZeroVector(VT, Subtarget->hasSSE2(), DAG);
3662
3663   if (isIdentityMask(PermMask.Val))
3664     return V1;
3665   else if (isIdentityMask(PermMask.Val, true))
3666     return V2;
3667
3668   if (isSplatMask(PermMask.Val)) {
3669     if (isMMX || NumElems < 4) return Op;
3670     // Promote it to a v4{if}32 splat.
3671     return PromoteSplat(Op, DAG, Subtarget->hasSSE2());
3672   }
3673
3674   // If the shuffle can be profitably rewritten as a narrower shuffle, then
3675   // do it!
3676   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
3677     SDOperand NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG, *this);
3678     if (NewOp.Val)
3679       return DAG.getNode(ISD::BIT_CONVERT, VT, LowerVECTOR_SHUFFLE(NewOp, DAG));
3680   } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
3681     // FIXME: Figure out a cleaner way to do this.
3682     // Try to make use of movq to zero out the top part.
3683     if (ISD::isBuildVectorAllZeros(V2.Val)) {
3684       SDOperand NewOp = RewriteAsNarrowerShuffle(V1, V2, VT, PermMask,
3685                                                  DAG, *this);
3686       if (NewOp.Val) {
3687         SDOperand NewV1 = NewOp.getOperand(0);
3688         SDOperand NewV2 = NewOp.getOperand(1);
3689         SDOperand NewMask = NewOp.getOperand(2);
3690         if (isCommutedMOVL(NewMask.Val, true, false)) {
3691           NewOp = CommuteVectorShuffle(NewOp, NewV1, NewV2, NewMask, DAG);
3692           return getVZextMovL(VT, NewOp.getValueType(), NewV2, DAG, Subtarget);
3693         }
3694       }
3695     } else if (ISD::isBuildVectorAllZeros(V1.Val)) {
3696       SDOperand NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask,
3697                                                 DAG, *this);
3698       if (NewOp.Val && X86::isMOVLMask(NewOp.getOperand(2).Val))
3699         return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
3700                              DAG, Subtarget);
3701     }
3702   }
3703
3704   // Check if this can be converted into a logical shift.
3705   bool isLeft = false;
3706   unsigned ShAmt = 0;
3707   SDOperand ShVal;
3708   bool isShift = isVectorShift(Op, PermMask, DAG, isLeft, ShVal, ShAmt);
3709   if (isShift && ShVal.hasOneUse()) {
3710     // If the shifted value has multiple uses, it may be cheaper to use 
3711     // v_set0 + movlhps or movhlps, etc.
3712     MVT EVT = VT.getVectorElementType();
3713     ShAmt *= EVT.getSizeInBits();
3714     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this);
3715   }
3716
3717   if (X86::isMOVLMask(PermMask.Val)) {
3718     if (V1IsUndef)
3719       return V2;
3720     if (ISD::isBuildVectorAllZeros(V1.Val))
3721       return getVZextMovL(VT, VT, V2, DAG, Subtarget);
3722     return Op;
3723   }
3724
3725   if (X86::isMOVSHDUPMask(PermMask.Val) ||
3726       X86::isMOVSLDUPMask(PermMask.Val) ||
3727       X86::isMOVHLPSMask(PermMask.Val) ||
3728       X86::isMOVHPMask(PermMask.Val) ||
3729       X86::isMOVLPMask(PermMask.Val))
3730     return Op;
3731
3732   if (ShouldXformToMOVHLPS(PermMask.Val) ||
3733       ShouldXformToMOVLP(V1.Val, V2.Val, PermMask.Val))
3734     return CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3735
3736   if (isShift) {
3737     // No better options. Use a vshl / vsrl.
3738     MVT EVT = VT.getVectorElementType();
3739     ShAmt *= EVT.getSizeInBits();
3740     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this);
3741   }
3742
3743   bool Commuted = false;
3744   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
3745   // 1,1,1,1 -> v8i16 though.
3746   V1IsSplat = isSplatVector(V1.Val);
3747   V2IsSplat = isSplatVector(V2.Val);
3748   
3749   // Canonicalize the splat or undef, if present, to be on the RHS.
3750   if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
3751     Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3752     std::swap(V1IsSplat, V2IsSplat);
3753     std::swap(V1IsUndef, V2IsUndef);
3754     Commuted = true;
3755   }
3756
3757   // FIXME: Figure out a cleaner way to do this.
3758   if (isCommutedMOVL(PermMask.Val, V2IsSplat, V2IsUndef)) {
3759     if (V2IsUndef) return V1;
3760     Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3761     if (V2IsSplat) {
3762       // V2 is a splat, so the mask may be malformed. That is, it may point
3763       // to any V2 element. The instruction selectior won't like this. Get
3764       // a corrected mask and commute to form a proper MOVS{S|D}.
3765       SDOperand NewMask = getMOVLMask(NumElems, DAG);
3766       if (NewMask.Val != PermMask.Val)
3767         Op = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3768     }
3769     return Op;
3770   }
3771
3772   if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
3773       X86::isUNPCKH_v_undef_Mask(PermMask.Val) ||
3774       X86::isUNPCKLMask(PermMask.Val) ||
3775       X86::isUNPCKHMask(PermMask.Val))
3776     return Op;
3777
3778   if (V2IsSplat) {
3779     // Normalize mask so all entries that point to V2 points to its first
3780     // element then try to match unpck{h|l} again. If match, return a
3781     // new vector_shuffle with the corrected mask.
3782     SDOperand NewMask = NormalizeMask(PermMask, DAG);
3783     if (NewMask.Val != PermMask.Val) {
3784       if (X86::isUNPCKLMask(PermMask.Val, true)) {
3785         SDOperand NewMask = getUnpacklMask(NumElems, DAG);
3786         return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3787       } else if (X86::isUNPCKHMask(PermMask.Val, true)) {
3788         SDOperand NewMask = getUnpackhMask(NumElems, DAG);
3789         return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3790       }
3791     }
3792   }
3793
3794   // Normalize the node to match x86 shuffle ops if needed
3795   if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(PermMask.Val))
3796       Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3797
3798   if (Commuted) {
3799     // Commute is back and try unpck* again.
3800     Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3801     if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
3802         X86::isUNPCKH_v_undef_Mask(PermMask.Val) ||
3803         X86::isUNPCKLMask(PermMask.Val) ||
3804         X86::isUNPCKHMask(PermMask.Val))
3805       return Op;
3806   }
3807
3808   // Try PSHUF* first, then SHUFP*.
3809   // MMX doesn't have PSHUFD but it does have PSHUFW. While it's theoretically
3810   // possible to shuffle a v2i32 using PSHUFW, that's not yet implemented.
3811   if (isMMX && NumElems == 4 && X86::isPSHUFDMask(PermMask.Val)) {
3812     if (V2.getOpcode() != ISD::UNDEF)
3813       return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
3814                          DAG.getNode(ISD::UNDEF, VT), PermMask);
3815     return Op;
3816   }
3817
3818   if (!isMMX) {
3819     if (Subtarget->hasSSE2() &&
3820         (X86::isPSHUFDMask(PermMask.Val) ||
3821          X86::isPSHUFHWMask(PermMask.Val) ||
3822          X86::isPSHUFLWMask(PermMask.Val))) {
3823       MVT RVT = VT;
3824       if (VT == MVT::v4f32) {
3825         RVT = MVT::v4i32;
3826         Op = DAG.getNode(ISD::VECTOR_SHUFFLE, RVT,
3827                          DAG.getNode(ISD::BIT_CONVERT, RVT, V1),
3828                          DAG.getNode(ISD::UNDEF, RVT), PermMask);
3829       } else if (V2.getOpcode() != ISD::UNDEF)
3830         Op = DAG.getNode(ISD::VECTOR_SHUFFLE, RVT, V1,
3831                          DAG.getNode(ISD::UNDEF, RVT), PermMask);
3832       if (RVT != VT)
3833         Op = DAG.getNode(ISD::BIT_CONVERT, VT, Op);
3834       return Op;
3835     }
3836
3837     // Binary or unary shufps.
3838     if (X86::isSHUFPMask(PermMask.Val) ||
3839         (V2.getOpcode() == ISD::UNDEF && X86::isPSHUFDMask(PermMask.Val)))
3840       return Op;
3841   }
3842
3843   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
3844   if (VT == MVT::v8i16) {
3845     SDOperand NewOp = LowerVECTOR_SHUFFLEv8i16(V1, V2, PermMask, DAG, *this);
3846     if (NewOp.Val)
3847       return NewOp;
3848   }
3849
3850   // Handle all 4 wide cases with a number of shuffles.
3851   if (NumElems == 4 && !isMMX) {
3852     // Don't do this for MMX.
3853     MVT MaskVT = PermMask.getValueType();
3854     MVT MaskEVT = MaskVT.getVectorElementType();
3855     SmallVector<std::pair<int, int>, 8> Locs;
3856     Locs.reserve(NumElems);
3857     SmallVector<SDOperand, 8> Mask1(NumElems,
3858                                     DAG.getNode(ISD::UNDEF, MaskEVT));
3859     SmallVector<SDOperand, 8> Mask2(NumElems,
3860                                     DAG.getNode(ISD::UNDEF, MaskEVT));
3861     unsigned NumHi = 0;
3862     unsigned NumLo = 0;
3863     // If no more than two elements come from either vector. This can be
3864     // implemented with two shuffles. First shuffle gather the elements.
3865     // The second shuffle, which takes the first shuffle as both of its
3866     // vector operands, put the elements into the right order.
3867     for (unsigned i = 0; i != NumElems; ++i) {
3868       SDOperand Elt = PermMask.getOperand(i);
3869       if (Elt.getOpcode() == ISD::UNDEF) {
3870         Locs[i] = std::make_pair(-1, -1);
3871       } else {
3872         unsigned Val = cast<ConstantSDNode>(Elt)->getValue();
3873         if (Val < NumElems) {
3874           Locs[i] = std::make_pair(0, NumLo);
3875           Mask1[NumLo] = Elt;
3876           NumLo++;
3877         } else {
3878           Locs[i] = std::make_pair(1, NumHi);
3879           if (2+NumHi < NumElems)
3880             Mask1[2+NumHi] = Elt;
3881           NumHi++;
3882         }
3883       }
3884     }
3885     if (NumLo <= 2 && NumHi <= 2) {
3886       V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3887                        DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3888                                    &Mask1[0], Mask1.size()));
3889       for (unsigned i = 0; i != NumElems; ++i) {
3890         if (Locs[i].first == -1)
3891           continue;
3892         else {
3893           unsigned Idx = (i < NumElems/2) ? 0 : NumElems;
3894           Idx += Locs[i].first * (NumElems/2) + Locs[i].second;
3895           Mask2[i] = DAG.getConstant(Idx, MaskEVT);
3896         }
3897       }
3898
3899       return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1,
3900                          DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3901                                      &Mask2[0], Mask2.size()));
3902     }
3903
3904     // Break it into (shuffle shuffle_hi, shuffle_lo).
3905     Locs.clear();
3906     SmallVector<SDOperand,8> LoMask(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
3907     SmallVector<SDOperand,8> HiMask(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
3908     SmallVector<SDOperand,8> *MaskPtr = &LoMask;
3909     unsigned MaskIdx = 0;
3910     unsigned LoIdx = 0;
3911     unsigned HiIdx = NumElems/2;
3912     for (unsigned i = 0; i != NumElems; ++i) {
3913       if (i == NumElems/2) {
3914         MaskPtr = &HiMask;
3915         MaskIdx = 1;
3916         LoIdx = 0;
3917         HiIdx = NumElems/2;
3918       }
3919       SDOperand Elt = PermMask.getOperand(i);
3920       if (Elt.getOpcode() == ISD::UNDEF) {
3921         Locs[i] = std::make_pair(-1, -1);
3922       } else if (cast<ConstantSDNode>(Elt)->getValue() < NumElems) {
3923         Locs[i] = std::make_pair(MaskIdx, LoIdx);
3924         (*MaskPtr)[LoIdx] = Elt;
3925         LoIdx++;
3926       } else {
3927         Locs[i] = std::make_pair(MaskIdx, HiIdx);
3928         (*MaskPtr)[HiIdx] = Elt;
3929         HiIdx++;
3930       }
3931     }
3932
3933     SDOperand LoShuffle =
3934       DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3935                   DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3936                               &LoMask[0], LoMask.size()));
3937     SDOperand HiShuffle =
3938       DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3939                   DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3940                               &HiMask[0], HiMask.size()));
3941     SmallVector<SDOperand, 8> MaskOps;
3942     for (unsigned i = 0; i != NumElems; ++i) {
3943       if (Locs[i].first == -1) {
3944         MaskOps.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3945       } else {
3946         unsigned Idx = Locs[i].first * NumElems + Locs[i].second;
3947         MaskOps.push_back(DAG.getConstant(Idx, MaskEVT));
3948       }
3949     }
3950     return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, LoShuffle, HiShuffle,
3951                        DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3952                                    &MaskOps[0], MaskOps.size()));
3953   }
3954
3955   return SDOperand();
3956 }
3957
3958 SDOperand
3959 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDOperand Op,
3960                                                 SelectionDAG &DAG) {
3961   MVT VT = Op.getValueType();
3962   if (VT.getSizeInBits() == 8) {
3963     SDOperand Extract = DAG.getNode(X86ISD::PEXTRB, MVT::i32,
3964                                     Op.getOperand(0), Op.getOperand(1));
3965     SDOperand Assert  = DAG.getNode(ISD::AssertZext, MVT::i32, Extract,
3966                                     DAG.getValueType(VT));
3967     return DAG.getNode(ISD::TRUNCATE, VT, Assert);
3968   } else if (VT.getSizeInBits() == 16) {
3969     SDOperand Extract = DAG.getNode(X86ISD::PEXTRW, MVT::i32,
3970                                     Op.getOperand(0), Op.getOperand(1));
3971     SDOperand Assert  = DAG.getNode(ISD::AssertZext, MVT::i32, Extract,
3972                                     DAG.getValueType(VT));
3973     return DAG.getNode(ISD::TRUNCATE, VT, Assert);
3974   } else if (VT == MVT::f32) {
3975     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
3976     // the result back to FR32 register. It's only worth matching if the
3977     // result has a single use which is a store or a bitcast to i32.
3978     if (!Op.hasOneUse())
3979       return SDOperand();
3980     SDNode *User = Op.Val->use_begin()->getUser();
3981     if (User->getOpcode() != ISD::STORE &&
3982         (User->getOpcode() != ISD::BIT_CONVERT ||
3983          User->getValueType(0) != MVT::i32))
3984       return SDOperand();
3985     SDOperand Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32,
3986                     DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, Op.getOperand(0)),
3987                                     Op.getOperand(1));
3988     return DAG.getNode(ISD::BIT_CONVERT, MVT::f32, Extract);
3989   }
3990   return SDOperand();
3991 }
3992
3993
3994 SDOperand
3995 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDOperand Op, SelectionDAG &DAG) {
3996   if (!isa<ConstantSDNode>(Op.getOperand(1)))
3997     return SDOperand();
3998
3999   if (Subtarget->hasSSE41()) {
4000     SDOperand Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
4001     if (Res.Val)
4002       return Res;
4003   }
4004
4005   MVT VT = Op.getValueType();
4006   // TODO: handle v16i8.
4007   if (VT.getSizeInBits() == 16) {
4008     SDOperand Vec = Op.getOperand(0);
4009     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
4010     if (Idx == 0)
4011       return DAG.getNode(ISD::TRUNCATE, MVT::i16,
4012                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32,
4013                                  DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, Vec),
4014                                      Op.getOperand(1)));
4015     // Transform it so it match pextrw which produces a 32-bit result.
4016     MVT EVT = (MVT::SimpleValueType)(VT.getSimpleVT()+1);
4017     SDOperand Extract = DAG.getNode(X86ISD::PEXTRW, EVT,
4018                                     Op.getOperand(0), Op.getOperand(1));
4019     SDOperand Assert  = DAG.getNode(ISD::AssertZext, EVT, Extract,
4020                                     DAG.getValueType(VT));
4021     return DAG.getNode(ISD::TRUNCATE, VT, Assert);
4022   } else if (VT.getSizeInBits() == 32) {
4023     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
4024     if (Idx == 0)
4025       return Op;
4026     // SHUFPS the element to the lowest double word, then movss.
4027     MVT MaskVT = MVT::getIntVectorWithNumElements(4);
4028     SmallVector<SDOperand, 8> IdxVec;
4029     IdxVec.
4030       push_back(DAG.getConstant(Idx, MaskVT.getVectorElementType()));
4031     IdxVec.
4032       push_back(DAG.getNode(ISD::UNDEF, MaskVT.getVectorElementType()));
4033     IdxVec.
4034       push_back(DAG.getNode(ISD::UNDEF, MaskVT.getVectorElementType()));
4035     IdxVec.
4036       push_back(DAG.getNode(ISD::UNDEF, MaskVT.getVectorElementType()));
4037     SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
4038                                  &IdxVec[0], IdxVec.size());
4039     SDOperand Vec = Op.getOperand(0);
4040     Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
4041                       Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
4042     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
4043                        DAG.getIntPtrConstant(0));
4044   } else if (VT.getSizeInBits() == 64) {
4045     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
4046     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
4047     //        to match extract_elt for f64.
4048     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
4049     if (Idx == 0)
4050       return Op;
4051
4052     // UNPCKHPD the element to the lowest double word, then movsd.
4053     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
4054     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
4055     MVT MaskVT = MVT::getIntVectorWithNumElements(4);
4056     SmallVector<SDOperand, 8> IdxVec;
4057     IdxVec.push_back(DAG.getConstant(1, MaskVT.getVectorElementType()));
4058     IdxVec.
4059       push_back(DAG.getNode(ISD::UNDEF, MaskVT.getVectorElementType()));
4060     SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
4061                                  &IdxVec[0], IdxVec.size());
4062     SDOperand Vec = Op.getOperand(0);
4063     Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
4064                       Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
4065     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
4066                        DAG.getIntPtrConstant(0));
4067   }
4068
4069   return SDOperand();
4070 }
4071
4072 SDOperand
4073 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDOperand Op, SelectionDAG &DAG){
4074   MVT VT = Op.getValueType();
4075   MVT EVT = VT.getVectorElementType();
4076
4077   SDOperand N0 = Op.getOperand(0);
4078   SDOperand N1 = Op.getOperand(1);
4079   SDOperand N2 = Op.getOperand(2);
4080
4081   if ((EVT.getSizeInBits() == 8) || (EVT.getSizeInBits() == 16)) {
4082     unsigned Opc = (EVT.getSizeInBits() == 8) ? X86ISD::PINSRB
4083                                                   : X86ISD::PINSRW;
4084     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
4085     // argument.
4086     if (N1.getValueType() != MVT::i32)
4087       N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
4088     if (N2.getValueType() != MVT::i32)
4089       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getValue());
4090     return DAG.getNode(Opc, VT, N0, N1, N2);
4091   } else if (EVT == MVT::f32) {
4092     // Bits [7:6] of the constant are the source select.  This will always be
4093     //  zero here.  The DAG Combiner may combine an extract_elt index into these
4094     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
4095     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
4096     // Bits [5:4] of the constant are the destination select.  This is the 
4097     //  value of the incoming immediate.
4098     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may 
4099     //   combine either bitwise AND or insert of float 0.0 to set these bits.
4100     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getValue() << 4);
4101     return DAG.getNode(X86ISD::INSERTPS, VT, N0, N1, N2);
4102   }
4103   return SDOperand();
4104 }
4105
4106 SDOperand
4107 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDOperand Op, SelectionDAG &DAG) {
4108   MVT VT = Op.getValueType();
4109   MVT EVT = VT.getVectorElementType();
4110
4111   if (Subtarget->hasSSE41())
4112     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
4113
4114   if (EVT == MVT::i8)
4115     return SDOperand();
4116
4117   SDOperand N0 = Op.getOperand(0);
4118   SDOperand N1 = Op.getOperand(1);
4119   SDOperand N2 = Op.getOperand(2);
4120
4121   if (EVT.getSizeInBits() == 16) {
4122     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
4123     // as its second argument.
4124     if (N1.getValueType() != MVT::i32)
4125       N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
4126     if (N2.getValueType() != MVT::i32)
4127       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getValue());
4128     return DAG.getNode(X86ISD::PINSRW, VT, N0, N1, N2);
4129   }
4130   return SDOperand();
4131 }
4132
4133 SDOperand
4134 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDOperand Op, SelectionDAG &DAG) {
4135   SDOperand AnyExt = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, Op.getOperand(0));
4136   MVT VT = MVT::v2i32;
4137   switch (Op.getValueType().getSimpleVT()) {
4138   default: break;
4139   case MVT::v16i8:
4140   case MVT::v8i16:
4141     VT = MVT::v4i32;
4142     break;
4143   }
4144   return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(),
4145                      DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, AnyExt));
4146 }
4147
4148 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
4149 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
4150 // one of the above mentioned nodes. It has to be wrapped because otherwise
4151 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
4152 // be used to form addressing mode. These wrapped nodes will be selected
4153 // into MOV32ri.
4154 SDOperand
4155 X86TargetLowering::LowerConstantPool(SDOperand Op, SelectionDAG &DAG) {
4156   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4157   SDOperand Result = DAG.getTargetConstantPool(CP->getConstVal(),
4158                                                getPointerTy(),
4159                                                CP->getAlignment());
4160   Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4161   // With PIC, the address is actually $g + Offset.
4162   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4163       !Subtarget->isPICStyleRIPRel()) {
4164     Result = DAG.getNode(ISD::ADD, getPointerTy(),
4165                          DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4166                          Result);
4167   }
4168
4169   return Result;
4170 }
4171
4172 SDOperand
4173 X86TargetLowering::LowerGlobalAddress(SDOperand Op, SelectionDAG &DAG) {
4174   GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4175   SDOperand Result = DAG.getTargetGlobalAddress(GV, getPointerTy());
4176   Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4177   // With PIC, the address is actually $g + Offset.
4178   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4179       !Subtarget->isPICStyleRIPRel()) {
4180     Result = DAG.getNode(ISD::ADD, getPointerTy(),
4181                          DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4182                          Result);
4183   }
4184   
4185   // For Darwin & Mingw32, external and weak symbols are indirect, so we want to
4186   // load the value at address GV, not the value of GV itself. This means that
4187   // the GlobalAddress must be in the base or index register of the address, not
4188   // the GV offset field. Platform check is inside GVRequiresExtraLoad() call
4189   // The same applies for external symbols during PIC codegen
4190   if (Subtarget->GVRequiresExtraLoad(GV, getTargetMachine(), false))
4191     Result = DAG.getLoad(getPointerTy(), DAG.getEntryNode(), Result,
4192                          PseudoSourceValue::getGOT(), 0);
4193
4194   return Result;
4195 }
4196
4197 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
4198 static SDOperand
4199 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4200                                 const MVT PtrVT) {
4201   SDOperand InFlag;
4202   SDOperand Chain = DAG.getCopyToReg(DAG.getEntryNode(), X86::EBX,
4203                                      DAG.getNode(X86ISD::GlobalBaseReg,
4204                                                  PtrVT), InFlag);
4205   InFlag = Chain.getValue(1);
4206
4207   // emit leal symbol@TLSGD(,%ebx,1), %eax
4208   SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
4209   SDOperand TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4210                                              GA->getValueType(0),
4211                                              GA->getOffset());
4212   SDOperand Ops[] = { Chain,  TGA, InFlag };
4213   SDOperand Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 3);
4214   InFlag = Result.getValue(2);
4215   Chain = Result.getValue(1);
4216
4217   // call ___tls_get_addr. This function receives its argument in
4218   // the register EAX.
4219   Chain = DAG.getCopyToReg(Chain, X86::EAX, Result, InFlag);
4220   InFlag = Chain.getValue(1);
4221
4222   NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4223   SDOperand Ops1[] = { Chain,
4224                       DAG.getTargetExternalSymbol("___tls_get_addr",
4225                                                   PtrVT),
4226                       DAG.getRegister(X86::EAX, PtrVT),
4227                       DAG.getRegister(X86::EBX, PtrVT),
4228                       InFlag };
4229   Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 5);
4230   InFlag = Chain.getValue(1);
4231
4232   return DAG.getCopyFromReg(Chain, X86::EAX, PtrVT, InFlag);
4233 }
4234
4235 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
4236 static SDOperand
4237 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4238                                 const MVT PtrVT) {
4239   SDOperand InFlag, Chain;
4240
4241   // emit leaq symbol@TLSGD(%rip), %rdi
4242   SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
4243   SDOperand TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4244                                              GA->getValueType(0),
4245                                              GA->getOffset());
4246   SDOperand Ops[]  = { DAG.getEntryNode(), TGA};
4247   SDOperand Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 2);
4248   Chain  = Result.getValue(1);
4249   InFlag = Result.getValue(2);
4250
4251   // call ___tls_get_addr. This function receives its argument in
4252   // the register RDI.
4253   Chain = DAG.getCopyToReg(Chain, X86::RDI, Result, InFlag);
4254   InFlag = Chain.getValue(1);
4255
4256   NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4257   SDOperand Ops1[] = { Chain,
4258                       DAG.getTargetExternalSymbol("___tls_get_addr",
4259                                                   PtrVT),
4260                       DAG.getRegister(X86::RDI, PtrVT),
4261                       InFlag };
4262   Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 4);
4263   InFlag = Chain.getValue(1);
4264
4265   return DAG.getCopyFromReg(Chain, X86::RAX, PtrVT, InFlag);
4266 }
4267
4268 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
4269 // "local exec" model.
4270 static SDOperand LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4271                                      const MVT PtrVT) {
4272   // Get the Thread Pointer
4273   SDOperand ThreadPointer = DAG.getNode(X86ISD::THREAD_POINTER, PtrVT);
4274   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
4275   // exec)
4276   SDOperand TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4277                                              GA->getValueType(0),
4278                                              GA->getOffset());
4279   SDOperand Offset = DAG.getNode(X86ISD::Wrapper, PtrVT, TGA);
4280
4281   if (GA->getGlobal()->isDeclaration()) // initial exec TLS model
4282     Offset = DAG.getLoad(PtrVT, DAG.getEntryNode(), Offset,
4283                          PseudoSourceValue::getGOT(), 0);
4284
4285   // The address of the thread local variable is the add of the thread
4286   // pointer with the offset of the variable.
4287   return DAG.getNode(ISD::ADD, PtrVT, ThreadPointer, Offset);
4288 }
4289
4290 SDOperand
4291 X86TargetLowering::LowerGlobalTLSAddress(SDOperand Op, SelectionDAG &DAG) {
4292   // TODO: implement the "local dynamic" model
4293   // TODO: implement the "initial exec"model for pic executables
4294   assert(Subtarget->isTargetELF() &&
4295          "TLS not implemented for non-ELF targets");
4296   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4297   // If the relocation model is PIC, use the "General Dynamic" TLS Model,
4298   // otherwise use the "Local Exec"TLS Model
4299   if (Subtarget->is64Bit()) {
4300     return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
4301   } else {
4302     if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
4303       return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
4304     else
4305       return LowerToTLSExecModel(GA, DAG, getPointerTy());
4306   }
4307 }
4308
4309 SDOperand
4310 X86TargetLowering::LowerExternalSymbol(SDOperand Op, SelectionDAG &DAG) {
4311   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
4312   SDOperand Result = DAG.getTargetExternalSymbol(Sym, getPointerTy());
4313   Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4314   // With PIC, the address is actually $g + Offset.
4315   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4316       !Subtarget->isPICStyleRIPRel()) {
4317     Result = DAG.getNode(ISD::ADD, getPointerTy(),
4318                          DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4319                          Result);
4320   }
4321
4322   return Result;
4323 }
4324
4325 SDOperand X86TargetLowering::LowerJumpTable(SDOperand Op, SelectionDAG &DAG) {
4326   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4327   SDOperand Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy());
4328   Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4329   // With PIC, the address is actually $g + Offset.
4330   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4331       !Subtarget->isPICStyleRIPRel()) {
4332     Result = DAG.getNode(ISD::ADD, getPointerTy(),
4333                          DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4334                          Result);
4335   }
4336
4337   return Result;
4338 }
4339
4340 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
4341 /// take a 2 x i32 value to shift plus a shift amount. 
4342 SDOperand X86TargetLowering::LowerShift(SDOperand Op, SelectionDAG &DAG) {
4343   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4344   MVT VT = Op.getValueType();
4345   unsigned VTBits = VT.getSizeInBits();
4346   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
4347   SDOperand ShOpLo = Op.getOperand(0);
4348   SDOperand ShOpHi = Op.getOperand(1);
4349   SDOperand ShAmt  = Op.getOperand(2);
4350   SDOperand Tmp1 = isSRA ?
4351     DAG.getNode(ISD::SRA, VT, ShOpHi, DAG.getConstant(VTBits - 1, MVT::i8)) :
4352     DAG.getConstant(0, VT);
4353
4354   SDOperand Tmp2, Tmp3;
4355   if (Op.getOpcode() == ISD::SHL_PARTS) {
4356     Tmp2 = DAG.getNode(X86ISD::SHLD, VT, ShOpHi, ShOpLo, ShAmt);
4357     Tmp3 = DAG.getNode(ISD::SHL, VT, ShOpLo, ShAmt);
4358   } else {
4359     Tmp2 = DAG.getNode(X86ISD::SHRD, VT, ShOpLo, ShOpHi, ShAmt);
4360     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, VT, ShOpHi, ShAmt);
4361   }
4362
4363   const MVT *VTs = DAG.getNodeValueTypes(MVT::Other, MVT::Flag);
4364   SDOperand AndNode = DAG.getNode(ISD::AND, MVT::i8, ShAmt,
4365                                   DAG.getConstant(VTBits, MVT::i8));
4366   SDOperand Cond = DAG.getNode(X86ISD::CMP, VT,
4367                                AndNode, DAG.getConstant(0, MVT::i8));
4368
4369   SDOperand Hi, Lo;
4370   SDOperand CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4371   VTs = DAG.getNodeValueTypes(VT, MVT::Flag);
4372   SmallVector<SDOperand, 4> Ops;
4373   if (Op.getOpcode() == ISD::SHL_PARTS) {
4374     Ops.push_back(Tmp2);
4375     Ops.push_back(Tmp3);
4376     Ops.push_back(CC);
4377     Ops.push_back(Cond);
4378     Hi = DAG.getNode(X86ISD::CMOV, VT, &Ops[0], Ops.size());
4379
4380     Ops.clear();
4381     Ops.push_back(Tmp3);
4382     Ops.push_back(Tmp1);
4383     Ops.push_back(CC);
4384     Ops.push_back(Cond);
4385     Lo = DAG.getNode(X86ISD::CMOV, VT, &Ops[0], Ops.size());
4386   } else {
4387     Ops.push_back(Tmp2);
4388     Ops.push_back(Tmp3);
4389     Ops.push_back(CC);
4390     Ops.push_back(Cond);
4391     Lo = DAG.getNode(X86ISD::CMOV, VT, &Ops[0], Ops.size());
4392
4393     Ops.clear();
4394     Ops.push_back(Tmp3);
4395     Ops.push_back(Tmp1);
4396     Ops.push_back(CC);
4397     Ops.push_back(Cond);
4398     Hi = DAG.getNode(X86ISD::CMOV, VT, &Ops[0], Ops.size());
4399   }
4400
4401   VTs = DAG.getNodeValueTypes(VT, VT);
4402   Ops.clear();
4403   Ops.push_back(Lo);
4404   Ops.push_back(Hi);
4405   return DAG.getNode(ISD::MERGE_VALUES, VTs, 2, &Ops[0], Ops.size());
4406 }
4407
4408 SDOperand X86TargetLowering::LowerSINT_TO_FP(SDOperand Op, SelectionDAG &DAG) {
4409   MVT SrcVT = Op.getOperand(0).getValueType();
4410   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
4411          "Unknown SINT_TO_FP to lower!");
4412   
4413   // These are really Legal; caller falls through into that case.
4414   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
4415     return SDOperand();
4416   if (SrcVT == MVT::i64 && Op.getValueType() != MVT::f80 && 
4417       Subtarget->is64Bit())
4418     return SDOperand();
4419   
4420   unsigned Size = SrcVT.getSizeInBits()/8;
4421   MachineFunction &MF = DAG.getMachineFunction();
4422   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
4423   SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4424   SDOperand Chain = DAG.getStore(DAG.getEntryNode(), Op.getOperand(0),
4425                                  StackSlot,
4426                                  PseudoSourceValue::getFixedStack(),
4427                                  SSFI);
4428
4429   // Build the FILD
4430   SDVTList Tys;
4431   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
4432   if (useSSE)
4433     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
4434   else
4435     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
4436   SmallVector<SDOperand, 8> Ops;
4437   Ops.push_back(Chain);
4438   Ops.push_back(StackSlot);
4439   Ops.push_back(DAG.getValueType(SrcVT));
4440   SDOperand Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD,
4441                                  Tys, &Ops[0], Ops.size());
4442
4443   if (useSSE) {
4444     Chain = Result.getValue(1);
4445     SDOperand InFlag = Result.getValue(2);
4446
4447     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
4448     // shouldn't be necessary except that RFP cannot be live across
4449     // multiple blocks. When stackifier is fixed, they can be uncoupled.
4450     MachineFunction &MF = DAG.getMachineFunction();
4451     int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
4452     SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4453     Tys = DAG.getVTList(MVT::Other);
4454     SmallVector<SDOperand, 8> Ops;
4455     Ops.push_back(Chain);
4456     Ops.push_back(Result);
4457     Ops.push_back(StackSlot);
4458     Ops.push_back(DAG.getValueType(Op.getValueType()));
4459     Ops.push_back(InFlag);
4460     Chain = DAG.getNode(X86ISD::FST, Tys, &Ops[0], Ops.size());
4461     Result = DAG.getLoad(Op.getValueType(), Chain, StackSlot,
4462                          PseudoSourceValue::getFixedStack(), SSFI);
4463   }
4464
4465   return Result;
4466 }
4467
4468 std::pair<SDOperand,SDOperand> X86TargetLowering::
4469 FP_TO_SINTHelper(SDOperand Op, SelectionDAG &DAG) {
4470   assert(Op.getValueType().getSimpleVT() <= MVT::i64 &&
4471          Op.getValueType().getSimpleVT() >= MVT::i16 &&
4472          "Unknown FP_TO_SINT to lower!");
4473
4474   // These are really Legal.
4475   if (Op.getValueType() == MVT::i32 && 
4476       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
4477     return std::make_pair(SDOperand(), SDOperand());
4478   if (Subtarget->is64Bit() &&
4479       Op.getValueType() == MVT::i64 &&
4480       Op.getOperand(0).getValueType() != MVT::f80)
4481     return std::make_pair(SDOperand(), SDOperand());
4482
4483   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
4484   // stack slot.
4485   MachineFunction &MF = DAG.getMachineFunction();
4486   unsigned MemSize = Op.getValueType().getSizeInBits()/8;
4487   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4488   SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4489   unsigned Opc;
4490   switch (Op.getValueType().getSimpleVT()) {
4491   default: assert(0 && "Invalid FP_TO_SINT to lower!");
4492   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
4493   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
4494   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
4495   }
4496
4497   SDOperand Chain = DAG.getEntryNode();
4498   SDOperand Value = Op.getOperand(0);
4499   if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
4500     assert(Op.getValueType() == MVT::i64 && "Invalid FP_TO_SINT to lower!");
4501     Chain = DAG.getStore(Chain, Value, StackSlot,
4502                          PseudoSourceValue::getFixedStack(), SSFI);
4503     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
4504     SDOperand Ops[] = {
4505       Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
4506     };
4507     Value = DAG.getNode(X86ISD::FLD, Tys, Ops, 3);
4508     Chain = Value.getValue(1);
4509     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4510     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4511   }
4512
4513   // Build the FP_TO_INT*_IN_MEM
4514   SDOperand Ops[] = { Chain, Value, StackSlot };
4515   SDOperand FIST = DAG.getNode(Opc, MVT::Other, Ops, 3);
4516
4517   return std::make_pair(FIST, StackSlot);
4518 }
4519
4520 SDOperand X86TargetLowering::LowerFP_TO_SINT(SDOperand Op, SelectionDAG &DAG) {
4521   std::pair<SDOperand,SDOperand> Vals = FP_TO_SINTHelper(Op, DAG);
4522   SDOperand FIST = Vals.first, StackSlot = Vals.second;
4523   if (FIST.Val == 0) return SDOperand();
4524   
4525   // Load the result.
4526   return DAG.getLoad(Op.getValueType(), FIST, StackSlot, NULL, 0);
4527 }
4528
4529 SDNode *X86TargetLowering::ExpandFP_TO_SINT(SDNode *N, SelectionDAG &DAG) {
4530   std::pair<SDOperand,SDOperand> Vals = FP_TO_SINTHelper(SDOperand(N, 0), DAG);
4531   SDOperand FIST = Vals.first, StackSlot = Vals.second;
4532   if (FIST.Val == 0) return 0;
4533   
4534   // Return an i64 load from the stack slot.
4535   SDOperand Res = DAG.getLoad(MVT::i64, FIST, StackSlot, NULL, 0);
4536
4537   // Use a MERGE_VALUES node to drop the chain result value.
4538   return DAG.getNode(ISD::MERGE_VALUES, MVT::i64, Res).Val;
4539 }  
4540
4541 SDOperand X86TargetLowering::LowerFABS(SDOperand Op, SelectionDAG &DAG) {
4542   MVT VT = Op.getValueType();
4543   MVT EltVT = VT;
4544   if (VT.isVector())
4545     EltVT = VT.getVectorElementType();
4546   std::vector<Constant*> CV;
4547   if (EltVT == MVT::f64) {
4548     Constant *C = ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63))));
4549     CV.push_back(C);
4550     CV.push_back(C);
4551   } else {
4552     Constant *C = ConstantFP::get(APFloat(APInt(32, ~(1U << 31))));
4553     CV.push_back(C);
4554     CV.push_back(C);
4555     CV.push_back(C);
4556     CV.push_back(C);
4557   }
4558   Constant *C = ConstantVector::get(CV);
4559   SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4560   SDOperand Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4561                                PseudoSourceValue::getConstantPool(), 0,
4562                                false, 16);
4563   return DAG.getNode(X86ISD::FAND, VT, Op.getOperand(0), Mask);
4564 }
4565
4566 SDOperand X86TargetLowering::LowerFNEG(SDOperand Op, SelectionDAG &DAG) {
4567   MVT VT = Op.getValueType();
4568   MVT EltVT = VT;
4569   unsigned EltNum = 1;
4570   if (VT.isVector()) {
4571     EltVT = VT.getVectorElementType();
4572     EltNum = VT.getVectorNumElements();
4573   }
4574   std::vector<Constant*> CV;
4575   if (EltVT == MVT::f64) {
4576     Constant *C = ConstantFP::get(APFloat(APInt(64, 1ULL << 63)));
4577     CV.push_back(C);
4578     CV.push_back(C);
4579   } else {
4580     Constant *C = ConstantFP::get(APFloat(APInt(32, 1U << 31)));
4581     CV.push_back(C);
4582     CV.push_back(C);
4583     CV.push_back(C);
4584     CV.push_back(C);
4585   }
4586   Constant *C = ConstantVector::get(CV);
4587   SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4588   SDOperand Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4589                                PseudoSourceValue::getConstantPool(), 0,
4590                                false, 16);
4591   if (VT.isVector()) {
4592     return DAG.getNode(ISD::BIT_CONVERT, VT,
4593                        DAG.getNode(ISD::XOR, MVT::v2i64,
4594                     DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Op.getOperand(0)),
4595                     DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Mask)));
4596   } else {
4597     return DAG.getNode(X86ISD::FXOR, VT, Op.getOperand(0), Mask);
4598   }
4599 }
4600
4601 SDOperand X86TargetLowering::LowerFCOPYSIGN(SDOperand Op, SelectionDAG &DAG) {
4602   SDOperand Op0 = Op.getOperand(0);
4603   SDOperand Op1 = Op.getOperand(1);
4604   MVT VT = Op.getValueType();
4605   MVT SrcVT = Op1.getValueType();
4606
4607   // If second operand is smaller, extend it first.
4608   if (SrcVT.bitsLT(VT)) {
4609     Op1 = DAG.getNode(ISD::FP_EXTEND, VT, Op1);
4610     SrcVT = VT;
4611   }
4612   // And if it is bigger, shrink it first.
4613   if (SrcVT.bitsGT(VT)) {
4614     Op1 = DAG.getNode(ISD::FP_ROUND, VT, Op1, DAG.getIntPtrConstant(1));
4615     SrcVT = VT;
4616   }
4617
4618   // At this point the operands and the result should have the same
4619   // type, and that won't be f80 since that is not custom lowered.
4620
4621   // First get the sign bit of second operand.
4622   std::vector<Constant*> CV;
4623   if (SrcVT == MVT::f64) {
4624     CV.push_back(ConstantFP::get(APFloat(APInt(64, 1ULL << 63))));
4625     CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
4626   } else {
4627     CV.push_back(ConstantFP::get(APFloat(APInt(32, 1U << 31))));
4628     CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4629     CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4630     CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4631   }
4632   Constant *C = ConstantVector::get(CV);
4633   SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4634   SDOperand Mask1 = DAG.getLoad(SrcVT, DAG.getEntryNode(), CPIdx,
4635                                 PseudoSourceValue::getConstantPool(), 0,
4636                                 false, 16);
4637   SDOperand SignBit = DAG.getNode(X86ISD::FAND, SrcVT, Op1, Mask1);
4638
4639   // Shift sign bit right or left if the two operands have different types.
4640   if (SrcVT.bitsGT(VT)) {
4641     // Op0 is MVT::f32, Op1 is MVT::f64.
4642     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2f64, SignBit);
4643     SignBit = DAG.getNode(X86ISD::FSRL, MVT::v2f64, SignBit,
4644                           DAG.getConstant(32, MVT::i32));
4645     SignBit = DAG.getNode(ISD::BIT_CONVERT, MVT::v4f32, SignBit);
4646     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::f32, SignBit,
4647                           DAG.getIntPtrConstant(0));
4648   }
4649
4650   // Clear first operand sign bit.
4651   CV.clear();
4652   if (VT == MVT::f64) {
4653     CV.push_back(ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63)))));
4654     CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
4655   } else {
4656     CV.push_back(ConstantFP::get(APFloat(APInt(32, ~(1U << 31)))));
4657     CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4658     CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4659     CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4660   }
4661   C = ConstantVector::get(CV);
4662   CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4663   SDOperand Mask2 = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4664                                 PseudoSourceValue::getConstantPool(), 0,
4665                                 false, 16);
4666   SDOperand Val = DAG.getNode(X86ISD::FAND, VT, Op0, Mask2);
4667
4668   // Or the value with the sign bit.
4669   return DAG.getNode(X86ISD::FOR, VT, Val, SignBit);
4670 }
4671
4672 SDOperand X86TargetLowering::LowerSETCC(SDOperand Op, SelectionDAG &DAG) {
4673   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
4674   SDOperand Cond;
4675   SDOperand Op0 = Op.getOperand(0);
4676   SDOperand Op1 = Op.getOperand(1);
4677   SDOperand CC = Op.getOperand(2);
4678   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4679   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
4680   unsigned X86CC;
4681
4682   if (translateX86CC(cast<CondCodeSDNode>(CC)->get(), isFP, X86CC,
4683                      Op0, Op1, DAG)) {
4684     Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
4685     return DAG.getNode(X86ISD::SETCC, MVT::i8,
4686                        DAG.getConstant(X86CC, MVT::i8), Cond);
4687   }
4688
4689   assert(isFP && "Illegal integer SetCC!");
4690
4691   Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
4692   switch (SetCCOpcode) {
4693   default: assert(false && "Illegal floating point SetCC!");
4694   case ISD::SETOEQ: {  // !PF & ZF
4695     SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4696                                  DAG.getConstant(X86::COND_NP, MVT::i8), Cond);
4697     SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4698                                  DAG.getConstant(X86::COND_E, MVT::i8), Cond);
4699     return DAG.getNode(ISD::AND, MVT::i8, Tmp1, Tmp2);
4700   }
4701   case ISD::SETUNE: {  // PF | !ZF
4702     SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4703                                  DAG.getConstant(X86::COND_P, MVT::i8), Cond);
4704     SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4705                                  DAG.getConstant(X86::COND_NE, MVT::i8), Cond);
4706     return DAG.getNode(ISD::OR, MVT::i8, Tmp1, Tmp2);
4707   }
4708   }
4709 }
4710
4711
4712 SDOperand X86TargetLowering::LowerSELECT(SDOperand Op, SelectionDAG &DAG) {
4713   bool addTest = true;
4714   SDOperand Cond  = Op.getOperand(0);
4715   SDOperand CC;
4716
4717   if (Cond.getOpcode() == ISD::SETCC)
4718     Cond = LowerSETCC(Cond, DAG);
4719
4720   // If condition flag is set by a X86ISD::CMP, then use it as the condition
4721   // setting operand in place of the X86ISD::SETCC.
4722   if (Cond.getOpcode() == X86ISD::SETCC) {
4723     CC = Cond.getOperand(0);
4724
4725     SDOperand Cmp = Cond.getOperand(1);
4726     unsigned Opc = Cmp.getOpcode();
4727     MVT VT = Op.getValueType();
4728     
4729     bool IllegalFPCMov = false;
4730     if (VT.isFloatingPoint() && !VT.isVector() &&
4731         !isScalarFPTypeInSSEReg(VT))  // FPStack?
4732       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSignExtended());
4733     
4734     if ((Opc == X86ISD::CMP ||
4735          Opc == X86ISD::COMI ||
4736          Opc == X86ISD::UCOMI) && !IllegalFPCMov) {
4737       Cond = Cmp;
4738       addTest = false;
4739     }
4740   }
4741
4742   if (addTest) {
4743     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4744     Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
4745   }
4746
4747   const MVT *VTs = DAG.getNodeValueTypes(Op.getValueType(),
4748                                                     MVT::Flag);
4749   SmallVector<SDOperand, 4> Ops;
4750   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
4751   // condition is true.
4752   Ops.push_back(Op.getOperand(2));
4753   Ops.push_back(Op.getOperand(1));
4754   Ops.push_back(CC);
4755   Ops.push_back(Cond);
4756   return DAG.getNode(X86ISD::CMOV, VTs, 2, &Ops[0], Ops.size());
4757 }
4758
4759 SDOperand X86TargetLowering::LowerBRCOND(SDOperand Op, SelectionDAG &DAG) {
4760   bool addTest = true;
4761   SDOperand Chain = Op.getOperand(0);
4762   SDOperand Cond  = Op.getOperand(1);
4763   SDOperand Dest  = Op.getOperand(2);
4764   SDOperand CC;
4765
4766   if (Cond.getOpcode() == ISD::SETCC)
4767     Cond = LowerSETCC(Cond, DAG);
4768
4769   // If condition flag is set by a X86ISD::CMP, then use it as the condition
4770   // setting operand in place of the X86ISD::SETCC.
4771   if (Cond.getOpcode() == X86ISD::SETCC) {
4772     CC = Cond.getOperand(0);
4773
4774     SDOperand Cmp = Cond.getOperand(1);
4775     unsigned Opc = Cmp.getOpcode();
4776     if (Opc == X86ISD::CMP ||
4777         Opc == X86ISD::COMI ||
4778         Opc == X86ISD::UCOMI) {
4779       Cond = Cmp;
4780       addTest = false;
4781     }
4782   }
4783
4784   if (addTest) {
4785     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4786     Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
4787   }
4788   return DAG.getNode(X86ISD::BRCOND, Op.getValueType(),
4789                      Chain, Op.getOperand(2), CC, Cond);
4790 }
4791
4792
4793 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
4794 // Calls to _alloca is needed to probe the stack when allocating more than 4k
4795 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
4796 // that the guard pages used by the OS virtual memory manager are allocated in
4797 // correct sequence.
4798 SDOperand
4799 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDOperand Op,
4800                                            SelectionDAG &DAG) {
4801   assert(Subtarget->isTargetCygMing() &&
4802          "This should be used only on Cygwin/Mingw targets");
4803
4804   // Get the inputs.
4805   SDOperand Chain = Op.getOperand(0);
4806   SDOperand Size  = Op.getOperand(1);
4807   // FIXME: Ensure alignment here
4808
4809   SDOperand Flag;
4810
4811   MVT IntPtr = getPointerTy();
4812   MVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
4813
4814   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0));
4815
4816   Chain = DAG.getCopyToReg(Chain, X86::EAX, Size, Flag);
4817   Flag = Chain.getValue(1);
4818
4819   SDVTList  NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4820   SDOperand Ops[] = { Chain,
4821                       DAG.getTargetExternalSymbol("_alloca", IntPtr),
4822                       DAG.getRegister(X86::EAX, IntPtr),
4823                       DAG.getRegister(X86StackPtr, SPTy),
4824                       Flag };
4825   Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops, 5);
4826   Flag = Chain.getValue(1);
4827
4828   Chain = DAG.getCALLSEQ_END(Chain,
4829                              DAG.getIntPtrConstant(0),
4830                              DAG.getIntPtrConstant(0),
4831                              Flag);
4832
4833   Chain = DAG.getCopyFromReg(Chain, X86StackPtr, SPTy).getValue(1);
4834
4835   std::vector<MVT> Tys;
4836   Tys.push_back(SPTy);
4837   Tys.push_back(MVT::Other);
4838   SDOperand Ops1[2] = { Chain.getValue(0), Chain };
4839   return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops1, 2);
4840 }
4841
4842 SDOperand
4843 X86TargetLowering::EmitTargetCodeForMemset(SelectionDAG &DAG,
4844                                            SDOperand Chain,
4845                                            SDOperand Dst, SDOperand Src,
4846                                            SDOperand Size, unsigned Align,
4847                                         const Value *DstSV, uint64_t DstSVOff) {
4848   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
4849
4850   /// If not DWORD aligned or size is more than the threshold, call the library.
4851   /// The libc version is likely to be faster for these cases. It can use the
4852   /// address value and run time information about the CPU.
4853   if ((Align & 3) == 0 ||
4854       !ConstantSize ||
4855       ConstantSize->getValue() > getSubtarget()->getMaxInlineSizeThreshold()) {
4856     SDOperand InFlag(0, 0);
4857
4858     // Check to see if there is a specialized entry-point for memory zeroing.
4859     ConstantSDNode *V = dyn_cast<ConstantSDNode>(Src);
4860     if (const char *bzeroEntry = 
4861           V && V->isNullValue() ? Subtarget->getBZeroEntry() : 0) {
4862       MVT IntPtr = getPointerTy();
4863       const Type *IntPtrTy = getTargetData()->getIntPtrType();
4864       TargetLowering::ArgListTy Args; 
4865       TargetLowering::ArgListEntry Entry;
4866       Entry.Node = Dst;
4867       Entry.Ty = IntPtrTy;
4868       Args.push_back(Entry);
4869       Entry.Node = Size;
4870       Args.push_back(Entry);
4871       std::pair<SDOperand,SDOperand> CallResult =
4872         LowerCallTo(Chain, Type::VoidTy, false, false, false, CallingConv::C,
4873                     false, DAG.getExternalSymbol(bzeroEntry, IntPtr),
4874                     Args, DAG);
4875       return CallResult.second;
4876     }
4877
4878     // Otherwise have the target-independent code call memset.
4879     return SDOperand();
4880   }
4881
4882   uint64_t SizeVal = ConstantSize->getValue();
4883   SDOperand InFlag(0, 0);
4884   MVT AVT;
4885   SDOperand Count;
4886   ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Src);
4887   unsigned BytesLeft = 0;
4888   bool TwoRepStos = false;
4889   if (ValC) {
4890     unsigned ValReg;
4891     uint64_t Val = ValC->getValue() & 255;
4892
4893     // If the value is a constant, then we can potentially use larger sets.
4894     switch (Align & 3) {
4895       case 2:   // WORD aligned
4896         AVT = MVT::i16;
4897         ValReg = X86::AX;
4898         Val = (Val << 8) | Val;
4899         break;
4900       case 0:  // DWORD aligned
4901         AVT = MVT::i32;
4902         ValReg = X86::EAX;
4903         Val = (Val << 8)  | Val;
4904         Val = (Val << 16) | Val;
4905         if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) {  // QWORD aligned
4906           AVT = MVT::i64;
4907           ValReg = X86::RAX;
4908           Val = (Val << 32) | Val;
4909         }
4910         break;
4911       default:  // Byte aligned
4912         AVT = MVT::i8;
4913         ValReg = X86::AL;
4914         Count = DAG.getIntPtrConstant(SizeVal);
4915         break;
4916     }
4917
4918     if (AVT.bitsGT(MVT::i8)) {
4919       unsigned UBytes = AVT.getSizeInBits() / 8;
4920       Count = DAG.getIntPtrConstant(SizeVal / UBytes);
4921       BytesLeft = SizeVal % UBytes;
4922     }
4923
4924     Chain  = DAG.getCopyToReg(Chain, ValReg, DAG.getConstant(Val, AVT),
4925                               InFlag);
4926     InFlag = Chain.getValue(1);
4927   } else {
4928     AVT = MVT::i8;
4929     Count  = DAG.getIntPtrConstant(SizeVal);
4930     Chain  = DAG.getCopyToReg(Chain, X86::AL, Src, InFlag);
4931     InFlag = Chain.getValue(1);
4932   }
4933
4934   Chain  = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
4935                             Count, InFlag);
4936   InFlag = Chain.getValue(1);
4937   Chain  = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
4938                             Dst, InFlag);
4939   InFlag = Chain.getValue(1);
4940
4941   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4942   SmallVector<SDOperand, 8> Ops;
4943   Ops.push_back(Chain);
4944   Ops.push_back(DAG.getValueType(AVT));
4945   Ops.push_back(InFlag);
4946   Chain  = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
4947
4948   if (TwoRepStos) {
4949     InFlag = Chain.getValue(1);
4950     Count  = Size;
4951     MVT CVT = Count.getValueType();
4952     SDOperand Left = DAG.getNode(ISD::AND, CVT, Count,
4953                                DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
4954     Chain  = DAG.getCopyToReg(Chain, (CVT == MVT::i64) ? X86::RCX : X86::ECX,
4955                               Left, InFlag);
4956     InFlag = Chain.getValue(1);
4957     Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4958     Ops.clear();
4959     Ops.push_back(Chain);
4960     Ops.push_back(DAG.getValueType(MVT::i8));
4961     Ops.push_back(InFlag);
4962     Chain  = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
4963   } else if (BytesLeft) {
4964     // Handle the last 1 - 7 bytes.
4965     unsigned Offset = SizeVal - BytesLeft;
4966     MVT AddrVT = Dst.getValueType();
4967     MVT SizeVT = Size.getValueType();
4968
4969     Chain = DAG.getMemset(Chain,
4970                           DAG.getNode(ISD::ADD, AddrVT, Dst,
4971                                       DAG.getConstant(Offset, AddrVT)),
4972                           Src,
4973                           DAG.getConstant(BytesLeft, SizeVT),
4974                           Align, DstSV, DstSVOff + Offset);
4975   }
4976
4977   // TODO: Use a Tokenfactor, as in memcpy, instead of a single chain.
4978   return Chain;
4979 }
4980
4981 SDOperand
4982 X86TargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG,
4983                                            SDOperand Chain,
4984                                            SDOperand Dst, SDOperand Src,
4985                                            SDOperand Size, unsigned Align,
4986                                            bool AlwaysInline,
4987                                            const Value *DstSV, uint64_t DstSVOff,
4988                                            const Value *SrcSV, uint64_t SrcSVOff){
4989   
4990   // This requires the copy size to be a constant, preferrably
4991   // within a subtarget-specific limit.
4992   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
4993   if (!ConstantSize)
4994     return SDOperand();
4995   uint64_t SizeVal = ConstantSize->getValue();
4996   if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
4997     return SDOperand();
4998
4999   MVT AVT;
5000   unsigned BytesLeft = 0;
5001   if (Align >= 8 && Subtarget->is64Bit())
5002     AVT = MVT::i64;
5003   else if (Align >= 4)
5004     AVT = MVT::i32;
5005   else if (Align >= 2)
5006     AVT = MVT::i16;
5007   else
5008     AVT = MVT::i8;
5009
5010   unsigned UBytes = AVT.getSizeInBits() / 8;
5011   unsigned CountVal = SizeVal / UBytes;
5012   SDOperand Count = DAG.getIntPtrConstant(CountVal);
5013   BytesLeft = SizeVal % UBytes;
5014
5015   SDOperand InFlag(0, 0);
5016   Chain  = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
5017                             Count, InFlag);
5018   InFlag = Chain.getValue(1);
5019   Chain  = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
5020                             Dst, InFlag);
5021   InFlag = Chain.getValue(1);
5022   Chain  = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RSI : X86::ESI,
5023                             Src, InFlag);
5024   InFlag = Chain.getValue(1);
5025
5026   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5027   SmallVector<SDOperand, 8> Ops;
5028   Ops.push_back(Chain);
5029   Ops.push_back(DAG.getValueType(AVT));
5030   Ops.push_back(InFlag);
5031   SDOperand RepMovs = DAG.getNode(X86ISD::REP_MOVS, Tys, &Ops[0], Ops.size());
5032
5033   SmallVector<SDOperand, 4> Results;
5034   Results.push_back(RepMovs);
5035   if (BytesLeft) {
5036     // Handle the last 1 - 7 bytes.
5037     unsigned Offset = SizeVal - BytesLeft;
5038     MVT DstVT = Dst.getValueType();
5039     MVT SrcVT = Src.getValueType();
5040     MVT SizeVT = Size.getValueType();
5041     Results.push_back(DAG.getMemcpy(Chain,
5042                                     DAG.getNode(ISD::ADD, DstVT, Dst,
5043                                                 DAG.getConstant(Offset, DstVT)),
5044                                     DAG.getNode(ISD::ADD, SrcVT, Src,
5045                                                 DAG.getConstant(Offset, SrcVT)),
5046                                     DAG.getConstant(BytesLeft, SizeVT),
5047                                     Align, AlwaysInline,
5048                                     DstSV, DstSVOff + Offset,
5049                                     SrcSV, SrcSVOff + Offset));
5050   }
5051
5052   return DAG.getNode(ISD::TokenFactor, MVT::Other, &Results[0], Results.size());
5053 }
5054
5055 /// Expand the result of: i64,outchain = READCYCLECOUNTER inchain
5056 SDNode *X86TargetLowering::ExpandREADCYCLECOUNTER(SDNode *N, SelectionDAG &DAG){
5057   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5058   SDOperand TheChain = N->getOperand(0);
5059   SDOperand rd = DAG.getNode(X86ISD::RDTSC_DAG, Tys, &TheChain, 1);
5060   if (Subtarget->is64Bit()) {
5061     SDOperand rax = DAG.getCopyFromReg(rd, X86::RAX, MVT::i64, rd.getValue(1));
5062     SDOperand rdx = DAG.getCopyFromReg(rax.getValue(1), X86::RDX,
5063                                        MVT::i64, rax.getValue(2));
5064     SDOperand Tmp = DAG.getNode(ISD::SHL, MVT::i64, rdx,
5065                                 DAG.getConstant(32, MVT::i8));
5066     SDOperand Ops[] = {
5067       DAG.getNode(ISD::OR, MVT::i64, rax, Tmp), rdx.getValue(1)
5068     };
5069     
5070     Tys = DAG.getVTList(MVT::i64, MVT::Other);
5071     return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops, 2).Val;
5072   }
5073   
5074   SDOperand eax = DAG.getCopyFromReg(rd, X86::EAX, MVT::i32, rd.getValue(1));
5075   SDOperand edx = DAG.getCopyFromReg(eax.getValue(1), X86::EDX,
5076                                        MVT::i32, eax.getValue(2));
5077   // Use a buildpair to merge the two 32-bit values into a 64-bit one. 
5078   SDOperand Ops[] = { eax, edx };
5079   Ops[0] = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, Ops, 2);
5080
5081   // Use a MERGE_VALUES to return the value and chain.
5082   Ops[1] = edx.getValue(1);
5083   Tys = DAG.getVTList(MVT::i64, MVT::Other);
5084   return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops, 2).Val;
5085 }
5086
5087 SDOperand X86TargetLowering::LowerVASTART(SDOperand Op, SelectionDAG &DAG) {
5088   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5089
5090   if (!Subtarget->is64Bit()) {
5091     // vastart just stores the address of the VarArgsFrameIndex slot into the
5092     // memory location argument.
5093     SDOperand FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
5094     return DAG.getStore(Op.getOperand(0), FR,Op.getOperand(1), SV, 0);
5095   }
5096
5097   // __va_list_tag:
5098   //   gp_offset         (0 - 6 * 8)
5099   //   fp_offset         (48 - 48 + 8 * 16)
5100   //   overflow_arg_area (point to parameters coming in memory).
5101   //   reg_save_area
5102   SmallVector<SDOperand, 8> MemOps;
5103   SDOperand FIN = Op.getOperand(1);
5104   // Store gp_offset
5105   SDOperand Store = DAG.getStore(Op.getOperand(0),
5106                                  DAG.getConstant(VarArgsGPOffset, MVT::i32),
5107                                  FIN, SV, 0);
5108   MemOps.push_back(Store);
5109
5110   // Store fp_offset
5111   FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(4));
5112   Store = DAG.getStore(Op.getOperand(0),
5113                        DAG.getConstant(VarArgsFPOffset, MVT::i32),
5114                        FIN, SV, 0);
5115   MemOps.push_back(Store);
5116
5117   // Store ptr to overflow_arg_area
5118   FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(4));
5119   SDOperand OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
5120   Store = DAG.getStore(Op.getOperand(0), OVFIN, FIN, SV, 0);
5121   MemOps.push_back(Store);
5122
5123   // Store ptr to reg_save_area.
5124   FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(8));
5125   SDOperand RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
5126   Store = DAG.getStore(Op.getOperand(0), RSFIN, FIN, SV, 0);
5127   MemOps.push_back(Store);
5128   return DAG.getNode(ISD::TokenFactor, MVT::Other, &MemOps[0], MemOps.size());
5129 }
5130
5131 SDOperand X86TargetLowering::LowerVAARG(SDOperand Op, SelectionDAG &DAG) {
5132   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
5133   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
5134   SDOperand Chain = Op.getOperand(0);
5135   SDOperand SrcPtr = Op.getOperand(1);
5136   SDOperand SrcSV = Op.getOperand(2);
5137
5138   assert(0 && "VAArgInst is not yet implemented for x86-64!");
5139   abort();
5140   return SDOperand();
5141 }
5142
5143 SDOperand X86TargetLowering::LowerVACOPY(SDOperand Op, SelectionDAG &DAG) {
5144   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
5145   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
5146   SDOperand Chain = Op.getOperand(0);
5147   SDOperand DstPtr = Op.getOperand(1);
5148   SDOperand SrcPtr = Op.getOperand(2);
5149   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
5150   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5151
5152   return DAG.getMemcpy(Chain, DstPtr, SrcPtr,
5153                        DAG.getIntPtrConstant(24), 8, false,
5154                        DstSV, 0, SrcSV, 0);
5155 }
5156
5157 SDOperand
5158 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDOperand Op, SelectionDAG &DAG) {
5159   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getValue();
5160   switch (IntNo) {
5161   default: return SDOperand();    // Don't custom lower most intrinsics.
5162   // Comparison intrinsics.
5163   case Intrinsic::x86_sse_comieq_ss:
5164   case Intrinsic::x86_sse_comilt_ss:
5165   case Intrinsic::x86_sse_comile_ss:
5166   case Intrinsic::x86_sse_comigt_ss:
5167   case Intrinsic::x86_sse_comige_ss:
5168   case Intrinsic::x86_sse_comineq_ss:
5169   case Intrinsic::x86_sse_ucomieq_ss:
5170   case Intrinsic::x86_sse_ucomilt_ss:
5171   case Intrinsic::x86_sse_ucomile_ss:
5172   case Intrinsic::x86_sse_ucomigt_ss:
5173   case Intrinsic::x86_sse_ucomige_ss:
5174   case Intrinsic::x86_sse_ucomineq_ss:
5175   case Intrinsic::x86_sse2_comieq_sd:
5176   case Intrinsic::x86_sse2_comilt_sd:
5177   case Intrinsic::x86_sse2_comile_sd:
5178   case Intrinsic::x86_sse2_comigt_sd:
5179   case Intrinsic::x86_sse2_comige_sd:
5180   case Intrinsic::x86_sse2_comineq_sd:
5181   case Intrinsic::x86_sse2_ucomieq_sd:
5182   case Intrinsic::x86_sse2_ucomilt_sd:
5183   case Intrinsic::x86_sse2_ucomile_sd:
5184   case Intrinsic::x86_sse2_ucomigt_sd:
5185   case Intrinsic::x86_sse2_ucomige_sd:
5186   case Intrinsic::x86_sse2_ucomineq_sd: {
5187     unsigned Opc = 0;
5188     ISD::CondCode CC = ISD::SETCC_INVALID;
5189     switch (IntNo) {
5190     default: break;
5191     case Intrinsic::x86_sse_comieq_ss:
5192     case Intrinsic::x86_sse2_comieq_sd:
5193       Opc = X86ISD::COMI;
5194       CC = ISD::SETEQ;
5195       break;
5196     case Intrinsic::x86_sse_comilt_ss:
5197     case Intrinsic::x86_sse2_comilt_sd:
5198       Opc = X86ISD::COMI;
5199       CC = ISD::SETLT;
5200       break;
5201     case Intrinsic::x86_sse_comile_ss:
5202     case Intrinsic::x86_sse2_comile_sd:
5203       Opc = X86ISD::COMI;
5204       CC = ISD::SETLE;
5205       break;
5206     case Intrinsic::x86_sse_comigt_ss:
5207     case Intrinsic::x86_sse2_comigt_sd:
5208       Opc = X86ISD::COMI;
5209       CC = ISD::SETGT;
5210       break;
5211     case Intrinsic::x86_sse_comige_ss:
5212     case Intrinsic::x86_sse2_comige_sd:
5213       Opc = X86ISD::COMI;
5214       CC = ISD::SETGE;
5215       break;
5216     case Intrinsic::x86_sse_comineq_ss:
5217     case Intrinsic::x86_sse2_comineq_sd:
5218       Opc = X86ISD::COMI;
5219       CC = ISD::SETNE;
5220       break;
5221     case Intrinsic::x86_sse_ucomieq_ss:
5222     case Intrinsic::x86_sse2_ucomieq_sd:
5223       Opc = X86ISD::UCOMI;
5224       CC = ISD::SETEQ;
5225       break;
5226     case Intrinsic::x86_sse_ucomilt_ss:
5227     case Intrinsic::x86_sse2_ucomilt_sd:
5228       Opc = X86ISD::UCOMI;
5229       CC = ISD::SETLT;
5230       break;
5231     case Intrinsic::x86_sse_ucomile_ss:
5232     case Intrinsic::x86_sse2_ucomile_sd:
5233       Opc = X86ISD::UCOMI;
5234       CC = ISD::SETLE;
5235       break;
5236     case Intrinsic::x86_sse_ucomigt_ss:
5237     case Intrinsic::x86_sse2_ucomigt_sd:
5238       Opc = X86ISD::UCOMI;
5239       CC = ISD::SETGT;
5240       break;
5241     case Intrinsic::x86_sse_ucomige_ss:
5242     case Intrinsic::x86_sse2_ucomige_sd:
5243       Opc = X86ISD::UCOMI;
5244       CC = ISD::SETGE;
5245       break;
5246     case Intrinsic::x86_sse_ucomineq_ss:
5247     case Intrinsic::x86_sse2_ucomineq_sd:
5248       Opc = X86ISD::UCOMI;
5249       CC = ISD::SETNE;
5250       break;
5251     }
5252
5253     unsigned X86CC;
5254     SDOperand LHS = Op.getOperand(1);
5255     SDOperand RHS = Op.getOperand(2);
5256     translateX86CC(CC, true, X86CC, LHS, RHS, DAG);
5257
5258     SDOperand Cond = DAG.getNode(Opc, MVT::i32, LHS, RHS);
5259     SDOperand SetCC = DAG.getNode(X86ISD::SETCC, MVT::i8,
5260                                   DAG.getConstant(X86CC, MVT::i8), Cond);
5261     return DAG.getNode(ISD::ANY_EXTEND, MVT::i32, SetCC);
5262   }
5263
5264   // Fix vector shift instructions where the last operand is a non-immediate
5265   // i32 value.
5266   case Intrinsic::x86_sse2_pslli_w:
5267   case Intrinsic::x86_sse2_pslli_d:
5268   case Intrinsic::x86_sse2_pslli_q:
5269   case Intrinsic::x86_sse2_psrli_w:
5270   case Intrinsic::x86_sse2_psrli_d:
5271   case Intrinsic::x86_sse2_psrli_q:
5272   case Intrinsic::x86_sse2_psrai_w:
5273   case Intrinsic::x86_sse2_psrai_d:
5274   case Intrinsic::x86_mmx_pslli_w:
5275   case Intrinsic::x86_mmx_pslli_d:
5276   case Intrinsic::x86_mmx_pslli_q:
5277   case Intrinsic::x86_mmx_psrli_w:
5278   case Intrinsic::x86_mmx_psrli_d:
5279   case Intrinsic::x86_mmx_psrli_q:
5280   case Intrinsic::x86_mmx_psrai_w:
5281   case Intrinsic::x86_mmx_psrai_d: {
5282     SDOperand ShAmt = Op.getOperand(2);
5283     if (isa<ConstantSDNode>(ShAmt))
5284       return SDOperand();
5285
5286     unsigned NewIntNo = 0;
5287     MVT ShAmtVT = MVT::v4i32;
5288     switch (IntNo) {
5289     case Intrinsic::x86_sse2_pslli_w:
5290       NewIntNo = Intrinsic::x86_sse2_psll_w;
5291       break;
5292     case Intrinsic::x86_sse2_pslli_d:
5293       NewIntNo = Intrinsic::x86_sse2_psll_d;
5294       break;
5295     case Intrinsic::x86_sse2_pslli_q:
5296       NewIntNo = Intrinsic::x86_sse2_psll_q;
5297       break;
5298     case Intrinsic::x86_sse2_psrli_w:
5299       NewIntNo = Intrinsic::x86_sse2_psrl_w;
5300       break;
5301     case Intrinsic::x86_sse2_psrli_d:
5302       NewIntNo = Intrinsic::x86_sse2_psrl_d;
5303       break;
5304     case Intrinsic::x86_sse2_psrli_q:
5305       NewIntNo = Intrinsic::x86_sse2_psrl_q;
5306       break;
5307     case Intrinsic::x86_sse2_psrai_w:
5308       NewIntNo = Intrinsic::x86_sse2_psra_w;
5309       break;
5310     case Intrinsic::x86_sse2_psrai_d:
5311       NewIntNo = Intrinsic::x86_sse2_psra_d;
5312       break;
5313     default: {
5314       ShAmtVT = MVT::v2i32;
5315       switch (IntNo) {
5316       case Intrinsic::x86_mmx_pslli_w:
5317         NewIntNo = Intrinsic::x86_mmx_psll_w;
5318         break;
5319       case Intrinsic::x86_mmx_pslli_d:
5320         NewIntNo = Intrinsic::x86_mmx_psll_d;
5321         break;
5322       case Intrinsic::x86_mmx_pslli_q:
5323         NewIntNo = Intrinsic::x86_mmx_psll_q;
5324         break;
5325       case Intrinsic::x86_mmx_psrli_w:
5326         NewIntNo = Intrinsic::x86_mmx_psrl_w;
5327         break;
5328       case Intrinsic::x86_mmx_psrli_d:
5329         NewIntNo = Intrinsic::x86_mmx_psrl_d;
5330         break;
5331       case Intrinsic::x86_mmx_psrli_q:
5332         NewIntNo = Intrinsic::x86_mmx_psrl_q;
5333         break;
5334       case Intrinsic::x86_mmx_psrai_w:
5335         NewIntNo = Intrinsic::x86_mmx_psra_w;
5336         break;
5337       case Intrinsic::x86_mmx_psrai_d:
5338         NewIntNo = Intrinsic::x86_mmx_psra_d;
5339         break;
5340       default: abort();  // Can't reach here.
5341       }
5342       break;
5343     }
5344     }
5345     MVT VT = Op.getValueType();
5346     ShAmt = DAG.getNode(ISD::BIT_CONVERT, VT,
5347                         DAG.getNode(ISD::SCALAR_TO_VECTOR, ShAmtVT, ShAmt));
5348     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
5349                        DAG.getConstant(NewIntNo, MVT::i32),
5350                        Op.getOperand(1), ShAmt);
5351   }
5352   }
5353 }
5354
5355 SDOperand X86TargetLowering::LowerRETURNADDR(SDOperand Op, SelectionDAG &DAG) {
5356   // Depths > 0 not supported yet!
5357   if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
5358     return SDOperand();
5359   
5360   // Just load the return address
5361   SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
5362   return DAG.getLoad(getPointerTy(), DAG.getEntryNode(), RetAddrFI, NULL, 0);
5363 }
5364
5365 SDOperand X86TargetLowering::LowerFRAMEADDR(SDOperand Op, SelectionDAG &DAG) {
5366   // Depths > 0 not supported yet!
5367   if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
5368     return SDOperand();
5369     
5370   SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
5371   return DAG.getNode(ISD::SUB, getPointerTy(), RetAddrFI, 
5372                      DAG.getIntPtrConstant(4));
5373 }
5374
5375 SDOperand X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDOperand Op,
5376                                                        SelectionDAG &DAG) {
5377   // Is not yet supported on x86-64
5378   if (Subtarget->is64Bit())
5379     return SDOperand();
5380   
5381   return DAG.getIntPtrConstant(8);
5382 }
5383
5384 SDOperand X86TargetLowering::LowerEH_RETURN(SDOperand Op, SelectionDAG &DAG)
5385 {
5386   assert(!Subtarget->is64Bit() &&
5387          "Lowering of eh_return builtin is not supported yet on x86-64");
5388     
5389   MachineFunction &MF = DAG.getMachineFunction();
5390   SDOperand Chain     = Op.getOperand(0);
5391   SDOperand Offset    = Op.getOperand(1);
5392   SDOperand Handler   = Op.getOperand(2);
5393
5394   SDOperand Frame = DAG.getRegister(RegInfo->getFrameRegister(MF),
5395                                     getPointerTy());
5396
5397   SDOperand StoreAddr = DAG.getNode(ISD::SUB, getPointerTy(), Frame,
5398                                     DAG.getIntPtrConstant(-4UL));
5399   StoreAddr = DAG.getNode(ISD::ADD, getPointerTy(), StoreAddr, Offset);
5400   Chain = DAG.getStore(Chain, Handler, StoreAddr, NULL, 0);
5401   Chain = DAG.getCopyToReg(Chain, X86::ECX, StoreAddr);
5402   MF.getRegInfo().addLiveOut(X86::ECX);
5403
5404   return DAG.getNode(X86ISD::EH_RETURN, MVT::Other,
5405                      Chain, DAG.getRegister(X86::ECX, getPointerTy()));
5406 }
5407
5408 SDOperand X86TargetLowering::LowerTRAMPOLINE(SDOperand Op,
5409                                              SelectionDAG &DAG) {
5410   SDOperand Root = Op.getOperand(0);
5411   SDOperand Trmp = Op.getOperand(1); // trampoline
5412   SDOperand FPtr = Op.getOperand(2); // nested function
5413   SDOperand Nest = Op.getOperand(3); // 'nest' parameter value
5414
5415   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5416
5417   const X86InstrInfo *TII =
5418     ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
5419
5420   if (Subtarget->is64Bit()) {
5421     SDOperand OutChains[6];
5422
5423     // Large code-model.
5424
5425     const unsigned char JMP64r  = TII->getBaseOpcodeFor(X86::JMP64r);
5426     const unsigned char MOV64ri = TII->getBaseOpcodeFor(X86::MOV64ri);
5427
5428     const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
5429     const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
5430
5431     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
5432
5433     // Load the pointer to the nested function into R11.
5434     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
5435     SDOperand Addr = Trmp;
5436     OutChains[0] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5437                                 TrmpAddr, 0);
5438
5439     Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(2, MVT::i64));
5440     OutChains[1] = DAG.getStore(Root, FPtr, Addr, TrmpAddr, 2, false, 2);
5441
5442     // Load the 'nest' parameter value into R10.
5443     // R10 is specified in X86CallingConv.td
5444     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
5445     Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(10, MVT::i64));
5446     OutChains[2] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5447                                 TrmpAddr, 10);
5448
5449     Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(12, MVT::i64));
5450     OutChains[3] = DAG.getStore(Root, Nest, Addr, TrmpAddr, 12, false, 2);
5451
5452     // Jump to the nested function.
5453     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
5454     Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(20, MVT::i64));
5455     OutChains[4] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5456                                 TrmpAddr, 20);
5457
5458     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
5459     Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(22, MVT::i64));
5460     OutChains[5] = DAG.getStore(Root, DAG.getConstant(ModRM, MVT::i8), Addr,
5461                                 TrmpAddr, 22);
5462
5463     SDOperand Ops[] =
5464       { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 6) };
5465     return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(), Ops, 2);
5466   } else {
5467     const Function *Func =
5468       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
5469     unsigned CC = Func->getCallingConv();
5470     unsigned NestReg;
5471
5472     switch (CC) {
5473     default:
5474       assert(0 && "Unsupported calling convention");
5475     case CallingConv::C:
5476     case CallingConv::X86_StdCall: {
5477       // Pass 'nest' parameter in ECX.
5478       // Must be kept in sync with X86CallingConv.td
5479       NestReg = X86::ECX;
5480
5481       // Check that ECX wasn't needed by an 'inreg' parameter.
5482       const FunctionType *FTy = Func->getFunctionType();
5483       const PAListPtr &Attrs = Func->getParamAttrs();
5484
5485       if (!Attrs.isEmpty() && !Func->isVarArg()) {
5486         unsigned InRegCount = 0;
5487         unsigned Idx = 1;
5488
5489         for (FunctionType::param_iterator I = FTy->param_begin(),
5490              E = FTy->param_end(); I != E; ++I, ++Idx)
5491           if (Attrs.paramHasAttr(Idx, ParamAttr::InReg))
5492             // FIXME: should only count parameters that are lowered to integers.
5493             InRegCount += (getTargetData()->getTypeSizeInBits(*I) + 31) / 32;
5494
5495         if (InRegCount > 2) {
5496           cerr << "Nest register in use - reduce number of inreg parameters!\n";
5497           abort();
5498         }
5499       }
5500       break;
5501     }
5502     case CallingConv::X86_FastCall:
5503       // Pass 'nest' parameter in EAX.
5504       // Must be kept in sync with X86CallingConv.td
5505       NestReg = X86::EAX;
5506       break;
5507     }
5508
5509     SDOperand OutChains[4];
5510     SDOperand Addr, Disp;
5511
5512     Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(10, MVT::i32));
5513     Disp = DAG.getNode(ISD::SUB, MVT::i32, FPtr, Addr);
5514
5515     const unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
5516     const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
5517     OutChains[0] = DAG.getStore(Root, DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
5518                                 Trmp, TrmpAddr, 0);
5519
5520     Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(1, MVT::i32));
5521     OutChains[1] = DAG.getStore(Root, Nest, Addr, TrmpAddr, 1, false, 1);
5522
5523     const unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
5524     Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(5, MVT::i32));
5525     OutChains[2] = DAG.getStore(Root, DAG.getConstant(JMP, MVT::i8), Addr,
5526                                 TrmpAddr, 5, false, 1);
5527
5528     Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(6, MVT::i32));
5529     OutChains[3] = DAG.getStore(Root, Disp, Addr, TrmpAddr, 6, false, 1);
5530
5531     SDOperand Ops[] =
5532       { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 4) };
5533     return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(), Ops, 2);
5534   }
5535 }
5536
5537 SDOperand X86TargetLowering::LowerFLT_ROUNDS_(SDOperand Op, SelectionDAG &DAG) {
5538   /*
5539    The rounding mode is in bits 11:10 of FPSR, and has the following
5540    settings:
5541      00 Round to nearest
5542      01 Round to -inf
5543      10 Round to +inf
5544      11 Round to 0
5545
5546   FLT_ROUNDS, on the other hand, expects the following:
5547     -1 Undefined
5548      0 Round to 0
5549      1 Round to nearest
5550      2 Round to +inf
5551      3 Round to -inf
5552
5553   To perform the conversion, we do:
5554     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
5555   */
5556
5557   MachineFunction &MF = DAG.getMachineFunction();
5558   const TargetMachine &TM = MF.getTarget();
5559   const TargetFrameInfo &TFI = *TM.getFrameInfo();
5560   unsigned StackAlignment = TFI.getStackAlignment();
5561   MVT VT = Op.getValueType();
5562
5563   // Save FP Control Word to stack slot
5564   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment);
5565   SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5566
5567   SDOperand Chain = DAG.getNode(X86ISD::FNSTCW16m, MVT::Other,
5568                                 DAG.getEntryNode(), StackSlot);
5569
5570   // Load FP Control Word from stack slot
5571   SDOperand CWD = DAG.getLoad(MVT::i16, Chain, StackSlot, NULL, 0);
5572
5573   // Transform as necessary
5574   SDOperand CWD1 =
5575     DAG.getNode(ISD::SRL, MVT::i16,
5576                 DAG.getNode(ISD::AND, MVT::i16,
5577                             CWD, DAG.getConstant(0x800, MVT::i16)),
5578                 DAG.getConstant(11, MVT::i8));
5579   SDOperand CWD2 =
5580     DAG.getNode(ISD::SRL, MVT::i16,
5581                 DAG.getNode(ISD::AND, MVT::i16,
5582                             CWD, DAG.getConstant(0x400, MVT::i16)),
5583                 DAG.getConstant(9, MVT::i8));
5584
5585   SDOperand RetVal =
5586     DAG.getNode(ISD::AND, MVT::i16,
5587                 DAG.getNode(ISD::ADD, MVT::i16,
5588                             DAG.getNode(ISD::OR, MVT::i16, CWD1, CWD2),
5589                             DAG.getConstant(1, MVT::i16)),
5590                 DAG.getConstant(3, MVT::i16));
5591
5592
5593   return DAG.getNode((VT.getSizeInBits() < 16 ?
5594                       ISD::TRUNCATE : ISD::ZERO_EXTEND), VT, RetVal);
5595 }
5596
5597 SDOperand X86TargetLowering::LowerCTLZ(SDOperand Op, SelectionDAG &DAG) {
5598   MVT VT = Op.getValueType();
5599   MVT OpVT = VT;
5600   unsigned NumBits = VT.getSizeInBits();
5601
5602   Op = Op.getOperand(0);
5603   if (VT == MVT::i8) {
5604     // Zero extend to i32 since there is not an i8 bsr.
5605     OpVT = MVT::i32;
5606     Op = DAG.getNode(ISD::ZERO_EXTEND, OpVT, Op);
5607   }
5608
5609   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
5610   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
5611   Op = DAG.getNode(X86ISD::BSR, VTs, Op);
5612
5613   // If src is zero (i.e. bsr sets ZF), returns NumBits.
5614   SmallVector<SDOperand, 4> Ops;
5615   Ops.push_back(Op);
5616   Ops.push_back(DAG.getConstant(NumBits+NumBits-1, OpVT));
5617   Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
5618   Ops.push_back(Op.getValue(1));
5619   Op = DAG.getNode(X86ISD::CMOV, OpVT, &Ops[0], 4);
5620
5621   // Finally xor with NumBits-1.
5622   Op = DAG.getNode(ISD::XOR, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
5623
5624   if (VT == MVT::i8)
5625     Op = DAG.getNode(ISD::TRUNCATE, MVT::i8, Op);
5626   return Op;
5627 }
5628
5629 SDOperand X86TargetLowering::LowerCTTZ(SDOperand Op, SelectionDAG &DAG) {
5630   MVT VT = Op.getValueType();
5631   MVT OpVT = VT;
5632   unsigned NumBits = VT.getSizeInBits();
5633
5634   Op = Op.getOperand(0);
5635   if (VT == MVT::i8) {
5636     OpVT = MVT::i32;
5637     Op = DAG.getNode(ISD::ZERO_EXTEND, OpVT, Op);
5638   }
5639
5640   // Issue a bsf (scan bits forward) which also sets EFLAGS.
5641   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
5642   Op = DAG.getNode(X86ISD::BSF, VTs, Op);
5643
5644   // If src is zero (i.e. bsf sets ZF), returns NumBits.
5645   SmallVector<SDOperand, 4> Ops;
5646   Ops.push_back(Op);
5647   Ops.push_back(DAG.getConstant(NumBits, OpVT));
5648   Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
5649   Ops.push_back(Op.getValue(1));
5650   Op = DAG.getNode(X86ISD::CMOV, OpVT, &Ops[0], 4);
5651
5652   if (VT == MVT::i8)
5653     Op = DAG.getNode(ISD::TRUNCATE, MVT::i8, Op);
5654   return Op;
5655 }
5656
5657 SDOperand X86TargetLowering::LowerLCS(SDOperand Op, SelectionDAG &DAG) {
5658   MVT T = cast<AtomicSDNode>(Op.Val)->getVT();
5659   unsigned Reg = 0;
5660   unsigned size = 0;
5661   switch(T.getSimpleVT()) {
5662   default:
5663     assert(false && "Invalid value type!");
5664   case MVT::i8:  Reg = X86::AL;  size = 1; break;
5665   case MVT::i16: Reg = X86::AX;  size = 2; break;
5666   case MVT::i32: Reg = X86::EAX; size = 4; break;
5667   case MVT::i64: 
5668     if (Subtarget->is64Bit()) {
5669       Reg = X86::RAX; size = 8;
5670     } else //Should go away when LowerType stuff lands
5671       return SDOperand(ExpandATOMIC_LCS(Op.Val, DAG), 0);
5672     break;
5673   };
5674   SDOperand cpIn = DAG.getCopyToReg(Op.getOperand(0), Reg,
5675                                     Op.getOperand(3), SDOperand());
5676   SDOperand Ops[] = { cpIn.getValue(0),
5677                       Op.getOperand(1),
5678                       Op.getOperand(2),
5679                       DAG.getTargetConstant(size, MVT::i8),
5680                       cpIn.getValue(1) };
5681   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5682   SDOperand Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, Tys, Ops, 5);
5683   SDOperand cpOut = 
5684     DAG.getCopyFromReg(Result.getValue(0), Reg, T, Result.getValue(1));
5685   return cpOut;
5686 }
5687
5688 SDNode* X86TargetLowering::ExpandATOMIC_LCS(SDNode* Op, SelectionDAG &DAG) {
5689   MVT T = cast<AtomicSDNode>(Op)->getVT();
5690   assert (T == MVT::i64 && "Only know how to expand i64 CAS");
5691   SDOperand cpInL, cpInH;
5692   cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(3),
5693                       DAG.getConstant(0, MVT::i32));
5694   cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(3),
5695                       DAG.getConstant(1, MVT::i32));
5696   cpInL = DAG.getCopyToReg(Op->getOperand(0), X86::EAX,
5697                            cpInL, SDOperand());
5698   cpInH = DAG.getCopyToReg(cpInL.getValue(0), X86::EDX,
5699                            cpInH, cpInL.getValue(1));
5700   SDOperand swapInL, swapInH;
5701   swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(2),
5702                         DAG.getConstant(0, MVT::i32));
5703   swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(2),
5704                         DAG.getConstant(1, MVT::i32));
5705   swapInL = DAG.getCopyToReg(cpInH.getValue(0), X86::EBX,
5706                              swapInL, cpInH.getValue(1));
5707   swapInH = DAG.getCopyToReg(swapInL.getValue(0), X86::ECX,
5708                              swapInH, swapInL.getValue(1));
5709   SDOperand Ops[] = { swapInH.getValue(0),
5710                       Op->getOperand(1),
5711                       swapInH.getValue(1)};
5712   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5713   SDOperand Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, Tys, Ops, 3);
5714   SDOperand cpOutL = DAG.getCopyFromReg(Result.getValue(0), X86::EAX, MVT::i32, 
5715                                         Result.getValue(1));
5716   SDOperand cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), X86::EDX, MVT::i32, 
5717                                         cpOutL.getValue(2));
5718   SDOperand OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
5719   SDOperand ResultVal = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, OpsF, 2);
5720   Tys = DAG.getVTList(MVT::i64, MVT::Other);
5721   return DAG.getNode(ISD::MERGE_VALUES, Tys, ResultVal, cpOutH.getValue(1)).Val;
5722 }
5723
5724 SDNode* X86TargetLowering::ExpandATOMIC_LSS(SDNode* Op, SelectionDAG &DAG) {
5725   MVT T = cast<AtomicSDNode>(Op)->getVT();
5726   assert (T == MVT::i32 && "Only know how to expand i32 LSS");
5727   SDOperand negOp = DAG.getNode(ISD::SUB, T,
5728                                 DAG.getConstant(0, T), Op->getOperand(2));
5729   return DAG.getAtomic(ISD::ATOMIC_LAS, Op->getOperand(0),
5730                        Op->getOperand(1), negOp, T).Val;
5731 }
5732
5733 /// LowerOperation - Provide custom lowering hooks for some operations.
5734 ///
5735 SDOperand X86TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
5736   switch (Op.getOpcode()) {
5737   default: assert(0 && "Should not custom lower this!");
5738   case ISD::ATOMIC_LCS:         return LowerLCS(Op,DAG);
5739   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
5740   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
5741   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5742   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
5743   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
5744   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
5745   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
5746   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
5747   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
5748   case ISD::SHL_PARTS:
5749   case ISD::SRA_PARTS:
5750   case ISD::SRL_PARTS:          return LowerShift(Op, DAG);
5751   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
5752   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
5753   case ISD::FABS:               return LowerFABS(Op, DAG);
5754   case ISD::FNEG:               return LowerFNEG(Op, DAG);
5755   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
5756   case ISD::SETCC:              return LowerSETCC(Op, DAG);
5757   case ISD::SELECT:             return LowerSELECT(Op, DAG);
5758   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
5759   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
5760   case ISD::CALL:               return LowerCALL(Op, DAG);
5761   case ISD::RET:                return LowerRET(Op, DAG);
5762   case ISD::FORMAL_ARGUMENTS:   return LowerFORMAL_ARGUMENTS(Op, DAG);
5763   case ISD::VASTART:            return LowerVASTART(Op, DAG);
5764   case ISD::VAARG:              return LowerVAARG(Op, DAG);
5765   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
5766   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
5767   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
5768   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
5769   case ISD::FRAME_TO_ARGS_OFFSET:
5770                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
5771   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
5772   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
5773   case ISD::TRAMPOLINE:         return LowerTRAMPOLINE(Op, DAG);
5774   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
5775   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
5776   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
5777       
5778   // FIXME: REMOVE THIS WHEN LegalizeDAGTypes lands.
5779   case ISD::READCYCLECOUNTER:
5780     return SDOperand(ExpandREADCYCLECOUNTER(Op.Val, DAG), 0);
5781   }
5782 }
5783
5784 /// ExpandOperation - Provide custom lowering hooks for expanding operations.
5785 SDNode *X86TargetLowering::ExpandOperationResult(SDNode *N, SelectionDAG &DAG) {
5786   switch (N->getOpcode()) {
5787   default: assert(0 && "Should not custom lower this!");
5788   case ISD::FP_TO_SINT:         return ExpandFP_TO_SINT(N, DAG);
5789   case ISD::READCYCLECOUNTER:   return ExpandREADCYCLECOUNTER(N, DAG);
5790   case ISD::ATOMIC_LCS:         return ExpandATOMIC_LCS(N, DAG);
5791   case ISD::ATOMIC_LSS:         return ExpandATOMIC_LSS(N,DAG);
5792   }
5793 }
5794
5795 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
5796   switch (Opcode) {
5797   default: return NULL;
5798   case X86ISD::BSF:                return "X86ISD::BSF";
5799   case X86ISD::BSR:                return "X86ISD::BSR";
5800   case X86ISD::SHLD:               return "X86ISD::SHLD";
5801   case X86ISD::SHRD:               return "X86ISD::SHRD";
5802   case X86ISD::FAND:               return "X86ISD::FAND";
5803   case X86ISD::FOR:                return "X86ISD::FOR";
5804   case X86ISD::FXOR:               return "X86ISD::FXOR";
5805   case X86ISD::FSRL:               return "X86ISD::FSRL";
5806   case X86ISD::FILD:               return "X86ISD::FILD";
5807   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
5808   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
5809   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
5810   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
5811   case X86ISD::FLD:                return "X86ISD::FLD";
5812   case X86ISD::FST:                return "X86ISD::FST";
5813   case X86ISD::CALL:               return "X86ISD::CALL";
5814   case X86ISD::TAILCALL:           return "X86ISD::TAILCALL";
5815   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
5816   case X86ISD::CMP:                return "X86ISD::CMP";
5817   case X86ISD::COMI:               return "X86ISD::COMI";
5818   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
5819   case X86ISD::SETCC:              return "X86ISD::SETCC";
5820   case X86ISD::CMOV:               return "X86ISD::CMOV";
5821   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
5822   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
5823   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
5824   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
5825   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
5826   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
5827   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
5828   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
5829   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
5830   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
5831   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
5832   case X86ISD::FMAX:               return "X86ISD::FMAX";
5833   case X86ISD::FMIN:               return "X86ISD::FMIN";
5834   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
5835   case X86ISD::FRCP:               return "X86ISD::FRCP";
5836   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
5837   case X86ISD::THREAD_POINTER:     return "X86ISD::THREAD_POINTER";
5838   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
5839   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
5840   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
5841   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
5842   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
5843   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
5844   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
5845   case X86ISD::VSHL:               return "X86ISD::VSHL";
5846   case X86ISD::VSRL:               return "X86ISD::VSRL";
5847   }
5848 }
5849
5850 // isLegalAddressingMode - Return true if the addressing mode represented
5851 // by AM is legal for this target, for a load/store of the specified type.
5852 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM, 
5853                                               const Type *Ty) const {
5854   // X86 supports extremely general addressing modes.
5855   
5856   // X86 allows a sign-extended 32-bit immediate field as a displacement.
5857   if (AM.BaseOffs <= -(1LL << 32) || AM.BaseOffs >= (1LL << 32)-1)
5858     return false;
5859   
5860   if (AM.BaseGV) {
5861     // We can only fold this if we don't need an extra load.
5862     if (Subtarget->GVRequiresExtraLoad(AM.BaseGV, getTargetMachine(), false))
5863       return false;
5864
5865     // X86-64 only supports addr of globals in small code model.
5866     if (Subtarget->is64Bit()) {
5867       if (getTargetMachine().getCodeModel() != CodeModel::Small)
5868         return false;
5869       // If lower 4G is not available, then we must use rip-relative addressing.
5870       if (AM.BaseOffs || AM.Scale > 1)
5871         return false;
5872     }
5873   }
5874   
5875   switch (AM.Scale) {
5876   case 0:
5877   case 1:
5878   case 2:
5879   case 4:
5880   case 8:
5881     // These scales always work.
5882     break;
5883   case 3:
5884   case 5:
5885   case 9:
5886     // These scales are formed with basereg+scalereg.  Only accept if there is
5887     // no basereg yet.
5888     if (AM.HasBaseReg)
5889       return false;
5890     break;
5891   default:  // Other stuff never works.
5892     return false;
5893   }
5894   
5895   return true;
5896 }
5897
5898
5899 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
5900   if (!Ty1->isInteger() || !Ty2->isInteger())
5901     return false;
5902   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
5903   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
5904   if (NumBits1 <= NumBits2)
5905     return false;
5906   return Subtarget->is64Bit() || NumBits1 < 64;
5907 }
5908
5909 bool X86TargetLowering::isTruncateFree(MVT VT1, MVT VT2) const {
5910   if (!VT1.isInteger() || !VT2.isInteger())
5911     return false;
5912   unsigned NumBits1 = VT1.getSizeInBits();
5913   unsigned NumBits2 = VT2.getSizeInBits();
5914   if (NumBits1 <= NumBits2)
5915     return false;
5916   return Subtarget->is64Bit() || NumBits1 < 64;
5917 }
5918
5919 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5920 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5921 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5922 /// are assumed to be legal.
5923 bool
5924 X86TargetLowering::isShuffleMaskLegal(SDOperand Mask, MVT VT) const {
5925   // Only do shuffles on 128-bit vector types for now.
5926   if (VT.getSizeInBits() == 64) return false;
5927   return (Mask.Val->getNumOperands() <= 4 ||
5928           isIdentityMask(Mask.Val) ||
5929           isIdentityMask(Mask.Val, true) ||
5930           isSplatMask(Mask.Val)  ||
5931           isPSHUFHW_PSHUFLWMask(Mask.Val) ||
5932           X86::isUNPCKLMask(Mask.Val) ||
5933           X86::isUNPCKHMask(Mask.Val) ||
5934           X86::isUNPCKL_v_undef_Mask(Mask.Val) ||
5935           X86::isUNPCKH_v_undef_Mask(Mask.Val));
5936 }
5937
5938 bool
5939 X86TargetLowering::isVectorClearMaskLegal(const std::vector<SDOperand> &BVOps,
5940                                           MVT EVT, SelectionDAG &DAG) const {
5941   unsigned NumElts = BVOps.size();
5942   // Only do shuffles on 128-bit vector types for now.
5943   if (EVT.getSizeInBits() * NumElts == 64) return false;
5944   if (NumElts == 2) return true;
5945   if (NumElts == 4) {
5946     return (isMOVLMask(&BVOps[0], 4)  ||
5947             isCommutedMOVL(&BVOps[0], 4, true) ||
5948             isSHUFPMask(&BVOps[0], 4) || 
5949             isCommutedSHUFP(&BVOps[0], 4));
5950   }
5951   return false;
5952 }
5953
5954 //===----------------------------------------------------------------------===//
5955 //                           X86 Scheduler Hooks
5956 //===----------------------------------------------------------------------===//
5957
5958 // private utility function
5959 MachineBasicBlock *
5960 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
5961                                                        MachineBasicBlock *MBB,
5962                                                        unsigned regOpc,
5963                                                        unsigned immOpc,
5964                                                        bool invSrc) {
5965   // For the atomic bitwise operator, we generate
5966   //   thisMBB:
5967   //   newMBB:
5968   //     ld  t1 = [bitinstr.addr]
5969   //     op  t2 = t1, [bitinstr.val]
5970   //     mov EAX = t1
5971   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
5972   //     bz  newMBB
5973   //     fallthrough -->nextMBB
5974   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5975   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
5976   ilist<MachineBasicBlock>::iterator MBBIter = MBB;
5977   ++MBBIter;
5978   
5979   /// First build the CFG
5980   MachineFunction *F = MBB->getParent();
5981   MachineBasicBlock *thisMBB = MBB;
5982   MachineBasicBlock *newMBB = new MachineBasicBlock(LLVM_BB);
5983   MachineBasicBlock *nextMBB = new MachineBasicBlock(LLVM_BB);
5984   F->getBasicBlockList().insert(MBBIter, newMBB);
5985   F->getBasicBlockList().insert(MBBIter, nextMBB);
5986   
5987   // Move all successors to thisMBB to nextMBB
5988   nextMBB->transferSuccessors(thisMBB);
5989     
5990   // Update thisMBB to fall through to newMBB
5991   thisMBB->addSuccessor(newMBB);
5992   
5993   // newMBB jumps to itself and fall through to nextMBB
5994   newMBB->addSuccessor(nextMBB);
5995   newMBB->addSuccessor(newMBB);
5996   
5997   // Insert instructions into newMBB based on incoming instruction
5998   assert(bInstr->getNumOperands() < 8 && "unexpected number of operands");
5999   MachineOperand& destOper = bInstr->getOperand(0);
6000   MachineOperand* argOpers[6];
6001   int numArgs = bInstr->getNumOperands() - 1;
6002   for (int i=0; i < numArgs; ++i)
6003     argOpers[i] = &bInstr->getOperand(i+1);
6004
6005   // x86 address has 4 operands: base, index, scale, and displacement
6006   int lastAddrIndx = 3; // [0,3]
6007   int valArgIndx = 4;
6008   
6009   unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
6010   MachineInstrBuilder MIB = BuildMI(newMBB, TII->get(X86::MOV32rm), t1);
6011   for (int i=0; i <= lastAddrIndx; ++i)
6012     (*MIB).addOperand(*argOpers[i]);
6013
6014   unsigned tt = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
6015   if (invSrc) {
6016     MIB = BuildMI(newMBB, TII->get(X86::NOT32r), tt).addReg(t1);
6017   }
6018   else 
6019     tt = t1;
6020
6021   unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
6022   assert(   (argOpers[valArgIndx]->isReg() || argOpers[valArgIndx]->isImm())
6023          && "invalid operand");
6024   if (argOpers[valArgIndx]->isReg())
6025     MIB = BuildMI(newMBB, TII->get(regOpc), t2);
6026   else
6027     MIB = BuildMI(newMBB, TII->get(immOpc), t2);
6028   MIB.addReg(tt);
6029   (*MIB).addOperand(*argOpers[valArgIndx]);
6030
6031   MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), X86::EAX);
6032   MIB.addReg(t1);
6033   
6034   MIB = BuildMI(newMBB, TII->get(X86::LCMPXCHG32));
6035   for (int i=0; i <= lastAddrIndx; ++i)
6036     (*MIB).addOperand(*argOpers[i]);
6037   MIB.addReg(t2);
6038   
6039   MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), destOper.getReg());
6040   MIB.addReg(X86::EAX);
6041   
6042   // insert branch
6043   BuildMI(newMBB, TII->get(X86::JNE)).addMBB(newMBB);
6044
6045   delete bInstr;   // The pseudo instruction is gone now.
6046   return nextMBB;
6047 }
6048
6049 // private utility function
6050 MachineBasicBlock *
6051 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
6052                                                       MachineBasicBlock *MBB,
6053                                                       unsigned cmovOpc) {
6054   // For the atomic min/max operator, we generate
6055   //   thisMBB:
6056   //   newMBB:
6057   //     ld t1 = [min/max.addr]
6058   //     mov t2 = [min/max.val] 
6059   //     cmp  t1, t2
6060   //     cmov[cond] t2 = t1
6061   //     mov EAX = t1
6062   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
6063   //     bz   newMBB
6064   //     fallthrough -->nextMBB
6065   //
6066   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6067   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
6068   ilist<MachineBasicBlock>::iterator MBBIter = MBB;
6069   ++MBBIter;
6070   
6071   /// First build the CFG
6072   MachineFunction *F = MBB->getParent();
6073   MachineBasicBlock *thisMBB = MBB;
6074   MachineBasicBlock *newMBB = new MachineBasicBlock(LLVM_BB);
6075   MachineBasicBlock *nextMBB = new MachineBasicBlock(LLVM_BB);
6076   F->getBasicBlockList().insert(MBBIter, newMBB);
6077   F->getBasicBlockList().insert(MBBIter, nextMBB);
6078   
6079   // Move all successors to thisMBB to nextMBB
6080   nextMBB->transferSuccessors(thisMBB);
6081   
6082   // Update thisMBB to fall through to newMBB
6083   thisMBB->addSuccessor(newMBB);
6084   
6085   // newMBB jumps to newMBB and fall through to nextMBB
6086   newMBB->addSuccessor(nextMBB);
6087   newMBB->addSuccessor(newMBB);
6088   
6089   // Insert instructions into newMBB based on incoming instruction
6090   assert(mInstr->getNumOperands() < 8 && "unexpected number of operands");
6091   MachineOperand& destOper = mInstr->getOperand(0);
6092   MachineOperand* argOpers[6];
6093   int numArgs = mInstr->getNumOperands() - 1;
6094   for (int i=0; i < numArgs; ++i)
6095     argOpers[i] = &mInstr->getOperand(i+1);
6096   
6097   // x86 address has 4 operands: base, index, scale, and displacement
6098   int lastAddrIndx = 3; // [0,3]
6099   int valArgIndx = 4;
6100   
6101   unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
6102   MachineInstrBuilder MIB = BuildMI(newMBB, TII->get(X86::MOV32rm), t1);
6103   for (int i=0; i <= lastAddrIndx; ++i)
6104     (*MIB).addOperand(*argOpers[i]);
6105
6106   // We only support register and immediate values
6107   assert(   (argOpers[valArgIndx]->isReg() || argOpers[valArgIndx]->isImm())
6108          && "invalid operand");
6109   
6110   unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);  
6111   if (argOpers[valArgIndx]->isReg())
6112     MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), t2);
6113   else 
6114     MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), t2);
6115   (*MIB).addOperand(*argOpers[valArgIndx]);
6116
6117   MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), X86::EAX);
6118   MIB.addReg(t1);
6119
6120   MIB = BuildMI(newMBB, TII->get(X86::CMP32rr));
6121   MIB.addReg(t1);
6122   MIB.addReg(t2);
6123
6124   // Generate movc
6125   unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
6126   MIB = BuildMI(newMBB, TII->get(cmovOpc),t3);
6127   MIB.addReg(t2);
6128   MIB.addReg(t1);
6129
6130   // Cmp and exchange if none has modified the memory location
6131   MIB = BuildMI(newMBB, TII->get(X86::LCMPXCHG32));
6132   for (int i=0; i <= lastAddrIndx; ++i)
6133     (*MIB).addOperand(*argOpers[i]);
6134   MIB.addReg(t3);
6135   
6136   MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), destOper.getReg());
6137   MIB.addReg(X86::EAX);
6138   
6139   // insert branch
6140   BuildMI(newMBB, TII->get(X86::JNE)).addMBB(newMBB);
6141
6142   delete mInstr;   // The pseudo instruction is gone now.
6143   return nextMBB;
6144 }
6145
6146
6147 MachineBasicBlock *
6148 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
6149                                                MachineBasicBlock *BB) {
6150   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6151   switch (MI->getOpcode()) {
6152   default: assert(false && "Unexpected instr type to insert");
6153   case X86::CMOV_FR32:
6154   case X86::CMOV_FR64:
6155   case X86::CMOV_V4F32:
6156   case X86::CMOV_V2F64:
6157   case X86::CMOV_V2I64: {
6158     // To "insert" a SELECT_CC instruction, we actually have to insert the
6159     // diamond control-flow pattern.  The incoming instruction knows the
6160     // destination vreg to set, the condition code register to branch on, the
6161     // true/false values to select between, and a branch opcode to use.
6162     const BasicBlock *LLVM_BB = BB->getBasicBlock();
6163     ilist<MachineBasicBlock>::iterator It = BB;
6164     ++It;
6165
6166     //  thisMBB:
6167     //  ...
6168     //   TrueVal = ...
6169     //   cmpTY ccX, r1, r2
6170     //   bCC copy1MBB
6171     //   fallthrough --> copy0MBB
6172     MachineBasicBlock *thisMBB = BB;
6173     MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
6174     MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
6175     unsigned Opc =
6176       X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
6177     BuildMI(BB, TII->get(Opc)).addMBB(sinkMBB);
6178     MachineFunction *F = BB->getParent();
6179     F->getBasicBlockList().insert(It, copy0MBB);
6180     F->getBasicBlockList().insert(It, sinkMBB);
6181     // Update machine-CFG edges by transferring all successors of the current
6182     // block to the new block which will contain the Phi node for the select.
6183     sinkMBB->transferSuccessors(BB);
6184
6185     // Add the true and fallthrough blocks as its successors.
6186     BB->addSuccessor(copy0MBB);
6187     BB->addSuccessor(sinkMBB);
6188
6189     //  copy0MBB:
6190     //   %FalseValue = ...
6191     //   # fallthrough to sinkMBB
6192     BB = copy0MBB;
6193
6194     // Update machine-CFG edges
6195     BB->addSuccessor(sinkMBB);
6196
6197     //  sinkMBB:
6198     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
6199     //  ...
6200     BB = sinkMBB;
6201     BuildMI(BB, TII->get(X86::PHI), MI->getOperand(0).getReg())
6202       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
6203       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
6204
6205     delete MI;   // The pseudo instruction is gone now.
6206     return BB;
6207   }
6208
6209   case X86::FP32_TO_INT16_IN_MEM:
6210   case X86::FP32_TO_INT32_IN_MEM:
6211   case X86::FP32_TO_INT64_IN_MEM:
6212   case X86::FP64_TO_INT16_IN_MEM:
6213   case X86::FP64_TO_INT32_IN_MEM:
6214   case X86::FP64_TO_INT64_IN_MEM:
6215   case X86::FP80_TO_INT16_IN_MEM:
6216   case X86::FP80_TO_INT32_IN_MEM:
6217   case X86::FP80_TO_INT64_IN_MEM: {
6218     // Change the floating point control register to use "round towards zero"
6219     // mode when truncating to an integer value.
6220     MachineFunction *F = BB->getParent();
6221     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
6222     addFrameReference(BuildMI(BB, TII->get(X86::FNSTCW16m)), CWFrameIdx);
6223
6224     // Load the old value of the high byte of the control word...
6225     unsigned OldCW =
6226       F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
6227     addFrameReference(BuildMI(BB, TII->get(X86::MOV16rm), OldCW), CWFrameIdx);
6228
6229     // Set the high part to be round to zero...
6230     addFrameReference(BuildMI(BB, TII->get(X86::MOV16mi)), CWFrameIdx)
6231       .addImm(0xC7F);
6232
6233     // Reload the modified control word now...
6234     addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
6235
6236     // Restore the memory image of control word to original value
6237     addFrameReference(BuildMI(BB, TII->get(X86::MOV16mr)), CWFrameIdx)
6238       .addReg(OldCW);
6239
6240     // Get the X86 opcode to use.
6241     unsigned Opc;
6242     switch (MI->getOpcode()) {
6243     default: assert(0 && "illegal opcode!");
6244     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
6245     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
6246     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
6247     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
6248     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
6249     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
6250     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
6251     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
6252     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
6253     }
6254
6255     X86AddressMode AM;
6256     MachineOperand &Op = MI->getOperand(0);
6257     if (Op.isRegister()) {
6258       AM.BaseType = X86AddressMode::RegBase;
6259       AM.Base.Reg = Op.getReg();
6260     } else {
6261       AM.BaseType = X86AddressMode::FrameIndexBase;
6262       AM.Base.FrameIndex = Op.getIndex();
6263     }
6264     Op = MI->getOperand(1);
6265     if (Op.isImmediate())
6266       AM.Scale = Op.getImm();
6267     Op = MI->getOperand(2);
6268     if (Op.isImmediate())
6269       AM.IndexReg = Op.getImm();
6270     Op = MI->getOperand(3);
6271     if (Op.isGlobalAddress()) {
6272       AM.GV = Op.getGlobal();
6273     } else {
6274       AM.Disp = Op.getImm();
6275     }
6276     addFullAddress(BuildMI(BB, TII->get(Opc)), AM)
6277                       .addReg(MI->getOperand(4).getReg());
6278
6279     // Reload the original control word now.
6280     addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
6281
6282     delete MI;   // The pseudo instruction is gone now.
6283     return BB;
6284   }
6285   case X86::ATOMAND32:
6286     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
6287                                                        X86::AND32ri);
6288   case X86::ATOMOR32:
6289     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr, 
6290                                                        X86::OR32ri);
6291   case X86::ATOMXOR32:
6292     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
6293                                                        X86::XOR32ri);
6294   case X86::ATOMNAND32:
6295     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
6296                                                X86::AND32ri, true);
6297   case X86::ATOMMIN32:
6298     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
6299   case X86::ATOMMAX32:
6300     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
6301   case X86::ATOMUMIN32:
6302     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
6303   case X86::ATOMUMAX32:
6304     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
6305   }
6306 }
6307
6308 //===----------------------------------------------------------------------===//
6309 //                           X86 Optimization Hooks
6310 //===----------------------------------------------------------------------===//
6311
6312 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDOperand Op,
6313                                                        const APInt &Mask,
6314                                                        APInt &KnownZero,
6315                                                        APInt &KnownOne,
6316                                                        const SelectionDAG &DAG,
6317                                                        unsigned Depth) const {
6318   unsigned Opc = Op.getOpcode();
6319   assert((Opc >= ISD::BUILTIN_OP_END ||
6320           Opc == ISD::INTRINSIC_WO_CHAIN ||
6321           Opc == ISD::INTRINSIC_W_CHAIN ||
6322           Opc == ISD::INTRINSIC_VOID) &&
6323          "Should use MaskedValueIsZero if you don't know whether Op"
6324          " is a target node!");
6325
6326   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
6327   switch (Opc) {
6328   default: break;
6329   case X86ISD::SETCC:
6330     KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
6331                                        Mask.getBitWidth() - 1);
6332     break;
6333   }
6334 }
6335
6336 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
6337 /// node is a GlobalAddress + offset.
6338 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
6339                                        GlobalValue* &GA, int64_t &Offset) const{
6340   if (N->getOpcode() == X86ISD::Wrapper) {
6341     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
6342       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
6343       return true;
6344     }
6345   }
6346   return TargetLowering::isGAPlusOffset(N, GA, Offset);
6347 }
6348
6349 static bool isBaseAlignmentOfN(unsigned N, SDNode *Base,
6350                                const TargetLowering &TLI) {
6351   GlobalValue *GV;
6352   int64_t Offset = 0;
6353   if (TLI.isGAPlusOffset(Base, GV, Offset))
6354     return (GV->getAlignment() >= N && (Offset % N) == 0);
6355   // DAG combine handles the stack object case.
6356   return false;
6357 }
6358
6359 static bool EltsFromConsecutiveLoads(SDNode *N, SDOperand PermMask,
6360                                      unsigned NumElems, MVT EVT,
6361                                      SDNode *&Base,
6362                                      SelectionDAG &DAG, MachineFrameInfo *MFI,
6363                                      const TargetLowering &TLI) {
6364   Base = NULL;
6365   for (unsigned i = 0; i < NumElems; ++i) {
6366     SDOperand Idx = PermMask.getOperand(i);
6367     if (Idx.getOpcode() == ISD::UNDEF) {
6368       if (!Base)
6369         return false;
6370       continue;
6371     }
6372
6373     unsigned Index = cast<ConstantSDNode>(Idx)->getValue();
6374     SDOperand Elt = DAG.getShuffleScalarElt(N, Index);
6375     if (!Elt.Val ||
6376         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.Val)))
6377       return false;
6378     if (!Base) {
6379       Base = Elt.Val;
6380       if (Base->getOpcode() == ISD::UNDEF)
6381         return false;
6382       continue;
6383     }
6384     if (Elt.getOpcode() == ISD::UNDEF)
6385       continue;
6386
6387     if (!TLI.isConsecutiveLoad(Elt.Val, Base,
6388                                EVT.getSizeInBits()/8, i, MFI))
6389       return false;
6390   }
6391   return true;
6392 }
6393
6394 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
6395 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
6396 /// if the load addresses are consecutive, non-overlapping, and in the right
6397 /// order.
6398 static SDOperand PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
6399                                        const TargetLowering &TLI) {
6400   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6401   MVT VT = N->getValueType(0);
6402   MVT EVT = VT.getVectorElementType();
6403   SDOperand PermMask = N->getOperand(2);
6404   unsigned NumElems = PermMask.getNumOperands();
6405   SDNode *Base = NULL;
6406   if (!EltsFromConsecutiveLoads(N, PermMask, NumElems, EVT, Base,
6407                                 DAG, MFI, TLI))
6408     return SDOperand();
6409
6410   LoadSDNode *LD = cast<LoadSDNode>(Base);
6411   if (isBaseAlignmentOfN(16, Base->getOperand(1).Val, TLI))
6412     return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
6413                        LD->getSrcValueOffset(), LD->isVolatile());
6414   return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
6415                      LD->getSrcValueOffset(), LD->isVolatile(),
6416                      LD->getAlignment());
6417 }
6418
6419 /// PerformBuildVectorCombine - build_vector 0,(load i64 / f64) -> movq / movsd.
6420 static SDOperand PerformBuildVectorCombine(SDNode *N, SelectionDAG &DAG,
6421                                            const X86Subtarget *Subtarget,
6422                                            const TargetLowering &TLI) {
6423   unsigned NumOps = N->getNumOperands();
6424
6425   // Ignore single operand BUILD_VECTOR.
6426   if (NumOps == 1)
6427     return SDOperand();
6428
6429   MVT VT = N->getValueType(0);
6430   MVT EVT = VT.getVectorElementType();
6431   if ((EVT != MVT::i64 && EVT != MVT::f64) || Subtarget->is64Bit())
6432     // We are looking for load i64 and zero extend. We want to transform
6433     // it before legalizer has a chance to expand it. Also look for i64
6434     // BUILD_PAIR bit casted to f64.
6435     return SDOperand();
6436   // This must be an insertion into a zero vector.
6437   SDOperand HighElt = N->getOperand(1);
6438   if (!isZeroNode(HighElt))
6439     return SDOperand();
6440
6441   // Value must be a load.
6442   SDNode *Base = N->getOperand(0).Val;
6443   if (!isa<LoadSDNode>(Base)) {
6444     if (Base->getOpcode() != ISD::BIT_CONVERT)
6445       return SDOperand();
6446     Base = Base->getOperand(0).Val;
6447     if (!isa<LoadSDNode>(Base))
6448       return SDOperand();
6449   }
6450
6451   // Transform it into VZEXT_LOAD addr.
6452   LoadSDNode *LD = cast<LoadSDNode>(Base);
6453   
6454   // Load must not be an extload.
6455   if (LD->getExtensionType() != ISD::NON_EXTLOAD)
6456     return SDOperand();
6457   
6458   return DAG.getNode(X86ISD::VZEXT_LOAD, VT, LD->getChain(), LD->getBasePtr());
6459 }                                           
6460
6461 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
6462 static SDOperand PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
6463                                       const X86Subtarget *Subtarget) {
6464   SDOperand Cond = N->getOperand(0);
6465
6466   // If we have SSE[12] support, try to form min/max nodes.
6467   if (Subtarget->hasSSE2() &&
6468       (N->getValueType(0) == MVT::f32 || N->getValueType(0) == MVT::f64)) {
6469     if (Cond.getOpcode() == ISD::SETCC) {
6470       // Get the LHS/RHS of the select.
6471       SDOperand LHS = N->getOperand(1);
6472       SDOperand RHS = N->getOperand(2);
6473       ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
6474
6475       unsigned Opcode = 0;
6476       if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
6477         switch (CC) {
6478         default: break;
6479         case ISD::SETOLE: // (X <= Y) ? X : Y -> min
6480         case ISD::SETULE:
6481         case ISD::SETLE:
6482           if (!UnsafeFPMath) break;
6483           // FALL THROUGH.
6484         case ISD::SETOLT:  // (X olt/lt Y) ? X : Y -> min
6485         case ISD::SETLT:
6486           Opcode = X86ISD::FMIN;
6487           break;
6488
6489         case ISD::SETOGT: // (X > Y) ? X : Y -> max
6490         case ISD::SETUGT:
6491         case ISD::SETGT:
6492           if (!UnsafeFPMath) break;
6493           // FALL THROUGH.
6494         case ISD::SETUGE:  // (X uge/ge Y) ? X : Y -> max
6495         case ISD::SETGE:
6496           Opcode = X86ISD::FMAX;
6497           break;
6498         }
6499       } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
6500         switch (CC) {
6501         default: break;
6502         case ISD::SETOGT: // (X > Y) ? Y : X -> min
6503         case ISD::SETUGT:
6504         case ISD::SETGT:
6505           if (!UnsafeFPMath) break;
6506           // FALL THROUGH.
6507         case ISD::SETUGE:  // (X uge/ge Y) ? Y : X -> min
6508         case ISD::SETGE:
6509           Opcode = X86ISD::FMIN;
6510           break;
6511
6512         case ISD::SETOLE:   // (X <= Y) ? Y : X -> max
6513         case ISD::SETULE:
6514         case ISD::SETLE:
6515           if (!UnsafeFPMath) break;
6516           // FALL THROUGH.
6517         case ISD::SETOLT:   // (X olt/lt Y) ? Y : X -> max
6518         case ISD::SETLT:
6519           Opcode = X86ISD::FMAX;
6520           break;
6521         }
6522       }
6523
6524       if (Opcode)
6525         return DAG.getNode(Opcode, N->getValueType(0), LHS, RHS);
6526     }
6527
6528   }
6529
6530   return SDOperand();
6531 }
6532
6533 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
6534 static SDOperand PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
6535                                      const X86Subtarget *Subtarget) {
6536   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
6537   // the FP state in cases where an emms may be missing.
6538   // A preferable solution to the general problem is to figure out the right
6539   // places to insert EMMS.  This qualifies as a quick hack.
6540   StoreSDNode *St = cast<StoreSDNode>(N);
6541   if (St->getValue().getValueType().isVector() &&
6542       St->getValue().getValueType().getSizeInBits() == 64 &&
6543       isa<LoadSDNode>(St->getValue()) &&
6544       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
6545       St->getChain().hasOneUse() && !St->isVolatile()) {
6546     SDNode* LdVal = St->getValue().Val;
6547     LoadSDNode *Ld = 0;
6548     int TokenFactorIndex = -1;
6549     SmallVector<SDOperand, 8> Ops;
6550     SDNode* ChainVal = St->getChain().Val;
6551     // Must be a store of a load.  We currently handle two cases:  the load
6552     // is a direct child, and it's under an intervening TokenFactor.  It is
6553     // possible to dig deeper under nested TokenFactors.
6554     if (ChainVal == LdVal)
6555       Ld = cast<LoadSDNode>(St->getChain());
6556     else if (St->getValue().hasOneUse() &&
6557              ChainVal->getOpcode() == ISD::TokenFactor) {
6558       for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
6559         if (ChainVal->getOperand(i).Val == LdVal) {
6560           TokenFactorIndex = i;
6561           Ld = cast<LoadSDNode>(St->getValue());
6562         } else
6563           Ops.push_back(ChainVal->getOperand(i));
6564       }
6565     }
6566     if (Ld) {
6567       // If we are a 64-bit capable x86, lower to a single movq load/store pair.
6568       if (Subtarget->is64Bit()) {
6569         SDOperand NewLd = DAG.getLoad(MVT::i64, Ld->getChain(), 
6570                                       Ld->getBasePtr(), Ld->getSrcValue(), 
6571                                       Ld->getSrcValueOffset(), Ld->isVolatile(),
6572                                       Ld->getAlignment());
6573         SDOperand NewChain = NewLd.getValue(1);
6574         if (TokenFactorIndex != -1) {
6575           Ops.push_back(NewChain);
6576           NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0], 
6577                                  Ops.size());
6578         }
6579         return DAG.getStore(NewChain, NewLd, St->getBasePtr(),
6580                             St->getSrcValue(), St->getSrcValueOffset(),
6581                             St->isVolatile(), St->getAlignment());
6582       }
6583
6584       // Otherwise, lower to two 32-bit copies.
6585       SDOperand LoAddr = Ld->getBasePtr();
6586       SDOperand HiAddr = DAG.getNode(ISD::ADD, MVT::i32, LoAddr,
6587                                      DAG.getConstant(4, MVT::i32));
6588
6589       SDOperand LoLd = DAG.getLoad(MVT::i32, Ld->getChain(), LoAddr,
6590                                    Ld->getSrcValue(), Ld->getSrcValueOffset(),
6591                                    Ld->isVolatile(), Ld->getAlignment());
6592       SDOperand HiLd = DAG.getLoad(MVT::i32, Ld->getChain(), HiAddr,
6593                                    Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
6594                                    Ld->isVolatile(), 
6595                                    MinAlign(Ld->getAlignment(), 4));
6596
6597       SDOperand NewChain = LoLd.getValue(1);
6598       if (TokenFactorIndex != -1) {
6599         Ops.push_back(LoLd);
6600         Ops.push_back(HiLd);
6601         NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0], 
6602                                Ops.size());
6603       }
6604
6605       LoAddr = St->getBasePtr();
6606       HiAddr = DAG.getNode(ISD::ADD, MVT::i32, LoAddr,
6607                            DAG.getConstant(4, MVT::i32));
6608
6609       SDOperand LoSt = DAG.getStore(NewChain, LoLd, LoAddr,
6610                           St->getSrcValue(), St->getSrcValueOffset(),
6611                           St->isVolatile(), St->getAlignment());
6612       SDOperand HiSt = DAG.getStore(NewChain, HiLd, HiAddr,
6613                                     St->getSrcValue(), St->getSrcValueOffset()+4,
6614                                     St->isVolatile(), 
6615                                     MinAlign(St->getAlignment(), 4));
6616       return DAG.getNode(ISD::TokenFactor, MVT::Other, LoSt, HiSt);
6617     }
6618   }
6619   return SDOperand();
6620 }
6621
6622 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
6623 /// X86ISD::FXOR nodes.
6624 static SDOperand PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
6625   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
6626   // F[X]OR(0.0, x) -> x
6627   // F[X]OR(x, 0.0) -> x
6628   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
6629     if (C->getValueAPF().isPosZero())
6630       return N->getOperand(1);
6631   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
6632     if (C->getValueAPF().isPosZero())
6633       return N->getOperand(0);
6634   return SDOperand();
6635 }
6636
6637 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
6638 static SDOperand PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
6639   // FAND(0.0, x) -> 0.0
6640   // FAND(x, 0.0) -> 0.0
6641   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
6642     if (C->getValueAPF().isPosZero())
6643       return N->getOperand(0);
6644   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
6645     if (C->getValueAPF().isPosZero())
6646       return N->getOperand(1);
6647   return SDOperand();
6648 }
6649
6650
6651 SDOperand X86TargetLowering::PerformDAGCombine(SDNode *N,
6652                                                DAGCombinerInfo &DCI) const {
6653   SelectionDAG &DAG = DCI.DAG;
6654   switch (N->getOpcode()) {
6655   default: break;
6656   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
6657   case ISD::BUILD_VECTOR:
6658     return PerformBuildVectorCombine(N, DAG, Subtarget, *this);
6659   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
6660   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
6661   case X86ISD::FXOR:
6662   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
6663   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
6664   }
6665
6666   return SDOperand();
6667 }
6668
6669 //===----------------------------------------------------------------------===//
6670 //                           X86 Inline Assembly Support
6671 //===----------------------------------------------------------------------===//
6672
6673 /// getConstraintType - Given a constraint letter, return the type of
6674 /// constraint it is for this target.
6675 X86TargetLowering::ConstraintType
6676 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
6677   if (Constraint.size() == 1) {
6678     switch (Constraint[0]) {
6679     case 'A':
6680     case 'f':
6681     case 'r':
6682     case 'R':
6683     case 'l':
6684     case 'q':
6685     case 'Q':
6686     case 'x':
6687     case 'y':
6688     case 'Y':
6689       return C_RegisterClass;
6690     default:
6691       break;
6692     }
6693   }
6694   return TargetLowering::getConstraintType(Constraint);
6695 }
6696
6697 /// LowerXConstraint - try to replace an X constraint, which matches anything,
6698 /// with another that has more specific requirements based on the type of the
6699 /// corresponding operand.
6700 const char *X86TargetLowering::
6701 LowerXConstraint(MVT ConstraintVT) const {
6702   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
6703   // 'f' like normal targets.
6704   if (ConstraintVT.isFloatingPoint()) {
6705     if (Subtarget->hasSSE2())
6706       return "Y";
6707     if (Subtarget->hasSSE1())
6708       return "x";
6709   }
6710   
6711   return TargetLowering::LowerXConstraint(ConstraintVT);
6712 }
6713
6714 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
6715 /// vector.  If it is invalid, don't add anything to Ops.
6716 void X86TargetLowering::LowerAsmOperandForConstraint(SDOperand Op,
6717                                                      char Constraint,
6718                                                      std::vector<SDOperand>&Ops,
6719                                                      SelectionDAG &DAG) const {
6720   SDOperand Result(0, 0);
6721   
6722   switch (Constraint) {
6723   default: break;
6724   case 'I':
6725     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
6726       if (C->getValue() <= 31) {
6727         Result = DAG.getTargetConstant(C->getValue(), Op.getValueType());
6728         break;
6729       }
6730     }
6731     return;
6732   case 'N':
6733     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
6734       if (C->getValue() <= 255) {
6735         Result = DAG.getTargetConstant(C->getValue(), Op.getValueType());
6736         break;
6737       }
6738     }
6739     return;
6740   case 'i': {
6741     // Literal immediates are always ok.
6742     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
6743       Result = DAG.getTargetConstant(CST->getValue(), Op.getValueType());
6744       break;
6745     }
6746
6747     // If we are in non-pic codegen mode, we allow the address of a global (with
6748     // an optional displacement) to be used with 'i'.
6749     GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
6750     int64_t Offset = 0;
6751     
6752     // Match either (GA) or (GA+C)
6753     if (GA) {
6754       Offset = GA->getOffset();
6755     } else if (Op.getOpcode() == ISD::ADD) {
6756       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6757       GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
6758       if (C && GA) {
6759         Offset = GA->getOffset()+C->getValue();
6760       } else {
6761         C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6762         GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
6763         if (C && GA)
6764           Offset = GA->getOffset()+C->getValue();
6765         else
6766           C = 0, GA = 0;
6767       }
6768     }
6769     
6770     if (GA) {
6771       // If addressing this global requires a load (e.g. in PIC mode), we can't
6772       // match.
6773       if (Subtarget->GVRequiresExtraLoad(GA->getGlobal(), getTargetMachine(),
6774                                          false))
6775         return;
6776
6777       Op = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
6778                                       Offset);
6779       Result = Op;
6780       break;
6781     }
6782
6783     // Otherwise, not valid for this mode.
6784     return;
6785   }
6786   }
6787   
6788   if (Result.Val) {
6789     Ops.push_back(Result);
6790     return;
6791   }
6792   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
6793 }
6794
6795 std::vector<unsigned> X86TargetLowering::
6796 getRegClassForInlineAsmConstraint(const std::string &Constraint,
6797                                   MVT VT) const {
6798   if (Constraint.size() == 1) {
6799     // FIXME: not handling fp-stack yet!
6800     switch (Constraint[0]) {      // GCC X86 Constraint Letters
6801     default: break;  // Unknown constraint letter
6802     case 'A':   // EAX/EDX
6803       if (VT == MVT::i32 || VT == MVT::i64)
6804         return make_vector<unsigned>(X86::EAX, X86::EDX, 0);
6805       break;
6806     case 'q':   // Q_REGS (GENERAL_REGS in 64-bit mode)
6807     case 'Q':   // Q_REGS
6808       if (VT == MVT::i32)
6809         return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
6810       else if (VT == MVT::i16)
6811         return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
6812       else if (VT == MVT::i8)
6813         return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
6814       else if (VT == MVT::i64)
6815         return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
6816       break;
6817     }
6818   }
6819
6820   return std::vector<unsigned>();
6821 }
6822
6823 std::pair<unsigned, const TargetRegisterClass*>
6824 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
6825                                                 MVT VT) const {
6826   // First, see if this is a constraint that directly corresponds to an LLVM
6827   // register class.
6828   if (Constraint.size() == 1) {
6829     // GCC Constraint Letters
6830     switch (Constraint[0]) {
6831     default: break;
6832     case 'r':   // GENERAL_REGS
6833     case 'R':   // LEGACY_REGS
6834     case 'l':   // INDEX_REGS
6835       if (VT == MVT::i64 && Subtarget->is64Bit())
6836         return std::make_pair(0U, X86::GR64RegisterClass);
6837       if (VT == MVT::i32)
6838         return std::make_pair(0U, X86::GR32RegisterClass);
6839       else if (VT == MVT::i16)
6840         return std::make_pair(0U, X86::GR16RegisterClass);
6841       else if (VT == MVT::i8)
6842         return std::make_pair(0U, X86::GR8RegisterClass);
6843       break;
6844     case 'f':  // FP Stack registers.
6845       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
6846       // value to the correct fpstack register class.
6847       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
6848         return std::make_pair(0U, X86::RFP32RegisterClass);
6849       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
6850         return std::make_pair(0U, X86::RFP64RegisterClass);
6851       return std::make_pair(0U, X86::RFP80RegisterClass);
6852     case 'y':   // MMX_REGS if MMX allowed.
6853       if (!Subtarget->hasMMX()) break;
6854       return std::make_pair(0U, X86::VR64RegisterClass);
6855       break;
6856     case 'Y':   // SSE_REGS if SSE2 allowed
6857       if (!Subtarget->hasSSE2()) break;
6858       // FALL THROUGH.
6859     case 'x':   // SSE_REGS if SSE1 allowed
6860       if (!Subtarget->hasSSE1()) break;
6861
6862       switch (VT.getSimpleVT()) {
6863       default: break;
6864       // Scalar SSE types.
6865       case MVT::f32:
6866       case MVT::i32:
6867         return std::make_pair(0U, X86::FR32RegisterClass);
6868       case MVT::f64:
6869       case MVT::i64:
6870         return std::make_pair(0U, X86::FR64RegisterClass);
6871       // Vector types.
6872       case MVT::v16i8:
6873       case MVT::v8i16:
6874       case MVT::v4i32:
6875       case MVT::v2i64:
6876       case MVT::v4f32:
6877       case MVT::v2f64:
6878         return std::make_pair(0U, X86::VR128RegisterClass);
6879       }
6880       break;
6881     }
6882   }
6883   
6884   // Use the default implementation in TargetLowering to convert the register
6885   // constraint into a member of a register class.
6886   std::pair<unsigned, const TargetRegisterClass*> Res;
6887   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
6888
6889   // Not found as a standard register?
6890   if (Res.second == 0) {
6891     // GCC calls "st(0)" just plain "st".
6892     if (StringsEqualNoCase("{st}", Constraint)) {
6893       Res.first = X86::ST0;
6894       Res.second = X86::RFP80RegisterClass;
6895     }
6896
6897     return Res;
6898   }
6899
6900   // Otherwise, check to see if this is a register class of the wrong value
6901   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
6902   // turn into {ax},{dx}.
6903   if (Res.second->hasType(VT))
6904     return Res;   // Correct type already, nothing to do.
6905
6906   // All of the single-register GCC register classes map their values onto
6907   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
6908   // really want an 8-bit or 32-bit register, map to the appropriate register
6909   // class and return the appropriate register.
6910   if (Res.second != X86::GR16RegisterClass)
6911     return Res;
6912
6913   if (VT == MVT::i8) {
6914     unsigned DestReg = 0;
6915     switch (Res.first) {
6916     default: break;
6917     case X86::AX: DestReg = X86::AL; break;
6918     case X86::DX: DestReg = X86::DL; break;
6919     case X86::CX: DestReg = X86::CL; break;
6920     case X86::BX: DestReg = X86::BL; break;
6921     }
6922     if (DestReg) {
6923       Res.first = DestReg;
6924       Res.second = Res.second = X86::GR8RegisterClass;
6925     }
6926   } else if (VT == MVT::i32) {
6927     unsigned DestReg = 0;
6928     switch (Res.first) {
6929     default: break;
6930     case X86::AX: DestReg = X86::EAX; break;
6931     case X86::DX: DestReg = X86::EDX; break;
6932     case X86::CX: DestReg = X86::ECX; break;
6933     case X86::BX: DestReg = X86::EBX; break;
6934     case X86::SI: DestReg = X86::ESI; break;
6935     case X86::DI: DestReg = X86::EDI; break;
6936     case X86::BP: DestReg = X86::EBP; break;
6937     case X86::SP: DestReg = X86::ESP; break;
6938     }
6939     if (DestReg) {
6940       Res.first = DestReg;
6941       Res.second = Res.second = X86::GR32RegisterClass;
6942     }
6943   } else if (VT == MVT::i64) {
6944     unsigned DestReg = 0;
6945     switch (Res.first) {
6946     default: break;
6947     case X86::AX: DestReg = X86::RAX; break;
6948     case X86::DX: DestReg = X86::RDX; break;
6949     case X86::CX: DestReg = X86::RCX; break;
6950     case X86::BX: DestReg = X86::RBX; break;
6951     case X86::SI: DestReg = X86::RSI; break;
6952     case X86::DI: DestReg = X86::RDI; break;
6953     case X86::BP: DestReg = X86::RBP; break;
6954     case X86::SP: DestReg = X86::RSP; break;
6955     }
6956     if (DestReg) {
6957       Res.first = DestReg;
6958       Res.second = Res.second = X86::GR64RegisterClass;
6959     }
6960   }
6961
6962   return Res;
6963 }