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