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