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