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