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