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