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