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