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