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