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