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