9db0288c4e38b252ba487489507f5c7c0a1bbaa0
[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   if (Subtarget->is64Bit())
210     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
211   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
212   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
213   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
214   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
215   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
216   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
217   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
218   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
219   
220   setOperationAction(ISD::CTPOP            , MVT::i8   , Expand);
221   setOperationAction(ISD::CTTZ             , MVT::i8   , Custom);
222   setOperationAction(ISD::CTLZ             , MVT::i8   , Custom);
223   setOperationAction(ISD::CTPOP            , MVT::i16  , Expand);
224   setOperationAction(ISD::CTTZ             , MVT::i16  , Custom);
225   setOperationAction(ISD::CTLZ             , MVT::i16  , Custom);
226   setOperationAction(ISD::CTPOP            , MVT::i32  , Expand);
227   setOperationAction(ISD::CTTZ             , MVT::i32  , Custom);
228   setOperationAction(ISD::CTLZ             , MVT::i32  , Custom);
229   if (Subtarget->is64Bit()) {
230     setOperationAction(ISD::CTPOP          , MVT::i64  , Expand);
231     setOperationAction(ISD::CTTZ           , MVT::i64  , Custom);
232     setOperationAction(ISD::CTLZ           , MVT::i64  , Custom);
233   }
234
235   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
236   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
237
238   // These should be promoted to a larger select which is supported.
239   setOperationAction(ISD::SELECT           , MVT::i1   , Promote);
240   setOperationAction(ISD::SELECT           , MVT::i8   , Promote);
241   // X86 wants to expand cmov itself.
242   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
243   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
244   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
245   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
246   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
247   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
248   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
249   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
250   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
251   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
252   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
253   if (Subtarget->is64Bit()) {
254     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
255     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
256   }
257   // X86 ret instruction may pop stack.
258   setOperationAction(ISD::RET             , MVT::Other, Custom);
259   if (!Subtarget->is64Bit())
260     setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
261
262   // Darwin ABI issue.
263   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
264   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
265   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
266   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
267   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
268   if (Subtarget->is64Bit()) {
269     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
270     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
271     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
272     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
273   }
274   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
275   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
276   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
277   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
278   if (Subtarget->is64Bit()) {
279     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
280     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
281     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
282   }
283
284   if (Subtarget->hasSSE1())
285     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
286
287   if (!Subtarget->hasSSE2())
288     setOperationAction(ISD::MEMBARRIER    , MVT::Other, Expand);
289
290   setOperationAction(ISD::ATOMIC_LCS     , MVT::i8, Custom);
291   setOperationAction(ISD::ATOMIC_LCS     , MVT::i16, Custom);
292   setOperationAction(ISD::ATOMIC_LCS     , MVT::i32, Custom);
293   setOperationAction(ISD::ATOMIC_LCS     , MVT::i64, Custom);
294
295   // Use the default ISD::LOCATION, ISD::DECLARE expansion.
296   setOperationAction(ISD::LOCATION, MVT::Other, Expand);
297   // FIXME - use subtarget debug flags
298   if (!Subtarget->isTargetDarwin() &&
299       !Subtarget->isTargetELF() &&
300       !Subtarget->isTargetCygMing())
301     setOperationAction(ISD::LABEL, MVT::Other, Expand);
302
303   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
304   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
305   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
306   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
307   if (Subtarget->is64Bit()) {
308     // FIXME: Verify
309     setExceptionPointerRegister(X86::RAX);
310     setExceptionSelectorRegister(X86::RDX);
311   } else {
312     setExceptionPointerRegister(X86::EAX);
313     setExceptionSelectorRegister(X86::EDX);
314   }
315   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
316   
317   setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
318
319   setOperationAction(ISD::TRAP, MVT::Other, Legal);
320
321   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
322   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
323   setOperationAction(ISD::VAARG             , MVT::Other, Expand);
324   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
325   if (Subtarget->is64Bit())
326     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
327   else
328     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
329
330   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
331   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
332   if (Subtarget->is64Bit())
333     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
334   if (Subtarget->isTargetCygMing())
335     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
336   else
337     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
338
339   if (X86ScalarSSEf64) {
340     // f32 and f64 use SSE.
341     // Set up the FP register classes.
342     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
343     addRegisterClass(MVT::f64, X86::FR64RegisterClass);
344
345     // Use ANDPD to simulate FABS.
346     setOperationAction(ISD::FABS , MVT::f64, Custom);
347     setOperationAction(ISD::FABS , MVT::f32, Custom);
348
349     // Use XORP to simulate FNEG.
350     setOperationAction(ISD::FNEG , MVT::f64, Custom);
351     setOperationAction(ISD::FNEG , MVT::f32, Custom);
352
353     // Use ANDPD and ORPD to simulate FCOPYSIGN.
354     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
355     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
356
357     // We don't support sin/cos/fmod
358     setOperationAction(ISD::FSIN , MVT::f64, Expand);
359     setOperationAction(ISD::FCOS , MVT::f64, Expand);
360     setOperationAction(ISD::FSIN , MVT::f32, Expand);
361     setOperationAction(ISD::FCOS , MVT::f32, Expand);
362
363     // Expand FP immediates into loads from the stack, except for the special
364     // cases we handle.
365     addLegalFPImmediate(APFloat(+0.0)); // xorpd
366     addLegalFPImmediate(APFloat(+0.0f)); // xorps
367
368     // Floating truncations from f80 and extensions to f80 go through memory.
369     // If optimizing, we lie about this though and handle it in
370     // InstructionSelectPreprocess so that dagcombine2 can hack on these.
371     if (Fast) {
372       setConvertAction(MVT::f32, MVT::f80, Expand);
373       setConvertAction(MVT::f64, MVT::f80, Expand);
374       setConvertAction(MVT::f80, MVT::f32, Expand);
375       setConvertAction(MVT::f80, MVT::f64, Expand);
376     }
377   } else if (X86ScalarSSEf32) {
378     // Use SSE for f32, x87 for f64.
379     // Set up the FP register classes.
380     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
381     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
382
383     // Use ANDPS to simulate FABS.
384     setOperationAction(ISD::FABS , MVT::f32, Custom);
385
386     // Use XORP to simulate FNEG.
387     setOperationAction(ISD::FNEG , MVT::f32, Custom);
388
389     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
390
391     // Use ANDPS and ORPS to simulate FCOPYSIGN.
392     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
393     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
394
395     // We don't support sin/cos/fmod
396     setOperationAction(ISD::FSIN , MVT::f32, Expand);
397     setOperationAction(ISD::FCOS , MVT::f32, Expand);
398
399     // Special cases we handle for FP constants.
400     addLegalFPImmediate(APFloat(+0.0f)); // xorps
401     addLegalFPImmediate(APFloat(+0.0)); // FLD0
402     addLegalFPImmediate(APFloat(+1.0)); // FLD1
403     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
404     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
405
406     // SSE <-> X87 conversions go through memory.  If optimizing, we lie about
407     // this though and handle it in InstructionSelectPreprocess so that
408     // dagcombine2 can hack on these.
409     if (Fast) {
410       setConvertAction(MVT::f32, MVT::f64, Expand);
411       setConvertAction(MVT::f32, MVT::f80, Expand);
412       setConvertAction(MVT::f80, MVT::f32, Expand);    
413       setConvertAction(MVT::f64, MVT::f32, Expand);
414       // And x87->x87 truncations also.
415       setConvertAction(MVT::f80, MVT::f64, Expand);
416     }
417
418     if (!UnsafeFPMath) {
419       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
420       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
421     }
422   } else {
423     // f32 and f64 in x87.
424     // Set up the FP register classes.
425     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
426     addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
427
428     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
429     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
430     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
431     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
432
433     // Floating truncations go through memory.  If optimizing, we lie about
434     // this though and handle it in InstructionSelectPreprocess so that
435     // dagcombine2 can hack on these.
436     if (Fast) {
437       setConvertAction(MVT::f80, MVT::f32, Expand);    
438       setConvertAction(MVT::f64, MVT::f32, Expand);
439       setConvertAction(MVT::f80, MVT::f64, Expand);
440     }
441
442     if (!UnsafeFPMath) {
443       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
444       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
445     }
446     addLegalFPImmediate(APFloat(+0.0)); // FLD0
447     addLegalFPImmediate(APFloat(+1.0)); // FLD1
448     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
449     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
450     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
451     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
452     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
453     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
454   }
455
456   // Long double always uses X87.
457   addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
458   setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
459   setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
460   {
461     APFloat TmpFlt(+0.0);
462     TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven);
463     addLegalFPImmediate(TmpFlt);  // FLD0
464     TmpFlt.changeSign();
465     addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
466     APFloat TmpFlt2(+1.0);
467     TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven);
468     addLegalFPImmediate(TmpFlt2);  // FLD1
469     TmpFlt2.changeSign();
470     addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
471   }
472     
473   if (!UnsafeFPMath) {
474     setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
475     setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
476   }
477
478   // Always use a library call for pow.
479   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
480   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
481   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
482
483   // First set operation action for all vector types to expand. Then we
484   // will selectively turn on ones that can be effectively codegen'd.
485   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
486        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
487     setOperationAction(ISD::ADD , (MVT::ValueType)VT, Expand);
488     setOperationAction(ISD::SUB , (MVT::ValueType)VT, Expand);
489     setOperationAction(ISD::FADD, (MVT::ValueType)VT, Expand);
490     setOperationAction(ISD::FNEG, (MVT::ValueType)VT, Expand);
491     setOperationAction(ISD::FSUB, (MVT::ValueType)VT, Expand);
492     setOperationAction(ISD::MUL , (MVT::ValueType)VT, Expand);
493     setOperationAction(ISD::FMUL, (MVT::ValueType)VT, Expand);
494     setOperationAction(ISD::SDIV, (MVT::ValueType)VT, Expand);
495     setOperationAction(ISD::UDIV, (MVT::ValueType)VT, Expand);
496     setOperationAction(ISD::FDIV, (MVT::ValueType)VT, Expand);
497     setOperationAction(ISD::SREM, (MVT::ValueType)VT, Expand);
498     setOperationAction(ISD::UREM, (MVT::ValueType)VT, Expand);
499     setOperationAction(ISD::LOAD, (MVT::ValueType)VT, Expand);
500     setOperationAction(ISD::VECTOR_SHUFFLE,     (MVT::ValueType)VT, Expand);
501     setOperationAction(ISD::EXTRACT_VECTOR_ELT, (MVT::ValueType)VT, Expand);
502     setOperationAction(ISD::INSERT_VECTOR_ELT,  (MVT::ValueType)VT, Expand);
503     setOperationAction(ISD::FABS, (MVT::ValueType)VT, Expand);
504     setOperationAction(ISD::FSIN, (MVT::ValueType)VT, Expand);
505     setOperationAction(ISD::FCOS, (MVT::ValueType)VT, Expand);
506     setOperationAction(ISD::FREM, (MVT::ValueType)VT, Expand);
507     setOperationAction(ISD::FPOWI, (MVT::ValueType)VT, Expand);
508     setOperationAction(ISD::FSQRT, (MVT::ValueType)VT, Expand);
509     setOperationAction(ISD::FCOPYSIGN, (MVT::ValueType)VT, Expand);
510     setOperationAction(ISD::SMUL_LOHI, (MVT::ValueType)VT, Expand);
511     setOperationAction(ISD::UMUL_LOHI, (MVT::ValueType)VT, Expand);
512     setOperationAction(ISD::SDIVREM, (MVT::ValueType)VT, Expand);
513     setOperationAction(ISD::UDIVREM, (MVT::ValueType)VT, Expand);
514     setOperationAction(ISD::FPOW, (MVT::ValueType)VT, Expand);
515     setOperationAction(ISD::CTPOP, (MVT::ValueType)VT, Expand);
516     setOperationAction(ISD::CTTZ, (MVT::ValueType)VT, Expand);
517     setOperationAction(ISD::CTLZ, (MVT::ValueType)VT, Expand);
518     setOperationAction(ISD::SHL, (MVT::ValueType)VT, Expand);
519     setOperationAction(ISD::SRA, (MVT::ValueType)VT, Expand);
520     setOperationAction(ISD::SRL, (MVT::ValueType)VT, Expand);
521     setOperationAction(ISD::ROTL, (MVT::ValueType)VT, Expand);
522     setOperationAction(ISD::ROTR, (MVT::ValueType)VT, Expand);
523     setOperationAction(ISD::BSWAP, (MVT::ValueType)VT, Expand);
524   }
525
526   if (Subtarget->hasMMX()) {
527     addRegisterClass(MVT::v8i8,  X86::VR64RegisterClass);
528     addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
529     addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
530     addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
531
532     // FIXME: add MMX packed arithmetics
533
534     setOperationAction(ISD::ADD,                MVT::v8i8,  Legal);
535     setOperationAction(ISD::ADD,                MVT::v4i16, Legal);
536     setOperationAction(ISD::ADD,                MVT::v2i32, Legal);
537     setOperationAction(ISD::ADD,                MVT::v1i64, Legal);
538
539     setOperationAction(ISD::SUB,                MVT::v8i8,  Legal);
540     setOperationAction(ISD::SUB,                MVT::v4i16, Legal);
541     setOperationAction(ISD::SUB,                MVT::v2i32, Legal);
542     setOperationAction(ISD::SUB,                MVT::v1i64, Legal);
543
544     setOperationAction(ISD::MULHS,              MVT::v4i16, Legal);
545     setOperationAction(ISD::MUL,                MVT::v4i16, Legal);
546
547     setOperationAction(ISD::AND,                MVT::v8i8,  Promote);
548     AddPromotedToType (ISD::AND,                MVT::v8i8,  MVT::v1i64);
549     setOperationAction(ISD::AND,                MVT::v4i16, Promote);
550     AddPromotedToType (ISD::AND,                MVT::v4i16, MVT::v1i64);
551     setOperationAction(ISD::AND,                MVT::v2i32, Promote);
552     AddPromotedToType (ISD::AND,                MVT::v2i32, MVT::v1i64);
553     setOperationAction(ISD::AND,                MVT::v1i64, Legal);
554
555     setOperationAction(ISD::OR,                 MVT::v8i8,  Promote);
556     AddPromotedToType (ISD::OR,                 MVT::v8i8,  MVT::v1i64);
557     setOperationAction(ISD::OR,                 MVT::v4i16, Promote);
558     AddPromotedToType (ISD::OR,                 MVT::v4i16, MVT::v1i64);
559     setOperationAction(ISD::OR,                 MVT::v2i32, Promote);
560     AddPromotedToType (ISD::OR,                 MVT::v2i32, MVT::v1i64);
561     setOperationAction(ISD::OR,                 MVT::v1i64, Legal);
562
563     setOperationAction(ISD::XOR,                MVT::v8i8,  Promote);
564     AddPromotedToType (ISD::XOR,                MVT::v8i8,  MVT::v1i64);
565     setOperationAction(ISD::XOR,                MVT::v4i16, Promote);
566     AddPromotedToType (ISD::XOR,                MVT::v4i16, MVT::v1i64);
567     setOperationAction(ISD::XOR,                MVT::v2i32, Promote);
568     AddPromotedToType (ISD::XOR,                MVT::v2i32, MVT::v1i64);
569     setOperationAction(ISD::XOR,                MVT::v1i64, Legal);
570
571     setOperationAction(ISD::LOAD,               MVT::v8i8,  Promote);
572     AddPromotedToType (ISD::LOAD,               MVT::v8i8,  MVT::v1i64);
573     setOperationAction(ISD::LOAD,               MVT::v4i16, Promote);
574     AddPromotedToType (ISD::LOAD,               MVT::v4i16, MVT::v1i64);
575     setOperationAction(ISD::LOAD,               MVT::v2i32, Promote);
576     AddPromotedToType (ISD::LOAD,               MVT::v2i32, MVT::v1i64);
577     setOperationAction(ISD::LOAD,               MVT::v1i64, Legal);
578
579     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i8,  Custom);
580     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i16, Custom);
581     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i32, Custom);
582     setOperationAction(ISD::BUILD_VECTOR,       MVT::v1i64, Custom);
583
584     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8i8,  Custom);
585     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i16, Custom);
586     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i32, Custom);
587     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v1i64, Custom);
588
589     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Custom);
590     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Custom);
591     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Custom);
592   }
593
594   if (Subtarget->hasSSE1()) {
595     addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
596
597     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
598     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
599     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
600     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
601     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
602     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
603     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
604     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
605     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
606     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
607     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
608   }
609
610   if (Subtarget->hasSSE2()) {
611     addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
612     addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
613     addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
614     addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
615     addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
616
617     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
618     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
619     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
620     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
621     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
622     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
623     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
624     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
625     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
626     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
627     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
628     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
629     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
630     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
631     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
632
633     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
634     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
635     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
636     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
637     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
638
639     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
640     for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
641       // Do not attempt to custom lower non-power-of-2 vectors
642       if (!isPowerOf2_32(MVT::getVectorNumElements(VT)))
643         continue;
644       setOperationAction(ISD::BUILD_VECTOR,        (MVT::ValueType)VT, Custom);
645       setOperationAction(ISD::VECTOR_SHUFFLE,      (MVT::ValueType)VT, Custom);
646       setOperationAction(ISD::EXTRACT_VECTOR_ELT,  (MVT::ValueType)VT, Custom);
647     }
648     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
649     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
650     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
651     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
652     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
653     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
654     if (Subtarget->is64Bit()) {
655       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
656       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
657     }
658
659     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
660     for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
661       setOperationAction(ISD::AND,    (MVT::ValueType)VT, Promote);
662       AddPromotedToType (ISD::AND,    (MVT::ValueType)VT, MVT::v2i64);
663       setOperationAction(ISD::OR,     (MVT::ValueType)VT, Promote);
664       AddPromotedToType (ISD::OR,     (MVT::ValueType)VT, MVT::v2i64);
665       setOperationAction(ISD::XOR,    (MVT::ValueType)VT, Promote);
666       AddPromotedToType (ISD::XOR,    (MVT::ValueType)VT, MVT::v2i64);
667       setOperationAction(ISD::LOAD,   (MVT::ValueType)VT, Promote);
668       AddPromotedToType (ISD::LOAD,   (MVT::ValueType)VT, MVT::v2i64);
669       setOperationAction(ISD::SELECT, (MVT::ValueType)VT, Promote);
670       AddPromotedToType (ISD::SELECT, (MVT::ValueType)VT, MVT::v2i64);
671     }
672
673     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
674
675     // Custom lower v2i64 and v2f64 selects.
676     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
677     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
678     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
679     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
680   }
681   
682   if (Subtarget->hasSSE41()) {
683     // FIXME: Do we need to handle scalar-to-vector here?
684     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
685
686     // i8 and i16 vectors are custom , because the source register and source
687     // source memory operand types are not the same width.  f32 vectors are
688     // custom since the immediate controlling the insert encodes additional
689     // information.
690     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
691     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
692     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Legal);
693     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
694
695     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
696     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
697     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
698     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
699
700     if (Subtarget->is64Bit()) {
701       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Legal);
702       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
703     }
704   }
705
706   // We want to custom lower some of our intrinsics.
707   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
708
709   // We have target-specific dag combine patterns for the following nodes:
710   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
711   setTargetDAGCombine(ISD::SELECT);
712   setTargetDAGCombine(ISD::STORE);
713
714   computeRegisterProperties();
715
716   // FIXME: These should be based on subtarget info. Plus, the values should
717   // be smaller when we are in optimizing for size mode.
718   maxStoresPerMemset = 16; // For %llvm.memset -> sequence of stores
719   maxStoresPerMemcpy = 16; // For %llvm.memcpy -> sequence of stores
720   maxStoresPerMemmove = 16; // For %llvm.memmove -> sequence of stores
721   allowUnalignedMemoryAccesses = true; // x86 supports it!
722   setPrefLoopAlignment(16);
723 }
724
725
726 MVT::ValueType
727 X86TargetLowering::getSetCCResultType(const SDOperand &) const {
728   return MVT::i8;
729 }
730
731
732 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
733 /// the desired ByVal argument alignment.
734 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
735   if (MaxAlign == 16)
736     return;
737   if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
738     if (VTy->getBitWidth() == 128)
739       MaxAlign = 16;
740   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
741     unsigned EltAlign = 0;
742     getMaxByValAlign(ATy->getElementType(), EltAlign);
743     if (EltAlign > MaxAlign)
744       MaxAlign = EltAlign;
745   } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
746     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
747       unsigned EltAlign = 0;
748       getMaxByValAlign(STy->getElementType(i), EltAlign);
749       if (EltAlign > MaxAlign)
750         MaxAlign = EltAlign;
751       if (MaxAlign == 16)
752         break;
753     }
754   }
755   return;
756 }
757
758 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
759 /// function arguments in the caller parameter area. For X86, aggregates
760 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
761 /// are at 4-byte boundaries.
762 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
763   if (Subtarget->is64Bit())
764     return getTargetData()->getABITypeAlignment(Ty);
765   unsigned Align = 4;
766   if (Subtarget->hasSSE1())
767     getMaxByValAlign(Ty, Align);
768   return Align;
769 }
770
771 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
772 /// jumptable.
773 SDOperand X86TargetLowering::getPICJumpTableRelocBase(SDOperand Table,
774                                                       SelectionDAG &DAG) const {
775   if (usesGlobalOffsetTable())
776     return DAG.getNode(ISD::GLOBAL_OFFSET_TABLE, getPointerTy());
777   if (!Subtarget->isPICStyleRIPRel())
778     return DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy());
779   return Table;
780 }
781
782 //===----------------------------------------------------------------------===//
783 //               Return Value Calling Convention Implementation
784 //===----------------------------------------------------------------------===//
785
786 #include "X86GenCallingConv.inc"
787
788 /// GetPossiblePreceedingTailCall - Get preceeding X86ISD::TAILCALL node if it
789 /// exists skip possible ISD:TokenFactor.
790 static SDOperand GetPossiblePreceedingTailCall(SDOperand Chain) {
791   if (Chain.getOpcode() == X86ISD::TAILCALL) {
792     return Chain;
793   } else if (Chain.getOpcode() == ISD::TokenFactor) {
794     if (Chain.getNumOperands() &&
795         Chain.getOperand(0).getOpcode() == X86ISD::TAILCALL)
796       return Chain.getOperand(0);
797   }
798   return Chain;
799 }
800
801 /// LowerRET - Lower an ISD::RET node.
802 SDOperand X86TargetLowering::LowerRET(SDOperand Op, SelectionDAG &DAG) {
803   assert((Op.getNumOperands() & 1) == 1 && "ISD::RET should have odd # args");
804   
805   SmallVector<CCValAssign, 16> RVLocs;
806   unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
807   bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
808   CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs);
809   CCInfo.AnalyzeReturn(Op.Val, RetCC_X86);
810     
811   // If this is the first return lowered for this function, add the regs to the
812   // liveout set for the function.
813   if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
814     for (unsigned i = 0; i != RVLocs.size(); ++i)
815       if (RVLocs[i].isRegLoc())
816         DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
817   }
818   SDOperand Chain = Op.getOperand(0);
819   
820   // Handle tail call return.
821   Chain = GetPossiblePreceedingTailCall(Chain);
822   if (Chain.getOpcode() == X86ISD::TAILCALL) {
823     SDOperand TailCall = Chain;
824     SDOperand TargetAddress = TailCall.getOperand(1);
825     SDOperand StackAdjustment = TailCall.getOperand(2);
826     assert(((TargetAddress.getOpcode() == ISD::Register &&
827                (cast<RegisterSDNode>(TargetAddress)->getReg() == X86::ECX ||
828                 cast<RegisterSDNode>(TargetAddress)->getReg() == X86::R9)) ||
829               TargetAddress.getOpcode() == ISD::TargetExternalSymbol ||
830               TargetAddress.getOpcode() == ISD::TargetGlobalAddress) && 
831              "Expecting an global address, external symbol, or register");
832     assert(StackAdjustment.getOpcode() == ISD::Constant &&
833            "Expecting a const value");
834
835     SmallVector<SDOperand,8> Operands;
836     Operands.push_back(Chain.getOperand(0));
837     Operands.push_back(TargetAddress);
838     Operands.push_back(StackAdjustment);
839     // Copy registers used by the call. Last operand is a flag so it is not
840     // copied.
841     for (unsigned i=3; i < TailCall.getNumOperands()-1; i++) {
842       Operands.push_back(Chain.getOperand(i));
843     }
844     return DAG.getNode(X86ISD::TC_RETURN, MVT::Other, &Operands[0], 
845                        Operands.size());
846   }
847   
848   // Regular return.
849   SDOperand Flag;
850
851   SmallVector<SDOperand, 6> RetOps;
852   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
853   // Operand #1 = Bytes To Pop
854   RetOps.push_back(DAG.getConstant(getBytesToPopOnReturn(), MVT::i16));
855   
856   // Copy the result values into the output registers.
857   for (unsigned i = 0; i != RVLocs.size(); ++i) {
858     CCValAssign &VA = RVLocs[i];
859     assert(VA.isRegLoc() && "Can only return in registers!");
860     SDOperand ValToCopy = Op.getOperand(i*2+1);
861     
862     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
863     // the RET instruction and handled by the FP Stackifier.
864     if (RVLocs[i].getLocReg() == X86::ST0 ||
865         RVLocs[i].getLocReg() == X86::ST1) {
866       // If this is a copy from an xmm register to ST(0), use an FPExtend to
867       // change the value to the FP stack register class.
868       if (isScalarFPTypeInSSEReg(RVLocs[i].getValVT()))
869         ValToCopy = DAG.getNode(ISD::FP_EXTEND, MVT::f80, ValToCopy);
870       RetOps.push_back(ValToCopy);
871       // Don't emit a copytoreg.
872       continue;
873     }
874     
875     Chain = DAG.getCopyToReg(Chain, VA.getLocReg(), ValToCopy, Flag);
876     Flag = Chain.getValue(1);
877   }
878   
879   RetOps[0] = Chain;  // Update chain.
880
881   // Add the flag if we have it.
882   if (Flag.Val)
883     RetOps.push_back(Flag);
884   
885   return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, &RetOps[0], RetOps.size());
886 }
887
888
889 /// LowerCallResult - Lower the result values of an ISD::CALL into the
890 /// appropriate copies out of appropriate physical registers.  This assumes that
891 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
892 /// being lowered.  The returns a SDNode with the same number of values as the
893 /// ISD::CALL.
894 SDNode *X86TargetLowering::
895 LowerCallResult(SDOperand Chain, SDOperand InFlag, SDNode *TheCall, 
896                 unsigned CallingConv, SelectionDAG &DAG) {
897   
898   // Assign locations to each value returned by this call.
899   SmallVector<CCValAssign, 16> RVLocs;
900   bool isVarArg = cast<ConstantSDNode>(TheCall->getOperand(2))->getValue() != 0;
901   CCState CCInfo(CallingConv, isVarArg, getTargetMachine(), RVLocs);
902   CCInfo.AnalyzeCallResult(TheCall, RetCC_X86);
903
904   SmallVector<SDOperand, 8> ResultVals;
905   
906   // Copy all of the result registers out of their specified physreg.
907   for (unsigned i = 0; i != RVLocs.size(); ++i) {
908     MVT::ValueType CopyVT = RVLocs[i].getValVT();
909     
910     // If this is a call to a function that returns an fp value on the floating
911     // point stack, but where we prefer to use the value in xmm registers, copy
912     // it out as F80 and use a truncate to move it from fp stack reg to xmm reg.
913     if (RVLocs[i].getLocReg() == X86::ST0 &&
914         isScalarFPTypeInSSEReg(RVLocs[i].getValVT())) {
915       CopyVT = MVT::f80;
916     }
917     
918     Chain = DAG.getCopyFromReg(Chain, RVLocs[i].getLocReg(),
919                                CopyVT, InFlag).getValue(1);
920     SDOperand Val = Chain.getValue(0);
921     InFlag = Chain.getValue(2);
922
923     if (CopyVT != RVLocs[i].getValVT()) {
924       // Round the F80 the right size, which also moves to the appropriate xmm
925       // register.
926       Val = DAG.getNode(ISD::FP_ROUND, RVLocs[i].getValVT(), Val,
927                         // This truncation won't change the value.
928                         DAG.getIntPtrConstant(1));
929     }
930     
931     ResultVals.push_back(Val);
932   }
933   
934   // Merge everything together with a MERGE_VALUES node.
935   ResultVals.push_back(Chain);
936   return DAG.getNode(ISD::MERGE_VALUES, TheCall->getVTList(),
937                      &ResultVals[0], ResultVals.size()).Val;
938 }
939
940
941 //===----------------------------------------------------------------------===//
942 //                C & StdCall & Fast Calling Convention implementation
943 //===----------------------------------------------------------------------===//
944 //  StdCall calling convention seems to be standard for many Windows' API
945 //  routines and around. It differs from C calling convention just a little:
946 //  callee should clean up the stack, not caller. Symbols should be also
947 //  decorated in some fancy way :) It doesn't support any vector arguments.
948 //  For info on fast calling convention see Fast Calling Convention (tail call)
949 //  implementation LowerX86_32FastCCCallTo.
950
951 /// AddLiveIn - This helper function adds the specified physical register to the
952 /// MachineFunction as a live in value.  It also creates a corresponding virtual
953 /// register for it.
954 static unsigned AddLiveIn(MachineFunction &MF, unsigned PReg,
955                           const TargetRegisterClass *RC) {
956   assert(RC->contains(PReg) && "Not the correct regclass!");
957   unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
958   MF.getRegInfo().addLiveIn(PReg, VReg);
959   return VReg;
960 }
961
962 /// CallIsStructReturn - Determines whether a CALL node uses struct return
963 /// semantics.
964 static bool CallIsStructReturn(SDOperand Op) {
965   unsigned NumOps = (Op.getNumOperands() - 5) / 2;
966   if (!NumOps)
967     return false;
968
969   return cast<ARG_FLAGSSDNode>(Op.getOperand(6))->getArgFlags().isSRet();
970 }
971
972 /// ArgsAreStructReturn - Determines whether a FORMAL_ARGUMENTS node uses struct
973 /// return semantics.
974 static bool ArgsAreStructReturn(SDOperand Op) {
975   unsigned NumArgs = Op.Val->getNumValues() - 1;
976   if (!NumArgs)
977     return false;
978
979   return cast<ARG_FLAGSSDNode>(Op.getOperand(3))->getArgFlags().isSRet();
980 }
981
982 /// IsCalleePop - Determines whether a CALL or FORMAL_ARGUMENTS node requires the
983 /// callee to pop its own arguments. Callee pop is necessary to support tail
984 /// calls.
985 bool X86TargetLowering::IsCalleePop(SDOperand Op) {
986   bool IsVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
987   if (IsVarArg)
988     return false;
989
990   switch (cast<ConstantSDNode>(Op.getOperand(1))->getValue()) {
991   default:
992     return false;
993   case CallingConv::X86_StdCall:
994     return !Subtarget->is64Bit();
995   case CallingConv::X86_FastCall:
996     return !Subtarget->is64Bit();
997   case CallingConv::Fast:
998     return PerformTailCallOpt;
999   }
1000 }
1001
1002 /// CCAssignFnForNode - Selects the correct CCAssignFn for a CALL or
1003 /// FORMAL_ARGUMENTS node.
1004 CCAssignFn *X86TargetLowering::CCAssignFnForNode(SDOperand Op) const {
1005   unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
1006   
1007   if (Subtarget->is64Bit()) {
1008     if (Subtarget->isTargetWin64())
1009       return CC_X86_Win64_C;
1010     else {
1011       if (CC == CallingConv::Fast && PerformTailCallOpt)
1012         return CC_X86_64_TailCall;
1013       else
1014         return CC_X86_64_C;
1015     }
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 SizeNode     = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1113   return DAG.getMemcpy(Chain, Dst, Src, SizeNode, Flags.getByValAlign(),
1114                        /*AlwaysInline=*/true,
1115                        NULL, 0, NULL, 0);
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 v4f32, v8i16 or v16i8 to v4i32.
2782 static SDOperand PromoteSplat(SDOperand Op, SelectionDAG &DAG, bool HasSSE2) {
2783   MVT::ValueType PVT = HasSSE2 ? MVT::v4i32 : MVT::v4f32;
2784   MVT::ValueType VT = Op.getValueType();
2785   if (PVT == VT)
2786     return Op;
2787   SDOperand V1 = Op.getOperand(0);
2788   SDOperand Mask = Op.getOperand(2);
2789   unsigned NumElems = Mask.getNumOperands();
2790   // Special handling of v4f32 -> v4i32.
2791   if (VT != MVT::v4f32) {
2792     Mask = getUnpacklMask(NumElems, DAG);
2793     while (NumElems > 4) {
2794       V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1, Mask);
2795       NumElems >>= 1;
2796     }
2797     Mask = getZeroVector(MVT::v4i32, DAG);
2798   }
2799
2800   V1 = DAG.getNode(ISD::BIT_CONVERT, PVT, V1);
2801   SDOperand Shuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, PVT, V1,
2802                                   DAG.getNode(ISD::UNDEF, PVT), Mask);
2803   return DAG.getNode(ISD::BIT_CONVERT, VT, Shuffle);
2804 }
2805
2806 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
2807 /// vector of zero or undef vector.  This produces a shuffle where the low
2808 /// element of V2 is swizzled into the zero/undef vector, landing at element
2809 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
2810 static SDOperand getShuffleVectorZeroOrUndef(SDOperand V2, unsigned Idx,
2811                                              bool isZero, SelectionDAG &DAG) {
2812   MVT::ValueType VT = V2.getValueType();
2813   SDOperand V1 = isZero ? getZeroVector(VT, DAG) : DAG.getNode(ISD::UNDEF, VT);
2814   unsigned NumElems = MVT::getVectorNumElements(V2.getValueType());
2815   MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2816   MVT::ValueType EVT = MVT::getVectorElementType(MaskVT);
2817   SmallVector<SDOperand, 16> MaskVec;
2818   for (unsigned i = 0; i != NumElems; ++i)
2819     if (i == Idx)  // If this is the insertion idx, put the low elt of V2 here.
2820       MaskVec.push_back(DAG.getConstant(NumElems, EVT));
2821     else
2822       MaskVec.push_back(DAG.getConstant(i, EVT));
2823   SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2824                                &MaskVec[0], MaskVec.size());
2825   return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2826 }
2827
2828 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
2829 ///
2830 static SDOperand LowerBuildVectorv16i8(SDOperand Op, unsigned NonZeros,
2831                                        unsigned NumNonZero, unsigned NumZero,
2832                                        SelectionDAG &DAG, TargetLowering &TLI) {
2833   if (NumNonZero > 8)
2834     return SDOperand();
2835
2836   SDOperand V(0, 0);
2837   bool First = true;
2838   for (unsigned i = 0; i < 16; ++i) {
2839     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
2840     if (ThisIsNonZero && First) {
2841       if (NumZero)
2842         V = getZeroVector(MVT::v8i16, DAG);
2843       else
2844         V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
2845       First = false;
2846     }
2847
2848     if ((i & 1) != 0) {
2849       SDOperand ThisElt(0, 0), LastElt(0, 0);
2850       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
2851       if (LastIsNonZero) {
2852         LastElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i-1));
2853       }
2854       if (ThisIsNonZero) {
2855         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i));
2856         ThisElt = DAG.getNode(ISD::SHL, MVT::i16,
2857                               ThisElt, DAG.getConstant(8, MVT::i8));
2858         if (LastIsNonZero)
2859           ThisElt = DAG.getNode(ISD::OR, MVT::i16, ThisElt, LastElt);
2860       } else
2861         ThisElt = LastElt;
2862
2863       if (ThisElt.Val)
2864         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, ThisElt,
2865                         DAG.getIntPtrConstant(i/2));
2866     }
2867   }
2868
2869   return DAG.getNode(ISD::BIT_CONVERT, MVT::v16i8, V);
2870 }
2871
2872 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
2873 ///
2874 static SDOperand LowerBuildVectorv8i16(SDOperand Op, unsigned NonZeros,
2875                                        unsigned NumNonZero, unsigned NumZero,
2876                                        SelectionDAG &DAG, TargetLowering &TLI) {
2877   if (NumNonZero > 4)
2878     return SDOperand();
2879
2880   SDOperand V(0, 0);
2881   bool First = true;
2882   for (unsigned i = 0; i < 8; ++i) {
2883     bool isNonZero = (NonZeros & (1 << i)) != 0;
2884     if (isNonZero) {
2885       if (First) {
2886         if (NumZero)
2887           V = getZeroVector(MVT::v8i16, DAG);
2888         else
2889           V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
2890         First = false;
2891       }
2892       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, Op.getOperand(i),
2893                       DAG.getIntPtrConstant(i));
2894     }
2895   }
2896
2897   return V;
2898 }
2899
2900 SDOperand
2901 X86TargetLowering::LowerBUILD_VECTOR(SDOperand Op, SelectionDAG &DAG) {
2902   // All zero's are handled with pxor, all one's are handled with pcmpeqd.
2903   if (ISD::isBuildVectorAllZeros(Op.Val) || ISD::isBuildVectorAllOnes(Op.Val)) {
2904     // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
2905     // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
2906     // eliminated on x86-32 hosts.
2907     if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
2908       return Op;
2909
2910     if (ISD::isBuildVectorAllOnes(Op.Val))
2911       return getOnesVector(Op.getValueType(), DAG);
2912     return getZeroVector(Op.getValueType(), DAG);
2913   }
2914
2915   MVT::ValueType VT = Op.getValueType();
2916   MVT::ValueType EVT = MVT::getVectorElementType(VT);
2917   unsigned EVTBits = MVT::getSizeInBits(EVT);
2918
2919   unsigned NumElems = Op.getNumOperands();
2920   unsigned NumZero  = 0;
2921   unsigned NumNonZero = 0;
2922   unsigned NonZeros = 0;
2923   bool IsAllConstants = true;
2924   SmallSet<SDOperand, 8> Values;
2925   for (unsigned i = 0; i < NumElems; ++i) {
2926     SDOperand Elt = Op.getOperand(i);
2927     if (Elt.getOpcode() == ISD::UNDEF)
2928       continue;
2929     Values.insert(Elt);
2930     if (Elt.getOpcode() != ISD::Constant &&
2931         Elt.getOpcode() != ISD::ConstantFP)
2932       IsAllConstants = false;
2933     if (isZeroNode(Elt))
2934       NumZero++;
2935     else {
2936       NonZeros |= (1 << i);
2937       NumNonZero++;
2938     }
2939   }
2940
2941   if (NumNonZero == 0) {
2942     // All undef vector. Return an UNDEF.  All zero vectors were handled above.
2943     return DAG.getNode(ISD::UNDEF, VT);
2944   }
2945
2946   // Special case for single non-zero, non-undef, element.
2947   if (NumNonZero == 1 && NumElems <= 4) {
2948     unsigned Idx = CountTrailingZeros_32(NonZeros);
2949     SDOperand Item = Op.getOperand(Idx);
2950     
2951     // If this is an insertion of an i64 value on x86-32, and if the top bits of
2952     // the value are obviously zero, truncate the value to i32 and do the
2953     // insertion that way.  Only do this if the value is non-constant or if the
2954     // value is a constant being inserted into element 0.  It is cheaper to do
2955     // a constant pool load than it is to do a movd + shuffle.
2956     if (EVT == MVT::i64 && !Subtarget->is64Bit() &&
2957         (!IsAllConstants || Idx == 0)) {
2958       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
2959         // Handle MMX and SSE both.
2960         MVT::ValueType VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
2961         MVT::ValueType VecElts = VT == MVT::v2i64 ? 4 : 2;
2962         
2963         // Truncate the value (which may itself be a constant) to i32, and
2964         // convert it to a vector with movd (S2V+shuffle to zero extend).
2965         Item = DAG.getNode(ISD::TRUNCATE, MVT::i32, Item);
2966         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VecVT, Item);
2967         Item = getShuffleVectorZeroOrUndef(Item, 0, true, DAG);
2968         
2969         // Now we have our 32-bit value zero extended in the low element of
2970         // a vector.  If Idx != 0, swizzle it into place.
2971         if (Idx != 0) {
2972           SDOperand Ops[] = { 
2973             Item, DAG.getNode(ISD::UNDEF, Item.getValueType()),
2974             getSwapEltZeroMask(VecElts, Idx, DAG)
2975           };
2976           Item = DAG.getNode(ISD::VECTOR_SHUFFLE, VecVT, Ops, 3);
2977         }
2978         return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(), Item);
2979       }
2980     }
2981     
2982     // If we have a constant or non-constant insertion into the low element of
2983     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
2984     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
2985     // depending on what the source datatype is.  Because we can only get here
2986     // when NumElems <= 4, this only needs to handle i32/f32/i64/f64.
2987     if (Idx == 0 &&
2988         // Don't do this for i64 values on x86-32.
2989         (EVT != MVT::i64 || Subtarget->is64Bit())) {
2990       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
2991       // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
2992       return getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, DAG);
2993     }
2994     
2995     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
2996       return SDOperand();
2997
2998     // Otherwise, if this is a vector with i32 or f32 elements, and the element
2999     // is a non-constant being inserted into an element other than the low one,
3000     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
3001     // movd/movss) to move this into the low element, then shuffle it into
3002     // place.
3003     if (EVTBits == 32) {
3004       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
3005       
3006       // Turn it into a shuffle of zero and zero-extended scalar to vector.
3007       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, DAG);
3008       MVT::ValueType MaskVT  = MVT::getIntVectorWithNumElements(NumElems);
3009       MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3010       SmallVector<SDOperand, 8> MaskVec;
3011       for (unsigned i = 0; i < NumElems; i++)
3012         MaskVec.push_back(DAG.getConstant((i == Idx) ? 0 : 1, MaskEVT));
3013       SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3014                                    &MaskVec[0], MaskVec.size());
3015       return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Item,
3016                          DAG.getNode(ISD::UNDEF, VT), Mask);
3017     }
3018   }
3019
3020   // Splat is obviously ok. Let legalizer expand it to a shuffle.
3021   if (Values.size() == 1)
3022     return SDOperand();
3023   
3024   // A vector full of immediates; various special cases are already
3025   // handled, so this is best done with a single constant-pool load.
3026   if (IsAllConstants)
3027     return SDOperand();
3028
3029   // Let legalizer expand 2-wide build_vectors.
3030   if (EVTBits == 64)
3031     return SDOperand();
3032
3033   // If element VT is < 32 bits, convert it to inserts into a zero vector.
3034   if (EVTBits == 8 && NumElems == 16) {
3035     SDOperand V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3036                                         *this);
3037     if (V.Val) return V;
3038   }
3039
3040   if (EVTBits == 16 && NumElems == 8) {
3041     SDOperand V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3042                                         *this);
3043     if (V.Val) return V;
3044   }
3045
3046   // If element VT is == 32 bits, turn it into a number of shuffles.
3047   SmallVector<SDOperand, 8> V;
3048   V.resize(NumElems);
3049   if (NumElems == 4 && NumZero > 0) {
3050     for (unsigned i = 0; i < 4; ++i) {
3051       bool isZero = !(NonZeros & (1 << i));
3052       if (isZero)
3053         V[i] = getZeroVector(VT, DAG);
3054       else
3055         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3056     }
3057
3058     for (unsigned i = 0; i < 2; ++i) {
3059       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3060         default: break;
3061         case 0:
3062           V[i] = V[i*2];  // Must be a zero vector.
3063           break;
3064         case 1:
3065           V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2+1], V[i*2],
3066                              getMOVLMask(NumElems, DAG));
3067           break;
3068         case 2:
3069           V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3070                              getMOVLMask(NumElems, DAG));
3071           break;
3072         case 3:
3073           V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3074                              getUnpacklMask(NumElems, DAG));
3075           break;
3076       }
3077     }
3078
3079     // Take advantage of the fact GR32 to VR128 scalar_to_vector (i.e. movd)
3080     // clears the upper bits.
3081     // FIXME: we can do the same for v4f32 case when we know both parts of
3082     // the lower half come from scalar_to_vector (loadf32). We should do
3083     // that in post legalizer dag combiner with target specific hooks.
3084     if (MVT::isInteger(EVT) && (NonZeros & (0x3 << 2)) == 0)
3085       return V[0];
3086     MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3087     MVT::ValueType EVT = MVT::getVectorElementType(MaskVT);
3088     SmallVector<SDOperand, 8> MaskVec;
3089     bool Reverse = (NonZeros & 0x3) == 2;
3090     for (unsigned i = 0; i < 2; ++i)
3091       if (Reverse)
3092         MaskVec.push_back(DAG.getConstant(1-i, EVT));
3093       else
3094         MaskVec.push_back(DAG.getConstant(i, EVT));
3095     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3096     for (unsigned i = 0; i < 2; ++i)
3097       if (Reverse)
3098         MaskVec.push_back(DAG.getConstant(1-i+NumElems, EVT));
3099       else
3100         MaskVec.push_back(DAG.getConstant(i+NumElems, EVT));
3101     SDOperand ShufMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3102                                      &MaskVec[0], MaskVec.size());
3103     return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[0], V[1], ShufMask);
3104   }
3105
3106   if (Values.size() > 2) {
3107     // Expand into a number of unpckl*.
3108     // e.g. for v4f32
3109     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3110     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3111     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
3112     SDOperand UnpckMask = getUnpacklMask(NumElems, DAG);
3113     for (unsigned i = 0; i < NumElems; ++i)
3114       V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3115     NumElems >>= 1;
3116     while (NumElems != 0) {
3117       for (unsigned i = 0; i < NumElems; ++i)
3118         V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i], V[i + NumElems],
3119                            UnpckMask);
3120       NumElems >>= 1;
3121     }
3122     return V[0];
3123   }
3124
3125   return SDOperand();
3126 }
3127
3128 static
3129 SDOperand LowerVECTOR_SHUFFLEv8i16(SDOperand V1, SDOperand V2,
3130                                    SDOperand PermMask, SelectionDAG &DAG,
3131                                    TargetLowering &TLI) {
3132   SDOperand NewV;
3133   MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(8);
3134   MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3135   MVT::ValueType PtrVT = TLI.getPointerTy();
3136   SmallVector<SDOperand, 8> MaskElts(PermMask.Val->op_begin(),
3137                                      PermMask.Val->op_end());
3138
3139   // First record which half of which vector the low elements come from.
3140   SmallVector<unsigned, 4> LowQuad(4);
3141   for (unsigned i = 0; i < 4; ++i) {
3142     SDOperand Elt = MaskElts[i];
3143     if (Elt.getOpcode() == ISD::UNDEF)
3144       continue;
3145     unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3146     int QuadIdx = EltIdx / 4;
3147     ++LowQuad[QuadIdx];
3148   }
3149   int BestLowQuad = -1;
3150   unsigned MaxQuad = 1;
3151   for (unsigned i = 0; i < 4; ++i) {
3152     if (LowQuad[i] > MaxQuad) {
3153       BestLowQuad = i;
3154       MaxQuad = LowQuad[i];
3155     }
3156   }
3157
3158   // Record which half of which vector the high elements come from.
3159   SmallVector<unsigned, 4> HighQuad(4);
3160   for (unsigned i = 4; i < 8; ++i) {
3161     SDOperand Elt = MaskElts[i];
3162     if (Elt.getOpcode() == ISD::UNDEF)
3163       continue;
3164     unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3165     int QuadIdx = EltIdx / 4;
3166     ++HighQuad[QuadIdx];
3167   }
3168   int BestHighQuad = -1;
3169   MaxQuad = 1;
3170   for (unsigned i = 0; i < 4; ++i) {
3171     if (HighQuad[i] > MaxQuad) {
3172       BestHighQuad = i;
3173       MaxQuad = HighQuad[i];
3174     }
3175   }
3176
3177   // If it's possible to sort parts of either half with PSHUF{H|L}W, then do it.
3178   if (BestLowQuad != -1 || BestHighQuad != -1) {
3179     // First sort the 4 chunks in order using shufpd.
3180     SmallVector<SDOperand, 8> MaskVec;
3181     if (BestLowQuad != -1)
3182       MaskVec.push_back(DAG.getConstant(BestLowQuad, MVT::i32));
3183     else
3184       MaskVec.push_back(DAG.getConstant(0, MVT::i32));
3185     if (BestHighQuad != -1)
3186       MaskVec.push_back(DAG.getConstant(BestHighQuad, MVT::i32));
3187     else
3188       MaskVec.push_back(DAG.getConstant(1, MVT::i32));
3189     SDOperand Mask= DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, &MaskVec[0],2);
3190     NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v2i64,
3191                        DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V1),
3192                        DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V2), Mask);
3193     NewV = DAG.getNode(ISD::BIT_CONVERT, MVT::v8i16, NewV);
3194
3195     // Now sort high and low parts separately.
3196     BitVector InOrder(8);
3197     if (BestLowQuad != -1) {
3198       // Sort lower half in order using PSHUFLW.
3199       MaskVec.clear();
3200       bool AnyOutOrder = false;
3201       for (unsigned i = 0; i != 4; ++i) {
3202         SDOperand Elt = MaskElts[i];
3203         if (Elt.getOpcode() == ISD::UNDEF) {
3204           MaskVec.push_back(Elt);
3205           InOrder.set(i);
3206         } else {
3207           unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3208           if (EltIdx != i)
3209             AnyOutOrder = true;
3210           MaskVec.push_back(DAG.getConstant(EltIdx % 4, MaskEVT));
3211           // If this element is in the right place after this shuffle, then
3212           // remember it.
3213           if ((int)(EltIdx / 4) == BestLowQuad)
3214             InOrder.set(i);
3215         }
3216       }
3217       if (AnyOutOrder) {
3218         for (unsigned i = 4; i != 8; ++i)
3219           MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3220         SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3221         NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
3222       }
3223     }
3224
3225     if (BestHighQuad != -1) {
3226       // Sort high half in order using PSHUFHW if possible.
3227       MaskVec.clear();
3228       for (unsigned i = 0; i != 4; ++i)
3229         MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3230       bool AnyOutOrder = false;
3231       for (unsigned i = 4; i != 8; ++i) {
3232         SDOperand Elt = MaskElts[i];
3233         if (Elt.getOpcode() == ISD::UNDEF) {
3234           MaskVec.push_back(Elt);
3235           InOrder.set(i);
3236         } else {
3237           unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3238           if (EltIdx != i)
3239             AnyOutOrder = true;
3240           MaskVec.push_back(DAG.getConstant((EltIdx % 4) + 4, MaskEVT));
3241           // If this element is in the right place after this shuffle, then
3242           // remember it.
3243           if ((int)(EltIdx / 4) == BestHighQuad)
3244             InOrder.set(i);
3245         }
3246       }
3247       if (AnyOutOrder) {
3248         SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3249         NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
3250       }
3251     }
3252
3253     // The other elements are put in the right place using pextrw and pinsrw.
3254     for (unsigned i = 0; i != 8; ++i) {
3255       if (InOrder[i])
3256         continue;
3257       SDOperand Elt = MaskElts[i];
3258       unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3259       if (EltIdx == i)
3260         continue;
3261       SDOperand ExtOp = (EltIdx < 8)
3262         ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
3263                       DAG.getConstant(EltIdx, PtrVT))
3264         : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3265                       DAG.getConstant(EltIdx - 8, PtrVT));
3266       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3267                          DAG.getConstant(i, PtrVT));
3268     }
3269     return NewV;
3270   }
3271
3272   // PSHUF{H|L}W are not used. Lower into extracts and inserts but try to use
3273   ///as few as possible.
3274   // First, let's find out how many elements are already in the right order.
3275   unsigned V1InOrder = 0;
3276   unsigned V1FromV1 = 0;
3277   unsigned V2InOrder = 0;
3278   unsigned V2FromV2 = 0;
3279   SmallVector<SDOperand, 8> V1Elts;
3280   SmallVector<SDOperand, 8> V2Elts;
3281   for (unsigned i = 0; i < 8; ++i) {
3282     SDOperand Elt = MaskElts[i];
3283     if (Elt.getOpcode() == ISD::UNDEF) {
3284       V1Elts.push_back(Elt);
3285       V2Elts.push_back(Elt);
3286       ++V1InOrder;
3287       ++V2InOrder;
3288       continue;
3289     }
3290     unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3291     if (EltIdx == i) {
3292       V1Elts.push_back(Elt);
3293       V2Elts.push_back(DAG.getConstant(i+8, MaskEVT));
3294       ++V1InOrder;
3295     } else if (EltIdx == i+8) {
3296       V1Elts.push_back(Elt);
3297       V2Elts.push_back(DAG.getConstant(i, MaskEVT));
3298       ++V2InOrder;
3299     } else if (EltIdx < 8) {
3300       V1Elts.push_back(Elt);
3301       ++V1FromV1;
3302     } else {
3303       V2Elts.push_back(DAG.getConstant(EltIdx-8, MaskEVT));
3304       ++V2FromV2;
3305     }
3306   }
3307
3308   if (V2InOrder > V1InOrder) {
3309     PermMask = CommuteVectorShuffleMask(PermMask, DAG);
3310     std::swap(V1, V2);
3311     std::swap(V1Elts, V2Elts);
3312     std::swap(V1FromV1, V2FromV2);
3313   }
3314
3315   if ((V1FromV1 + V1InOrder) != 8) {
3316     // Some elements are from V2.
3317     if (V1FromV1) {
3318       // If there are elements that are from V1 but out of place,
3319       // then first sort them in place
3320       SmallVector<SDOperand, 8> MaskVec;
3321       for (unsigned i = 0; i < 8; ++i) {
3322         SDOperand Elt = V1Elts[i];
3323         if (Elt.getOpcode() == ISD::UNDEF) {
3324           MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3325           continue;
3326         }
3327         unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3328         if (EltIdx >= 8)
3329           MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3330         else
3331           MaskVec.push_back(DAG.getConstant(EltIdx, MaskEVT));
3332       }
3333       SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3334       V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, V1, V1, Mask);
3335     }
3336
3337     NewV = V1;
3338     for (unsigned i = 0; i < 8; ++i) {
3339       SDOperand Elt = V1Elts[i];
3340       if (Elt.getOpcode() == ISD::UNDEF)
3341         continue;
3342       unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3343       if (EltIdx < 8)
3344         continue;
3345       SDOperand ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3346                                     DAG.getConstant(EltIdx - 8, PtrVT));
3347       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3348                          DAG.getConstant(i, PtrVT));
3349     }
3350     return NewV;
3351   } else {
3352     // All elements are from V1.
3353     NewV = V1;
3354     for (unsigned i = 0; i < 8; ++i) {
3355       SDOperand Elt = V1Elts[i];
3356       if (Elt.getOpcode() == ISD::UNDEF)
3357         continue;
3358       unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3359       SDOperand ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
3360                                     DAG.getConstant(EltIdx, PtrVT));
3361       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3362                          DAG.getConstant(i, PtrVT));
3363     }
3364     return NewV;
3365   }
3366 }
3367
3368 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
3369 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
3370 /// done when every pair / quad of shuffle mask elements point to elements in
3371 /// the right sequence. e.g.
3372 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
3373 static
3374 SDOperand RewriteAsNarrowerShuffle(SDOperand V1, SDOperand V2,
3375                                 MVT::ValueType VT,
3376                                 SDOperand PermMask, SelectionDAG &DAG,
3377                                 TargetLowering &TLI) {
3378   unsigned NumElems = PermMask.getNumOperands();
3379   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
3380   MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
3381   MVT::ValueType NewVT = MaskVT;
3382   switch (VT) {
3383   case MVT::v4f32: NewVT = MVT::v2f64; break;
3384   case MVT::v4i32: NewVT = MVT::v2i64; break;
3385   case MVT::v8i16: NewVT = MVT::v4i32; break;
3386   case MVT::v16i8: NewVT = MVT::v4i32; break;
3387   default: assert(false && "Unexpected!");
3388   }
3389
3390   if (NewWidth == 2) {
3391     if (MVT::isInteger(VT))
3392       NewVT = MVT::v2i64;
3393     else
3394       NewVT = MVT::v2f64;
3395   }
3396   unsigned Scale = NumElems / NewWidth;
3397   SmallVector<SDOperand, 8> MaskVec;
3398   for (unsigned i = 0; i < NumElems; i += Scale) {
3399     unsigned StartIdx = ~0U;
3400     for (unsigned j = 0; j < Scale; ++j) {
3401       SDOperand Elt = PermMask.getOperand(i+j);
3402       if (Elt.getOpcode() == ISD::UNDEF)
3403         continue;
3404       unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3405       if (StartIdx == ~0U)
3406         StartIdx = EltIdx - (EltIdx % Scale);
3407       if (EltIdx != StartIdx + j)
3408         return SDOperand();
3409     }
3410     if (StartIdx == ~0U)
3411       MaskVec.push_back(DAG.getNode(ISD::UNDEF, MVT::i32));
3412     else
3413       MaskVec.push_back(DAG.getConstant(StartIdx / Scale, MVT::i32));
3414   }
3415
3416   V1 = DAG.getNode(ISD::BIT_CONVERT, NewVT, V1);
3417   V2 = DAG.getNode(ISD::BIT_CONVERT, NewVT, V2);
3418   return DAG.getNode(ISD::VECTOR_SHUFFLE, NewVT, V1, V2,
3419                      DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3420                                  &MaskVec[0], MaskVec.size()));
3421 }
3422
3423 SDOperand
3424 X86TargetLowering::LowerVECTOR_SHUFFLE(SDOperand Op, SelectionDAG &DAG) {
3425   SDOperand V1 = Op.getOperand(0);
3426   SDOperand V2 = Op.getOperand(1);
3427   SDOperand PermMask = Op.getOperand(2);
3428   MVT::ValueType VT = Op.getValueType();
3429   unsigned NumElems = PermMask.getNumOperands();
3430   bool isMMX = MVT::getSizeInBits(VT) == 64;
3431   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
3432   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
3433   bool V1IsSplat = false;
3434   bool V2IsSplat = false;
3435
3436   if (isUndefShuffle(Op.Val))
3437     return DAG.getNode(ISD::UNDEF, VT);
3438
3439   if (isZeroShuffle(Op.Val))
3440     return getZeroVector(VT, DAG);
3441
3442   if (isIdentityMask(PermMask.Val))
3443     return V1;
3444   else if (isIdentityMask(PermMask.Val, true))
3445     return V2;
3446
3447   if (isSplatMask(PermMask.Val)) {
3448     if (isMMX || NumElems < 4) return Op;
3449     // Promote it to a v4{if}32 splat.
3450     return PromoteSplat(Op, DAG, Subtarget->hasSSE2());
3451   }
3452
3453   // If the shuffle can be profitably rewritten as a narrower shuffle, then
3454   // do it!
3455   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
3456     SDOperand NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG, *this);
3457     if (NewOp.Val)
3458       return DAG.getNode(ISD::BIT_CONVERT, VT, LowerVECTOR_SHUFFLE(NewOp, DAG));
3459   } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
3460     // FIXME: Figure out a cleaner way to do this.
3461     // Try to make use of movq to zero out the top part.
3462     if (ISD::isBuildVectorAllZeros(V2.Val)) {
3463       SDOperand NewOp = RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG, *this);
3464       if (NewOp.Val) {
3465         SDOperand NewV1 = NewOp.getOperand(0);
3466         SDOperand NewV2 = NewOp.getOperand(1);
3467         SDOperand NewMask = NewOp.getOperand(2);
3468         if (isCommutedMOVL(NewMask.Val, true, false)) {
3469           NewOp = CommuteVectorShuffle(NewOp, NewV1, NewV2, NewMask, DAG);
3470           NewOp = DAG.getNode(ISD::VECTOR_SHUFFLE, NewOp.getValueType(),
3471                               NewV1, NewV2, getMOVLMask(2, DAG));
3472           return DAG.getNode(ISD::BIT_CONVERT, VT, LowerVECTOR_SHUFFLE(NewOp, DAG));
3473         }
3474       }
3475     } else if (ISD::isBuildVectorAllZeros(V1.Val)) {
3476       SDOperand NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG, *this);
3477       if (NewOp.Val && X86::isMOVLMask(NewOp.getOperand(2).Val))
3478         return DAG.getNode(ISD::BIT_CONVERT, VT, LowerVECTOR_SHUFFLE(NewOp, DAG));
3479     }
3480   }
3481
3482   if (X86::isMOVLMask(PermMask.Val))
3483     return (V1IsUndef) ? V2 : Op;
3484
3485   if (X86::isMOVSHDUPMask(PermMask.Val) ||
3486       X86::isMOVSLDUPMask(PermMask.Val) ||
3487       X86::isMOVHLPSMask(PermMask.Val) ||
3488       X86::isMOVHPMask(PermMask.Val) ||
3489       X86::isMOVLPMask(PermMask.Val))
3490     return Op;
3491
3492   if (ShouldXformToMOVHLPS(PermMask.Val) ||
3493       ShouldXformToMOVLP(V1.Val, V2.Val, PermMask.Val))
3494     return CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3495
3496   bool Commuted = false;
3497   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
3498   // 1,1,1,1 -> v8i16 though.
3499   V1IsSplat = isSplatVector(V1.Val);
3500   V2IsSplat = isSplatVector(V2.Val);
3501   
3502   // Canonicalize the splat or undef, if present, to be on the RHS.
3503   if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
3504     Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3505     std::swap(V1IsSplat, V2IsSplat);
3506     std::swap(V1IsUndef, V2IsUndef);
3507     Commuted = true;
3508   }
3509
3510   // FIXME: Figure out a cleaner way to do this.
3511   if (isCommutedMOVL(PermMask.Val, V2IsSplat, V2IsUndef)) {
3512     if (V2IsUndef) return V1;
3513     Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3514     if (V2IsSplat) {
3515       // V2 is a splat, so the mask may be malformed. That is, it may point
3516       // to any V2 element. The instruction selectior won't like this. Get
3517       // a corrected mask and commute to form a proper MOVS{S|D}.
3518       SDOperand NewMask = getMOVLMask(NumElems, DAG);
3519       if (NewMask.Val != PermMask.Val)
3520         Op = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3521     }
3522     return Op;
3523   }
3524
3525   if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
3526       X86::isUNPCKH_v_undef_Mask(PermMask.Val) ||
3527       X86::isUNPCKLMask(PermMask.Val) ||
3528       X86::isUNPCKHMask(PermMask.Val))
3529     return Op;
3530
3531   if (V2IsSplat) {
3532     // Normalize mask so all entries that point to V2 points to its first
3533     // element then try to match unpck{h|l} again. If match, return a
3534     // new vector_shuffle with the corrected mask.
3535     SDOperand NewMask = NormalizeMask(PermMask, DAG);
3536     if (NewMask.Val != PermMask.Val) {
3537       if (X86::isUNPCKLMask(PermMask.Val, true)) {
3538         SDOperand NewMask = getUnpacklMask(NumElems, DAG);
3539         return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3540       } else if (X86::isUNPCKHMask(PermMask.Val, true)) {
3541         SDOperand NewMask = getUnpackhMask(NumElems, DAG);
3542         return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3543       }
3544     }
3545   }
3546
3547   // Normalize the node to match x86 shuffle ops if needed
3548   if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(PermMask.Val))
3549       Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3550
3551   if (Commuted) {
3552     // Commute is back and try unpck* again.
3553     Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3554     if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
3555         X86::isUNPCKH_v_undef_Mask(PermMask.Val) ||
3556         X86::isUNPCKLMask(PermMask.Val) ||
3557         X86::isUNPCKHMask(PermMask.Val))
3558       return Op;
3559   }
3560
3561   // Try PSHUF* first, then SHUFP*.
3562   // MMX doesn't have PSHUFD but it does have PSHUFW. While it's theoretically
3563   // possible to shuffle a v2i32 using PSHUFW, that's not yet implemented.
3564   if (isMMX && NumElems == 4 && X86::isPSHUFDMask(PermMask.Val)) {
3565     if (V2.getOpcode() != ISD::UNDEF)
3566       return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
3567                          DAG.getNode(ISD::UNDEF, VT), PermMask);
3568     return Op;
3569   }
3570
3571   if (!isMMX) {
3572     if (Subtarget->hasSSE2() &&
3573         (X86::isPSHUFDMask(PermMask.Val) ||
3574          X86::isPSHUFHWMask(PermMask.Val) ||
3575          X86::isPSHUFLWMask(PermMask.Val))) {
3576       MVT::ValueType RVT = VT;
3577       if (VT == MVT::v4f32) {
3578         RVT = MVT::v4i32;
3579         Op = DAG.getNode(ISD::VECTOR_SHUFFLE, RVT,
3580                          DAG.getNode(ISD::BIT_CONVERT, RVT, V1),
3581                          DAG.getNode(ISD::UNDEF, RVT), PermMask);
3582       } else if (V2.getOpcode() != ISD::UNDEF)
3583         Op = DAG.getNode(ISD::VECTOR_SHUFFLE, RVT, V1,
3584                          DAG.getNode(ISD::UNDEF, RVT), PermMask);
3585       if (RVT != VT)
3586         Op = DAG.getNode(ISD::BIT_CONVERT, VT, Op);
3587       return Op;
3588     }
3589
3590     // Binary or unary shufps.
3591     if (X86::isSHUFPMask(PermMask.Val) ||
3592         (V2.getOpcode() == ISD::UNDEF && X86::isPSHUFDMask(PermMask.Val)))
3593       return Op;
3594   }
3595
3596   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
3597   if (VT == MVT::v8i16) {
3598     SDOperand NewOp = LowerVECTOR_SHUFFLEv8i16(V1, V2, PermMask, DAG, *this);
3599     if (NewOp.Val)
3600       return NewOp;
3601   }
3602
3603   // Handle all 4 wide cases with a number of shuffles.
3604   if (NumElems == 4 && !isMMX) {
3605     // Don't do this for MMX.
3606     MVT::ValueType MaskVT = PermMask.getValueType();
3607     MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3608     SmallVector<std::pair<int, int>, 8> Locs;
3609     Locs.reserve(NumElems);
3610     SmallVector<SDOperand, 8> Mask1(NumElems,
3611                                     DAG.getNode(ISD::UNDEF, MaskEVT));
3612     SmallVector<SDOperand, 8> Mask2(NumElems,
3613                                     DAG.getNode(ISD::UNDEF, MaskEVT));
3614     unsigned NumHi = 0;
3615     unsigned NumLo = 0;
3616     // If no more than two elements come from either vector. This can be
3617     // implemented with two shuffles. First shuffle gather the elements.
3618     // The second shuffle, which takes the first shuffle as both of its
3619     // vector operands, put the elements into the right order.
3620     for (unsigned i = 0; i != NumElems; ++i) {
3621       SDOperand Elt = PermMask.getOperand(i);
3622       if (Elt.getOpcode() == ISD::UNDEF) {
3623         Locs[i] = std::make_pair(-1, -1);
3624       } else {
3625         unsigned Val = cast<ConstantSDNode>(Elt)->getValue();
3626         if (Val < NumElems) {
3627           Locs[i] = std::make_pair(0, NumLo);
3628           Mask1[NumLo] = Elt;
3629           NumLo++;
3630         } else {
3631           Locs[i] = std::make_pair(1, NumHi);
3632           if (2+NumHi < NumElems)
3633             Mask1[2+NumHi] = Elt;
3634           NumHi++;
3635         }
3636       }
3637     }
3638     if (NumLo <= 2 && NumHi <= 2) {
3639       V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3640                        DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3641                                    &Mask1[0], Mask1.size()));
3642       for (unsigned i = 0; i != NumElems; ++i) {
3643         if (Locs[i].first == -1)
3644           continue;
3645         else {
3646           unsigned Idx = (i < NumElems/2) ? 0 : NumElems;
3647           Idx += Locs[i].first * (NumElems/2) + Locs[i].second;
3648           Mask2[i] = DAG.getConstant(Idx, MaskEVT);
3649         }
3650       }
3651
3652       return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1,
3653                          DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3654                                      &Mask2[0], Mask2.size()));
3655     }
3656
3657     // Break it into (shuffle shuffle_hi, shuffle_lo).
3658     Locs.clear();
3659     SmallVector<SDOperand,8> LoMask(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
3660     SmallVector<SDOperand,8> HiMask(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
3661     SmallVector<SDOperand,8> *MaskPtr = &LoMask;
3662     unsigned MaskIdx = 0;
3663     unsigned LoIdx = 0;
3664     unsigned HiIdx = NumElems/2;
3665     for (unsigned i = 0; i != NumElems; ++i) {
3666       if (i == NumElems/2) {
3667         MaskPtr = &HiMask;
3668         MaskIdx = 1;
3669         LoIdx = 0;
3670         HiIdx = NumElems/2;
3671       }
3672       SDOperand Elt = PermMask.getOperand(i);
3673       if (Elt.getOpcode() == ISD::UNDEF) {
3674         Locs[i] = std::make_pair(-1, -1);
3675       } else if (cast<ConstantSDNode>(Elt)->getValue() < NumElems) {
3676         Locs[i] = std::make_pair(MaskIdx, LoIdx);
3677         (*MaskPtr)[LoIdx] = Elt;
3678         LoIdx++;
3679       } else {
3680         Locs[i] = std::make_pair(MaskIdx, HiIdx);
3681         (*MaskPtr)[HiIdx] = Elt;
3682         HiIdx++;
3683       }
3684     }
3685
3686     SDOperand LoShuffle =
3687       DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3688                   DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3689                               &LoMask[0], LoMask.size()));
3690     SDOperand HiShuffle =
3691       DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3692                   DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3693                               &HiMask[0], HiMask.size()));
3694     SmallVector<SDOperand, 8> MaskOps;
3695     for (unsigned i = 0; i != NumElems; ++i) {
3696       if (Locs[i].first == -1) {
3697         MaskOps.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3698       } else {
3699         unsigned Idx = Locs[i].first * NumElems + Locs[i].second;
3700         MaskOps.push_back(DAG.getConstant(Idx, MaskEVT));
3701       }
3702     }
3703     return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, LoShuffle, HiShuffle,
3704                        DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3705                                    &MaskOps[0], MaskOps.size()));
3706   }
3707
3708   return SDOperand();
3709 }
3710
3711 SDOperand
3712 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDOperand Op,
3713                                                 SelectionDAG &DAG) {
3714   MVT::ValueType VT = Op.getValueType();
3715   if (MVT::getSizeInBits(VT) == 8) {
3716     SDOperand Extract = DAG.getNode(X86ISD::PEXTRB, MVT::i32,
3717                                     Op.getOperand(0), Op.getOperand(1));
3718     SDOperand Assert  = DAG.getNode(ISD::AssertZext, MVT::i32, Extract,
3719                                     DAG.getValueType(VT));
3720     return DAG.getNode(ISD::TRUNCATE, VT, Assert);
3721   } else if (MVT::getSizeInBits(VT) == 16) {
3722     SDOperand Extract = DAG.getNode(X86ISD::PEXTRW, MVT::i32,
3723                                     Op.getOperand(0), Op.getOperand(1));
3724     SDOperand Assert  = DAG.getNode(ISD::AssertZext, MVT::i32, Extract,
3725                                     DAG.getValueType(VT));
3726     return DAG.getNode(ISD::TRUNCATE, VT, Assert);
3727   } else if (VT == MVT::f32) {
3728     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
3729     // the result back to FR32 register. It's only worth matching if the
3730     // result has a single use which is a store.
3731     if (!Op.hasOneUse())
3732       return SDOperand();
3733     SDNode *User = Op.Val->use_begin()->getUser();
3734     if (User->getOpcode() != ISD::STORE)
3735       return SDOperand();
3736     SDOperand Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32,
3737                     DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, Op.getOperand(0)),
3738                                     Op.getOperand(1));
3739     return DAG.getNode(ISD::BIT_CONVERT, MVT::f32, Extract);
3740   }
3741   return SDOperand();
3742 }
3743
3744
3745 SDOperand
3746 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDOperand Op, SelectionDAG &DAG) {
3747   if (!isa<ConstantSDNode>(Op.getOperand(1)))
3748     return SDOperand();
3749
3750   if (Subtarget->hasSSE41()) {
3751     SDOperand Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
3752     if (Res.Val)
3753       return Res;
3754   }
3755
3756   MVT::ValueType VT = Op.getValueType();
3757   // TODO: handle v16i8.
3758   if (MVT::getSizeInBits(VT) == 16) {
3759     SDOperand Vec = Op.getOperand(0);
3760     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3761     if (Idx == 0)
3762       return DAG.getNode(ISD::TRUNCATE, MVT::i16,
3763                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32,
3764                                  DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, Vec),
3765                                      Op.getOperand(1)));
3766     // Transform it so it match pextrw which produces a 32-bit result.
3767     MVT::ValueType EVT = (MVT::ValueType)(VT+1);
3768     SDOperand Extract = DAG.getNode(X86ISD::PEXTRW, EVT,
3769                                     Op.getOperand(0), Op.getOperand(1));
3770     SDOperand Assert  = DAG.getNode(ISD::AssertZext, EVT, Extract,
3771                                     DAG.getValueType(VT));
3772     return DAG.getNode(ISD::TRUNCATE, VT, Assert);
3773   } else if (MVT::getSizeInBits(VT) == 32) {
3774     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3775     if (Idx == 0)
3776       return Op;
3777     // SHUFPS the element to the lowest double word, then movss.
3778     MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
3779     SmallVector<SDOperand, 8> IdxVec;
3780     IdxVec.
3781       push_back(DAG.getConstant(Idx, MVT::getVectorElementType(MaskVT)));
3782     IdxVec.
3783       push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3784     IdxVec.
3785       push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3786     IdxVec.
3787       push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3788     SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3789                                  &IdxVec[0], IdxVec.size());
3790     SDOperand Vec = Op.getOperand(0);
3791     Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
3792                       Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
3793     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
3794                        DAG.getIntPtrConstant(0));
3795   } else if (MVT::getSizeInBits(VT) == 64) {
3796     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
3797     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
3798     //        to match extract_elt for f64.
3799     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3800     if (Idx == 0)
3801       return Op;
3802
3803     // UNPCKHPD the element to the lowest double word, then movsd.
3804     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
3805     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
3806     MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
3807     SmallVector<SDOperand, 8> IdxVec;
3808     IdxVec.push_back(DAG.getConstant(1, MVT::getVectorElementType(MaskVT)));
3809     IdxVec.
3810       push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3811     SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3812                                  &IdxVec[0], IdxVec.size());
3813     SDOperand Vec = Op.getOperand(0);
3814     Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
3815                       Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
3816     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
3817                        DAG.getIntPtrConstant(0));
3818   }
3819
3820   return SDOperand();
3821 }
3822
3823 SDOperand
3824 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDOperand Op, SelectionDAG &DAG){
3825   MVT::ValueType VT = Op.getValueType();
3826   MVT::ValueType EVT = MVT::getVectorElementType(VT);
3827
3828   SDOperand N0 = Op.getOperand(0);
3829   SDOperand N1 = Op.getOperand(1);
3830   SDOperand N2 = Op.getOperand(2);
3831
3832   if ((MVT::getSizeInBits(EVT) == 8) || (MVT::getSizeInBits(EVT) == 16)) {
3833     unsigned Opc = (MVT::getSizeInBits(EVT) == 8) ? X86ISD::PINSRB
3834                                                   : X86ISD::PINSRW;
3835     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
3836     // argument.
3837     if (N1.getValueType() != MVT::i32)
3838       N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
3839     if (N2.getValueType() != MVT::i32)
3840       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getValue());
3841     return DAG.getNode(Opc, VT, N0, N1, N2);
3842   } else if (EVT == MVT::f32) {
3843     // Bits [7:6] of the constant are the source select.  This will always be
3844     //  zero here.  The DAG Combiner may combine an extract_elt index into these
3845     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
3846     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
3847     // Bits [5:4] of the constant are the destination select.  This is the 
3848     //  value of the incoming immediate.
3849     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may 
3850     //   combine either bitwise AND or insert of float 0.0 to set these bits.
3851     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getValue() << 4);
3852     return DAG.getNode(X86ISD::INSERTPS, VT, N0, N1, N2);
3853   }
3854   return SDOperand();
3855 }
3856
3857 SDOperand
3858 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDOperand Op, SelectionDAG &DAG) {
3859   MVT::ValueType VT = Op.getValueType();
3860   MVT::ValueType EVT = MVT::getVectorElementType(VT);
3861
3862   if (Subtarget->hasSSE41())
3863     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
3864
3865   if (EVT == MVT::i8)
3866     return SDOperand();
3867
3868   SDOperand N0 = Op.getOperand(0);
3869   SDOperand N1 = Op.getOperand(1);
3870   SDOperand N2 = Op.getOperand(2);
3871
3872   if (MVT::getSizeInBits(EVT) == 16) {
3873     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
3874     // as its second argument.
3875     if (N1.getValueType() != MVT::i32)
3876       N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
3877     if (N2.getValueType() != MVT::i32)
3878       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getValue());
3879     return DAG.getNode(X86ISD::PINSRW, VT, N0, N1, N2);
3880   }
3881   return SDOperand();
3882 }
3883
3884 SDOperand
3885 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDOperand Op, SelectionDAG &DAG) {
3886   SDOperand AnyExt = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, Op.getOperand(0));
3887   MVT::ValueType VT = MVT::v2i32;
3888   switch (Op.getValueType()) {
3889   default: break;
3890   case MVT::v16i8:
3891   case MVT::v8i16:
3892     VT = MVT::v4i32;
3893     break;
3894   }
3895   return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(),
3896                      DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, AnyExt));
3897 }
3898
3899 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
3900 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
3901 // one of the above mentioned nodes. It has to be wrapped because otherwise
3902 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
3903 // be used to form addressing mode. These wrapped nodes will be selected
3904 // into MOV32ri.
3905 SDOperand
3906 X86TargetLowering::LowerConstantPool(SDOperand Op, SelectionDAG &DAG) {
3907   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
3908   SDOperand Result = DAG.getTargetConstantPool(CP->getConstVal(),
3909                                                getPointerTy(),
3910                                                CP->getAlignment());
3911   Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
3912   // With PIC, the address is actually $g + Offset.
3913   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
3914       !Subtarget->isPICStyleRIPRel()) {
3915     Result = DAG.getNode(ISD::ADD, getPointerTy(),
3916                          DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
3917                          Result);
3918   }
3919
3920   return Result;
3921 }
3922
3923 SDOperand
3924 X86TargetLowering::LowerGlobalAddress(SDOperand Op, SelectionDAG &DAG) {
3925   GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3926   SDOperand Result = DAG.getTargetGlobalAddress(GV, getPointerTy());
3927   // If it's a debug information descriptor, don't mess with it.
3928   if (DAG.isVerifiedDebugInfoDesc(Op))
3929     return Result;
3930   Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
3931   // With PIC, the address is actually $g + Offset.
3932   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
3933       !Subtarget->isPICStyleRIPRel()) {
3934     Result = DAG.getNode(ISD::ADD, getPointerTy(),
3935                          DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
3936                          Result);
3937   }
3938   
3939   // For Darwin & Mingw32, external and weak symbols are indirect, so we want to
3940   // load the value at address GV, not the value of GV itself. This means that
3941   // the GlobalAddress must be in the base or index register of the address, not
3942   // the GV offset field. Platform check is inside GVRequiresExtraLoad() call
3943   // The same applies for external symbols during PIC codegen
3944   if (Subtarget->GVRequiresExtraLoad(GV, getTargetMachine(), false))
3945     Result = DAG.getLoad(getPointerTy(), DAG.getEntryNode(), Result,
3946                          PseudoSourceValue::getGOT(), 0);
3947
3948   return Result;
3949 }
3950
3951 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
3952 static SDOperand
3953 LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
3954                               const MVT::ValueType PtrVT) {
3955   SDOperand InFlag;
3956   SDOperand Chain = DAG.getCopyToReg(DAG.getEntryNode(), X86::EBX,
3957                                      DAG.getNode(X86ISD::GlobalBaseReg,
3958                                                  PtrVT), InFlag);
3959   InFlag = Chain.getValue(1);
3960
3961   // emit leal symbol@TLSGD(,%ebx,1), %eax
3962   SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
3963   SDOperand TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
3964                                              GA->getValueType(0),
3965                                              GA->getOffset());
3966   SDOperand Ops[] = { Chain,  TGA, InFlag };
3967   SDOperand Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 3);
3968   InFlag = Result.getValue(2);
3969   Chain = Result.getValue(1);
3970
3971   // call ___tls_get_addr. This function receives its argument in
3972   // the register EAX.
3973   Chain = DAG.getCopyToReg(Chain, X86::EAX, Result, InFlag);
3974   InFlag = Chain.getValue(1);
3975
3976   NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
3977   SDOperand Ops1[] = { Chain,
3978                       DAG.getTargetExternalSymbol("___tls_get_addr",
3979                                                   PtrVT),
3980                       DAG.getRegister(X86::EAX, PtrVT),
3981                       DAG.getRegister(X86::EBX, PtrVT),
3982                       InFlag };
3983   Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 5);
3984   InFlag = Chain.getValue(1);
3985
3986   return DAG.getCopyFromReg(Chain, X86::EAX, PtrVT, InFlag);
3987 }
3988
3989 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
3990 // "local exec" model.
3991 static SDOperand
3992 LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
3993                          const MVT::ValueType PtrVT) {
3994   // Get the Thread Pointer
3995   SDOperand ThreadPointer = DAG.getNode(X86ISD::THREAD_POINTER, PtrVT);
3996   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
3997   // exec)
3998   SDOperand TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
3999                                              GA->getValueType(0),
4000                                              GA->getOffset());
4001   SDOperand Offset = DAG.getNode(X86ISD::Wrapper, PtrVT, TGA);
4002
4003   if (GA->getGlobal()->isDeclaration()) // initial exec TLS model
4004     Offset = DAG.getLoad(PtrVT, DAG.getEntryNode(), Offset,
4005                          PseudoSourceValue::getGOT(), 0);
4006
4007   // The address of the thread local variable is the add of the thread
4008   // pointer with the offset of the variable.
4009   return DAG.getNode(ISD::ADD, PtrVT, ThreadPointer, Offset);
4010 }
4011
4012 SDOperand
4013 X86TargetLowering::LowerGlobalTLSAddress(SDOperand Op, SelectionDAG &DAG) {
4014   // TODO: implement the "local dynamic" model
4015   // TODO: implement the "initial exec"model for pic executables
4016   assert(!Subtarget->is64Bit() && Subtarget->isTargetELF() &&
4017          "TLS not implemented for non-ELF and 64-bit targets");
4018   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4019   // If the relocation model is PIC, use the "General Dynamic" TLS Model,
4020   // otherwise use the "Local Exec"TLS Model
4021   if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
4022     return LowerToTLSGeneralDynamicModel(GA, DAG, getPointerTy());
4023   else
4024     return LowerToTLSExecModel(GA, DAG, getPointerTy());
4025 }
4026
4027 SDOperand
4028 X86TargetLowering::LowerExternalSymbol(SDOperand Op, SelectionDAG &DAG) {
4029   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
4030   SDOperand Result = DAG.getTargetExternalSymbol(Sym, getPointerTy());
4031   Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4032   // With PIC, the address is actually $g + Offset.
4033   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4034       !Subtarget->isPICStyleRIPRel()) {
4035     Result = DAG.getNode(ISD::ADD, getPointerTy(),
4036                          DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4037                          Result);
4038   }
4039
4040   return Result;
4041 }
4042
4043 SDOperand X86TargetLowering::LowerJumpTable(SDOperand Op, SelectionDAG &DAG) {
4044   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4045   SDOperand Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy());
4046   Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4047   // With PIC, the address is actually $g + Offset.
4048   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4049       !Subtarget->isPICStyleRIPRel()) {
4050     Result = DAG.getNode(ISD::ADD, getPointerTy(),
4051                          DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4052                          Result);
4053   }
4054
4055   return Result;
4056 }
4057
4058 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
4059 /// take a 2 x i32 value to shift plus a shift amount. 
4060 SDOperand X86TargetLowering::LowerShift(SDOperand Op, SelectionDAG &DAG) {
4061   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4062   MVT::ValueType VT = Op.getValueType();
4063   unsigned VTBits = MVT::getSizeInBits(VT);
4064   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
4065   SDOperand ShOpLo = Op.getOperand(0);
4066   SDOperand ShOpHi = Op.getOperand(1);
4067   SDOperand ShAmt  = Op.getOperand(2);
4068   SDOperand Tmp1 = isSRA ?
4069     DAG.getNode(ISD::SRA, VT, ShOpHi, DAG.getConstant(VTBits - 1, MVT::i8)) :
4070     DAG.getConstant(0, VT);
4071
4072   SDOperand Tmp2, Tmp3;
4073   if (Op.getOpcode() == ISD::SHL_PARTS) {
4074     Tmp2 = DAG.getNode(X86ISD::SHLD, VT, ShOpHi, ShOpLo, ShAmt);
4075     Tmp3 = DAG.getNode(ISD::SHL, VT, ShOpLo, ShAmt);
4076   } else {
4077     Tmp2 = DAG.getNode(X86ISD::SHRD, VT, ShOpLo, ShOpHi, ShAmt);
4078     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, VT, ShOpHi, ShAmt);
4079   }
4080
4081   const MVT::ValueType *VTs = DAG.getNodeValueTypes(MVT::Other, MVT::Flag);
4082   SDOperand AndNode = DAG.getNode(ISD::AND, MVT::i8, ShAmt,
4083                                   DAG.getConstant(VTBits, MVT::i8));
4084   SDOperand Cond = DAG.getNode(X86ISD::CMP, VT,
4085                                AndNode, DAG.getConstant(0, MVT::i8));
4086
4087   SDOperand Hi, Lo;
4088   SDOperand CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4089   VTs = DAG.getNodeValueTypes(VT, MVT::Flag);
4090   SmallVector<SDOperand, 4> Ops;
4091   if (Op.getOpcode() == ISD::SHL_PARTS) {
4092     Ops.push_back(Tmp2);
4093     Ops.push_back(Tmp3);
4094     Ops.push_back(CC);
4095     Ops.push_back(Cond);
4096     Hi = DAG.getNode(X86ISD::CMOV, VT, &Ops[0], Ops.size());
4097
4098     Ops.clear();
4099     Ops.push_back(Tmp3);
4100     Ops.push_back(Tmp1);
4101     Ops.push_back(CC);
4102     Ops.push_back(Cond);
4103     Lo = DAG.getNode(X86ISD::CMOV, VT, &Ops[0], Ops.size());
4104   } else {
4105     Ops.push_back(Tmp2);
4106     Ops.push_back(Tmp3);
4107     Ops.push_back(CC);
4108     Ops.push_back(Cond);
4109     Lo = DAG.getNode(X86ISD::CMOV, VT, &Ops[0], Ops.size());
4110
4111     Ops.clear();
4112     Ops.push_back(Tmp3);
4113     Ops.push_back(Tmp1);
4114     Ops.push_back(CC);
4115     Ops.push_back(Cond);
4116     Hi = DAG.getNode(X86ISD::CMOV, VT, &Ops[0], Ops.size());
4117   }
4118
4119   VTs = DAG.getNodeValueTypes(VT, VT);
4120   Ops.clear();
4121   Ops.push_back(Lo);
4122   Ops.push_back(Hi);
4123   return DAG.getNode(ISD::MERGE_VALUES, VTs, 2, &Ops[0], Ops.size());
4124 }
4125
4126 SDOperand X86TargetLowering::LowerSINT_TO_FP(SDOperand Op, SelectionDAG &DAG) {
4127   MVT::ValueType SrcVT = Op.getOperand(0).getValueType();
4128   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
4129          "Unknown SINT_TO_FP to lower!");
4130   
4131   // These are really Legal; caller falls through into that case.
4132   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
4133     return SDOperand();
4134   if (SrcVT == MVT::i64 && Op.getValueType() != MVT::f80 && 
4135       Subtarget->is64Bit())
4136     return SDOperand();
4137   
4138   unsigned Size = MVT::getSizeInBits(SrcVT)/8;
4139   MachineFunction &MF = DAG.getMachineFunction();
4140   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
4141   SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4142   SDOperand Chain = DAG.getStore(DAG.getEntryNode(), Op.getOperand(0),
4143                                  StackSlot,
4144                                  PseudoSourceValue::getFixedStack(),
4145                                  SSFI);
4146
4147   // Build the FILD
4148   SDVTList Tys;
4149   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
4150   if (useSSE)
4151     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
4152   else
4153     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
4154   SmallVector<SDOperand, 8> Ops;
4155   Ops.push_back(Chain);
4156   Ops.push_back(StackSlot);
4157   Ops.push_back(DAG.getValueType(SrcVT));
4158   SDOperand Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD,
4159                                  Tys, &Ops[0], Ops.size());
4160
4161   if (useSSE) {
4162     Chain = Result.getValue(1);
4163     SDOperand InFlag = Result.getValue(2);
4164
4165     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
4166     // shouldn't be necessary except that RFP cannot be live across
4167     // multiple blocks. When stackifier is fixed, they can be uncoupled.
4168     MachineFunction &MF = DAG.getMachineFunction();
4169     int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
4170     SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4171     Tys = DAG.getVTList(MVT::Other);
4172     SmallVector<SDOperand, 8> Ops;
4173     Ops.push_back(Chain);
4174     Ops.push_back(Result);
4175     Ops.push_back(StackSlot);
4176     Ops.push_back(DAG.getValueType(Op.getValueType()));
4177     Ops.push_back(InFlag);
4178     Chain = DAG.getNode(X86ISD::FST, Tys, &Ops[0], Ops.size());
4179     Result = DAG.getLoad(Op.getValueType(), Chain, StackSlot,
4180                          PseudoSourceValue::getFixedStack(), SSFI);
4181   }
4182
4183   return Result;
4184 }
4185
4186 std::pair<SDOperand,SDOperand> X86TargetLowering::
4187 FP_TO_SINTHelper(SDOperand Op, SelectionDAG &DAG) {
4188   assert(Op.getValueType() <= MVT::i64 && Op.getValueType() >= MVT::i16 &&
4189          "Unknown FP_TO_SINT to lower!");
4190
4191   // These are really Legal.
4192   if (Op.getValueType() == MVT::i32 && 
4193       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
4194     return std::make_pair(SDOperand(), SDOperand());
4195   if (Subtarget->is64Bit() &&
4196       Op.getValueType() == MVT::i64 &&
4197       Op.getOperand(0).getValueType() != MVT::f80)
4198     return std::make_pair(SDOperand(), SDOperand());
4199
4200   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
4201   // stack slot.
4202   MachineFunction &MF = DAG.getMachineFunction();
4203   unsigned MemSize = MVT::getSizeInBits(Op.getValueType())/8;
4204   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4205   SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4206   unsigned Opc;
4207   switch (Op.getValueType()) {
4208   default: assert(0 && "Invalid FP_TO_SINT to lower!");
4209   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
4210   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
4211   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
4212   }
4213
4214   SDOperand Chain = DAG.getEntryNode();
4215   SDOperand Value = Op.getOperand(0);
4216   if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
4217     assert(Op.getValueType() == MVT::i64 && "Invalid FP_TO_SINT to lower!");
4218     Chain = DAG.getStore(Chain, Value, StackSlot,
4219                          PseudoSourceValue::getFixedStack(), SSFI);
4220     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
4221     SDOperand Ops[] = {
4222       Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
4223     };
4224     Value = DAG.getNode(X86ISD::FLD, Tys, Ops, 3);
4225     Chain = Value.getValue(1);
4226     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4227     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4228   }
4229
4230   // Build the FP_TO_INT*_IN_MEM
4231   SDOperand Ops[] = { Chain, Value, StackSlot };
4232   SDOperand FIST = DAG.getNode(Opc, MVT::Other, Ops, 3);
4233
4234   return std::make_pair(FIST, StackSlot);
4235 }
4236
4237 SDOperand X86TargetLowering::LowerFP_TO_SINT(SDOperand Op, SelectionDAG &DAG) {
4238   std::pair<SDOperand,SDOperand> Vals = FP_TO_SINTHelper(Op, DAG);
4239   SDOperand FIST = Vals.first, StackSlot = Vals.second;
4240   if (FIST.Val == 0) return SDOperand();
4241   
4242   // Load the result.
4243   return DAG.getLoad(Op.getValueType(), FIST, StackSlot, NULL, 0);
4244 }
4245
4246 SDNode *X86TargetLowering::ExpandFP_TO_SINT(SDNode *N, SelectionDAG &DAG) {
4247   std::pair<SDOperand,SDOperand> Vals = FP_TO_SINTHelper(SDOperand(N, 0), DAG);
4248   SDOperand FIST = Vals.first, StackSlot = Vals.second;
4249   if (FIST.Val == 0) return 0;
4250   
4251   // Return an i64 load from the stack slot.
4252   SDOperand Res = DAG.getLoad(MVT::i64, FIST, StackSlot, NULL, 0);
4253
4254   // Use a MERGE_VALUES node to drop the chain result value.
4255   return DAG.getNode(ISD::MERGE_VALUES, MVT::i64, Res).Val;
4256 }  
4257
4258 SDOperand X86TargetLowering::LowerFABS(SDOperand Op, SelectionDAG &DAG) {
4259   MVT::ValueType VT = Op.getValueType();
4260   MVT::ValueType EltVT = VT;
4261   if (MVT::isVector(VT))
4262     EltVT = MVT::getVectorElementType(VT);
4263   const Type *OpNTy =  MVT::getTypeForValueType(EltVT);
4264   std::vector<Constant*> CV;
4265   if (EltVT == MVT::f64) {
4266     Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(64, ~(1ULL << 63))));
4267     CV.push_back(C);
4268     CV.push_back(C);
4269   } else {
4270     Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(32, ~(1U << 31))));
4271     CV.push_back(C);
4272     CV.push_back(C);
4273     CV.push_back(C);
4274     CV.push_back(C);
4275   }
4276   Constant *C = ConstantVector::get(CV);
4277   SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4278   SDOperand Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4279                                PseudoSourceValue::getConstantPool(), 0,
4280                                false, 16);
4281   return DAG.getNode(X86ISD::FAND, VT, Op.getOperand(0), Mask);
4282 }
4283
4284 SDOperand X86TargetLowering::LowerFNEG(SDOperand Op, SelectionDAG &DAG) {
4285   MVT::ValueType VT = Op.getValueType();
4286   MVT::ValueType EltVT = VT;
4287   unsigned EltNum = 1;
4288   if (MVT::isVector(VT)) {
4289     EltVT = MVT::getVectorElementType(VT);
4290     EltNum = MVT::getVectorNumElements(VT);
4291   }
4292   const Type *OpNTy =  MVT::getTypeForValueType(EltVT);
4293   std::vector<Constant*> CV;
4294   if (EltVT == MVT::f64) {
4295     Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(64, 1ULL << 63)));
4296     CV.push_back(C);
4297     CV.push_back(C);
4298   } else {
4299     Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(32, 1U << 31)));
4300     CV.push_back(C);
4301     CV.push_back(C);
4302     CV.push_back(C);
4303     CV.push_back(C);
4304   }
4305   Constant *C = ConstantVector::get(CV);
4306   SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4307   SDOperand Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4308                                PseudoSourceValue::getConstantPool(), 0,
4309                                false, 16);
4310   if (MVT::isVector(VT)) {
4311     return DAG.getNode(ISD::BIT_CONVERT, VT,
4312                        DAG.getNode(ISD::XOR, MVT::v2i64,
4313                     DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Op.getOperand(0)),
4314                     DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Mask)));
4315   } else {
4316     return DAG.getNode(X86ISD::FXOR, VT, Op.getOperand(0), Mask);
4317   }
4318 }
4319
4320 SDOperand X86TargetLowering::LowerFCOPYSIGN(SDOperand Op, SelectionDAG &DAG) {
4321   SDOperand Op0 = Op.getOperand(0);
4322   SDOperand Op1 = Op.getOperand(1);
4323   MVT::ValueType VT = Op.getValueType();
4324   MVT::ValueType SrcVT = Op1.getValueType();
4325   const Type *SrcTy =  MVT::getTypeForValueType(SrcVT);
4326
4327   // If second operand is smaller, extend it first.
4328   if (MVT::getSizeInBits(SrcVT) < MVT::getSizeInBits(VT)) {
4329     Op1 = DAG.getNode(ISD::FP_EXTEND, VT, Op1);
4330     SrcVT = VT;
4331     SrcTy = MVT::getTypeForValueType(SrcVT);
4332   }
4333   // And if it is bigger, shrink it first.
4334   if (MVT::getSizeInBits(SrcVT) > MVT::getSizeInBits(VT)) {
4335     Op1 = DAG.getNode(ISD::FP_ROUND, VT, Op1, DAG.getIntPtrConstant(1));
4336     SrcVT = VT;
4337     SrcTy = MVT::getTypeForValueType(SrcVT);
4338   }
4339
4340   // At this point the operands and the result should have the same
4341   // type, and that won't be f80 since that is not custom lowered.
4342
4343   // First get the sign bit of second operand.
4344   std::vector<Constant*> CV;
4345   if (SrcVT == MVT::f64) {
4346     CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, 1ULL << 63))));
4347     CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, 0))));
4348   } else {
4349     CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 1U << 31))));
4350     CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4351     CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4352     CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4353   }
4354   Constant *C = ConstantVector::get(CV);
4355   SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4356   SDOperand Mask1 = DAG.getLoad(SrcVT, DAG.getEntryNode(), CPIdx,
4357                                 PseudoSourceValue::getConstantPool(), 0,
4358                                 false, 16);
4359   SDOperand SignBit = DAG.getNode(X86ISD::FAND, SrcVT, Op1, Mask1);
4360
4361   // Shift sign bit right or left if the two operands have different types.
4362   if (MVT::getSizeInBits(SrcVT) > MVT::getSizeInBits(VT)) {
4363     // Op0 is MVT::f32, Op1 is MVT::f64.
4364     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2f64, SignBit);
4365     SignBit = DAG.getNode(X86ISD::FSRL, MVT::v2f64, SignBit,
4366                           DAG.getConstant(32, MVT::i32));
4367     SignBit = DAG.getNode(ISD::BIT_CONVERT, MVT::v4f32, SignBit);
4368     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::f32, SignBit,
4369                           DAG.getIntPtrConstant(0));
4370   }
4371
4372   // Clear first operand sign bit.
4373   CV.clear();
4374   if (VT == MVT::f64) {
4375     CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, ~(1ULL << 63)))));
4376     CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, 0))));
4377   } else {
4378     CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, ~(1U << 31)))));
4379     CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4380     CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4381     CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4382   }
4383   C = ConstantVector::get(CV);
4384   CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4385   SDOperand Mask2 = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4386                                 PseudoSourceValue::getConstantPool(), 0,
4387                                 false, 16);
4388   SDOperand Val = DAG.getNode(X86ISD::FAND, VT, Op0, Mask2);
4389
4390   // Or the value with the sign bit.
4391   return DAG.getNode(X86ISD::FOR, VT, Val, SignBit);
4392 }
4393
4394 SDOperand X86TargetLowering::LowerSETCC(SDOperand Op, SelectionDAG &DAG) {
4395   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
4396   SDOperand Cond;
4397   SDOperand Op0 = Op.getOperand(0);
4398   SDOperand Op1 = Op.getOperand(1);
4399   SDOperand CC = Op.getOperand(2);
4400   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4401   bool isFP = MVT::isFloatingPoint(Op.getOperand(1).getValueType());
4402   unsigned X86CC;
4403
4404   if (translateX86CC(cast<CondCodeSDNode>(CC)->get(), isFP, X86CC,
4405                      Op0, Op1, DAG)) {
4406     Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
4407     return DAG.getNode(X86ISD::SETCC, MVT::i8,
4408                        DAG.getConstant(X86CC, MVT::i8), Cond);
4409   }
4410
4411   assert(isFP && "Illegal integer SetCC!");
4412
4413   Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
4414   switch (SetCCOpcode) {
4415   default: assert(false && "Illegal floating point SetCC!");
4416   case ISD::SETOEQ: {  // !PF & ZF
4417     SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4418                                  DAG.getConstant(X86::COND_NP, MVT::i8), Cond);
4419     SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4420                                  DAG.getConstant(X86::COND_E, MVT::i8), Cond);
4421     return DAG.getNode(ISD::AND, MVT::i8, Tmp1, Tmp2);
4422   }
4423   case ISD::SETUNE: {  // PF | !ZF
4424     SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4425                                  DAG.getConstant(X86::COND_P, MVT::i8), Cond);
4426     SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4427                                  DAG.getConstant(X86::COND_NE, MVT::i8), Cond);
4428     return DAG.getNode(ISD::OR, MVT::i8, Tmp1, Tmp2);
4429   }
4430   }
4431 }
4432
4433
4434 SDOperand X86TargetLowering::LowerSELECT(SDOperand Op, SelectionDAG &DAG) {
4435   bool addTest = true;
4436   SDOperand Cond  = Op.getOperand(0);
4437   SDOperand CC;
4438
4439   if (Cond.getOpcode() == ISD::SETCC)
4440     Cond = LowerSETCC(Cond, DAG);
4441
4442   // If condition flag is set by a X86ISD::CMP, then use it as the condition
4443   // setting operand in place of the X86ISD::SETCC.
4444   if (Cond.getOpcode() == X86ISD::SETCC) {
4445     CC = Cond.getOperand(0);
4446
4447     SDOperand Cmp = Cond.getOperand(1);
4448     unsigned Opc = Cmp.getOpcode();
4449     MVT::ValueType VT = Op.getValueType();
4450     
4451     bool IllegalFPCMov = false;
4452     if (MVT::isFloatingPoint(VT) && !MVT::isVector(VT) &&
4453         !isScalarFPTypeInSSEReg(VT))  // FPStack?
4454       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSignExtended());
4455     
4456     if ((Opc == X86ISD::CMP ||
4457          Opc == X86ISD::COMI ||
4458          Opc == X86ISD::UCOMI) && !IllegalFPCMov) {
4459       Cond = Cmp;
4460       addTest = false;
4461     }
4462   }
4463
4464   if (addTest) {
4465     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4466     Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
4467   }
4468
4469   const MVT::ValueType *VTs = DAG.getNodeValueTypes(Op.getValueType(),
4470                                                     MVT::Flag);
4471   SmallVector<SDOperand, 4> Ops;
4472   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
4473   // condition is true.
4474   Ops.push_back(Op.getOperand(2));
4475   Ops.push_back(Op.getOperand(1));
4476   Ops.push_back(CC);
4477   Ops.push_back(Cond);
4478   return DAG.getNode(X86ISD::CMOV, VTs, 2, &Ops[0], Ops.size());
4479 }
4480
4481 SDOperand X86TargetLowering::LowerBRCOND(SDOperand Op, SelectionDAG &DAG) {
4482   bool addTest = true;
4483   SDOperand Chain = Op.getOperand(0);
4484   SDOperand Cond  = Op.getOperand(1);
4485   SDOperand Dest  = Op.getOperand(2);
4486   SDOperand CC;
4487
4488   if (Cond.getOpcode() == ISD::SETCC)
4489     Cond = LowerSETCC(Cond, DAG);
4490
4491   // If condition flag is set by a X86ISD::CMP, then use it as the condition
4492   // setting operand in place of the X86ISD::SETCC.
4493   if (Cond.getOpcode() == X86ISD::SETCC) {
4494     CC = Cond.getOperand(0);
4495
4496     SDOperand Cmp = Cond.getOperand(1);
4497     unsigned Opc = Cmp.getOpcode();
4498     if (Opc == X86ISD::CMP ||
4499         Opc == X86ISD::COMI ||
4500         Opc == X86ISD::UCOMI) {
4501       Cond = Cmp;
4502       addTest = false;
4503     }
4504   }
4505
4506   if (addTest) {
4507     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4508     Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
4509   }
4510   return DAG.getNode(X86ISD::BRCOND, Op.getValueType(),
4511                      Chain, Op.getOperand(2), CC, Cond);
4512 }
4513
4514
4515 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
4516 // Calls to _alloca is needed to probe the stack when allocating more than 4k
4517 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
4518 // that the guard pages used by the OS virtual memory manager are allocated in
4519 // correct sequence.
4520 SDOperand
4521 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDOperand Op,
4522                                            SelectionDAG &DAG) {
4523   assert(Subtarget->isTargetCygMing() &&
4524          "This should be used only on Cygwin/Mingw targets");
4525   
4526   // Get the inputs.
4527   SDOperand Chain = Op.getOperand(0);
4528   SDOperand Size  = Op.getOperand(1);
4529   // FIXME: Ensure alignment here
4530
4531   SDOperand Flag;
4532   
4533   MVT::ValueType IntPtr = getPointerTy();
4534   MVT::ValueType SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
4535
4536   Chain = DAG.getCopyToReg(Chain, X86::EAX, Size, Flag);
4537   Flag = Chain.getValue(1);
4538
4539   SDVTList  NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4540   SDOperand Ops[] = { Chain,
4541                       DAG.getTargetExternalSymbol("_alloca", IntPtr),
4542                       DAG.getRegister(X86::EAX, IntPtr),
4543                       Flag };
4544   Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops, 4);
4545   Flag = Chain.getValue(1);
4546
4547   Chain = DAG.getCopyFromReg(Chain, X86StackPtr, SPTy).getValue(1);
4548   
4549   std::vector<MVT::ValueType> Tys;
4550   Tys.push_back(SPTy);
4551   Tys.push_back(MVT::Other);
4552   SDOperand Ops1[2] = { Chain.getValue(0), Chain };
4553   return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops1, 2);
4554 }
4555
4556 SDOperand
4557 X86TargetLowering::EmitTargetCodeForMemset(SelectionDAG &DAG,
4558                                            SDOperand Chain,
4559                                            SDOperand Dst, SDOperand Src,
4560                                            SDOperand Size, unsigned Align,
4561                                            Value *DstSV, uint64_t DstOff) {
4562   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
4563
4564   /// If not DWORD aligned or size is more than the threshold, call the library.
4565   /// The libc version is likely to be faster for these cases. It can use the
4566   /// address value and run time information about the CPU.
4567   if ((Align & 3) == 0 ||
4568       !ConstantSize ||
4569       ConstantSize->getValue() > getSubtarget()->getMaxInlineSizeThreshold()) {
4570     SDOperand InFlag(0, 0);
4571
4572     // Check to see if there is a specialized entry-point for memory zeroing.
4573     ConstantSDNode *V = dyn_cast<ConstantSDNode>(Src);
4574     if (const char *bzeroEntry = 
4575           V && V->isNullValue() ? Subtarget->getBZeroEntry() : 0) {
4576       MVT::ValueType IntPtr = getPointerTy();
4577       const Type *IntPtrTy = getTargetData()->getIntPtrType();
4578       TargetLowering::ArgListTy Args; 
4579       TargetLowering::ArgListEntry Entry;
4580       Entry.Node = Dst;
4581       Entry.Ty = IntPtrTy;
4582       Args.push_back(Entry);
4583       Entry.Node = Size;
4584       Args.push_back(Entry);
4585       std::pair<SDOperand,SDOperand> CallResult =
4586         LowerCallTo(Chain, Type::VoidTy, false, false, false, CallingConv::C,
4587                     false, DAG.getExternalSymbol(bzeroEntry, IntPtr),
4588                     Args, DAG);
4589       return CallResult.second;
4590     }
4591
4592     // Otherwise have the target-independent code call memset.
4593     return SDOperand();
4594   }
4595
4596   uint64_t SizeVal = ConstantSize->getValue();
4597   SDOperand InFlag(0, 0);
4598   MVT::ValueType AVT;
4599   SDOperand Count;
4600   ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Src);
4601   unsigned BytesLeft = 0;
4602   bool TwoRepStos = false;
4603   if (ValC) {
4604     unsigned ValReg;
4605     uint64_t Val = ValC->getValue() & 255;
4606
4607     // If the value is a constant, then we can potentially use larger sets.
4608     switch (Align & 3) {
4609       case 2:   // WORD aligned
4610         AVT = MVT::i16;
4611         ValReg = X86::AX;
4612         Val = (Val << 8) | Val;
4613         break;
4614       case 0:  // DWORD aligned
4615         AVT = MVT::i32;
4616         ValReg = X86::EAX;
4617         Val = (Val << 8)  | Val;
4618         Val = (Val << 16) | Val;
4619         if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) {  // QWORD aligned
4620           AVT = MVT::i64;
4621           ValReg = X86::RAX;
4622           Val = (Val << 32) | Val;
4623         }
4624         break;
4625       default:  // Byte aligned
4626         AVT = MVT::i8;
4627         ValReg = X86::AL;
4628         Count = Size;
4629         break;
4630     }
4631
4632     if (AVT > MVT::i8) {
4633       unsigned UBytes = MVT::getSizeInBits(AVT) / 8;
4634       Count = DAG.getIntPtrConstant(SizeVal / UBytes);
4635       BytesLeft = SizeVal % UBytes;
4636     }
4637
4638     Chain  = DAG.getCopyToReg(Chain, ValReg, DAG.getConstant(Val, AVT),
4639                               InFlag);
4640     InFlag = Chain.getValue(1);
4641   } else {
4642     AVT = MVT::i8;
4643     Count  = Size;
4644     Chain  = DAG.getCopyToReg(Chain, X86::AL, Src, InFlag);
4645     InFlag = Chain.getValue(1);
4646   }
4647
4648   Chain  = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
4649                             Count, InFlag);
4650   InFlag = Chain.getValue(1);
4651   Chain  = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
4652                             Dst, InFlag);
4653   InFlag = Chain.getValue(1);
4654
4655   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4656   SmallVector<SDOperand, 8> Ops;
4657   Ops.push_back(Chain);
4658   Ops.push_back(DAG.getValueType(AVT));
4659   Ops.push_back(InFlag);
4660   Chain  = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
4661
4662   if (TwoRepStos) {
4663     InFlag = Chain.getValue(1);
4664     Count  = Size;
4665     MVT::ValueType CVT = Count.getValueType();
4666     SDOperand Left = DAG.getNode(ISD::AND, CVT, Count,
4667                                DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
4668     Chain  = DAG.getCopyToReg(Chain, (CVT == MVT::i64) ? X86::RCX : X86::ECX,
4669                               Left, InFlag);
4670     InFlag = Chain.getValue(1);
4671     Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4672     Ops.clear();
4673     Ops.push_back(Chain);
4674     Ops.push_back(DAG.getValueType(MVT::i8));
4675     Ops.push_back(InFlag);
4676     Chain  = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
4677   } else if (BytesLeft) {
4678     // Handle the last 1 - 7 bytes.
4679     unsigned Offset = SizeVal - BytesLeft;
4680     MVT::ValueType AddrVT = Dst.getValueType();
4681     MVT::ValueType SizeVT = Size.getValueType();
4682
4683     Chain = DAG.getMemset(Chain,
4684                           DAG.getNode(ISD::ADD, AddrVT, Dst,
4685                                       DAG.getConstant(Offset, AddrVT)),
4686                           Src,
4687                           DAG.getConstant(BytesLeft, SizeVT),
4688                           Align, DstSV, Offset);
4689   }
4690
4691   // TODO: Use a Tokenfactor, as in memcpy, instead of a single chain.
4692   return Chain;
4693 }
4694
4695 SDOperand
4696 X86TargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG,
4697                                            SDOperand Chain,
4698                                            SDOperand Dst, SDOperand Src,
4699                                            SDOperand Size, unsigned Align,
4700                                            bool AlwaysInline,
4701                                            Value *DstSV, uint64_t DstOff,
4702                                            Value *SrcSV, uint64_t SrcOff){
4703   
4704   // This requires the copy size to be a constant, preferrably
4705   // within a subtarget-specific limit.
4706   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
4707   if (!ConstantSize)
4708     return SDOperand();
4709   uint64_t SizeVal = ConstantSize->getValue();
4710   if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
4711     return SDOperand();
4712
4713   SmallVector<SDOperand, 4> Results;
4714
4715   MVT::ValueType AVT;
4716   unsigned BytesLeft = 0;
4717   if (Align >= 8 && Subtarget->is64Bit())
4718     AVT = MVT::i64;
4719   else if (Align >= 4)
4720     AVT = MVT::i32;
4721   else if (Align >= 2)
4722     AVT = MVT::i16;
4723   else
4724     AVT = MVT::i8;
4725
4726   unsigned UBytes = MVT::getSizeInBits(AVT) / 8;
4727   unsigned CountVal = SizeVal / UBytes;
4728   SDOperand Count = DAG.getIntPtrConstant(CountVal);
4729   BytesLeft = SizeVal % UBytes;
4730
4731   SDOperand InFlag(0, 0);
4732   Chain  = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
4733                             Count, InFlag);
4734   InFlag = Chain.getValue(1);
4735   Chain  = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
4736                             Dst, InFlag);
4737   InFlag = Chain.getValue(1);
4738   Chain  = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RSI : X86::ESI,
4739                             Src, InFlag);
4740   InFlag = Chain.getValue(1);
4741
4742   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4743   SmallVector<SDOperand, 8> Ops;
4744   Ops.push_back(Chain);
4745   Ops.push_back(DAG.getValueType(AVT));
4746   Ops.push_back(InFlag);
4747   Results.push_back(DAG.getNode(X86ISD::REP_MOVS, Tys, &Ops[0], Ops.size()));
4748
4749   if (BytesLeft) {
4750     // Handle the last 1 - 7 bytes.
4751     unsigned Offset = SizeVal - BytesLeft;
4752     MVT::ValueType DstVT = Dst.getValueType();
4753     MVT::ValueType SrcVT = Src.getValueType();
4754     MVT::ValueType SizeVT = Size.getValueType();
4755
4756     Results.push_back(DAG.getMemcpy(Chain, 
4757                                     DAG.getNode(ISD::ADD, DstVT, Dst,
4758                                                 DAG.getConstant(Offset,
4759                                                                 DstVT)),
4760                                     DAG.getNode(ISD::ADD, SrcVT, Src,
4761                                                 DAG.getConstant(Offset,
4762                                                                 SrcVT)),
4763                                     DAG.getConstant(BytesLeft, SizeVT),
4764                                     Align, AlwaysInline,
4765                                     DstSV, Offset, SrcSV, Offset));
4766   }
4767
4768   return DAG.getNode(ISD::TokenFactor, MVT::Other, &Results[0], Results.size());
4769 }
4770
4771 /// Expand the result of: i64,outchain = READCYCLECOUNTER inchain
4772 SDNode *X86TargetLowering::ExpandREADCYCLECOUNTER(SDNode *N, SelectionDAG &DAG){
4773   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4774   SDOperand TheChain = N->getOperand(0);
4775   SDOperand rd = DAG.getNode(X86ISD::RDTSC_DAG, Tys, &TheChain, 1);
4776   if (Subtarget->is64Bit()) {
4777     SDOperand rax = DAG.getCopyFromReg(rd, X86::RAX, MVT::i64, rd.getValue(1));
4778     SDOperand rdx = DAG.getCopyFromReg(rax.getValue(1), X86::RDX,
4779                                        MVT::i64, rax.getValue(2));
4780     SDOperand Tmp = DAG.getNode(ISD::SHL, MVT::i64, rdx,
4781                                 DAG.getConstant(32, MVT::i8));
4782     SDOperand Ops[] = {
4783       DAG.getNode(ISD::OR, MVT::i64, rax, Tmp), rdx.getValue(1)
4784     };
4785     
4786     Tys = DAG.getVTList(MVT::i64, MVT::Other);
4787     return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops, 2).Val;
4788   }
4789   
4790   SDOperand eax = DAG.getCopyFromReg(rd, X86::EAX, MVT::i32, rd.getValue(1));
4791   SDOperand edx = DAG.getCopyFromReg(eax.getValue(1), X86::EDX,
4792                                        MVT::i32, eax.getValue(2));
4793   // Use a buildpair to merge the two 32-bit values into a 64-bit one. 
4794   SDOperand Ops[] = { eax, edx };
4795   Ops[0] = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, Ops, 2);
4796
4797   // Use a MERGE_VALUES to return the value and chain.
4798   Ops[1] = edx.getValue(1);
4799   Tys = DAG.getVTList(MVT::i64, MVT::Other);
4800   return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops, 2).Val;
4801 }
4802
4803 SDOperand X86TargetLowering::LowerVASTART(SDOperand Op, SelectionDAG &DAG) {
4804   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4805
4806   if (!Subtarget->is64Bit()) {
4807     // vastart just stores the address of the VarArgsFrameIndex slot into the
4808     // memory location argument.
4809     SDOperand FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
4810     return DAG.getStore(Op.getOperand(0), FR,Op.getOperand(1), SV, 0);
4811   }
4812
4813   // __va_list_tag:
4814   //   gp_offset         (0 - 6 * 8)
4815   //   fp_offset         (48 - 48 + 8 * 16)
4816   //   overflow_arg_area (point to parameters coming in memory).
4817   //   reg_save_area
4818   SmallVector<SDOperand, 8> MemOps;
4819   SDOperand FIN = Op.getOperand(1);
4820   // Store gp_offset
4821   SDOperand Store = DAG.getStore(Op.getOperand(0),
4822                                  DAG.getConstant(VarArgsGPOffset, MVT::i32),
4823                                  FIN, SV, 0);
4824   MemOps.push_back(Store);
4825
4826   // Store fp_offset
4827   FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(4));
4828   Store = DAG.getStore(Op.getOperand(0),
4829                        DAG.getConstant(VarArgsFPOffset, MVT::i32),
4830                        FIN, SV, 0);
4831   MemOps.push_back(Store);
4832
4833   // Store ptr to overflow_arg_area
4834   FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(4));
4835   SDOperand OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
4836   Store = DAG.getStore(Op.getOperand(0), OVFIN, FIN, SV, 0);
4837   MemOps.push_back(Store);
4838
4839   // Store ptr to reg_save_area.
4840   FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(8));
4841   SDOperand RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
4842   Store = DAG.getStore(Op.getOperand(0), RSFIN, FIN, SV, 0);
4843   MemOps.push_back(Store);
4844   return DAG.getNode(ISD::TokenFactor, MVT::Other, &MemOps[0], MemOps.size());
4845 }
4846
4847 SDOperand X86TargetLowering::LowerVACOPY(SDOperand Op, SelectionDAG &DAG) {
4848   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
4849   SDOperand Chain = Op.getOperand(0);
4850   SDOperand DstPtr = Op.getOperand(1);
4851   SDOperand SrcPtr = Op.getOperand(2);
4852   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
4853   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
4854
4855   SrcPtr = DAG.getLoad(getPointerTy(), Chain, SrcPtr, SrcSV, 0);
4856   Chain = SrcPtr.getValue(1);
4857   for (unsigned i = 0; i < 3; ++i) {
4858     SDOperand Val = DAG.getLoad(MVT::i64, Chain, SrcPtr, SrcSV, 0);
4859     Chain = Val.getValue(1);
4860     Chain = DAG.getStore(Chain, Val, DstPtr, DstSV, 0);
4861     if (i == 2)
4862       break;
4863     SrcPtr = DAG.getNode(ISD::ADD, getPointerTy(), SrcPtr, 
4864                          DAG.getIntPtrConstant(8));
4865     DstPtr = DAG.getNode(ISD::ADD, getPointerTy(), DstPtr, 
4866                          DAG.getIntPtrConstant(8));
4867   }
4868   return Chain;
4869 }
4870
4871 SDOperand
4872 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDOperand Op, SelectionDAG &DAG) {
4873   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getValue();
4874   switch (IntNo) {
4875   default: return SDOperand();    // Don't custom lower most intrinsics.
4876     // Comparison intrinsics.
4877   case Intrinsic::x86_sse_comieq_ss:
4878   case Intrinsic::x86_sse_comilt_ss:
4879   case Intrinsic::x86_sse_comile_ss:
4880   case Intrinsic::x86_sse_comigt_ss:
4881   case Intrinsic::x86_sse_comige_ss:
4882   case Intrinsic::x86_sse_comineq_ss:
4883   case Intrinsic::x86_sse_ucomieq_ss:
4884   case Intrinsic::x86_sse_ucomilt_ss:
4885   case Intrinsic::x86_sse_ucomile_ss:
4886   case Intrinsic::x86_sse_ucomigt_ss:
4887   case Intrinsic::x86_sse_ucomige_ss:
4888   case Intrinsic::x86_sse_ucomineq_ss:
4889   case Intrinsic::x86_sse2_comieq_sd:
4890   case Intrinsic::x86_sse2_comilt_sd:
4891   case Intrinsic::x86_sse2_comile_sd:
4892   case Intrinsic::x86_sse2_comigt_sd:
4893   case Intrinsic::x86_sse2_comige_sd:
4894   case Intrinsic::x86_sse2_comineq_sd:
4895   case Intrinsic::x86_sse2_ucomieq_sd:
4896   case Intrinsic::x86_sse2_ucomilt_sd:
4897   case Intrinsic::x86_sse2_ucomile_sd:
4898   case Intrinsic::x86_sse2_ucomigt_sd:
4899   case Intrinsic::x86_sse2_ucomige_sd:
4900   case Intrinsic::x86_sse2_ucomineq_sd: {
4901     unsigned Opc = 0;
4902     ISD::CondCode CC = ISD::SETCC_INVALID;
4903     switch (IntNo) {
4904     default: break;
4905     case Intrinsic::x86_sse_comieq_ss:
4906     case Intrinsic::x86_sse2_comieq_sd:
4907       Opc = X86ISD::COMI;
4908       CC = ISD::SETEQ;
4909       break;
4910     case Intrinsic::x86_sse_comilt_ss:
4911     case Intrinsic::x86_sse2_comilt_sd:
4912       Opc = X86ISD::COMI;
4913       CC = ISD::SETLT;
4914       break;
4915     case Intrinsic::x86_sse_comile_ss:
4916     case Intrinsic::x86_sse2_comile_sd:
4917       Opc = X86ISD::COMI;
4918       CC = ISD::SETLE;
4919       break;
4920     case Intrinsic::x86_sse_comigt_ss:
4921     case Intrinsic::x86_sse2_comigt_sd:
4922       Opc = X86ISD::COMI;
4923       CC = ISD::SETGT;
4924       break;
4925     case Intrinsic::x86_sse_comige_ss:
4926     case Intrinsic::x86_sse2_comige_sd:
4927       Opc = X86ISD::COMI;
4928       CC = ISD::SETGE;
4929       break;
4930     case Intrinsic::x86_sse_comineq_ss:
4931     case Intrinsic::x86_sse2_comineq_sd:
4932       Opc = X86ISD::COMI;
4933       CC = ISD::SETNE;
4934       break;
4935     case Intrinsic::x86_sse_ucomieq_ss:
4936     case Intrinsic::x86_sse2_ucomieq_sd:
4937       Opc = X86ISD::UCOMI;
4938       CC = ISD::SETEQ;
4939       break;
4940     case Intrinsic::x86_sse_ucomilt_ss:
4941     case Intrinsic::x86_sse2_ucomilt_sd:
4942       Opc = X86ISD::UCOMI;
4943       CC = ISD::SETLT;
4944       break;
4945     case Intrinsic::x86_sse_ucomile_ss:
4946     case Intrinsic::x86_sse2_ucomile_sd:
4947       Opc = X86ISD::UCOMI;
4948       CC = ISD::SETLE;
4949       break;
4950     case Intrinsic::x86_sse_ucomigt_ss:
4951     case Intrinsic::x86_sse2_ucomigt_sd:
4952       Opc = X86ISD::UCOMI;
4953       CC = ISD::SETGT;
4954       break;
4955     case Intrinsic::x86_sse_ucomige_ss:
4956     case Intrinsic::x86_sse2_ucomige_sd:
4957       Opc = X86ISD::UCOMI;
4958       CC = ISD::SETGE;
4959       break;
4960     case Intrinsic::x86_sse_ucomineq_ss:
4961     case Intrinsic::x86_sse2_ucomineq_sd:
4962       Opc = X86ISD::UCOMI;
4963       CC = ISD::SETNE;
4964       break;
4965     }
4966
4967     unsigned X86CC;
4968     SDOperand LHS = Op.getOperand(1);
4969     SDOperand RHS = Op.getOperand(2);
4970     translateX86CC(CC, true, X86CC, LHS, RHS, DAG);
4971
4972     SDOperand Cond = DAG.getNode(Opc, MVT::i32, LHS, RHS);
4973     SDOperand SetCC = DAG.getNode(X86ISD::SETCC, MVT::i8,
4974                                   DAG.getConstant(X86CC, MVT::i8), Cond);
4975     return DAG.getNode(ISD::ANY_EXTEND, MVT::i32, SetCC);
4976   }
4977   }
4978 }
4979
4980 SDOperand X86TargetLowering::LowerRETURNADDR(SDOperand Op, SelectionDAG &DAG) {
4981   // Depths > 0 not supported yet!
4982   if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
4983     return SDOperand();
4984   
4985   // Just load the return address
4986   SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
4987   return DAG.getLoad(getPointerTy(), DAG.getEntryNode(), RetAddrFI, NULL, 0);
4988 }
4989
4990 SDOperand X86TargetLowering::LowerFRAMEADDR(SDOperand Op, SelectionDAG &DAG) {
4991   // Depths > 0 not supported yet!
4992   if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
4993     return SDOperand();
4994     
4995   SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
4996   return DAG.getNode(ISD::SUB, getPointerTy(), RetAddrFI, 
4997                      DAG.getIntPtrConstant(4));
4998 }
4999
5000 SDOperand X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDOperand Op,
5001                                                        SelectionDAG &DAG) {
5002   // Is not yet supported on x86-64
5003   if (Subtarget->is64Bit())
5004     return SDOperand();
5005   
5006   return DAG.getIntPtrConstant(8);
5007 }
5008
5009 SDOperand X86TargetLowering::LowerEH_RETURN(SDOperand Op, SelectionDAG &DAG)
5010 {
5011   assert(!Subtarget->is64Bit() &&
5012          "Lowering of eh_return builtin is not supported yet on x86-64");
5013     
5014   MachineFunction &MF = DAG.getMachineFunction();
5015   SDOperand Chain     = Op.getOperand(0);
5016   SDOperand Offset    = Op.getOperand(1);
5017   SDOperand Handler   = Op.getOperand(2);
5018
5019   SDOperand Frame = DAG.getRegister(RegInfo->getFrameRegister(MF),
5020                                     getPointerTy());
5021
5022   SDOperand StoreAddr = DAG.getNode(ISD::SUB, getPointerTy(), Frame,
5023                                     DAG.getIntPtrConstant(-4UL));
5024   StoreAddr = DAG.getNode(ISD::ADD, getPointerTy(), StoreAddr, Offset);
5025   Chain = DAG.getStore(Chain, Handler, StoreAddr, NULL, 0);
5026   Chain = DAG.getCopyToReg(Chain, X86::ECX, StoreAddr);
5027   MF.getRegInfo().addLiveOut(X86::ECX);
5028
5029   return DAG.getNode(X86ISD::EH_RETURN, MVT::Other,
5030                      Chain, DAG.getRegister(X86::ECX, getPointerTy()));
5031 }
5032
5033 SDOperand X86TargetLowering::LowerTRAMPOLINE(SDOperand Op,
5034                                              SelectionDAG &DAG) {
5035   SDOperand Root = Op.getOperand(0);
5036   SDOperand Trmp = Op.getOperand(1); // trampoline
5037   SDOperand FPtr = Op.getOperand(2); // nested function
5038   SDOperand Nest = Op.getOperand(3); // 'nest' parameter value
5039
5040   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5041
5042   const X86InstrInfo *TII =
5043     ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
5044
5045   if (Subtarget->is64Bit()) {
5046     SDOperand OutChains[6];
5047
5048     // Large code-model.
5049
5050     const unsigned char JMP64r  = TII->getBaseOpcodeFor(X86::JMP64r);
5051     const unsigned char MOV64ri = TII->getBaseOpcodeFor(X86::MOV64ri);
5052
5053     const unsigned char N86R10 =
5054       ((const X86RegisterInfo*)RegInfo)->getX86RegNum(X86::R10);
5055     const unsigned char N86R11 =
5056       ((const X86RegisterInfo*)RegInfo)->getX86RegNum(X86::R11);
5057
5058     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
5059
5060     // Load the pointer to the nested function into R11.
5061     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
5062     SDOperand Addr = Trmp;
5063     OutChains[0] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5064                                 TrmpAddr, 0);
5065
5066     Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(2, MVT::i64));
5067     OutChains[1] = DAG.getStore(Root, FPtr, Addr, TrmpAddr, 2, false, 2);
5068
5069     // Load the 'nest' parameter value into R10.
5070     // R10 is specified in X86CallingConv.td
5071     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
5072     Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(10, MVT::i64));
5073     OutChains[2] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5074                                 TrmpAddr, 10);
5075
5076     Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(12, MVT::i64));
5077     OutChains[3] = DAG.getStore(Root, Nest, Addr, TrmpAddr, 12, false, 2);
5078
5079     // Jump to the nested function.
5080     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
5081     Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(20, MVT::i64));
5082     OutChains[4] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5083                                 TrmpAddr, 20);
5084
5085     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
5086     Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(22, MVT::i64));
5087     OutChains[5] = DAG.getStore(Root, DAG.getConstant(ModRM, MVT::i8), Addr,
5088                                 TrmpAddr, 22);
5089
5090     SDOperand Ops[] =
5091       { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 6) };
5092     return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(), Ops, 2);
5093   } else {
5094     const Function *Func =
5095       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
5096     unsigned CC = Func->getCallingConv();
5097     unsigned NestReg;
5098
5099     switch (CC) {
5100     default:
5101       assert(0 && "Unsupported calling convention");
5102     case CallingConv::C:
5103     case CallingConv::X86_StdCall: {
5104       // Pass 'nest' parameter in ECX.
5105       // Must be kept in sync with X86CallingConv.td
5106       NestReg = X86::ECX;
5107
5108       // Check that ECX wasn't needed by an 'inreg' parameter.
5109       const FunctionType *FTy = Func->getFunctionType();
5110       const PAListPtr &Attrs = Func->getParamAttrs();
5111
5112       if (!Attrs.isEmpty() && !Func->isVarArg()) {
5113         unsigned InRegCount = 0;
5114         unsigned Idx = 1;
5115
5116         for (FunctionType::param_iterator I = FTy->param_begin(),
5117              E = FTy->param_end(); I != E; ++I, ++Idx)
5118           if (Attrs.paramHasAttr(Idx, ParamAttr::InReg))
5119             // FIXME: should only count parameters that are lowered to integers.
5120             InRegCount += (getTargetData()->getTypeSizeInBits(*I) + 31) / 32;
5121
5122         if (InRegCount > 2) {
5123           cerr << "Nest register in use - reduce number of inreg parameters!\n";
5124           abort();
5125         }
5126       }
5127       break;
5128     }
5129     case CallingConv::X86_FastCall:
5130       // Pass 'nest' parameter in EAX.
5131       // Must be kept in sync with X86CallingConv.td
5132       NestReg = X86::EAX;
5133       break;
5134     }
5135
5136     SDOperand OutChains[4];
5137     SDOperand Addr, Disp;
5138
5139     Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(10, MVT::i32));
5140     Disp = DAG.getNode(ISD::SUB, MVT::i32, FPtr, Addr);
5141
5142     const unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
5143     const unsigned char N86Reg =
5144       ((const X86RegisterInfo*)RegInfo)->getX86RegNum(NestReg);
5145     OutChains[0] = DAG.getStore(Root, DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
5146                                 Trmp, TrmpAddr, 0);
5147
5148     Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(1, MVT::i32));
5149     OutChains[1] = DAG.getStore(Root, Nest, Addr, TrmpAddr, 1, false, 1);
5150
5151     const unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
5152     Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(5, MVT::i32));
5153     OutChains[2] = DAG.getStore(Root, DAG.getConstant(JMP, MVT::i8), Addr,
5154                                 TrmpAddr, 5, false, 1);
5155
5156     Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(6, MVT::i32));
5157     OutChains[3] = DAG.getStore(Root, Disp, Addr, TrmpAddr, 6, false, 1);
5158
5159     SDOperand Ops[] =
5160       { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 4) };
5161     return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(), Ops, 2);
5162   }
5163 }
5164
5165 SDOperand X86TargetLowering::LowerFLT_ROUNDS_(SDOperand Op, SelectionDAG &DAG) {
5166   /*
5167    The rounding mode is in bits 11:10 of FPSR, and has the following
5168    settings:
5169      00 Round to nearest
5170      01 Round to -inf
5171      10 Round to +inf
5172      11 Round to 0
5173
5174   FLT_ROUNDS, on the other hand, expects the following:
5175     -1 Undefined
5176      0 Round to 0
5177      1 Round to nearest
5178      2 Round to +inf
5179      3 Round to -inf
5180
5181   To perform the conversion, we do:
5182     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
5183   */
5184
5185   MachineFunction &MF = DAG.getMachineFunction();
5186   const TargetMachine &TM = MF.getTarget();
5187   const TargetFrameInfo &TFI = *TM.getFrameInfo();
5188   unsigned StackAlignment = TFI.getStackAlignment();
5189   MVT::ValueType VT = Op.getValueType();
5190
5191   // Save FP Control Word to stack slot
5192   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment);
5193   SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5194
5195   SDOperand Chain = DAG.getNode(X86ISD::FNSTCW16m, MVT::Other,
5196                                 DAG.getEntryNode(), StackSlot);
5197
5198   // Load FP Control Word from stack slot
5199   SDOperand CWD = DAG.getLoad(MVT::i16, Chain, StackSlot, NULL, 0);
5200
5201   // Transform as necessary
5202   SDOperand CWD1 =
5203     DAG.getNode(ISD::SRL, MVT::i16,
5204                 DAG.getNode(ISD::AND, MVT::i16,
5205                             CWD, DAG.getConstant(0x800, MVT::i16)),
5206                 DAG.getConstant(11, MVT::i8));
5207   SDOperand CWD2 =
5208     DAG.getNode(ISD::SRL, MVT::i16,
5209                 DAG.getNode(ISD::AND, MVT::i16,
5210                             CWD, DAG.getConstant(0x400, MVT::i16)),
5211                 DAG.getConstant(9, MVT::i8));
5212
5213   SDOperand RetVal =
5214     DAG.getNode(ISD::AND, MVT::i16,
5215                 DAG.getNode(ISD::ADD, MVT::i16,
5216                             DAG.getNode(ISD::OR, MVT::i16, CWD1, CWD2),
5217                             DAG.getConstant(1, MVT::i16)),
5218                 DAG.getConstant(3, MVT::i16));
5219
5220
5221   return DAG.getNode((MVT::getSizeInBits(VT) < 16 ?
5222                       ISD::TRUNCATE : ISD::ZERO_EXTEND), VT, RetVal);
5223 }
5224
5225 SDOperand X86TargetLowering::LowerCTLZ(SDOperand Op, SelectionDAG &DAG) {
5226   MVT::ValueType VT = Op.getValueType();
5227   MVT::ValueType OpVT = VT;
5228   unsigned NumBits = MVT::getSizeInBits(VT);
5229
5230   Op = Op.getOperand(0);
5231   if (VT == MVT::i8) {
5232     // Zero extend to i32 since there is not an i8 bsr.
5233     OpVT = MVT::i32;
5234     Op = DAG.getNode(ISD::ZERO_EXTEND, OpVT, Op);
5235   }
5236
5237   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
5238   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
5239   Op = DAG.getNode(X86ISD::BSR, VTs, Op);
5240
5241   // If src is zero (i.e. bsr sets ZF), returns NumBits.
5242   SmallVector<SDOperand, 4> Ops;
5243   Ops.push_back(Op);
5244   Ops.push_back(DAG.getConstant(NumBits+NumBits-1, OpVT));
5245   Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
5246   Ops.push_back(Op.getValue(1));
5247   Op = DAG.getNode(X86ISD::CMOV, OpVT, &Ops[0], 4);
5248
5249   // Finally xor with NumBits-1.
5250   Op = DAG.getNode(ISD::XOR, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
5251
5252   if (VT == MVT::i8)
5253     Op = DAG.getNode(ISD::TRUNCATE, MVT::i8, Op);
5254   return Op;
5255 }
5256
5257 SDOperand X86TargetLowering::LowerCTTZ(SDOperand Op, SelectionDAG &DAG) {
5258   MVT::ValueType VT = Op.getValueType();
5259   MVT::ValueType OpVT = VT;
5260   unsigned NumBits = MVT::getSizeInBits(VT);
5261
5262   Op = Op.getOperand(0);
5263   if (VT == MVT::i8) {
5264     OpVT = MVT::i32;
5265     Op = DAG.getNode(ISD::ZERO_EXTEND, OpVT, Op);
5266   }
5267
5268   // Issue a bsf (scan bits forward) which also sets EFLAGS.
5269   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
5270   Op = DAG.getNode(X86ISD::BSF, VTs, Op);
5271
5272   // If src is zero (i.e. bsf sets ZF), returns NumBits.
5273   SmallVector<SDOperand, 4> Ops;
5274   Ops.push_back(Op);
5275   Ops.push_back(DAG.getConstant(NumBits, OpVT));
5276   Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
5277   Ops.push_back(Op.getValue(1));
5278   Op = DAG.getNode(X86ISD::CMOV, OpVT, &Ops[0], 4);
5279
5280   if (VT == MVT::i8)
5281     Op = DAG.getNode(ISD::TRUNCATE, MVT::i8, Op);
5282   return Op;
5283 }
5284
5285 SDOperand X86TargetLowering::LowerLCS(SDOperand Op, SelectionDAG &DAG) {
5286   MVT::ValueType T = cast<AtomicSDNode>(Op.Val)->getVT();
5287   unsigned Reg = 0;
5288   unsigned size = 0;
5289   switch(T) {
5290   case MVT::i8:  Reg = X86::AL;  size = 1; break;
5291   case MVT::i16: Reg = X86::AX;  size = 2; break;
5292   case MVT::i32: Reg = X86::EAX; size = 4; break;
5293   case MVT::i64: 
5294     if (Subtarget->is64Bit()) {
5295       Reg = X86::RAX; size = 8;
5296     } else //Should go away when LowerType stuff lands
5297       return SDOperand(ExpandATOMIC_LCS(Op.Val, DAG), 0);
5298     break;
5299   };
5300   SDOperand cpIn = DAG.getCopyToReg(Op.getOperand(0), Reg,
5301                                     Op.getOperand(3), SDOperand());
5302   SDOperand Ops[] = { cpIn.getValue(0),
5303                       Op.getOperand(1),
5304                       Op.getOperand(2),
5305                       DAG.getTargetConstant(size, MVT::i8),
5306                       cpIn.getValue(1) };
5307   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5308   SDOperand Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, Tys, Ops, 5);
5309   SDOperand cpOut = 
5310     DAG.getCopyFromReg(Result.getValue(0), Reg, T, Result.getValue(1));
5311   return cpOut;
5312 }
5313
5314 SDNode* X86TargetLowering::ExpandATOMIC_LCS(SDNode* Op, SelectionDAG &DAG) {
5315   MVT::ValueType T = cast<AtomicSDNode>(Op)->getVT();
5316   assert (T == MVT::i64 && "Only know how to expand i64 CAS");
5317   SDOperand cpInL, cpInH;
5318   cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(3),
5319                       DAG.getConstant(0, MVT::i32));
5320   cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(3),
5321                       DAG.getConstant(1, MVT::i32));
5322   cpInL = DAG.getCopyToReg(Op->getOperand(0), X86::EAX,
5323                            cpInL, SDOperand());
5324   cpInH = DAG.getCopyToReg(cpInL.getValue(0), X86::EDX,
5325                            cpInH, cpInL.getValue(1));
5326   SDOperand swapInL, swapInH;
5327   swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(2),
5328                         DAG.getConstant(0, MVT::i32));
5329   swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(2),
5330                         DAG.getConstant(1, MVT::i32));
5331   swapInL = DAG.getCopyToReg(cpInH.getValue(0), X86::EBX,
5332                              swapInL, cpInH.getValue(1));
5333   swapInH = DAG.getCopyToReg(swapInL.getValue(0), X86::ECX,
5334                              swapInH, swapInL.getValue(1));
5335   SDOperand Ops[] = { swapInH.getValue(0),
5336                       Op->getOperand(1),
5337                       swapInH.getValue(1)};
5338   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5339   SDOperand Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, Tys, Ops, 3);
5340   SDOperand cpOutL = DAG.getCopyFromReg(Result.getValue(0), X86::EAX, MVT::i32, 
5341                                         Result.getValue(1));
5342   SDOperand cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), X86::EDX, MVT::i32, 
5343                                         cpOutL.getValue(2));
5344   SDOperand OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
5345   SDOperand ResultVal = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, OpsF, 2);
5346   Tys = DAG.getVTList(MVT::i64, MVT::Other);
5347   return DAG.getNode(ISD::MERGE_VALUES, Tys, ResultVal, cpOutH.getValue(1)).Val;
5348 }
5349
5350 /// LowerOperation - Provide custom lowering hooks for some operations.
5351 ///
5352 SDOperand X86TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
5353   switch (Op.getOpcode()) {
5354   default: assert(0 && "Should not custom lower this!");
5355   case ISD::ATOMIC_LCS:         return LowerLCS(Op,DAG);
5356   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
5357   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
5358   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5359   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
5360   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
5361   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
5362   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
5363   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
5364   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
5365   case ISD::SHL_PARTS:
5366   case ISD::SRA_PARTS:
5367   case ISD::SRL_PARTS:          return LowerShift(Op, DAG);
5368   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
5369   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
5370   case ISD::FABS:               return LowerFABS(Op, DAG);
5371   case ISD::FNEG:               return LowerFNEG(Op, DAG);
5372   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
5373   case ISD::SETCC:              return LowerSETCC(Op, DAG);
5374   case ISD::SELECT:             return LowerSELECT(Op, DAG);
5375   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
5376   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
5377   case ISD::CALL:               return LowerCALL(Op, DAG);
5378   case ISD::RET:                return LowerRET(Op, DAG);
5379   case ISD::FORMAL_ARGUMENTS:   return LowerFORMAL_ARGUMENTS(Op, DAG);
5380   case ISD::VASTART:            return LowerVASTART(Op, DAG);
5381   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
5382   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
5383   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
5384   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
5385   case ISD::FRAME_TO_ARGS_OFFSET:
5386                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
5387   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
5388   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
5389   case ISD::TRAMPOLINE:         return LowerTRAMPOLINE(Op, DAG);
5390   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
5391   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
5392   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
5393       
5394   // FIXME: REMOVE THIS WHEN LegalizeDAGTypes lands.
5395   case ISD::READCYCLECOUNTER:
5396     return SDOperand(ExpandREADCYCLECOUNTER(Op.Val, DAG), 0);
5397   }
5398 }
5399
5400 /// ExpandOperation - Provide custom lowering hooks for expanding operations.
5401 SDNode *X86TargetLowering::ExpandOperationResult(SDNode *N, SelectionDAG &DAG) {
5402   switch (N->getOpcode()) {
5403   default: assert(0 && "Should not custom lower this!");
5404   case ISD::FP_TO_SINT:         return ExpandFP_TO_SINT(N, DAG);
5405   case ISD::READCYCLECOUNTER:   return ExpandREADCYCLECOUNTER(N, DAG);
5406   case ISD::ATOMIC_LCS:         return ExpandATOMIC_LCS(N, DAG);
5407   }
5408 }
5409
5410 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
5411   switch (Opcode) {
5412   default: return NULL;
5413   case X86ISD::BSF:                return "X86ISD::BSF";
5414   case X86ISD::BSR:                return "X86ISD::BSR";
5415   case X86ISD::SHLD:               return "X86ISD::SHLD";
5416   case X86ISD::SHRD:               return "X86ISD::SHRD";
5417   case X86ISD::FAND:               return "X86ISD::FAND";
5418   case X86ISD::FOR:                return "X86ISD::FOR";
5419   case X86ISD::FXOR:               return "X86ISD::FXOR";
5420   case X86ISD::FSRL:               return "X86ISD::FSRL";
5421   case X86ISD::FILD:               return "X86ISD::FILD";
5422   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
5423   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
5424   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
5425   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
5426   case X86ISD::FLD:                return "X86ISD::FLD";
5427   case X86ISD::FST:                return "X86ISD::FST";
5428   case X86ISD::CALL:               return "X86ISD::CALL";
5429   case X86ISD::TAILCALL:           return "X86ISD::TAILCALL";
5430   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
5431   case X86ISD::CMP:                return "X86ISD::CMP";
5432   case X86ISD::COMI:               return "X86ISD::COMI";
5433   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
5434   case X86ISD::SETCC:              return "X86ISD::SETCC";
5435   case X86ISD::CMOV:               return "X86ISD::CMOV";
5436   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
5437   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
5438   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
5439   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
5440   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
5441   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
5442   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
5443   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
5444   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
5445   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
5446   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
5447   case X86ISD::FMAX:               return "X86ISD::FMAX";
5448   case X86ISD::FMIN:               return "X86ISD::FMIN";
5449   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
5450   case X86ISD::FRCP:               return "X86ISD::FRCP";
5451   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
5452   case X86ISD::THREAD_POINTER:     return "X86ISD::THREAD_POINTER";
5453   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
5454   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
5455   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
5456   case X86ISD::LCMPXCHG_DAG:       return "x86ISD::LCMPXCHG_DAG";
5457   case X86ISD::LCMPXCHG8_DAG:      return "x86ISD::LCMPXCHG8_DAG";
5458   }
5459 }
5460
5461 // isLegalAddressingMode - Return true if the addressing mode represented
5462 // by AM is legal for this target, for a load/store of the specified type.
5463 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM, 
5464                                               const Type *Ty) const {
5465   // X86 supports extremely general addressing modes.
5466   
5467   // X86 allows a sign-extended 32-bit immediate field as a displacement.
5468   if (AM.BaseOffs <= -(1LL << 32) || AM.BaseOffs >= (1LL << 32)-1)
5469     return false;
5470   
5471   if (AM.BaseGV) {
5472     // We can only fold this if we don't need an extra load.
5473     if (Subtarget->GVRequiresExtraLoad(AM.BaseGV, getTargetMachine(), false))
5474       return false;
5475
5476     // X86-64 only supports addr of globals in small code model.
5477     if (Subtarget->is64Bit()) {
5478       if (getTargetMachine().getCodeModel() != CodeModel::Small)
5479         return false;
5480       // If lower 4G is not available, then we must use rip-relative addressing.
5481       if (AM.BaseOffs || AM.Scale > 1)
5482         return false;
5483     }
5484   }
5485   
5486   switch (AM.Scale) {
5487   case 0:
5488   case 1:
5489   case 2:
5490   case 4:
5491   case 8:
5492     // These scales always work.
5493     break;
5494   case 3:
5495   case 5:
5496   case 9:
5497     // These scales are formed with basereg+scalereg.  Only accept if there is
5498     // no basereg yet.
5499     if (AM.HasBaseReg)
5500       return false;
5501     break;
5502   default:  // Other stuff never works.
5503     return false;
5504   }
5505   
5506   return true;
5507 }
5508
5509
5510 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
5511   if (!Ty1->isInteger() || !Ty2->isInteger())
5512     return false;
5513   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
5514   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
5515   if (NumBits1 <= NumBits2)
5516     return false;
5517   return Subtarget->is64Bit() || NumBits1 < 64;
5518 }
5519
5520 bool X86TargetLowering::isTruncateFree(MVT::ValueType VT1,
5521                                        MVT::ValueType VT2) const {
5522   if (!MVT::isInteger(VT1) || !MVT::isInteger(VT2))
5523     return false;
5524   unsigned NumBits1 = MVT::getSizeInBits(VT1);
5525   unsigned NumBits2 = MVT::getSizeInBits(VT2);
5526   if (NumBits1 <= NumBits2)
5527     return false;
5528   return Subtarget->is64Bit() || NumBits1 < 64;
5529 }
5530
5531 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5532 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5533 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5534 /// are assumed to be legal.
5535 bool
5536 X86TargetLowering::isShuffleMaskLegal(SDOperand Mask, MVT::ValueType VT) const {
5537   // Only do shuffles on 128-bit vector types for now.
5538   if (MVT::getSizeInBits(VT) == 64) return false;
5539   return (Mask.Val->getNumOperands() <= 4 ||
5540           isIdentityMask(Mask.Val) ||
5541           isIdentityMask(Mask.Val, true) ||
5542           isSplatMask(Mask.Val)  ||
5543           isPSHUFHW_PSHUFLWMask(Mask.Val) ||
5544           X86::isUNPCKLMask(Mask.Val) ||
5545           X86::isUNPCKHMask(Mask.Val) ||
5546           X86::isUNPCKL_v_undef_Mask(Mask.Val) ||
5547           X86::isUNPCKH_v_undef_Mask(Mask.Val));
5548 }
5549
5550 bool
5551 X86TargetLowering::isVectorClearMaskLegal(const std::vector<SDOperand> &BVOps,
5552                                           MVT::ValueType EVT,
5553                                           SelectionDAG &DAG) const {
5554   unsigned NumElts = BVOps.size();
5555   // Only do shuffles on 128-bit vector types for now.
5556   if (MVT::getSizeInBits(EVT) * NumElts == 64) return false;
5557   if (NumElts == 2) return true;
5558   if (NumElts == 4) {
5559     return (isMOVLMask(&BVOps[0], 4)  ||
5560             isCommutedMOVL(&BVOps[0], 4, true) ||
5561             isSHUFPMask(&BVOps[0], 4) || 
5562             isCommutedSHUFP(&BVOps[0], 4));
5563   }
5564   return false;
5565 }
5566
5567 //===----------------------------------------------------------------------===//
5568 //                           X86 Scheduler Hooks
5569 //===----------------------------------------------------------------------===//
5570
5571 MachineBasicBlock *
5572 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
5573                                                MachineBasicBlock *BB) {
5574   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5575   switch (MI->getOpcode()) {
5576   default: assert(false && "Unexpected instr type to insert");
5577   case X86::CMOV_FR32:
5578   case X86::CMOV_FR64:
5579   case X86::CMOV_V4F32:
5580   case X86::CMOV_V2F64:
5581   case X86::CMOV_V2I64: {
5582     // To "insert" a SELECT_CC instruction, we actually have to insert the
5583     // diamond control-flow pattern.  The incoming instruction knows the
5584     // destination vreg to set, the condition code register to branch on, the
5585     // true/false values to select between, and a branch opcode to use.
5586     const BasicBlock *LLVM_BB = BB->getBasicBlock();
5587     ilist<MachineBasicBlock>::iterator It = BB;
5588     ++It;
5589
5590     //  thisMBB:
5591     //  ...
5592     //   TrueVal = ...
5593     //   cmpTY ccX, r1, r2
5594     //   bCC copy1MBB
5595     //   fallthrough --> copy0MBB
5596     MachineBasicBlock *thisMBB = BB;
5597     MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
5598     MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
5599     unsigned Opc =
5600       X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
5601     BuildMI(BB, TII->get(Opc)).addMBB(sinkMBB);
5602     MachineFunction *F = BB->getParent();
5603     F->getBasicBlockList().insert(It, copy0MBB);
5604     F->getBasicBlockList().insert(It, sinkMBB);
5605     // Update machine-CFG edges by first adding all successors of the current
5606     // block to the new block which will contain the Phi node for the select.
5607     for(MachineBasicBlock::succ_iterator i = BB->succ_begin(),
5608         e = BB->succ_end(); i != e; ++i)
5609       sinkMBB->addSuccessor(*i);
5610     // Next, remove all successors of the current block, and add the true
5611     // and fallthrough blocks as its successors.
5612     while(!BB->succ_empty())
5613       BB->removeSuccessor(BB->succ_begin());
5614     BB->addSuccessor(copy0MBB);
5615     BB->addSuccessor(sinkMBB);
5616
5617     //  copy0MBB:
5618     //   %FalseValue = ...
5619     //   # fallthrough to sinkMBB
5620     BB = copy0MBB;
5621
5622     // Update machine-CFG edges
5623     BB->addSuccessor(sinkMBB);
5624
5625     //  sinkMBB:
5626     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
5627     //  ...
5628     BB = sinkMBB;
5629     BuildMI(BB, TII->get(X86::PHI), MI->getOperand(0).getReg())
5630       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
5631       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
5632
5633     delete MI;   // The pseudo instruction is gone now.
5634     return BB;
5635   }
5636
5637   case X86::FP32_TO_INT16_IN_MEM:
5638   case X86::FP32_TO_INT32_IN_MEM:
5639   case X86::FP32_TO_INT64_IN_MEM:
5640   case X86::FP64_TO_INT16_IN_MEM:
5641   case X86::FP64_TO_INT32_IN_MEM:
5642   case X86::FP64_TO_INT64_IN_MEM:
5643   case X86::FP80_TO_INT16_IN_MEM:
5644   case X86::FP80_TO_INT32_IN_MEM:
5645   case X86::FP80_TO_INT64_IN_MEM: {
5646     // Change the floating point control register to use "round towards zero"
5647     // mode when truncating to an integer value.
5648     MachineFunction *F = BB->getParent();
5649     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
5650     addFrameReference(BuildMI(BB, TII->get(X86::FNSTCW16m)), CWFrameIdx);
5651
5652     // Load the old value of the high byte of the control word...
5653     unsigned OldCW =
5654       F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
5655     addFrameReference(BuildMI(BB, TII->get(X86::MOV16rm), OldCW), CWFrameIdx);
5656
5657     // Set the high part to be round to zero...
5658     addFrameReference(BuildMI(BB, TII->get(X86::MOV16mi)), CWFrameIdx)
5659       .addImm(0xC7F);
5660
5661     // Reload the modified control word now...
5662     addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
5663
5664     // Restore the memory image of control word to original value
5665     addFrameReference(BuildMI(BB, TII->get(X86::MOV16mr)), CWFrameIdx)
5666       .addReg(OldCW);
5667
5668     // Get the X86 opcode to use.
5669     unsigned Opc;
5670     switch (MI->getOpcode()) {
5671     default: assert(0 && "illegal opcode!");
5672     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
5673     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
5674     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
5675     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
5676     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
5677     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
5678     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
5679     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
5680     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
5681     }
5682
5683     X86AddressMode AM;
5684     MachineOperand &Op = MI->getOperand(0);
5685     if (Op.isRegister()) {
5686       AM.BaseType = X86AddressMode::RegBase;
5687       AM.Base.Reg = Op.getReg();
5688     } else {
5689       AM.BaseType = X86AddressMode::FrameIndexBase;
5690       AM.Base.FrameIndex = Op.getIndex();
5691     }
5692     Op = MI->getOperand(1);
5693     if (Op.isImmediate())
5694       AM.Scale = Op.getImm();
5695     Op = MI->getOperand(2);
5696     if (Op.isImmediate())
5697       AM.IndexReg = Op.getImm();
5698     Op = MI->getOperand(3);
5699     if (Op.isGlobalAddress()) {
5700       AM.GV = Op.getGlobal();
5701     } else {
5702       AM.Disp = Op.getImm();
5703     }
5704     addFullAddress(BuildMI(BB, TII->get(Opc)), AM)
5705                       .addReg(MI->getOperand(4).getReg());
5706
5707     // Reload the original control word now.
5708     addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
5709
5710     delete MI;   // The pseudo instruction is gone now.
5711     return BB;
5712   }
5713   }
5714 }
5715
5716 //===----------------------------------------------------------------------===//
5717 //                           X86 Optimization Hooks
5718 //===----------------------------------------------------------------------===//
5719
5720 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDOperand Op,
5721                                                        const APInt &Mask,
5722                                                        APInt &KnownZero,
5723                                                        APInt &KnownOne,
5724                                                        const SelectionDAG &DAG,
5725                                                        unsigned Depth) const {
5726   unsigned Opc = Op.getOpcode();
5727   assert((Opc >= ISD::BUILTIN_OP_END ||
5728           Opc == ISD::INTRINSIC_WO_CHAIN ||
5729           Opc == ISD::INTRINSIC_W_CHAIN ||
5730           Opc == ISD::INTRINSIC_VOID) &&
5731          "Should use MaskedValueIsZero if you don't know whether Op"
5732          " is a target node!");
5733
5734   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
5735   switch (Opc) {
5736   default: break;
5737   case X86ISD::SETCC:
5738     KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
5739                                        Mask.getBitWidth() - 1);
5740     break;
5741   }
5742 }
5743
5744 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5745 /// element of the result of the vector shuffle.
5746 static SDOperand getShuffleScalarElt(SDNode *N, unsigned i, SelectionDAG &DAG) {
5747   MVT::ValueType VT = N->getValueType(0);
5748   SDOperand PermMask = N->getOperand(2);
5749   unsigned NumElems = PermMask.getNumOperands();
5750   SDOperand V = (i < NumElems) ? N->getOperand(0) : N->getOperand(1);
5751   i %= NumElems;
5752   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5753     return (i == 0)
5754      ? V.getOperand(0) : DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(VT));
5755   } else if (V.getOpcode() == ISD::VECTOR_SHUFFLE) {
5756     SDOperand Idx = PermMask.getOperand(i);
5757     if (Idx.getOpcode() == ISD::UNDEF)
5758       return DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(VT));
5759     return getShuffleScalarElt(V.Val,cast<ConstantSDNode>(Idx)->getValue(),DAG);
5760   }
5761   return SDOperand();
5762 }
5763
5764 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
5765 /// node is a GlobalAddress + an offset.
5766 static bool isGAPlusOffset(SDNode *N, GlobalValue* &GA, int64_t &Offset) {
5767   unsigned Opc = N->getOpcode();
5768   if (Opc == X86ISD::Wrapper) {
5769     if (dyn_cast<GlobalAddressSDNode>(N->getOperand(0))) {
5770       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
5771       return true;
5772     }
5773   } else if (Opc == ISD::ADD) {
5774     SDOperand N1 = N->getOperand(0);
5775     SDOperand N2 = N->getOperand(1);
5776     if (isGAPlusOffset(N1.Val, GA, Offset)) {
5777       ConstantSDNode *V = dyn_cast<ConstantSDNode>(N2);
5778       if (V) {
5779         Offset += V->getSignExtended();
5780         return true;
5781       }
5782     } else if (isGAPlusOffset(N2.Val, GA, Offset)) {
5783       ConstantSDNode *V = dyn_cast<ConstantSDNode>(N1);
5784       if (V) {
5785         Offset += V->getSignExtended();
5786         return true;
5787       }
5788     }
5789   }
5790   return false;
5791 }
5792
5793 /// isConsecutiveLoad - Returns true if N is loading from an address of Base
5794 /// + Dist * Size.
5795 static bool isConsecutiveLoad(SDNode *N, SDNode *Base, int Dist, int Size,
5796                               MachineFrameInfo *MFI) {
5797   if (N->getOperand(0).Val != Base->getOperand(0).Val)
5798     return false;
5799
5800   SDOperand Loc = N->getOperand(1);
5801   SDOperand BaseLoc = Base->getOperand(1);
5802   if (Loc.getOpcode() == ISD::FrameIndex) {
5803     if (BaseLoc.getOpcode() != ISD::FrameIndex)
5804       return false;
5805     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
5806     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
5807     int FS  = MFI->getObjectSize(FI);
5808     int BFS = MFI->getObjectSize(BFI);
5809     if (FS != BFS || FS != Size) return false;
5810     return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Size);
5811   } else {
5812     GlobalValue *GV1 = NULL;
5813     GlobalValue *GV2 = NULL;
5814     int64_t Offset1 = 0;
5815     int64_t Offset2 = 0;
5816     bool isGA1 = isGAPlusOffset(Loc.Val, GV1, Offset1);
5817     bool isGA2 = isGAPlusOffset(BaseLoc.Val, GV2, Offset2);
5818     if (isGA1 && isGA2 && GV1 == GV2)
5819       return Offset1 == (Offset2 + Dist*Size);
5820   }
5821
5822   return false;
5823 }
5824
5825 static bool isBaseAlignment16(SDNode *Base, MachineFrameInfo *MFI,
5826                               const X86Subtarget *Subtarget) {
5827   GlobalValue *GV;
5828   int64_t Offset = 0;
5829   if (isGAPlusOffset(Base, GV, Offset))
5830     return (GV->getAlignment() >= 16 && (Offset % 16) == 0);
5831   // DAG combine handles the stack object case.
5832   return false;
5833 }
5834
5835
5836 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
5837 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
5838 /// if the load addresses are consecutive, non-overlapping, and in the right
5839 /// order.
5840 static SDOperand PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
5841                                        const X86Subtarget *Subtarget) {
5842   MachineFunction &MF = DAG.getMachineFunction();
5843   MachineFrameInfo *MFI = MF.getFrameInfo();
5844   MVT::ValueType VT = N->getValueType(0);
5845   MVT::ValueType EVT = MVT::getVectorElementType(VT);
5846   SDOperand PermMask = N->getOperand(2);
5847   int NumElems = (int)PermMask.getNumOperands();
5848   SDNode *Base = NULL;
5849   for (int i = 0; i < NumElems; ++i) {
5850     SDOperand Idx = PermMask.getOperand(i);
5851     if (Idx.getOpcode() == ISD::UNDEF) {
5852       if (!Base) return SDOperand();
5853     } else {
5854       SDOperand Arg =
5855         getShuffleScalarElt(N, cast<ConstantSDNode>(Idx)->getValue(), DAG);
5856       if (!Arg.Val || !ISD::isNON_EXTLoad(Arg.Val))
5857         return SDOperand();
5858       if (!Base)
5859         Base = Arg.Val;
5860       else if (!isConsecutiveLoad(Arg.Val, Base,
5861                                   i, MVT::getSizeInBits(EVT)/8,MFI))
5862         return SDOperand();
5863     }
5864   }
5865
5866   bool isAlign16 = isBaseAlignment16(Base->getOperand(1).Val, MFI, Subtarget);
5867   LoadSDNode *LD = cast<LoadSDNode>(Base);
5868   if (isAlign16) {
5869     return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
5870                        LD->getSrcValueOffset(), LD->isVolatile());
5871   } else {
5872     return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
5873                        LD->getSrcValueOffset(), LD->isVolatile(),
5874                        LD->getAlignment());
5875   }
5876 }
5877
5878 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
5879 static SDOperand PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
5880                                       const X86Subtarget *Subtarget) {
5881   SDOperand Cond = N->getOperand(0);
5882
5883   // If we have SSE[12] support, try to form min/max nodes.
5884   if (Subtarget->hasSSE2() &&
5885       (N->getValueType(0) == MVT::f32 || N->getValueType(0) == MVT::f64)) {
5886     if (Cond.getOpcode() == ISD::SETCC) {
5887       // Get the LHS/RHS of the select.
5888       SDOperand LHS = N->getOperand(1);
5889       SDOperand RHS = N->getOperand(2);
5890       ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
5891
5892       unsigned Opcode = 0;
5893       if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
5894         switch (CC) {
5895         default: break;
5896         case ISD::SETOLE: // (X <= Y) ? X : Y -> min
5897         case ISD::SETULE:
5898         case ISD::SETLE:
5899           if (!UnsafeFPMath) break;
5900           // FALL THROUGH.
5901         case ISD::SETOLT:  // (X olt/lt Y) ? X : Y -> min
5902         case ISD::SETLT:
5903           Opcode = X86ISD::FMIN;
5904           break;
5905
5906         case ISD::SETOGT: // (X > Y) ? X : Y -> max
5907         case ISD::SETUGT:
5908         case ISD::SETGT:
5909           if (!UnsafeFPMath) break;
5910           // FALL THROUGH.
5911         case ISD::SETUGE:  // (X uge/ge Y) ? X : Y -> max
5912         case ISD::SETGE:
5913           Opcode = X86ISD::FMAX;
5914           break;
5915         }
5916       } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
5917         switch (CC) {
5918         default: break;
5919         case ISD::SETOGT: // (X > Y) ? Y : X -> min
5920         case ISD::SETUGT:
5921         case ISD::SETGT:
5922           if (!UnsafeFPMath) break;
5923           // FALL THROUGH.
5924         case ISD::SETUGE:  // (X uge/ge Y) ? Y : X -> min
5925         case ISD::SETGE:
5926           Opcode = X86ISD::FMIN;
5927           break;
5928
5929         case ISD::SETOLE:   // (X <= Y) ? Y : X -> max
5930         case ISD::SETULE:
5931         case ISD::SETLE:
5932           if (!UnsafeFPMath) break;
5933           // FALL THROUGH.
5934         case ISD::SETOLT:   // (X olt/lt Y) ? Y : X -> max
5935         case ISD::SETLT:
5936           Opcode = X86ISD::FMAX;
5937           break;
5938         }
5939       }
5940
5941       if (Opcode)
5942         return DAG.getNode(Opcode, N->getValueType(0), LHS, RHS);
5943     }
5944
5945   }
5946
5947   return SDOperand();
5948 }
5949
5950 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
5951 static SDOperand PerformSTORECombine(StoreSDNode *St, SelectionDAG &DAG,
5952                                      const X86Subtarget *Subtarget) {
5953   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
5954   // the FP state in cases where an emms may be missing.
5955   // A preferable solution to the general problem is to figure out the right
5956   // places to insert EMMS.  This qualifies as a quick hack.
5957   if (MVT::isVector(St->getValue().getValueType()) && 
5958       MVT::getSizeInBits(St->getValue().getValueType()) == 64 &&
5959       isa<LoadSDNode>(St->getValue()) &&
5960       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
5961       St->getChain().hasOneUse() && !St->isVolatile()) {
5962     SDNode* LdVal = St->getValue().Val;
5963     LoadSDNode *Ld = 0;
5964     int TokenFactorIndex = -1;
5965     SmallVector<SDOperand, 8> Ops;
5966     SDNode* ChainVal = St->getChain().Val;
5967     // Must be a store of a load.  We currently handle two cases:  the load
5968     // is a direct child, and it's under an intervening TokenFactor.  It is
5969     // possible to dig deeper under nested TokenFactors.
5970     if (ChainVal == LdVal)
5971       Ld = cast<LoadSDNode>(St->getChain());
5972     else if (St->getValue().hasOneUse() &&
5973              ChainVal->getOpcode() == ISD::TokenFactor) {
5974       for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
5975         if (ChainVal->getOperand(i).Val == LdVal) {
5976           TokenFactorIndex = i;
5977           Ld = cast<LoadSDNode>(St->getValue());
5978         } else
5979           Ops.push_back(ChainVal->getOperand(i));
5980       }
5981     }
5982     if (Ld) {
5983       // If we are a 64-bit capable x86, lower to a single movq load/store pair.
5984       if (Subtarget->is64Bit()) {
5985         SDOperand NewLd = DAG.getLoad(MVT::i64, Ld->getChain(), 
5986                                       Ld->getBasePtr(), Ld->getSrcValue(), 
5987                                       Ld->getSrcValueOffset(), Ld->isVolatile(),
5988                                       Ld->getAlignment());
5989         SDOperand NewChain = NewLd.getValue(1);
5990         if (TokenFactorIndex != -1) {
5991           Ops.push_back(NewChain);
5992           NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0], 
5993                                  Ops.size());
5994         }
5995         return DAG.getStore(NewChain, NewLd, St->getBasePtr(),
5996                             St->getSrcValue(), St->getSrcValueOffset(),
5997                             St->isVolatile(), St->getAlignment());
5998       }
5999
6000       // Otherwise, lower to two 32-bit copies.
6001       SDOperand LoAddr = Ld->getBasePtr();
6002       SDOperand HiAddr = DAG.getNode(ISD::ADD, MVT::i32, LoAddr,
6003                                      DAG.getConstant(MVT::i32, 4));
6004
6005       SDOperand LoLd = DAG.getLoad(MVT::i32, Ld->getChain(), LoAddr,
6006                                    Ld->getSrcValue(), Ld->getSrcValueOffset(),
6007                                    Ld->isVolatile(), Ld->getAlignment());
6008       SDOperand HiLd = DAG.getLoad(MVT::i32, Ld->getChain(), HiAddr,
6009                                    Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
6010                                    Ld->isVolatile(), 
6011                                    MinAlign(Ld->getAlignment(), 4));
6012
6013       SDOperand NewChain = LoLd.getValue(1);
6014       if (TokenFactorIndex != -1) {
6015         Ops.push_back(LoLd);
6016         Ops.push_back(HiLd);
6017         NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0], 
6018                                Ops.size());
6019       }
6020
6021       LoAddr = St->getBasePtr();
6022       HiAddr = DAG.getNode(ISD::ADD, MVT::i32, LoAddr,
6023                            DAG.getConstant(MVT::i32, 4));
6024
6025       SDOperand LoSt = DAG.getStore(NewChain, LoLd, LoAddr,
6026                           St->getSrcValue(), St->getSrcValueOffset(),
6027                           St->isVolatile(), St->getAlignment());
6028       SDOperand HiSt = DAG.getStore(NewChain, HiLd, HiAddr,
6029                                     St->getSrcValue(), St->getSrcValueOffset()+4,
6030                                     St->isVolatile(), 
6031                                     MinAlign(St->getAlignment(), 4));
6032       return DAG.getNode(ISD::TokenFactor, MVT::Other, LoSt, HiSt);
6033     }
6034   }
6035   return SDOperand();
6036 }
6037
6038 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
6039 /// X86ISD::FXOR nodes.
6040 static SDOperand PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
6041   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
6042   // F[X]OR(0.0, x) -> x
6043   // F[X]OR(x, 0.0) -> x
6044   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
6045     if (C->getValueAPF().isPosZero())
6046       return N->getOperand(1);
6047   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
6048     if (C->getValueAPF().isPosZero())
6049       return N->getOperand(0);
6050   return SDOperand();
6051 }
6052
6053 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
6054 static SDOperand PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
6055   // FAND(0.0, x) -> 0.0
6056   // FAND(x, 0.0) -> 0.0
6057   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
6058     if (C->getValueAPF().isPosZero())
6059       return N->getOperand(0);
6060   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
6061     if (C->getValueAPF().isPosZero())
6062       return N->getOperand(1);
6063   return SDOperand();
6064 }
6065
6066
6067 SDOperand X86TargetLowering::PerformDAGCombine(SDNode *N,
6068                                                DAGCombinerInfo &DCI) const {
6069   SelectionDAG &DAG = DCI.DAG;
6070   switch (N->getOpcode()) {
6071   default: break;
6072   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, Subtarget);
6073   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
6074   case ISD::STORE:          
6075       return PerformSTORECombine(cast<StoreSDNode>(N), DAG, Subtarget);
6076   case X86ISD::FXOR:
6077   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
6078   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
6079   }
6080
6081   return SDOperand();
6082 }
6083
6084 //===----------------------------------------------------------------------===//
6085 //                           X86 Inline Assembly Support
6086 //===----------------------------------------------------------------------===//
6087
6088 /// getConstraintType - Given a constraint letter, return the type of
6089 /// constraint it is for this target.
6090 X86TargetLowering::ConstraintType
6091 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
6092   if (Constraint.size() == 1) {
6093     switch (Constraint[0]) {
6094     case 'A':
6095     case 'f':
6096     case 'r':
6097     case 'R':
6098     case 'l':
6099     case 'q':
6100     case 'Q':
6101     case 'x':
6102     case 'y':
6103     case 'Y':
6104       return C_RegisterClass;
6105     default:
6106       break;
6107     }
6108   }
6109   return TargetLowering::getConstraintType(Constraint);
6110 }
6111
6112 /// LowerXConstraint - try to replace an X constraint, which matches anything,
6113 /// with another that has more specific requirements based on the type of the
6114 /// corresponding operand.
6115 void X86TargetLowering::lowerXConstraint(MVT::ValueType ConstraintVT, 
6116                                          std::string& s) const {
6117   if (MVT::isFloatingPoint(ConstraintVT)) {
6118     if (Subtarget->hasSSE2())
6119       s = "Y";
6120     else if (Subtarget->hasSSE1())
6121       s = "x";
6122     else
6123       s = "f";
6124   } else
6125     return TargetLowering::lowerXConstraint(ConstraintVT, s);
6126 }
6127
6128 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
6129 /// vector.  If it is invalid, don't add anything to Ops.
6130 void X86TargetLowering::LowerAsmOperandForConstraint(SDOperand Op,
6131                                                      char Constraint,
6132                                                      std::vector<SDOperand>&Ops,
6133                                                      SelectionDAG &DAG) {
6134   SDOperand Result(0, 0);
6135   
6136   switch (Constraint) {
6137   default: break;
6138   case 'I':
6139     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
6140       if (C->getValue() <= 31) {
6141         Result = DAG.getTargetConstant(C->getValue(), Op.getValueType());
6142         break;
6143       }
6144     }
6145     return;
6146   case 'N':
6147     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
6148       if (C->getValue() <= 255) {
6149         Result = DAG.getTargetConstant(C->getValue(), Op.getValueType());
6150         break;
6151       }
6152     }
6153     return;
6154   case 'i': {
6155     // Literal immediates are always ok.
6156     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
6157       Result = DAG.getTargetConstant(CST->getValue(), Op.getValueType());
6158       break;
6159     }
6160
6161     // If we are in non-pic codegen mode, we allow the address of a global (with
6162     // an optional displacement) to be used with 'i'.
6163     GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
6164     int64_t Offset = 0;
6165     
6166     // Match either (GA) or (GA+C)
6167     if (GA) {
6168       Offset = GA->getOffset();
6169     } else if (Op.getOpcode() == ISD::ADD) {
6170       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6171       GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
6172       if (C && GA) {
6173         Offset = GA->getOffset()+C->getValue();
6174       } else {
6175         C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6176         GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
6177         if (C && GA)
6178           Offset = GA->getOffset()+C->getValue();
6179         else
6180           C = 0, GA = 0;
6181       }
6182     }
6183     
6184     if (GA) {
6185       // If addressing this global requires a load (e.g. in PIC mode), we can't
6186       // match.
6187       if (Subtarget->GVRequiresExtraLoad(GA->getGlobal(), getTargetMachine(),
6188                                          false))
6189         return;
6190
6191       Op = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
6192                                       Offset);
6193       Result = Op;
6194       break;
6195     }
6196
6197     // Otherwise, not valid for this mode.
6198     return;
6199   }
6200   }
6201   
6202   if (Result.Val) {
6203     Ops.push_back(Result);
6204     return;
6205   }
6206   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
6207 }
6208
6209 std::vector<unsigned> X86TargetLowering::
6210 getRegClassForInlineAsmConstraint(const std::string &Constraint,
6211                                   MVT::ValueType VT) const {
6212   if (Constraint.size() == 1) {
6213     // FIXME: not handling fp-stack yet!
6214     switch (Constraint[0]) {      // GCC X86 Constraint Letters
6215     default: break;  // Unknown constraint letter
6216     case 'A':   // EAX/EDX
6217       if (VT == MVT::i32 || VT == MVT::i64)
6218         return make_vector<unsigned>(X86::EAX, X86::EDX, 0);
6219       break;
6220     case 'q':   // Q_REGS (GENERAL_REGS in 64-bit mode)
6221     case 'Q':   // Q_REGS
6222       if (VT == MVT::i32)
6223         return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
6224       else if (VT == MVT::i16)
6225         return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
6226       else if (VT == MVT::i8)
6227         return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
6228       else if (VT == MVT::i64)
6229         return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
6230       break;
6231     }
6232   }
6233
6234   return std::vector<unsigned>();
6235 }
6236
6237 std::pair<unsigned, const TargetRegisterClass*>
6238 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
6239                                                 MVT::ValueType VT) const {
6240   // First, see if this is a constraint that directly corresponds to an LLVM
6241   // register class.
6242   if (Constraint.size() == 1) {
6243     // GCC Constraint Letters
6244     switch (Constraint[0]) {
6245     default: break;
6246     case 'r':   // GENERAL_REGS
6247     case 'R':   // LEGACY_REGS
6248     case 'l':   // INDEX_REGS
6249       if (VT == MVT::i64 && Subtarget->is64Bit())
6250         return std::make_pair(0U, X86::GR64RegisterClass);
6251       if (VT == MVT::i32)
6252         return std::make_pair(0U, X86::GR32RegisterClass);
6253       else if (VT == MVT::i16)
6254         return std::make_pair(0U, X86::GR16RegisterClass);
6255       else if (VT == MVT::i8)
6256         return std::make_pair(0U, X86::GR8RegisterClass);
6257       break;
6258     case 'f':  // FP Stack registers.
6259       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
6260       // value to the correct fpstack register class.
6261       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
6262         return std::make_pair(0U, X86::RFP32RegisterClass);
6263       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
6264         return std::make_pair(0U, X86::RFP64RegisterClass);
6265       return std::make_pair(0U, X86::RFP80RegisterClass);
6266     case 'y':   // MMX_REGS if MMX allowed.
6267       if (!Subtarget->hasMMX()) break;
6268       return std::make_pair(0U, X86::VR64RegisterClass);
6269       break;
6270     case 'Y':   // SSE_REGS if SSE2 allowed
6271       if (!Subtarget->hasSSE2()) break;
6272       // FALL THROUGH.
6273     case 'x':   // SSE_REGS if SSE1 allowed
6274       if (!Subtarget->hasSSE1()) break;
6275       
6276       switch (VT) {
6277       default: break;
6278       // Scalar SSE types.
6279       case MVT::f32:
6280       case MVT::i32:
6281         return std::make_pair(0U, X86::FR32RegisterClass);
6282       case MVT::f64:
6283       case MVT::i64:
6284         return std::make_pair(0U, X86::FR64RegisterClass);
6285       // Vector types.
6286       case MVT::v16i8:
6287       case MVT::v8i16:
6288       case MVT::v4i32:
6289       case MVT::v2i64:
6290       case MVT::v4f32:
6291       case MVT::v2f64:
6292         return std::make_pair(0U, X86::VR128RegisterClass);
6293       }
6294       break;
6295     }
6296   }
6297   
6298   // Use the default implementation in TargetLowering to convert the register
6299   // constraint into a member of a register class.
6300   std::pair<unsigned, const TargetRegisterClass*> Res;
6301   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
6302
6303   // Not found as a standard register?
6304   if (Res.second == 0) {
6305     // GCC calls "st(0)" just plain "st".
6306     if (StringsEqualNoCase("{st}", Constraint)) {
6307       Res.first = X86::ST0;
6308       Res.second = X86::RFP80RegisterClass;
6309     }
6310
6311     return Res;
6312   }
6313
6314   // Otherwise, check to see if this is a register class of the wrong value
6315   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
6316   // turn into {ax},{dx}.
6317   if (Res.second->hasType(VT))
6318     return Res;   // Correct type already, nothing to do.
6319
6320   // All of the single-register GCC register classes map their values onto
6321   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
6322   // really want an 8-bit or 32-bit register, map to the appropriate register
6323   // class and return the appropriate register.
6324   if (Res.second != X86::GR16RegisterClass)
6325     return Res;
6326
6327   if (VT == MVT::i8) {
6328     unsigned DestReg = 0;
6329     switch (Res.first) {
6330     default: break;
6331     case X86::AX: DestReg = X86::AL; break;
6332     case X86::DX: DestReg = X86::DL; break;
6333     case X86::CX: DestReg = X86::CL; break;
6334     case X86::BX: DestReg = X86::BL; break;
6335     }
6336     if (DestReg) {
6337       Res.first = DestReg;
6338       Res.second = Res.second = X86::GR8RegisterClass;
6339     }
6340   } else if (VT == MVT::i32) {
6341     unsigned DestReg = 0;
6342     switch (Res.first) {
6343     default: break;
6344     case X86::AX: DestReg = X86::EAX; break;
6345     case X86::DX: DestReg = X86::EDX; break;
6346     case X86::CX: DestReg = X86::ECX; break;
6347     case X86::BX: DestReg = X86::EBX; break;
6348     case X86::SI: DestReg = X86::ESI; break;
6349     case X86::DI: DestReg = X86::EDI; break;
6350     case X86::BP: DestReg = X86::EBP; break;
6351     case X86::SP: DestReg = X86::ESP; break;
6352     }
6353     if (DestReg) {
6354       Res.first = DestReg;
6355       Res.second = Res.second = X86::GR32RegisterClass;
6356     }
6357   } else if (VT == MVT::i64) {
6358     unsigned DestReg = 0;
6359     switch (Res.first) {
6360     default: break;
6361     case X86::AX: DestReg = X86::RAX; break;
6362     case X86::DX: DestReg = X86::RDX; break;
6363     case X86::CX: DestReg = X86::RCX; break;
6364     case X86::BX: DestReg = X86::RBX; break;
6365     case X86::SI: DestReg = X86::RSI; break;
6366     case X86::DI: DestReg = X86::RDI; break;
6367     case X86::BP: DestReg = X86::RBP; break;
6368     case X86::SP: DestReg = X86::RSP; break;
6369     }
6370     if (DestReg) {
6371       Res.first = DestReg;
6372       Res.second = Res.second = X86::GR64RegisterClass;
6373     }
6374   }
6375
6376   return Res;
6377 }