Don't use a BT instruction if the AND has multiple uses.
[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(MVT VT) 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 = NULL;
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                                   DwarfWriter *dw,
1927                                   DenseMap<const Value *, unsigned> &vm,
1928                                   DenseMap<const BasicBlock *,
1929                                            MachineBasicBlock *> &bm,
1930                                   DenseMap<const AllocaInst *, int> &am
1931 #ifndef NDEBUG
1932                                   , SmallSet<Instruction*, 8> &cil
1933 #endif
1934                                   ) {
1935   return X86::createFastISel(mf, mmo, dw, vm, bm, am
1936 #ifndef NDEBUG
1937                              , cil
1938 #endif
1939                              );
1940 }
1941
1942
1943 //===----------------------------------------------------------------------===//
1944 //                           Other Lowering Hooks
1945 //===----------------------------------------------------------------------===//
1946
1947
1948 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
1949   MachineFunction &MF = DAG.getMachineFunction();
1950   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1951   int ReturnAddrIndex = FuncInfo->getRAIndex();
1952   uint64_t SlotSize = TD->getPointerSize();
1953
1954   if (ReturnAddrIndex == 0) {
1955     // Set up a frame object for the return address.
1956     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize);
1957     FuncInfo->setRAIndex(ReturnAddrIndex);
1958   }
1959
1960   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
1961 }
1962
1963
1964 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
1965 /// specific condition code, returning the condition code and the LHS/RHS of the
1966 /// comparison to make.
1967 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
1968                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
1969   if (!isFP) {
1970     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
1971       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
1972         // X > -1   -> X == 0, jump !sign.
1973         RHS = DAG.getConstant(0, RHS.getValueType());
1974         return X86::COND_NS;
1975       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
1976         // X < 0   -> X == 0, jump on sign.
1977         return X86::COND_S;
1978       } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
1979         // X < 1   -> X <= 0
1980         RHS = DAG.getConstant(0, RHS.getValueType());
1981         return X86::COND_LE;
1982       }
1983     }
1984
1985     switch (SetCCOpcode) {
1986     default: assert(0 && "Invalid integer condition!");
1987     case ISD::SETEQ:  return X86::COND_E;
1988     case ISD::SETGT:  return X86::COND_G;
1989     case ISD::SETGE:  return X86::COND_GE;
1990     case ISD::SETLT:  return X86::COND_L;
1991     case ISD::SETLE:  return X86::COND_LE;
1992     case ISD::SETNE:  return X86::COND_NE;
1993     case ISD::SETULT: return X86::COND_B;
1994     case ISD::SETUGT: return X86::COND_A;
1995     case ISD::SETULE: return X86::COND_BE;
1996     case ISD::SETUGE: return X86::COND_AE;
1997     }
1998   }
1999   
2000   // First determine if it is required or is profitable to flip the operands.
2001
2002   // If LHS is a foldable load, but RHS is not, flip the condition.
2003   if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2004       !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2005     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2006     std::swap(LHS, RHS);
2007   }
2008
2009   switch (SetCCOpcode) {
2010   default: break;
2011   case ISD::SETOLT:
2012   case ISD::SETOLE:
2013   case ISD::SETUGT:
2014   case ISD::SETUGE:
2015     std::swap(LHS, RHS);
2016     break;
2017   }
2018
2019   // On a floating point condition, the flags are set as follows:
2020   // ZF  PF  CF   op
2021   //  0 | 0 | 0 | X > Y
2022   //  0 | 0 | 1 | X < Y
2023   //  1 | 0 | 0 | X == Y
2024   //  1 | 1 | 1 | unordered
2025   switch (SetCCOpcode) {
2026   default: assert(0 && "Condcode should be pre-legalized away");
2027   case ISD::SETUEQ:
2028   case ISD::SETEQ:   return X86::COND_E;
2029   case ISD::SETOLT:              // flipped
2030   case ISD::SETOGT:
2031   case ISD::SETGT:   return X86::COND_A;
2032   case ISD::SETOLE:              // flipped
2033   case ISD::SETOGE:
2034   case ISD::SETGE:   return X86::COND_AE;
2035   case ISD::SETUGT:              // flipped
2036   case ISD::SETULT:
2037   case ISD::SETLT:   return X86::COND_B;
2038   case ISD::SETUGE:              // flipped
2039   case ISD::SETULE:
2040   case ISD::SETLE:   return X86::COND_BE;
2041   case ISD::SETONE:
2042   case ISD::SETNE:   return X86::COND_NE;
2043   case ISD::SETUO:   return X86::COND_P;
2044   case ISD::SETO:    return X86::COND_NP;
2045   }
2046 }
2047
2048 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2049 /// code. Current x86 isa includes the following FP cmov instructions:
2050 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2051 static bool hasFPCMov(unsigned X86CC) {
2052   switch (X86CC) {
2053   default:
2054     return false;
2055   case X86::COND_B:
2056   case X86::COND_BE:
2057   case X86::COND_E:
2058   case X86::COND_P:
2059   case X86::COND_A:
2060   case X86::COND_AE:
2061   case X86::COND_NE:
2062   case X86::COND_NP:
2063     return true;
2064   }
2065 }
2066
2067 /// isUndefOrInRange - Op is either an undef node or a ConstantSDNode.  Return
2068 /// true if Op is undef or if its value falls within the specified range (L, H].
2069 static bool isUndefOrInRange(SDValue Op, unsigned Low, unsigned Hi) {
2070   if (Op.getOpcode() == ISD::UNDEF)
2071     return true;
2072
2073   unsigned Val = cast<ConstantSDNode>(Op)->getZExtValue();
2074   return (Val >= Low && Val < Hi);
2075 }
2076
2077 /// isUndefOrEqual - Op is either an undef node or a ConstantSDNode.  Return
2078 /// true if Op is undef or if its value equal to the specified value.
2079 static bool isUndefOrEqual(SDValue Op, unsigned Val) {
2080   if (Op.getOpcode() == ISD::UNDEF)
2081     return true;
2082   return cast<ConstantSDNode>(Op)->getZExtValue() == Val;
2083 }
2084
2085 /// isPSHUFDMask - Return true if the specified VECTOR_SHUFFLE operand
2086 /// specifies a shuffle of elements that is suitable for input to PSHUFD.
2087 bool X86::isPSHUFDMask(SDNode *N) {
2088   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2089
2090   if (N->getNumOperands() != 2 && N->getNumOperands() != 4)
2091     return false;
2092
2093   // Check if the value doesn't reference the second vector.
2094   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2095     SDValue Arg = N->getOperand(i);
2096     if (Arg.getOpcode() == ISD::UNDEF) continue;
2097     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2098     if (cast<ConstantSDNode>(Arg)->getZExtValue() >= e)
2099       return false;
2100   }
2101
2102   return true;
2103 }
2104
2105 /// isPSHUFHWMask - Return true if the specified VECTOR_SHUFFLE operand
2106 /// specifies a shuffle of elements that is suitable for input to PSHUFHW.
2107 bool X86::isPSHUFHWMask(SDNode *N) {
2108   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2109
2110   if (N->getNumOperands() != 8)
2111     return false;
2112
2113   // Lower quadword copied in order.
2114   for (unsigned i = 0; i != 4; ++i) {
2115     SDValue Arg = N->getOperand(i);
2116     if (Arg.getOpcode() == ISD::UNDEF) continue;
2117     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2118     if (cast<ConstantSDNode>(Arg)->getZExtValue() != i)
2119       return false;
2120   }
2121
2122   // Upper quadword shuffled.
2123   for (unsigned i = 4; i != 8; ++i) {
2124     SDValue Arg = N->getOperand(i);
2125     if (Arg.getOpcode() == ISD::UNDEF) continue;
2126     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2127     unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2128     if (Val < 4 || Val > 7)
2129       return false;
2130   }
2131
2132   return true;
2133 }
2134
2135 /// isPSHUFLWMask - Return true if the specified VECTOR_SHUFFLE operand
2136 /// specifies a shuffle of elements that is suitable for input to PSHUFLW.
2137 bool X86::isPSHUFLWMask(SDNode *N) {
2138   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2139
2140   if (N->getNumOperands() != 8)
2141     return false;
2142
2143   // Upper quadword copied in order.
2144   for (unsigned i = 4; i != 8; ++i)
2145     if (!isUndefOrEqual(N->getOperand(i), i))
2146       return false;
2147
2148   // Lower quadword shuffled.
2149   for (unsigned i = 0; i != 4; ++i)
2150     if (!isUndefOrInRange(N->getOperand(i), 0, 4))
2151       return false;
2152
2153   return true;
2154 }
2155
2156 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2157 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2158 static bool isSHUFPMask(SDOperandPtr Elems, unsigned NumElems) {
2159   if (NumElems != 2 && NumElems != 4) return false;
2160
2161   unsigned Half = NumElems / 2;
2162   for (unsigned i = 0; i < Half; ++i)
2163     if (!isUndefOrInRange(Elems[i], 0, NumElems))
2164       return false;
2165   for (unsigned i = Half; i < NumElems; ++i)
2166     if (!isUndefOrInRange(Elems[i], NumElems, NumElems*2))
2167       return false;
2168
2169   return true;
2170 }
2171
2172 bool X86::isSHUFPMask(SDNode *N) {
2173   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2174   return ::isSHUFPMask(N->op_begin(), N->getNumOperands());
2175 }
2176
2177 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2178 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2179 /// half elements to come from vector 1 (which would equal the dest.) and
2180 /// the upper half to come from vector 2.
2181 static bool isCommutedSHUFP(SDOperandPtr Ops, unsigned NumOps) {
2182   if (NumOps != 2 && NumOps != 4) return false;
2183
2184   unsigned Half = NumOps / 2;
2185   for (unsigned i = 0; i < Half; ++i)
2186     if (!isUndefOrInRange(Ops[i], NumOps, NumOps*2))
2187       return false;
2188   for (unsigned i = Half; i < NumOps; ++i)
2189     if (!isUndefOrInRange(Ops[i], 0, NumOps))
2190       return false;
2191   return true;
2192 }
2193
2194 static bool isCommutedSHUFP(SDNode *N) {
2195   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2196   return isCommutedSHUFP(N->op_begin(), N->getNumOperands());
2197 }
2198
2199 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2200 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2201 bool X86::isMOVHLPSMask(SDNode *N) {
2202   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2203
2204   if (N->getNumOperands() != 4)
2205     return false;
2206
2207   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2208   return isUndefOrEqual(N->getOperand(0), 6) &&
2209          isUndefOrEqual(N->getOperand(1), 7) &&
2210          isUndefOrEqual(N->getOperand(2), 2) &&
2211          isUndefOrEqual(N->getOperand(3), 3);
2212 }
2213
2214 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2215 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2216 /// <2, 3, 2, 3>
2217 bool X86::isMOVHLPS_v_undef_Mask(SDNode *N) {
2218   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2219
2220   if (N->getNumOperands() != 4)
2221     return false;
2222
2223   // Expect bit0 == 2, bit1 == 3, bit2 == 2, bit3 == 3
2224   return isUndefOrEqual(N->getOperand(0), 2) &&
2225          isUndefOrEqual(N->getOperand(1), 3) &&
2226          isUndefOrEqual(N->getOperand(2), 2) &&
2227          isUndefOrEqual(N->getOperand(3), 3);
2228 }
2229
2230 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2231 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2232 bool X86::isMOVLPMask(SDNode *N) {
2233   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2234
2235   unsigned NumElems = N->getNumOperands();
2236   if (NumElems != 2 && NumElems != 4)
2237     return false;
2238
2239   for (unsigned i = 0; i < NumElems/2; ++i)
2240     if (!isUndefOrEqual(N->getOperand(i), i + NumElems))
2241       return false;
2242
2243   for (unsigned i = NumElems/2; i < NumElems; ++i)
2244     if (!isUndefOrEqual(N->getOperand(i), i))
2245       return false;
2246
2247   return true;
2248 }
2249
2250 /// isMOVHPMask - Return true if the specified VECTOR_SHUFFLE operand
2251 /// specifies a shuffle of elements that is suitable for input to MOVHP{S|D}
2252 /// and MOVLHPS.
2253 bool X86::isMOVHPMask(SDNode *N) {
2254   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2255
2256   unsigned NumElems = N->getNumOperands();
2257   if (NumElems != 2 && NumElems != 4)
2258     return false;
2259
2260   for (unsigned i = 0; i < NumElems/2; ++i)
2261     if (!isUndefOrEqual(N->getOperand(i), i))
2262       return false;
2263
2264   for (unsigned i = 0; i < NumElems/2; ++i) {
2265     SDValue Arg = N->getOperand(i + NumElems/2);
2266     if (!isUndefOrEqual(Arg, i + NumElems))
2267       return false;
2268   }
2269
2270   return true;
2271 }
2272
2273 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2274 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2275 bool static isUNPCKLMask(SDOperandPtr Elts, unsigned NumElts,
2276                          bool V2IsSplat = false) {
2277   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2278     return false;
2279
2280   for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2281     SDValue BitI  = Elts[i];
2282     SDValue BitI1 = Elts[i+1];
2283     if (!isUndefOrEqual(BitI, j))
2284       return false;
2285     if (V2IsSplat) {
2286       if (isUndefOrEqual(BitI1, NumElts))
2287         return false;
2288     } else {
2289       if (!isUndefOrEqual(BitI1, j + NumElts))
2290         return false;
2291     }
2292   }
2293
2294   return true;
2295 }
2296
2297 bool X86::isUNPCKLMask(SDNode *N, bool V2IsSplat) {
2298   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2299   return ::isUNPCKLMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2300 }
2301
2302 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2303 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2304 bool static isUNPCKHMask(SDOperandPtr Elts, unsigned NumElts,
2305                          bool V2IsSplat = false) {
2306   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2307     return false;
2308
2309   for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2310     SDValue BitI  = Elts[i];
2311     SDValue BitI1 = Elts[i+1];
2312     if (!isUndefOrEqual(BitI, j + NumElts/2))
2313       return false;
2314     if (V2IsSplat) {
2315       if (isUndefOrEqual(BitI1, NumElts))
2316         return false;
2317     } else {
2318       if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2319         return false;
2320     }
2321   }
2322
2323   return true;
2324 }
2325
2326 bool X86::isUNPCKHMask(SDNode *N, bool V2IsSplat) {
2327   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2328   return ::isUNPCKHMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2329 }
2330
2331 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2332 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2333 /// <0, 0, 1, 1>
2334 bool X86::isUNPCKL_v_undef_Mask(SDNode *N) {
2335   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2336
2337   unsigned NumElems = N->getNumOperands();
2338   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2339     return false;
2340
2341   for (unsigned i = 0, j = 0; i != NumElems; i += 2, ++j) {
2342     SDValue BitI  = N->getOperand(i);
2343     SDValue BitI1 = N->getOperand(i+1);
2344
2345     if (!isUndefOrEqual(BitI, j))
2346       return false;
2347     if (!isUndefOrEqual(BitI1, j))
2348       return false;
2349   }
2350
2351   return true;
2352 }
2353
2354 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2355 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2356 /// <2, 2, 3, 3>
2357 bool X86::isUNPCKH_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 = NumElems / 2; 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 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2378 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2379 /// MOVSD, and MOVD, i.e. setting the lowest element.
2380 static bool isMOVLMask(SDOperandPtr Elts, unsigned NumElts) {
2381   if (NumElts != 2 && NumElts != 4)
2382     return false;
2383
2384   if (!isUndefOrEqual(Elts[0], NumElts))
2385     return false;
2386
2387   for (unsigned i = 1; i < NumElts; ++i) {
2388     if (!isUndefOrEqual(Elts[i], i))
2389       return false;
2390   }
2391
2392   return true;
2393 }
2394
2395 bool X86::isMOVLMask(SDNode *N) {
2396   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2397   return ::isMOVLMask(N->op_begin(), N->getNumOperands());
2398 }
2399
2400 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2401 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
2402 /// element of vector 2 and the other elements to come from vector 1 in order.
2403 static bool isCommutedMOVL(SDOperandPtr Ops, unsigned NumOps,
2404                            bool V2IsSplat = false,
2405                            bool V2IsUndef = false) {
2406   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2407     return false;
2408
2409   if (!isUndefOrEqual(Ops[0], 0))
2410     return false;
2411
2412   for (unsigned i = 1; i < NumOps; ++i) {
2413     SDValue Arg = Ops[i];
2414     if (!(isUndefOrEqual(Arg, i+NumOps) ||
2415           (V2IsUndef && isUndefOrInRange(Arg, NumOps, NumOps*2)) ||
2416           (V2IsSplat && isUndefOrEqual(Arg, NumOps))))
2417       return false;
2418   }
2419
2420   return true;
2421 }
2422
2423 static bool isCommutedMOVL(SDNode *N, bool V2IsSplat = false,
2424                            bool V2IsUndef = false) {
2425   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2426   return isCommutedMOVL(N->op_begin(), N->getNumOperands(),
2427                         V2IsSplat, V2IsUndef);
2428 }
2429
2430 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2431 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2432 bool X86::isMOVSHDUPMask(SDNode *N) {
2433   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2434
2435   if (N->getNumOperands() != 4)
2436     return false;
2437
2438   // Expect 1, 1, 3, 3
2439   for (unsigned i = 0; i < 2; ++i) {
2440     SDValue Arg = N->getOperand(i);
2441     if (Arg.getOpcode() == ISD::UNDEF) continue;
2442     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2443     unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2444     if (Val != 1) return false;
2445   }
2446
2447   bool HasHi = false;
2448   for (unsigned i = 2; i < 4; ++i) {
2449     SDValue Arg = N->getOperand(i);
2450     if (Arg.getOpcode() == ISD::UNDEF) continue;
2451     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2452     unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2453     if (Val != 3) return false;
2454     HasHi = true;
2455   }
2456
2457   // Don't use movshdup if it can be done with a shufps.
2458   return HasHi;
2459 }
2460
2461 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2462 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2463 bool X86::isMOVSLDUPMask(SDNode *N) {
2464   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2465
2466   if (N->getNumOperands() != 4)
2467     return false;
2468
2469   // Expect 0, 0, 2, 2
2470   for (unsigned i = 0; i < 2; ++i) {
2471     SDValue Arg = N->getOperand(i);
2472     if (Arg.getOpcode() == ISD::UNDEF) continue;
2473     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2474     unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2475     if (Val != 0) return false;
2476   }
2477
2478   bool HasHi = false;
2479   for (unsigned i = 2; i < 4; ++i) {
2480     SDValue Arg = N->getOperand(i);
2481     if (Arg.getOpcode() == ISD::UNDEF) continue;
2482     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2483     unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2484     if (Val != 2) return false;
2485     HasHi = true;
2486   }
2487
2488   // Don't use movshdup if it can be done with a shufps.
2489   return HasHi;
2490 }
2491
2492 /// isIdentityMask - Return true if the specified VECTOR_SHUFFLE operand
2493 /// specifies a identity operation on the LHS or RHS.
2494 static bool isIdentityMask(SDNode *N, bool RHS = false) {
2495   unsigned NumElems = N->getNumOperands();
2496   for (unsigned i = 0; i < NumElems; ++i)
2497     if (!isUndefOrEqual(N->getOperand(i), i + (RHS ? NumElems : 0)))
2498       return false;
2499   return true;
2500 }
2501
2502 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2503 /// a splat of a single element.
2504 static bool isSplatMask(SDNode *N) {
2505   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2506
2507   // This is a splat operation if each element of the permute is the same, and
2508   // if the value doesn't reference the second vector.
2509   unsigned NumElems = N->getNumOperands();
2510   SDValue ElementBase;
2511   unsigned i = 0;
2512   for (; i != NumElems; ++i) {
2513     SDValue Elt = N->getOperand(i);
2514     if (isa<ConstantSDNode>(Elt)) {
2515       ElementBase = Elt;
2516       break;
2517     }
2518   }
2519
2520   if (!ElementBase.getNode())
2521     return false;
2522
2523   for (; i != NumElems; ++i) {
2524     SDValue Arg = N->getOperand(i);
2525     if (Arg.getOpcode() == ISD::UNDEF) continue;
2526     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2527     if (Arg != ElementBase) return false;
2528   }
2529
2530   // Make sure it is a splat of the first vector operand.
2531   return cast<ConstantSDNode>(ElementBase)->getZExtValue() < NumElems;
2532 }
2533
2534 /// getSplatMaskEltNo - Given a splat mask, return the index to the element
2535 /// we want to splat.
2536 static SDValue getSplatMaskEltNo(SDNode *N) {
2537   assert(isSplatMask(N) && "Not a splat mask");
2538   unsigned NumElems = N->getNumOperands();
2539   SDValue ElementBase;
2540   unsigned i = 0;
2541   for (; i != NumElems; ++i) {
2542     SDValue Elt = N->getOperand(i);
2543     if (isa<ConstantSDNode>(Elt))
2544       return Elt;
2545   }
2546   assert(0 && " No splat value found!");
2547   return SDValue();
2548 }
2549
2550
2551 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2552 /// a splat of a single element and it's a 2 or 4 element mask.
2553 bool X86::isSplatMask(SDNode *N) {
2554   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2555
2556   // We can only splat 64-bit, and 32-bit quantities with a single instruction.
2557   if (N->getNumOperands() != 4 && N->getNumOperands() != 2)
2558     return false;
2559   return ::isSplatMask(N);
2560 }
2561
2562 /// isSplatLoMask - Return true if the specified VECTOR_SHUFFLE operand
2563 /// specifies a splat of zero element.
2564 bool X86::isSplatLoMask(SDNode *N) {
2565   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2566
2567   for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i)
2568     if (!isUndefOrEqual(N->getOperand(i), 0))
2569       return false;
2570   return true;
2571 }
2572
2573 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2574 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
2575 bool X86::isMOVDDUPMask(SDNode *N) {
2576   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2577
2578   unsigned e = N->getNumOperands() / 2;
2579   for (unsigned i = 0; i < e; ++i)
2580     if (!isUndefOrEqual(N->getOperand(i), i))
2581       return false;
2582   for (unsigned i = 0; i < e; ++i)
2583     if (!isUndefOrEqual(N->getOperand(e+i), i))
2584       return false;
2585   return true;
2586 }
2587
2588 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2589 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUF* and SHUFP*
2590 /// instructions.
2591 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2592   unsigned NumOperands = N->getNumOperands();
2593   unsigned Shift = (NumOperands == 4) ? 2 : 1;
2594   unsigned Mask = 0;
2595   for (unsigned i = 0; i < NumOperands; ++i) {
2596     unsigned Val = 0;
2597     SDValue Arg = N->getOperand(NumOperands-i-1);
2598     if (Arg.getOpcode() != ISD::UNDEF)
2599       Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2600     if (Val >= NumOperands) Val -= NumOperands;
2601     Mask |= Val;
2602     if (i != NumOperands - 1)
2603       Mask <<= Shift;
2604   }
2605
2606   return Mask;
2607 }
2608
2609 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2610 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFHW
2611 /// instructions.
2612 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2613   unsigned Mask = 0;
2614   // 8 nodes, but we only care about the last 4.
2615   for (unsigned i = 7; i >= 4; --i) {
2616     unsigned Val = 0;
2617     SDValue Arg = N->getOperand(i);
2618     if (Arg.getOpcode() != ISD::UNDEF)
2619       Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2620     Mask |= (Val - 4);
2621     if (i != 4)
2622       Mask <<= 2;
2623   }
2624
2625   return Mask;
2626 }
2627
2628 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2629 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFLW
2630 /// instructions.
2631 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2632   unsigned Mask = 0;
2633   // 8 nodes, but we only care about the first 4.
2634   for (int i = 3; i >= 0; --i) {
2635     unsigned Val = 0;
2636     SDValue Arg = N->getOperand(i);
2637     if (Arg.getOpcode() != ISD::UNDEF)
2638       Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2639     Mask |= Val;
2640     if (i != 0)
2641       Mask <<= 2;
2642   }
2643
2644   return Mask;
2645 }
2646
2647 /// isPSHUFHW_PSHUFLWMask - true if the specified VECTOR_SHUFFLE operand
2648 /// specifies a 8 element shuffle that can be broken into a pair of
2649 /// PSHUFHW and PSHUFLW.
2650 static bool isPSHUFHW_PSHUFLWMask(SDNode *N) {
2651   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2652
2653   if (N->getNumOperands() != 8)
2654     return false;
2655
2656   // Lower quadword shuffled.
2657   for (unsigned i = 0; i != 4; ++i) {
2658     SDValue Arg = N->getOperand(i);
2659     if (Arg.getOpcode() == ISD::UNDEF) continue;
2660     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2661     unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2662     if (Val >= 4)
2663       return false;
2664   }
2665
2666   // Upper quadword shuffled.
2667   for (unsigned i = 4; i != 8; ++i) {
2668     SDValue Arg = N->getOperand(i);
2669     if (Arg.getOpcode() == ISD::UNDEF) continue;
2670     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2671     unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2672     if (Val < 4 || Val > 7)
2673       return false;
2674   }
2675
2676   return true;
2677 }
2678
2679 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as
2680 /// values in ther permute mask.
2681 static SDValue CommuteVectorShuffle(SDValue Op, SDValue &V1,
2682                                       SDValue &V2, SDValue &Mask,
2683                                       SelectionDAG &DAG) {
2684   MVT VT = Op.getValueType();
2685   MVT MaskVT = Mask.getValueType();
2686   MVT EltVT = MaskVT.getVectorElementType();
2687   unsigned NumElems = Mask.getNumOperands();
2688   SmallVector<SDValue, 8> MaskVec;
2689
2690   for (unsigned i = 0; i != NumElems; ++i) {
2691     SDValue Arg = Mask.getOperand(i);
2692     if (Arg.getOpcode() == ISD::UNDEF) {
2693       MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2694       continue;
2695     }
2696     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2697     unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2698     if (Val < NumElems)
2699       MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2700     else
2701       MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2702   }
2703
2704   std::swap(V1, V2);
2705   Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
2706   return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2707 }
2708
2709 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
2710 /// the two vector operands have swapped position.
2711 static
2712 SDValue CommuteVectorShuffleMask(SDValue Mask, SelectionDAG &DAG) {
2713   MVT MaskVT = Mask.getValueType();
2714   MVT EltVT = MaskVT.getVectorElementType();
2715   unsigned NumElems = Mask.getNumOperands();
2716   SmallVector<SDValue, 8> MaskVec;
2717   for (unsigned i = 0; i != NumElems; ++i) {
2718     SDValue Arg = Mask.getOperand(i);
2719     if (Arg.getOpcode() == ISD::UNDEF) {
2720       MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2721       continue;
2722     }
2723     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2724     unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2725     if (Val < NumElems)
2726       MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2727     else
2728       MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2729   }
2730   return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
2731 }
2732
2733
2734 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2735 /// match movhlps. The lower half elements should come from upper half of
2736 /// V1 (and in order), and the upper half elements should come from the upper
2737 /// half of V2 (and in order).
2738 static bool ShouldXformToMOVHLPS(SDNode *Mask) {
2739   unsigned NumElems = Mask->getNumOperands();
2740   if (NumElems != 4)
2741     return false;
2742   for (unsigned i = 0, e = 2; i != e; ++i)
2743     if (!isUndefOrEqual(Mask->getOperand(i), i+2))
2744       return false;
2745   for (unsigned i = 2; i != 4; ++i)
2746     if (!isUndefOrEqual(Mask->getOperand(i), i+4))
2747       return false;
2748   return true;
2749 }
2750
2751 /// isScalarLoadToVector - Returns true if the node is a scalar load that
2752 /// is promoted to a vector. It also returns the LoadSDNode by reference if
2753 /// required.
2754 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
2755   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
2756     return false;
2757   N = N->getOperand(0).getNode();
2758   if (!ISD::isNON_EXTLoad(N))
2759     return false;
2760   if (LD)
2761     *LD = cast<LoadSDNode>(N);
2762   return true;
2763 }
2764
2765 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
2766 /// match movlp{s|d}. The lower half elements should come from lower half of
2767 /// V1 (and in order), and the upper half elements should come from the upper
2768 /// half of V2 (and in order). And since V1 will become the source of the
2769 /// MOVLP, it must be either a vector load or a scalar load to vector.
2770 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2, SDNode *Mask) {
2771   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
2772     return false;
2773   // Is V2 is a vector load, don't do this transformation. We will try to use
2774   // load folding shufps op.
2775   if (ISD::isNON_EXTLoad(V2))
2776     return false;
2777
2778   unsigned NumElems = Mask->getNumOperands();
2779   if (NumElems != 2 && NumElems != 4)
2780     return false;
2781   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
2782     if (!isUndefOrEqual(Mask->getOperand(i), i))
2783       return false;
2784   for (unsigned i = NumElems/2; i != NumElems; ++i)
2785     if (!isUndefOrEqual(Mask->getOperand(i), i+NumElems))
2786       return false;
2787   return true;
2788 }
2789
2790 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
2791 /// all the same.
2792 static bool isSplatVector(SDNode *N) {
2793   if (N->getOpcode() != ISD::BUILD_VECTOR)
2794     return false;
2795
2796   SDValue SplatValue = N->getOperand(0);
2797   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
2798     if (N->getOperand(i) != SplatValue)
2799       return false;
2800   return true;
2801 }
2802
2803 /// isUndefShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2804 /// to an undef.
2805 static bool isUndefShuffle(SDNode *N) {
2806   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2807     return false;
2808
2809   SDValue V1 = N->getOperand(0);
2810   SDValue V2 = N->getOperand(1);
2811   SDValue Mask = N->getOperand(2);
2812   unsigned NumElems = Mask.getNumOperands();
2813   for (unsigned i = 0; i != NumElems; ++i) {
2814     SDValue Arg = Mask.getOperand(i);
2815     if (Arg.getOpcode() != ISD::UNDEF) {
2816       unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2817       if (Val < NumElems && V1.getOpcode() != ISD::UNDEF)
2818         return false;
2819       else if (Val >= NumElems && V2.getOpcode() != ISD::UNDEF)
2820         return false;
2821     }
2822   }
2823   return true;
2824 }
2825
2826 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
2827 /// constant +0.0.
2828 static inline bool isZeroNode(SDValue Elt) {
2829   return ((isa<ConstantSDNode>(Elt) &&
2830            cast<ConstantSDNode>(Elt)->getZExtValue() == 0) ||
2831           (isa<ConstantFPSDNode>(Elt) &&
2832            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
2833 }
2834
2835 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2836 /// to an zero vector.
2837 static bool isZeroShuffle(SDNode *N) {
2838   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2839     return false;
2840
2841   SDValue V1 = N->getOperand(0);
2842   SDValue V2 = N->getOperand(1);
2843   SDValue Mask = N->getOperand(2);
2844   unsigned NumElems = Mask.getNumOperands();
2845   for (unsigned i = 0; i != NumElems; ++i) {
2846     SDValue Arg = Mask.getOperand(i);
2847     if (Arg.getOpcode() == ISD::UNDEF)
2848       continue;
2849     
2850     unsigned Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
2851     if (Idx < NumElems) {
2852       unsigned Opc = V1.getNode()->getOpcode();
2853       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
2854         continue;
2855       if (Opc != ISD::BUILD_VECTOR ||
2856           !isZeroNode(V1.getNode()->getOperand(Idx)))
2857         return false;
2858     } else if (Idx >= NumElems) {
2859       unsigned Opc = V2.getNode()->getOpcode();
2860       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
2861         continue;
2862       if (Opc != ISD::BUILD_VECTOR ||
2863           !isZeroNode(V2.getNode()->getOperand(Idx - NumElems)))
2864         return false;
2865     }
2866   }
2867   return true;
2868 }
2869
2870 /// getZeroVector - Returns a vector of specified type with all zero elements.
2871 ///
2872 static SDValue getZeroVector(MVT VT, bool HasSSE2, SelectionDAG &DAG) {
2873   assert(VT.isVector() && "Expected a vector type");
2874   
2875   // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2876   // type.  This ensures they get CSE'd.
2877   SDValue Vec;
2878   if (VT.getSizeInBits() == 64) { // MMX
2879     SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
2880     Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
2881   } else if (HasSSE2) {  // SSE2
2882     SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
2883     Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
2884   } else { // SSE1
2885     SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
2886     Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4f32, Cst, Cst, Cst, Cst);
2887   }
2888   return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
2889 }
2890
2891 /// getOnesVector - Returns a vector of specified type with all bits set.
2892 ///
2893 static SDValue getOnesVector(MVT VT, SelectionDAG &DAG) {
2894   assert(VT.isVector() && "Expected a vector type");
2895   
2896   // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2897   // type.  This ensures they get CSE'd.
2898   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
2899   SDValue Vec;
2900   if (VT.getSizeInBits() == 64)  // MMX
2901     Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
2902   else                                              // SSE
2903     Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
2904   return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
2905 }
2906
2907
2908 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
2909 /// that point to V2 points to its first element.
2910 static SDValue NormalizeMask(SDValue Mask, SelectionDAG &DAG) {
2911   assert(Mask.getOpcode() == ISD::BUILD_VECTOR);
2912
2913   bool Changed = false;
2914   SmallVector<SDValue, 8> MaskVec;
2915   unsigned NumElems = Mask.getNumOperands();
2916   for (unsigned i = 0; i != NumElems; ++i) {
2917     SDValue Arg = Mask.getOperand(i);
2918     if (Arg.getOpcode() != ISD::UNDEF) {
2919       unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2920       if (Val > NumElems) {
2921         Arg = DAG.getConstant(NumElems, Arg.getValueType());
2922         Changed = true;
2923       }
2924     }
2925     MaskVec.push_back(Arg);
2926   }
2927
2928   if (Changed)
2929     Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getValueType(),
2930                        &MaskVec[0], MaskVec.size());
2931   return Mask;
2932 }
2933
2934 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
2935 /// operation of specified width.
2936 static SDValue getMOVLMask(unsigned NumElems, SelectionDAG &DAG) {
2937   MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2938   MVT BaseVT = MaskVT.getVectorElementType();
2939
2940   SmallVector<SDValue, 8> MaskVec;
2941   MaskVec.push_back(DAG.getConstant(NumElems, BaseVT));
2942   for (unsigned i = 1; i != NumElems; ++i)
2943     MaskVec.push_back(DAG.getConstant(i, BaseVT));
2944   return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2945 }
2946
2947 /// getUnpacklMask - Returns a vector_shuffle mask for an unpackl operation
2948 /// of specified width.
2949 static SDValue getUnpacklMask(unsigned NumElems, SelectionDAG &DAG) {
2950   MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2951   MVT BaseVT = MaskVT.getVectorElementType();
2952   SmallVector<SDValue, 8> MaskVec;
2953   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
2954     MaskVec.push_back(DAG.getConstant(i,            BaseVT));
2955     MaskVec.push_back(DAG.getConstant(i + NumElems, BaseVT));
2956   }
2957   return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2958 }
2959
2960 /// getUnpackhMask - Returns a vector_shuffle mask for an unpackh operation
2961 /// of specified width.
2962 static SDValue getUnpackhMask(unsigned NumElems, SelectionDAG &DAG) {
2963   MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2964   MVT BaseVT = MaskVT.getVectorElementType();
2965   unsigned Half = NumElems/2;
2966   SmallVector<SDValue, 8> MaskVec;
2967   for (unsigned i = 0; i != Half; ++i) {
2968     MaskVec.push_back(DAG.getConstant(i + Half,            BaseVT));
2969     MaskVec.push_back(DAG.getConstant(i + NumElems + Half, BaseVT));
2970   }
2971   return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2972 }
2973
2974 /// getSwapEltZeroMask - Returns a vector_shuffle mask for a shuffle that swaps
2975 /// element #0 of a vector with the specified index, leaving the rest of the
2976 /// elements in place.
2977 static SDValue getSwapEltZeroMask(unsigned NumElems, unsigned DestElt,
2978                                    SelectionDAG &DAG) {
2979   MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2980   MVT BaseVT = MaskVT.getVectorElementType();
2981   SmallVector<SDValue, 8> MaskVec;
2982   // Element #0 of the result gets the elt we are replacing.
2983   MaskVec.push_back(DAG.getConstant(DestElt, BaseVT));
2984   for (unsigned i = 1; i != NumElems; ++i)
2985     MaskVec.push_back(DAG.getConstant(i == DestElt ? 0 : i, BaseVT));
2986   return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2987 }
2988
2989 /// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
2990 static SDValue PromoteSplat(SDValue Op, SelectionDAG &DAG, bool HasSSE2) {
2991   MVT PVT = HasSSE2 ? MVT::v4i32 : MVT::v4f32;
2992   MVT VT = Op.getValueType();
2993   if (PVT == VT)
2994     return Op;
2995   SDValue V1 = Op.getOperand(0);
2996   SDValue Mask = Op.getOperand(2);
2997   unsigned MaskNumElems = Mask.getNumOperands();
2998   unsigned NumElems = MaskNumElems;
2999   // Special handling of v4f32 -> v4i32.
3000   if (VT != MVT::v4f32) {
3001     // Find which element we want to splat.
3002     SDNode* EltNoNode = getSplatMaskEltNo(Mask.getNode()).getNode();
3003     unsigned EltNo = cast<ConstantSDNode>(EltNoNode)->getZExtValue();
3004     // unpack elements to the correct location
3005     while (NumElems > 4) {
3006       if (EltNo < NumElems/2) {
3007         Mask = getUnpacklMask(MaskNumElems, DAG);
3008       } else {
3009         Mask = getUnpackhMask(MaskNumElems, DAG);
3010         EltNo -= NumElems/2;
3011       }
3012       V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1, Mask);
3013       NumElems >>= 1;
3014     }
3015     SDValue Cst = DAG.getConstant(EltNo, MVT::i32);
3016     Mask = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
3017   }
3018
3019   V1 = DAG.getNode(ISD::BIT_CONVERT, PVT, V1);
3020   SDValue Shuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, PVT, V1,
3021                                   DAG.getNode(ISD::UNDEF, PVT), Mask);
3022   return DAG.getNode(ISD::BIT_CONVERT, VT, Shuffle);
3023 }
3024
3025 /// isVectorLoad - Returns true if the node is a vector load, a scalar
3026 /// load that's promoted to vector, or a load bitcasted.
3027 static bool isVectorLoad(SDValue Op) {
3028   assert(Op.getValueType().isVector() && "Expected a vector type");
3029   if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR ||
3030       Op.getOpcode() == ISD::BIT_CONVERT) {
3031     return isa<LoadSDNode>(Op.getOperand(0));
3032   }
3033   return isa<LoadSDNode>(Op);
3034 }
3035
3036
3037 /// CanonicalizeMovddup - Cannonicalize movddup shuffle to v2f64.
3038 ///
3039 static SDValue CanonicalizeMovddup(SDValue Op, SDValue V1, SDValue Mask,
3040                                    SelectionDAG &DAG, bool HasSSE3) {
3041   // If we have sse3 and shuffle has more than one use or input is a load, then
3042   // use movddup. Otherwise, use movlhps.
3043   bool UseMovddup = HasSSE3 && (!Op.hasOneUse() || isVectorLoad(V1));
3044   MVT PVT = UseMovddup ? MVT::v2f64 : MVT::v4f32;
3045   MVT VT = Op.getValueType();
3046   if (VT == PVT)
3047     return Op;
3048   unsigned NumElems = PVT.getVectorNumElements();
3049   if (NumElems == 2) {
3050     SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3051     Mask = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
3052   } else {
3053     assert(NumElems == 4);
3054     SDValue Cst0 = DAG.getTargetConstant(0, MVT::i32);
3055     SDValue Cst1 = DAG.getTargetConstant(1, MVT::i32);
3056     Mask = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst0, Cst1, Cst0, Cst1);
3057   }
3058
3059   V1 = DAG.getNode(ISD::BIT_CONVERT, PVT, V1);
3060   SDValue Shuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, PVT, V1,
3061                                 DAG.getNode(ISD::UNDEF, PVT), Mask);
3062   return DAG.getNode(ISD::BIT_CONVERT, VT, Shuffle);
3063 }
3064
3065 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3066 /// vector of zero or undef vector.  This produces a shuffle where the low
3067 /// element of V2 is swizzled into the zero/undef vector, landing at element
3068 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
3069 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3070                                              bool isZero, bool HasSSE2,
3071                                              SelectionDAG &DAG) {
3072   MVT VT = V2.getValueType();
3073   SDValue V1 = isZero
3074     ? getZeroVector(VT, HasSSE2, DAG) : DAG.getNode(ISD::UNDEF, VT);
3075   unsigned NumElems = V2.getValueType().getVectorNumElements();
3076   MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3077   MVT EVT = MaskVT.getVectorElementType();
3078   SmallVector<SDValue, 16> MaskVec;
3079   for (unsigned i = 0; i != NumElems; ++i)
3080     if (i == Idx)  // If this is the insertion idx, put the low elt of V2 here.
3081       MaskVec.push_back(DAG.getConstant(NumElems, EVT));
3082     else
3083       MaskVec.push_back(DAG.getConstant(i, EVT));
3084   SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3085                                &MaskVec[0], MaskVec.size());
3086   return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
3087 }
3088
3089 /// getNumOfConsecutiveZeros - Return the number of elements in a result of
3090 /// a shuffle that is zero.
3091 static
3092 unsigned getNumOfConsecutiveZeros(SDValue Op, SDValue Mask,
3093                                   unsigned NumElems, bool Low,
3094                                   SelectionDAG &DAG) {
3095   unsigned NumZeros = 0;
3096   for (unsigned i = 0; i < NumElems; ++i) {
3097     unsigned Index = Low ? i : NumElems-i-1;
3098     SDValue Idx = Mask.getOperand(Index);
3099     if (Idx.getOpcode() == ISD::UNDEF) {
3100       ++NumZeros;
3101       continue;
3102     }
3103     SDValue Elt = DAG.getShuffleScalarElt(Op.getNode(), Index);
3104     if (Elt.getNode() && isZeroNode(Elt))
3105       ++NumZeros;
3106     else
3107       break;
3108   }
3109   return NumZeros;
3110 }
3111
3112 /// isVectorShift - Returns true if the shuffle can be implemented as a
3113 /// logical left or right shift of a vector.
3114 static bool isVectorShift(SDValue Op, SDValue Mask, SelectionDAG &DAG,
3115                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3116   unsigned NumElems = Mask.getNumOperands();
3117
3118   isLeft = true;
3119   unsigned NumZeros= getNumOfConsecutiveZeros(Op, Mask, NumElems, true, DAG);
3120   if (!NumZeros) {
3121     isLeft = false;
3122     NumZeros = getNumOfConsecutiveZeros(Op, Mask, NumElems, false, DAG);
3123     if (!NumZeros)
3124       return false;
3125   }
3126
3127   bool SeenV1 = false;
3128   bool SeenV2 = false;
3129   for (unsigned i = NumZeros; i < NumElems; ++i) {
3130     unsigned Val = isLeft ? (i - NumZeros) : i;
3131     SDValue Idx = Mask.getOperand(isLeft ? i : (i - NumZeros));
3132     if (Idx.getOpcode() == ISD::UNDEF)
3133       continue;
3134     unsigned Index = cast<ConstantSDNode>(Idx)->getZExtValue();
3135     if (Index < NumElems)
3136       SeenV1 = true;
3137     else {
3138       Index -= NumElems;
3139       SeenV2 = true;
3140     }
3141     if (Index != Val)
3142       return false;
3143   }
3144   if (SeenV1 && SeenV2)
3145     return false;
3146
3147   ShVal = SeenV1 ? Op.getOperand(0) : Op.getOperand(1);
3148   ShAmt = NumZeros;
3149   return true;
3150 }
3151
3152
3153 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3154 ///
3155 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3156                                        unsigned NumNonZero, unsigned NumZero,
3157                                        SelectionDAG &DAG, TargetLowering &TLI) {
3158   if (NumNonZero > 8)
3159     return SDValue();
3160
3161   SDValue V(0, 0);
3162   bool First = true;
3163   for (unsigned i = 0; i < 16; ++i) {
3164     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3165     if (ThisIsNonZero && First) {
3166       if (NumZero)
3167         V = getZeroVector(MVT::v8i16, true, DAG);
3168       else
3169         V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
3170       First = false;
3171     }
3172
3173     if ((i & 1) != 0) {
3174       SDValue ThisElt(0, 0), LastElt(0, 0);
3175       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3176       if (LastIsNonZero) {
3177         LastElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i-1));
3178       }
3179       if (ThisIsNonZero) {
3180         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i));
3181         ThisElt = DAG.getNode(ISD::SHL, MVT::i16,
3182                               ThisElt, DAG.getConstant(8, MVT::i8));
3183         if (LastIsNonZero)
3184           ThisElt = DAG.getNode(ISD::OR, MVT::i16, ThisElt, LastElt);
3185       } else
3186         ThisElt = LastElt;
3187
3188       if (ThisElt.getNode())
3189         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, ThisElt,
3190                         DAG.getIntPtrConstant(i/2));
3191     }
3192   }
3193
3194   return DAG.getNode(ISD::BIT_CONVERT, MVT::v16i8, V);
3195 }
3196
3197 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3198 ///
3199 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3200                                        unsigned NumNonZero, unsigned NumZero,
3201                                        SelectionDAG &DAG, TargetLowering &TLI) {
3202   if (NumNonZero > 4)
3203     return SDValue();
3204
3205   SDValue V(0, 0);
3206   bool First = true;
3207   for (unsigned i = 0; i < 8; ++i) {
3208     bool isNonZero = (NonZeros & (1 << i)) != 0;
3209     if (isNonZero) {
3210       if (First) {
3211         if (NumZero)
3212           V = getZeroVector(MVT::v8i16, true, DAG);
3213         else
3214           V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
3215         First = false;
3216       }
3217       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, Op.getOperand(i),
3218                       DAG.getIntPtrConstant(i));
3219     }
3220   }
3221
3222   return V;
3223 }
3224
3225 /// getVShift - Return a vector logical shift node.
3226 ///
3227 static SDValue getVShift(bool isLeft, MVT VT, SDValue SrcOp,
3228                            unsigned NumBits, SelectionDAG &DAG,
3229                            const TargetLowering &TLI) {
3230   bool isMMX = VT.getSizeInBits() == 64;
3231   MVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
3232   unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3233   SrcOp = DAG.getNode(ISD::BIT_CONVERT, ShVT, SrcOp);
3234   return DAG.getNode(ISD::BIT_CONVERT, VT,
3235                      DAG.getNode(Opc, ShVT, SrcOp,
3236                              DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3237 }
3238
3239 SDValue
3240 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) {
3241   // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3242   if (ISD::isBuildVectorAllZeros(Op.getNode())
3243       || ISD::isBuildVectorAllOnes(Op.getNode())) {
3244     // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3245     // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3246     // eliminated on x86-32 hosts.
3247     if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3248       return Op;
3249
3250     if (ISD::isBuildVectorAllOnes(Op.getNode()))
3251       return getOnesVector(Op.getValueType(), DAG);
3252     return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG);
3253   }
3254
3255   MVT VT = Op.getValueType();
3256   MVT EVT = VT.getVectorElementType();
3257   unsigned EVTBits = EVT.getSizeInBits();
3258
3259   unsigned NumElems = Op.getNumOperands();
3260   unsigned NumZero  = 0;
3261   unsigned NumNonZero = 0;
3262   unsigned NonZeros = 0;
3263   bool IsAllConstants = true;
3264   SmallSet<SDValue, 8> Values;
3265   for (unsigned i = 0; i < NumElems; ++i) {
3266     SDValue Elt = Op.getOperand(i);
3267     if (Elt.getOpcode() == ISD::UNDEF)
3268       continue;
3269     Values.insert(Elt);
3270     if (Elt.getOpcode() != ISD::Constant &&
3271         Elt.getOpcode() != ISD::ConstantFP)
3272       IsAllConstants = false;
3273     if (isZeroNode(Elt))
3274       NumZero++;
3275     else {
3276       NonZeros |= (1 << i);
3277       NumNonZero++;
3278     }
3279   }
3280
3281   if (NumNonZero == 0) {
3282     // All undef vector. Return an UNDEF.  All zero vectors were handled above.
3283     return DAG.getNode(ISD::UNDEF, VT);
3284   }
3285
3286   // Special case for single non-zero, non-undef, element.
3287   if (NumNonZero == 1 && NumElems <= 4) {
3288     unsigned Idx = CountTrailingZeros_32(NonZeros);
3289     SDValue Item = Op.getOperand(Idx);
3290     
3291     // If this is an insertion of an i64 value on x86-32, and if the top bits of
3292     // the value are obviously zero, truncate the value to i32 and do the
3293     // insertion that way.  Only do this if the value is non-constant or if the
3294     // value is a constant being inserted into element 0.  It is cheaper to do
3295     // a constant pool load than it is to do a movd + shuffle.
3296     if (EVT == MVT::i64 && !Subtarget->is64Bit() &&
3297         (!IsAllConstants || Idx == 0)) {
3298       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3299         // Handle MMX and SSE both.
3300         MVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3301         unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
3302         
3303         // Truncate the value (which may itself be a constant) to i32, and
3304         // convert it to a vector with movd (S2V+shuffle to zero extend).
3305         Item = DAG.getNode(ISD::TRUNCATE, MVT::i32, Item);
3306         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VecVT, Item);
3307         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3308                                            Subtarget->hasSSE2(), DAG);
3309         
3310         // Now we have our 32-bit value zero extended in the low element of
3311         // a vector.  If Idx != 0, swizzle it into place.
3312         if (Idx != 0) {
3313           SDValue Ops[] = { 
3314             Item, DAG.getNode(ISD::UNDEF, Item.getValueType()),
3315             getSwapEltZeroMask(VecElts, Idx, DAG)
3316           };
3317           Item = DAG.getNode(ISD::VECTOR_SHUFFLE, VecVT, Ops, 3);
3318         }
3319         return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(), Item);
3320       }
3321     }
3322     
3323     // If we have a constant or non-constant insertion into the low element of
3324     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3325     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
3326     // depending on what the source datatype is.  Because we can only get here
3327     // when NumElems <= 4, this only needs to handle i32/f32/i64/f64.
3328     if (Idx == 0 &&
3329         // Don't do this for i64 values on x86-32.
3330         (EVT != MVT::i64 || Subtarget->is64Bit())) {
3331       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
3332       // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3333       return getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3334                                          Subtarget->hasSSE2(), DAG);
3335     }
3336
3337     // Is it a vector logical left shift?
3338     if (NumElems == 2 && Idx == 1 &&
3339         isZeroNode(Op.getOperand(0)) && !isZeroNode(Op.getOperand(1))) {
3340       unsigned NumBits = VT.getSizeInBits();
3341       return getVShift(true, VT,
3342                        DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(1)),
3343                        NumBits/2, DAG, *this);
3344     }
3345     
3346     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3347       return SDValue();
3348
3349     // Otherwise, if this is a vector with i32 or f32 elements, and the element
3350     // is a non-constant being inserted into an element other than the low one,
3351     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
3352     // movd/movss) to move this into the low element, then shuffle it into
3353     // place.
3354     if (EVTBits == 32) {
3355       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
3356       
3357       // Turn it into a shuffle of zero and zero-extended scalar to vector.
3358       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3359                                          Subtarget->hasSSE2(), DAG);
3360       MVT MaskVT  = MVT::getIntVectorWithNumElements(NumElems);
3361       MVT MaskEVT = MaskVT.getVectorElementType();
3362       SmallVector<SDValue, 8> MaskVec;
3363       for (unsigned i = 0; i < NumElems; i++)
3364         MaskVec.push_back(DAG.getConstant((i == Idx) ? 0 : 1, MaskEVT));
3365       SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3366                                    &MaskVec[0], MaskVec.size());
3367       return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Item,
3368                          DAG.getNode(ISD::UNDEF, VT), Mask);
3369     }
3370   }
3371
3372   // Splat is obviously ok. Let legalizer expand it to a shuffle.
3373   if (Values.size() == 1)
3374     return SDValue();
3375   
3376   // A vector full of immediates; various special cases are already
3377   // handled, so this is best done with a single constant-pool load.
3378   if (IsAllConstants)
3379     return SDValue();
3380
3381   // Let legalizer expand 2-wide build_vectors.
3382   if (EVTBits == 64) {
3383     if (NumNonZero == 1) {
3384       // One half is zero or undef.
3385       unsigned Idx = CountTrailingZeros_32(NonZeros);
3386       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT,
3387                                  Op.getOperand(Idx));
3388       return getShuffleVectorZeroOrUndef(V2, Idx, true,
3389                                          Subtarget->hasSSE2(), DAG);
3390     }
3391     return SDValue();
3392   }
3393
3394   // If element VT is < 32 bits, convert it to inserts into a zero vector.
3395   if (EVTBits == 8 && NumElems == 16) {
3396     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3397                                         *this);
3398     if (V.getNode()) return V;
3399   }
3400
3401   if (EVTBits == 16 && NumElems == 8) {
3402     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3403                                         *this);
3404     if (V.getNode()) return V;
3405   }
3406
3407   // If element VT is == 32 bits, turn it into a number of shuffles.
3408   SmallVector<SDValue, 8> V;
3409   V.resize(NumElems);
3410   if (NumElems == 4 && NumZero > 0) {
3411     for (unsigned i = 0; i < 4; ++i) {
3412       bool isZero = !(NonZeros & (1 << i));
3413       if (isZero)
3414         V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG);
3415       else
3416         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3417     }
3418
3419     for (unsigned i = 0; i < 2; ++i) {
3420       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3421         default: break;
3422         case 0:
3423           V[i] = V[i*2];  // Must be a zero vector.
3424           break;
3425         case 1:
3426           V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2+1], V[i*2],
3427                              getMOVLMask(NumElems, DAG));
3428           break;
3429         case 2:
3430           V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3431                              getMOVLMask(NumElems, DAG));
3432           break;
3433         case 3:
3434           V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3435                              getUnpacklMask(NumElems, DAG));
3436           break;
3437       }
3438     }
3439
3440     MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3441     MVT EVT = MaskVT.getVectorElementType();
3442     SmallVector<SDValue, 8> MaskVec;
3443     bool Reverse = (NonZeros & 0x3) == 2;
3444     for (unsigned i = 0; i < 2; ++i)
3445       if (Reverse)
3446         MaskVec.push_back(DAG.getConstant(1-i, EVT));
3447       else
3448         MaskVec.push_back(DAG.getConstant(i, EVT));
3449     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3450     for (unsigned i = 0; i < 2; ++i)
3451       if (Reverse)
3452         MaskVec.push_back(DAG.getConstant(1-i+NumElems, EVT));
3453       else
3454         MaskVec.push_back(DAG.getConstant(i+NumElems, EVT));
3455     SDValue ShufMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3456                                      &MaskVec[0], MaskVec.size());
3457     return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[0], V[1], ShufMask);
3458   }
3459
3460   if (Values.size() > 2) {
3461     // Expand into a number of unpckl*.
3462     // e.g. for v4f32
3463     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3464     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3465     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
3466     SDValue UnpckMask = getUnpacklMask(NumElems, DAG);
3467     for (unsigned i = 0; i < NumElems; ++i)
3468       V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3469     NumElems >>= 1;
3470     while (NumElems != 0) {
3471       for (unsigned i = 0; i < NumElems; ++i)
3472         V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i], V[i + NumElems],
3473                            UnpckMask);
3474       NumElems >>= 1;
3475     }
3476     return V[0];
3477   }
3478
3479   return SDValue();
3480 }
3481
3482 static
3483 SDValue LowerVECTOR_SHUFFLEv8i16(SDValue V1, SDValue V2,
3484                                  SDValue PermMask, SelectionDAG &DAG,
3485                                  TargetLowering &TLI) {
3486   SDValue NewV;
3487   MVT MaskVT = MVT::getIntVectorWithNumElements(8);
3488   MVT MaskEVT = MaskVT.getVectorElementType();
3489   MVT PtrVT = TLI.getPointerTy();
3490   SmallVector<SDValue, 8> MaskElts(PermMask.getNode()->op_begin(),
3491                                    PermMask.getNode()->op_end());
3492
3493   // First record which half of which vector the low elements come from.
3494   SmallVector<unsigned, 4> LowQuad(4);
3495   for (unsigned i = 0; i < 4; ++i) {
3496     SDValue Elt = MaskElts[i];
3497     if (Elt.getOpcode() == ISD::UNDEF)
3498       continue;
3499     unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3500     int QuadIdx = EltIdx / 4;
3501     ++LowQuad[QuadIdx];
3502   }
3503
3504   int BestLowQuad = -1;
3505   unsigned MaxQuad = 1;
3506   for (unsigned i = 0; i < 4; ++i) {
3507     if (LowQuad[i] > MaxQuad) {
3508       BestLowQuad = i;
3509       MaxQuad = LowQuad[i];
3510     }
3511   }
3512
3513   // Record which half of which vector the high elements come from.
3514   SmallVector<unsigned, 4> HighQuad(4);
3515   for (unsigned i = 4; i < 8; ++i) {
3516     SDValue Elt = MaskElts[i];
3517     if (Elt.getOpcode() == ISD::UNDEF)
3518       continue;
3519     unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3520     int QuadIdx = EltIdx / 4;
3521     ++HighQuad[QuadIdx];
3522   }
3523
3524   int BestHighQuad = -1;
3525   MaxQuad = 1;
3526   for (unsigned i = 0; i < 4; ++i) {
3527     if (HighQuad[i] > MaxQuad) {
3528       BestHighQuad = i;
3529       MaxQuad = HighQuad[i];
3530     }
3531   }
3532
3533   // If it's possible to sort parts of either half with PSHUF{H|L}W, then do it.
3534   if (BestLowQuad != -1 || BestHighQuad != -1) {
3535     // First sort the 4 chunks in order using shufpd.
3536     SmallVector<SDValue, 8> MaskVec;
3537
3538     if (BestLowQuad != -1)
3539       MaskVec.push_back(DAG.getConstant(BestLowQuad, MVT::i32));
3540     else
3541       MaskVec.push_back(DAG.getConstant(0, MVT::i32));
3542
3543     if (BestHighQuad != -1)
3544       MaskVec.push_back(DAG.getConstant(BestHighQuad, MVT::i32));
3545     else
3546       MaskVec.push_back(DAG.getConstant(1, MVT::i32));
3547
3548     SDValue Mask= DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, &MaskVec[0],2);
3549     NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v2i64,
3550                        DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V1),
3551                        DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V2), Mask);
3552     NewV = DAG.getNode(ISD::BIT_CONVERT, MVT::v8i16, NewV);
3553
3554     // Now sort high and low parts separately.
3555     BitVector InOrder(8);
3556     if (BestLowQuad != -1) {
3557       // Sort lower half in order using PSHUFLW.
3558       MaskVec.clear();
3559       bool AnyOutOrder = false;
3560
3561       for (unsigned i = 0; i != 4; ++i) {
3562         SDValue Elt = MaskElts[i];
3563         if (Elt.getOpcode() == ISD::UNDEF) {
3564           MaskVec.push_back(Elt);
3565           InOrder.set(i);
3566         } else {
3567           unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3568           if (EltIdx != i)
3569             AnyOutOrder = true;
3570
3571           MaskVec.push_back(DAG.getConstant(EltIdx % 4, MaskEVT));
3572
3573           // If this element is in the right place after this shuffle, then
3574           // remember it.
3575           if ((int)(EltIdx / 4) == BestLowQuad)
3576             InOrder.set(i);
3577         }
3578       }
3579       if (AnyOutOrder) {
3580         for (unsigned i = 4; i != 8; ++i)
3581           MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3582         SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3583         NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
3584       }
3585     }
3586
3587     if (BestHighQuad != -1) {
3588       // Sort high half in order using PSHUFHW if possible.
3589       MaskVec.clear();
3590
3591       for (unsigned i = 0; i != 4; ++i)
3592         MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3593
3594       bool AnyOutOrder = false;
3595       for (unsigned i = 4; i != 8; ++i) {
3596         SDValue Elt = MaskElts[i];
3597         if (Elt.getOpcode() == ISD::UNDEF) {
3598           MaskVec.push_back(Elt);
3599           InOrder.set(i);
3600         } else {
3601           unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3602           if (EltIdx != i)
3603             AnyOutOrder = true;
3604
3605           MaskVec.push_back(DAG.getConstant((EltIdx % 4) + 4, MaskEVT));
3606
3607           // If this element is in the right place after this shuffle, then
3608           // remember it.
3609           if ((int)(EltIdx / 4) == BestHighQuad)
3610             InOrder.set(i);
3611         }
3612       }
3613
3614       if (AnyOutOrder) {
3615         SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3616         NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
3617       }
3618     }
3619
3620     // The other elements are put in the right place using pextrw and pinsrw.
3621     for (unsigned i = 0; i != 8; ++i) {
3622       if (InOrder[i])
3623         continue;
3624       SDValue Elt = MaskElts[i];
3625       if (Elt.getOpcode() == ISD::UNDEF)
3626         continue;
3627       unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3628       SDValue ExtOp = (EltIdx < 8)
3629         ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
3630                       DAG.getConstant(EltIdx, PtrVT))
3631         : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3632                       DAG.getConstant(EltIdx - 8, PtrVT));
3633       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3634                          DAG.getConstant(i, PtrVT));
3635     }
3636
3637     return NewV;
3638   }
3639
3640   // PSHUF{H|L}W are not used. Lower into extracts and inserts but try to use as
3641   // few as possible. First, let's find out how many elements are already in the
3642   // right order.
3643   unsigned V1InOrder = 0;
3644   unsigned V1FromV1 = 0;
3645   unsigned V2InOrder = 0;
3646   unsigned V2FromV2 = 0;
3647   SmallVector<SDValue, 8> V1Elts;
3648   SmallVector<SDValue, 8> V2Elts;
3649   for (unsigned i = 0; i < 8; ++i) {
3650     SDValue Elt = MaskElts[i];
3651     if (Elt.getOpcode() == ISD::UNDEF) {
3652       V1Elts.push_back(Elt);
3653       V2Elts.push_back(Elt);
3654       ++V1InOrder;
3655       ++V2InOrder;
3656       continue;
3657     }
3658     unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3659     if (EltIdx == i) {
3660       V1Elts.push_back(Elt);
3661       V2Elts.push_back(DAG.getConstant(i+8, MaskEVT));
3662       ++V1InOrder;
3663     } else if (EltIdx == i+8) {
3664       V1Elts.push_back(Elt);
3665       V2Elts.push_back(DAG.getConstant(i, MaskEVT));
3666       ++V2InOrder;
3667     } else if (EltIdx < 8) {
3668       V1Elts.push_back(Elt);
3669       V2Elts.push_back(DAG.getConstant(i+8, MaskEVT));
3670       ++V1FromV1;
3671     } else {
3672       V1Elts.push_back(Elt);
3673       V2Elts.push_back(DAG.getConstant(EltIdx-8, MaskEVT));
3674       ++V2FromV2;
3675     }
3676   }
3677
3678   if (V2InOrder > V1InOrder) {
3679     PermMask = CommuteVectorShuffleMask(PermMask, DAG);
3680     std::swap(V1, V2);
3681     std::swap(V1Elts, V2Elts);
3682     std::swap(V1FromV1, V2FromV2);
3683   }
3684
3685   if ((V1FromV1 + V1InOrder) != 8) {
3686     // Some elements are from V2.
3687     if (V1FromV1) {
3688       // If there are elements that are from V1 but out of place,
3689       // then first sort them in place
3690       SmallVector<SDValue, 8> MaskVec;
3691       for (unsigned i = 0; i < 8; ++i) {
3692         SDValue Elt = V1Elts[i];
3693         if (Elt.getOpcode() == ISD::UNDEF) {
3694           MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3695           continue;
3696         }
3697         unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3698         if (EltIdx >= 8)
3699           MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3700         else
3701           MaskVec.push_back(DAG.getConstant(EltIdx, MaskEVT));
3702       }
3703       SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3704       V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, V1, V1, Mask);
3705     }
3706
3707     NewV = V1;
3708     for (unsigned i = 0; i < 8; ++i) {
3709       SDValue Elt = V1Elts[i];
3710       if (Elt.getOpcode() == ISD::UNDEF)
3711         continue;
3712       unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3713       if (EltIdx < 8)
3714         continue;
3715       SDValue ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3716                                     DAG.getConstant(EltIdx - 8, PtrVT));
3717       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3718                          DAG.getConstant(i, PtrVT));
3719     }
3720     return NewV;
3721   } else {
3722     // All elements are from V1.
3723     NewV = V1;
3724     for (unsigned i = 0; i < 8; ++i) {
3725       SDValue Elt = V1Elts[i];
3726       if (Elt.getOpcode() == ISD::UNDEF)
3727         continue;
3728       unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3729       SDValue ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
3730                                     DAG.getConstant(EltIdx, PtrVT));
3731       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3732                          DAG.getConstant(i, PtrVT));
3733     }
3734     return NewV;
3735   }
3736 }
3737
3738 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
3739 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
3740 /// done when every pair / quad of shuffle mask elements point to elements in
3741 /// the right sequence. e.g.
3742 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
3743 static
3744 SDValue RewriteAsNarrowerShuffle(SDValue V1, SDValue V2,
3745                                 MVT VT,
3746                                 SDValue PermMask, SelectionDAG &DAG,
3747                                 TargetLowering &TLI) {
3748   unsigned NumElems = PermMask.getNumOperands();
3749   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
3750   MVT MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
3751   MVT MaskEltVT = MaskVT.getVectorElementType();
3752   MVT NewVT = MaskVT;
3753   switch (VT.getSimpleVT()) {
3754   default: assert(false && "Unexpected!");
3755   case MVT::v4f32: NewVT = MVT::v2f64; break;
3756   case MVT::v4i32: NewVT = MVT::v2i64; break;
3757   case MVT::v8i16: NewVT = MVT::v4i32; break;
3758   case MVT::v16i8: NewVT = MVT::v4i32; break;
3759   }
3760
3761   if (NewWidth == 2) {
3762     if (VT.isInteger())
3763       NewVT = MVT::v2i64;
3764     else
3765       NewVT = MVT::v2f64;
3766   }
3767   unsigned Scale = NumElems / NewWidth;
3768   SmallVector<SDValue, 8> MaskVec;
3769   for (unsigned i = 0; i < NumElems; i += Scale) {
3770     unsigned StartIdx = ~0U;
3771     for (unsigned j = 0; j < Scale; ++j) {
3772       SDValue Elt = PermMask.getOperand(i+j);
3773       if (Elt.getOpcode() == ISD::UNDEF)
3774         continue;
3775       unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3776       if (StartIdx == ~0U)
3777         StartIdx = EltIdx - (EltIdx % Scale);
3778       if (EltIdx != StartIdx + j)
3779         return SDValue();
3780     }
3781     if (StartIdx == ~0U)
3782       MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEltVT));
3783     else
3784       MaskVec.push_back(DAG.getConstant(StartIdx / Scale, MaskEltVT));
3785   }
3786
3787   V1 = DAG.getNode(ISD::BIT_CONVERT, NewVT, V1);
3788   V2 = DAG.getNode(ISD::BIT_CONVERT, NewVT, V2);
3789   return DAG.getNode(ISD::VECTOR_SHUFFLE, NewVT, V1, V2,
3790                      DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3791                                  &MaskVec[0], MaskVec.size()));
3792 }
3793
3794 /// getVZextMovL - Return a zero-extending vector move low node.
3795 ///
3796 static SDValue getVZextMovL(MVT VT, MVT OpVT,
3797                               SDValue SrcOp, SelectionDAG &DAG,
3798                               const X86Subtarget *Subtarget) {
3799   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
3800     LoadSDNode *LD = NULL;
3801     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
3802       LD = dyn_cast<LoadSDNode>(SrcOp);
3803     if (!LD) {
3804       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
3805       // instead.
3806       MVT EVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
3807       if ((EVT != MVT::i64 || Subtarget->is64Bit()) &&
3808           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
3809           SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
3810           SrcOp.getOperand(0).getOperand(0).getValueType() == EVT) {
3811         // PR2108
3812         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
3813         return DAG.getNode(ISD::BIT_CONVERT, VT,
3814                            DAG.getNode(X86ISD::VZEXT_MOVL, OpVT,
3815                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, OpVT,
3816                                                    SrcOp.getOperand(0)
3817                                                           .getOperand(0))));
3818       }
3819     }
3820   }
3821
3822   return DAG.getNode(ISD::BIT_CONVERT, VT,
3823                      DAG.getNode(X86ISD::VZEXT_MOVL, OpVT,
3824                                  DAG.getNode(ISD::BIT_CONVERT, OpVT, SrcOp)));
3825 }
3826
3827 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
3828 /// shuffles.
3829 static SDValue
3830 LowerVECTOR_SHUFFLE_4wide(SDValue V1, SDValue V2,
3831                           SDValue PermMask, MVT VT, SelectionDAG &DAG) {
3832   MVT MaskVT = PermMask.getValueType();
3833   MVT MaskEVT = MaskVT.getVectorElementType();
3834   SmallVector<std::pair<int, int>, 8> Locs;
3835   Locs.resize(4);
3836   SmallVector<SDValue, 8> Mask1(4, DAG.getNode(ISD::UNDEF, MaskEVT));
3837   unsigned NumHi = 0;
3838   unsigned NumLo = 0;
3839   for (unsigned i = 0; i != 4; ++i) {
3840     SDValue Elt = PermMask.getOperand(i);
3841     if (Elt.getOpcode() == ISD::UNDEF) {
3842       Locs[i] = std::make_pair(-1, -1);
3843     } else {
3844       unsigned Val = cast<ConstantSDNode>(Elt)->getZExtValue();
3845       assert(Val < 8 && "Invalid VECTOR_SHUFFLE index!");
3846       if (Val < 4) {
3847         Locs[i] = std::make_pair(0, NumLo);
3848         Mask1[NumLo] = Elt;
3849         NumLo++;
3850       } else {
3851         Locs[i] = std::make_pair(1, NumHi);
3852         if (2+NumHi < 4)
3853           Mask1[2+NumHi] = Elt;
3854         NumHi++;
3855       }
3856     }
3857   }
3858
3859   if (NumLo <= 2 && NumHi <= 2) {
3860     // If no more than two elements come from either vector. This can be
3861     // implemented with two shuffles. First shuffle gather the elements.
3862     // The second shuffle, which takes the first shuffle as both of its
3863     // vector operands, put the elements into the right order.
3864     V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3865                      DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3866                                  &Mask1[0], Mask1.size()));
3867
3868     SmallVector<SDValue, 8> Mask2(4, DAG.getNode(ISD::UNDEF, MaskEVT));
3869     for (unsigned i = 0; i != 4; ++i) {
3870       if (Locs[i].first == -1)
3871         continue;
3872       else {
3873         unsigned Idx = (i < 2) ? 0 : 4;
3874         Idx += Locs[i].first * 2 + Locs[i].second;
3875         Mask2[i] = DAG.getConstant(Idx, MaskEVT);
3876       }
3877     }
3878
3879     return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1,
3880                        DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3881                                    &Mask2[0], Mask2.size()));
3882   } else if (NumLo == 3 || NumHi == 3) {
3883     // Otherwise, we must have three elements from one vector, call it X, and
3884     // one element from the other, call it Y.  First, use a shufps to build an
3885     // intermediate vector with the one element from Y and the element from X
3886     // that will be in the same half in the final destination (the indexes don't
3887     // matter). Then, use a shufps to build the final vector, taking the half
3888     // containing the element from Y from the intermediate, and the other half
3889     // from X.
3890     if (NumHi == 3) {
3891       // Normalize it so the 3 elements come from V1.
3892       PermMask = CommuteVectorShuffleMask(PermMask, DAG);
3893       std::swap(V1, V2);
3894     }
3895
3896     // Find the element from V2.
3897     unsigned HiIndex;
3898     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
3899       SDValue Elt = PermMask.getOperand(HiIndex);
3900       if (Elt.getOpcode() == ISD::UNDEF)
3901         continue;
3902       unsigned Val = cast<ConstantSDNode>(Elt)->getZExtValue();
3903       if (Val >= 4)
3904         break;
3905     }
3906
3907     Mask1[0] = PermMask.getOperand(HiIndex);
3908     Mask1[1] = DAG.getNode(ISD::UNDEF, MaskEVT);
3909     Mask1[2] = PermMask.getOperand(HiIndex^1);
3910     Mask1[3] = DAG.getNode(ISD::UNDEF, MaskEVT);
3911     V2 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3912                      DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &Mask1[0], 4));
3913
3914     if (HiIndex >= 2) {
3915       Mask1[0] = PermMask.getOperand(0);
3916       Mask1[1] = PermMask.getOperand(1);
3917       Mask1[2] = DAG.getConstant(HiIndex & 1 ? 6 : 4, MaskEVT);
3918       Mask1[3] = DAG.getConstant(HiIndex & 1 ? 4 : 6, MaskEVT);
3919       return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3920                          DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &Mask1[0], 4));
3921     } else {
3922       Mask1[0] = DAG.getConstant(HiIndex & 1 ? 2 : 0, MaskEVT);
3923       Mask1[1] = DAG.getConstant(HiIndex & 1 ? 0 : 2, MaskEVT);
3924       Mask1[2] = PermMask.getOperand(2);
3925       Mask1[3] = PermMask.getOperand(3);
3926       if (Mask1[2].getOpcode() != ISD::UNDEF)
3927         Mask1[2] =
3928           DAG.getConstant(cast<ConstantSDNode>(Mask1[2])->getZExtValue()+4,
3929                           MaskEVT);
3930       if (Mask1[3].getOpcode() != ISD::UNDEF)
3931         Mask1[3] =
3932           DAG.getConstant(cast<ConstantSDNode>(Mask1[3])->getZExtValue()+4,
3933                           MaskEVT);
3934       return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V2, V1,
3935                          DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &Mask1[0], 4));
3936     }
3937   }
3938
3939   // Break it into (shuffle shuffle_hi, shuffle_lo).
3940   Locs.clear();
3941   SmallVector<SDValue,8> LoMask(4, DAG.getNode(ISD::UNDEF, MaskEVT));
3942   SmallVector<SDValue,8> HiMask(4, DAG.getNode(ISD::UNDEF, MaskEVT));
3943   SmallVector<SDValue,8> *MaskPtr = &LoMask;
3944   unsigned MaskIdx = 0;
3945   unsigned LoIdx = 0;
3946   unsigned HiIdx = 2;
3947   for (unsigned i = 0; i != 4; ++i) {
3948     if (i == 2) {
3949       MaskPtr = &HiMask;
3950       MaskIdx = 1;
3951       LoIdx = 0;
3952       HiIdx = 2;
3953     }
3954     SDValue Elt = PermMask.getOperand(i);
3955     if (Elt.getOpcode() == ISD::UNDEF) {
3956       Locs[i] = std::make_pair(-1, -1);
3957     } else if (cast<ConstantSDNode>(Elt)->getZExtValue() < 4) {
3958       Locs[i] = std::make_pair(MaskIdx, LoIdx);
3959       (*MaskPtr)[LoIdx] = Elt;
3960       LoIdx++;
3961     } else {
3962       Locs[i] = std::make_pair(MaskIdx, HiIdx);
3963       (*MaskPtr)[HiIdx] = Elt;
3964       HiIdx++;
3965     }
3966   }
3967
3968   SDValue LoShuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3969                                     DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3970                                                 &LoMask[0], LoMask.size()));
3971   SDValue HiShuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3972                                     DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3973                                                 &HiMask[0], HiMask.size()));
3974   SmallVector<SDValue, 8> MaskOps;
3975   for (unsigned i = 0; i != 4; ++i) {
3976     if (Locs[i].first == -1) {
3977       MaskOps.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3978     } else {
3979       unsigned Idx = Locs[i].first * 4 + Locs[i].second;
3980       MaskOps.push_back(DAG.getConstant(Idx, MaskEVT));
3981     }
3982   }
3983   return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, LoShuffle, HiShuffle,
3984                      DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3985                                  &MaskOps[0], MaskOps.size()));
3986 }
3987
3988 SDValue
3989 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
3990   SDValue V1 = Op.getOperand(0);
3991   SDValue V2 = Op.getOperand(1);
3992   SDValue PermMask = Op.getOperand(2);
3993   MVT VT = Op.getValueType();
3994   unsigned NumElems = PermMask.getNumOperands();
3995   bool isMMX = VT.getSizeInBits() == 64;
3996   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
3997   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
3998   bool V1IsSplat = false;
3999   bool V2IsSplat = false;
4000
4001   if (isUndefShuffle(Op.getNode()))
4002     return DAG.getNode(ISD::UNDEF, VT);
4003
4004   if (isZeroShuffle(Op.getNode()))
4005     return getZeroVector(VT, Subtarget->hasSSE2(), DAG);
4006
4007   if (isIdentityMask(PermMask.getNode()))
4008     return V1;
4009   else if (isIdentityMask(PermMask.getNode(), true))
4010     return V2;
4011
4012   // Canonicalize movddup shuffles.
4013   if (V2IsUndef && Subtarget->hasSSE2() &&
4014       VT.getSizeInBits() == 128 &&
4015       X86::isMOVDDUPMask(PermMask.getNode()))
4016     return CanonicalizeMovddup(Op, V1, PermMask, DAG, Subtarget->hasSSE3());
4017
4018   if (isSplatMask(PermMask.getNode())) {
4019     if (isMMX || NumElems < 4) return Op;
4020     // Promote it to a v4{if}32 splat.
4021     return PromoteSplat(Op, DAG, Subtarget->hasSSE2());
4022   }
4023
4024   // If the shuffle can be profitably rewritten as a narrower shuffle, then
4025   // do it!
4026   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
4027     SDValue NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG, *this);
4028     if (NewOp.getNode())
4029       return DAG.getNode(ISD::BIT_CONVERT, VT, LowerVECTOR_SHUFFLE(NewOp, DAG));
4030   } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
4031     // FIXME: Figure out a cleaner way to do this.
4032     // Try to make use of movq to zero out the top part.
4033     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
4034       SDValue NewOp = RewriteAsNarrowerShuffle(V1, V2, VT, PermMask,
4035                                                  DAG, *this);
4036       if (NewOp.getNode()) {
4037         SDValue NewV1 = NewOp.getOperand(0);
4038         SDValue NewV2 = NewOp.getOperand(1);
4039         SDValue NewMask = NewOp.getOperand(2);
4040         if (isCommutedMOVL(NewMask.getNode(), true, false)) {
4041           NewOp = CommuteVectorShuffle(NewOp, NewV1, NewV2, NewMask, DAG);
4042           return getVZextMovL(VT, NewOp.getValueType(), NewV2, DAG, Subtarget);
4043         }
4044       }
4045     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
4046       SDValue NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask,
4047                                                 DAG, *this);
4048       if (NewOp.getNode() && X86::isMOVLMask(NewOp.getOperand(2).getNode()))
4049         return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
4050                              DAG, Subtarget);
4051     }
4052   }
4053
4054   // Check if this can be converted into a logical shift.
4055   bool isLeft = false;
4056   unsigned ShAmt = 0;
4057   SDValue ShVal;
4058   bool isShift = isVectorShift(Op, PermMask, DAG, isLeft, ShVal, ShAmt);
4059   if (isShift && ShVal.hasOneUse()) {
4060     // If the shifted value has multiple uses, it may be cheaper to use 
4061     // v_set0 + movlhps or movhlps, etc.
4062     MVT EVT = VT.getVectorElementType();
4063     ShAmt *= EVT.getSizeInBits();
4064     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this);
4065   }
4066
4067   if (X86::isMOVLMask(PermMask.getNode())) {
4068     if (V1IsUndef)
4069       return V2;
4070     if (ISD::isBuildVectorAllZeros(V1.getNode()))
4071       return getVZextMovL(VT, VT, V2, DAG, Subtarget);
4072     if (!isMMX)
4073       return Op;
4074   }
4075
4076   if (!isMMX && (X86::isMOVSHDUPMask(PermMask.getNode()) ||
4077                  X86::isMOVSLDUPMask(PermMask.getNode()) ||
4078                  X86::isMOVHLPSMask(PermMask.getNode()) ||
4079                  X86::isMOVHPMask(PermMask.getNode()) ||
4080                  X86::isMOVLPMask(PermMask.getNode())))
4081     return Op;
4082
4083   if (ShouldXformToMOVHLPS(PermMask.getNode()) ||
4084       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), PermMask.getNode()))
4085     return CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4086
4087   if (isShift) {
4088     // No better options. Use a vshl / vsrl.
4089     MVT EVT = VT.getVectorElementType();
4090     ShAmt *= EVT.getSizeInBits();
4091     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this);
4092   }
4093
4094   bool Commuted = false;
4095   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
4096   // 1,1,1,1 -> v8i16 though.
4097   V1IsSplat = isSplatVector(V1.getNode());
4098   V2IsSplat = isSplatVector(V2.getNode());
4099   
4100   // Canonicalize the splat or undef, if present, to be on the RHS.
4101   if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
4102     Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4103     std::swap(V1IsSplat, V2IsSplat);
4104     std::swap(V1IsUndef, V2IsUndef);
4105     Commuted = true;
4106   }
4107
4108   // FIXME: Figure out a cleaner way to do this.
4109   if (isCommutedMOVL(PermMask.getNode(), V2IsSplat, V2IsUndef)) {
4110     if (V2IsUndef) return V1;
4111     Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4112     if (V2IsSplat) {
4113       // V2 is a splat, so the mask may be malformed. That is, it may point
4114       // to any V2 element. The instruction selectior won't like this. Get
4115       // a corrected mask and commute to form a proper MOVS{S|D}.
4116       SDValue NewMask = getMOVLMask(NumElems, DAG);
4117       if (NewMask.getNode() != PermMask.getNode())
4118         Op = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
4119     }
4120     return Op;
4121   }
4122
4123   if (X86::isUNPCKL_v_undef_Mask(PermMask.getNode()) ||
4124       X86::isUNPCKH_v_undef_Mask(PermMask.getNode()) ||
4125       X86::isUNPCKLMask(PermMask.getNode()) ||
4126       X86::isUNPCKHMask(PermMask.getNode()))
4127     return Op;
4128
4129   if (V2IsSplat) {
4130     // Normalize mask so all entries that point to V2 points to its first
4131     // element then try to match unpck{h|l} again. If match, return a
4132     // new vector_shuffle with the corrected mask.
4133     SDValue NewMask = NormalizeMask(PermMask, DAG);
4134     if (NewMask.getNode() != PermMask.getNode()) {
4135       if (X86::isUNPCKLMask(PermMask.getNode(), true)) {
4136         SDValue NewMask = getUnpacklMask(NumElems, DAG);
4137         return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
4138       } else if (X86::isUNPCKHMask(PermMask.getNode(), true)) {
4139         SDValue NewMask = getUnpackhMask(NumElems, DAG);
4140         return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
4141       }
4142     }
4143   }
4144
4145   // Normalize the node to match x86 shuffle ops if needed
4146   if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(PermMask.getNode()))
4147       Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4148
4149   if (Commuted) {
4150     // Commute is back and try unpck* again.
4151     Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4152     if (X86::isUNPCKL_v_undef_Mask(PermMask.getNode()) ||
4153         X86::isUNPCKH_v_undef_Mask(PermMask.getNode()) ||
4154         X86::isUNPCKLMask(PermMask.getNode()) ||
4155         X86::isUNPCKHMask(PermMask.getNode()))
4156       return Op;
4157   }
4158
4159   // Try PSHUF* first, then SHUFP*.
4160   // MMX doesn't have PSHUFD but it does have PSHUFW. While it's theoretically
4161   // possible to shuffle a v2i32 using PSHUFW, that's not yet implemented.
4162   if (isMMX && NumElems == 4 && X86::isPSHUFDMask(PermMask.getNode())) {
4163     if (V2.getOpcode() != ISD::UNDEF)
4164       return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
4165                          DAG.getNode(ISD::UNDEF, VT), PermMask);
4166     return Op;
4167   }
4168
4169   if (!isMMX) {
4170     if (Subtarget->hasSSE2() &&
4171         (X86::isPSHUFDMask(PermMask.getNode()) ||
4172          X86::isPSHUFHWMask(PermMask.getNode()) ||
4173          X86::isPSHUFLWMask(PermMask.getNode()))) {
4174       MVT RVT = VT;
4175       if (VT == MVT::v4f32) {
4176         RVT = MVT::v4i32;
4177         Op = DAG.getNode(ISD::VECTOR_SHUFFLE, RVT,
4178                          DAG.getNode(ISD::BIT_CONVERT, RVT, V1),
4179                          DAG.getNode(ISD::UNDEF, RVT), PermMask);
4180       } else if (V2.getOpcode() != ISD::UNDEF)
4181         Op = DAG.getNode(ISD::VECTOR_SHUFFLE, RVT, V1,
4182                          DAG.getNode(ISD::UNDEF, RVT), PermMask);
4183       if (RVT != VT)
4184         Op = DAG.getNode(ISD::BIT_CONVERT, VT, Op);
4185       return Op;
4186     }
4187
4188     // Binary or unary shufps.
4189     if (X86::isSHUFPMask(PermMask.getNode()) ||
4190         (V2.getOpcode() == ISD::UNDEF && X86::isPSHUFDMask(PermMask.getNode())))
4191       return Op;
4192   }
4193
4194   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
4195   if (VT == MVT::v8i16) {
4196     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(V1, V2, PermMask, DAG, *this);
4197     if (NewOp.getNode())
4198       return NewOp;
4199   }
4200
4201   // Handle all 4 wide cases with a number of shuffles except for MMX.
4202   if (NumElems == 4 && !isMMX)
4203     return LowerVECTOR_SHUFFLE_4wide(V1, V2, PermMask, VT, DAG);
4204
4205   return SDValue();
4206 }
4207
4208 SDValue
4209 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
4210                                                 SelectionDAG &DAG) {
4211   MVT VT = Op.getValueType();
4212   if (VT.getSizeInBits() == 8) {
4213     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, MVT::i32,
4214                                     Op.getOperand(0), Op.getOperand(1));
4215     SDValue Assert  = DAG.getNode(ISD::AssertZext, MVT::i32, Extract,
4216                                     DAG.getValueType(VT));
4217     return DAG.getNode(ISD::TRUNCATE, VT, Assert);
4218   } else if (VT.getSizeInBits() == 16) {
4219     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4220     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
4221     if (Idx == 0)
4222       return DAG.getNode(ISD::TRUNCATE, MVT::i16,
4223                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32,
4224                                      DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32,
4225                                                  Op.getOperand(0)),
4226                                      Op.getOperand(1)));
4227     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, MVT::i32,
4228                                     Op.getOperand(0), Op.getOperand(1));
4229     SDValue Assert  = DAG.getNode(ISD::AssertZext, MVT::i32, Extract,
4230                                     DAG.getValueType(VT));
4231     return DAG.getNode(ISD::TRUNCATE, VT, Assert);
4232   } else if (VT == MVT::f32) {
4233     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
4234     // the result back to FR32 register. It's only worth matching if the
4235     // result has a single use which is a store or a bitcast to i32.  And in
4236     // the case of a store, it's not worth it if the index is a constant 0,
4237     // because a MOVSSmr can be used instead, which is smaller and faster.
4238     if (!Op.hasOneUse())
4239       return SDValue();
4240     SDNode *User = *Op.getNode()->use_begin();
4241     if ((User->getOpcode() != ISD::STORE ||
4242          (isa<ConstantSDNode>(Op.getOperand(1)) &&
4243           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
4244         (User->getOpcode() != ISD::BIT_CONVERT ||
4245          User->getValueType(0) != MVT::i32))
4246       return SDValue();
4247     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32,
4248                     DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, Op.getOperand(0)),
4249                                     Op.getOperand(1));
4250     return DAG.getNode(ISD::BIT_CONVERT, MVT::f32, Extract);
4251   }
4252   return SDValue();
4253 }
4254
4255
4256 SDValue
4257 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4258   if (!isa<ConstantSDNode>(Op.getOperand(1)))
4259     return SDValue();
4260
4261   if (Subtarget->hasSSE41()) {
4262     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
4263     if (Res.getNode())
4264       return Res;
4265   }
4266
4267   MVT VT = Op.getValueType();
4268   // TODO: handle v16i8.
4269   if (VT.getSizeInBits() == 16) {
4270     SDValue Vec = Op.getOperand(0);
4271     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4272     if (Idx == 0)
4273       return DAG.getNode(ISD::TRUNCATE, MVT::i16,
4274                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32,
4275                                  DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, Vec),
4276                                      Op.getOperand(1)));
4277     // Transform it so it match pextrw which produces a 32-bit result.
4278     MVT EVT = (MVT::SimpleValueType)(VT.getSimpleVT()+1);
4279     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, EVT,
4280                                     Op.getOperand(0), Op.getOperand(1));
4281     SDValue Assert  = DAG.getNode(ISD::AssertZext, EVT, Extract,
4282                                     DAG.getValueType(VT));
4283     return DAG.getNode(ISD::TRUNCATE, VT, Assert);
4284   } else if (VT.getSizeInBits() == 32) {
4285     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4286     if (Idx == 0)
4287       return Op;
4288     // SHUFPS the element to the lowest double word, then movss.
4289     MVT MaskVT = MVT::getIntVectorWithNumElements(4);
4290     SmallVector<SDValue, 8> IdxVec;
4291     IdxVec.
4292       push_back(DAG.getConstant(Idx, MaskVT.getVectorElementType()));
4293     IdxVec.
4294       push_back(DAG.getNode(ISD::UNDEF, MaskVT.getVectorElementType()));
4295     IdxVec.
4296       push_back(DAG.getNode(ISD::UNDEF, MaskVT.getVectorElementType()));
4297     IdxVec.
4298       push_back(DAG.getNode(ISD::UNDEF, MaskVT.getVectorElementType()));
4299     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
4300                                  &IdxVec[0], IdxVec.size());
4301     SDValue Vec = Op.getOperand(0);
4302     Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
4303                       Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
4304     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
4305                        DAG.getIntPtrConstant(0));
4306   } else if (VT.getSizeInBits() == 64) {
4307     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
4308     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
4309     //        to match extract_elt for f64.
4310     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4311     if (Idx == 0)
4312       return Op;
4313
4314     // UNPCKHPD the element to the lowest double word, then movsd.
4315     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
4316     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
4317     MVT MaskVT = MVT::getIntVectorWithNumElements(2);
4318     SmallVector<SDValue, 8> IdxVec;
4319     IdxVec.push_back(DAG.getConstant(1, MaskVT.getVectorElementType()));
4320     IdxVec.
4321       push_back(DAG.getNode(ISD::UNDEF, MaskVT.getVectorElementType()));
4322     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
4323                                  &IdxVec[0], IdxVec.size());
4324     SDValue Vec = Op.getOperand(0);
4325     Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
4326                       Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
4327     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
4328                        DAG.getIntPtrConstant(0));
4329   }
4330
4331   return SDValue();
4332 }
4333
4334 SDValue
4335 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG){
4336   MVT VT = Op.getValueType();
4337   MVT EVT = VT.getVectorElementType();
4338
4339   SDValue N0 = Op.getOperand(0);
4340   SDValue N1 = Op.getOperand(1);
4341   SDValue N2 = Op.getOperand(2);
4342
4343   if ((EVT.getSizeInBits() == 8 || EVT.getSizeInBits() == 16) &&
4344       isa<ConstantSDNode>(N2)) {
4345     unsigned Opc = (EVT.getSizeInBits() == 8) ? X86ISD::PINSRB
4346                                                   : X86ISD::PINSRW;
4347     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
4348     // argument.
4349     if (N1.getValueType() != MVT::i32)
4350       N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
4351     if (N2.getValueType() != MVT::i32)
4352       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4353     return DAG.getNode(Opc, VT, N0, N1, N2);
4354   } else if (EVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
4355     // Bits [7:6] of the constant are the source select.  This will always be
4356     //  zero here.  The DAG Combiner may combine an extract_elt index into these
4357     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
4358     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
4359     // Bits [5:4] of the constant are the destination select.  This is the 
4360     //  value of the incoming immediate.
4361     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may 
4362     //   combine either bitwise AND or insert of float 0.0 to set these bits.
4363     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
4364     return DAG.getNode(X86ISD::INSERTPS, VT, N0, N1, N2);
4365   }
4366   return SDValue();
4367 }
4368
4369 SDValue
4370 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4371   MVT VT = Op.getValueType();
4372   MVT EVT = VT.getVectorElementType();
4373
4374   if (Subtarget->hasSSE41())
4375     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
4376
4377   if (EVT == MVT::i8)
4378     return SDValue();
4379
4380   SDValue N0 = Op.getOperand(0);
4381   SDValue N1 = Op.getOperand(1);
4382   SDValue N2 = Op.getOperand(2);
4383
4384   if (EVT.getSizeInBits() == 16) {
4385     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
4386     // as its second argument.
4387     if (N1.getValueType() != MVT::i32)
4388       N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
4389     if (N2.getValueType() != MVT::i32)
4390       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4391     return DAG.getNode(X86ISD::PINSRW, VT, N0, N1, N2);
4392   }
4393   return SDValue();
4394 }
4395
4396 SDValue
4397 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
4398   if (Op.getValueType() == MVT::v2f32)
4399     return DAG.getNode(ISD::BIT_CONVERT, MVT::v2f32,
4400                        DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2i32,
4401                                    DAG.getNode(ISD::BIT_CONVERT, MVT::i32,
4402                                                Op.getOperand(0))));
4403
4404   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, Op.getOperand(0));
4405   MVT VT = MVT::v2i32;
4406   switch (Op.getValueType().getSimpleVT()) {
4407   default: break;
4408   case MVT::v16i8:
4409   case MVT::v8i16:
4410     VT = MVT::v4i32;
4411     break;
4412   }
4413   return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(),
4414                      DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, AnyExt));
4415 }
4416
4417 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
4418 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
4419 // one of the above mentioned nodes. It has to be wrapped because otherwise
4420 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
4421 // be used to form addressing mode. These wrapped nodes will be selected
4422 // into MOV32ri.
4423 SDValue
4424 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
4425   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4426   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(),
4427                                                getPointerTy(),
4428                                                CP->getAlignment());
4429   Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4430   // With PIC, the address is actually $g + Offset.
4431   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4432       !Subtarget->isPICStyleRIPRel()) {
4433     Result = DAG.getNode(ISD::ADD, getPointerTy(),
4434                          DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4435                          Result);
4436   }
4437
4438   return Result;
4439 }
4440
4441 SDValue
4442 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV,
4443                                       int64_t Offset,
4444                                       SelectionDAG &DAG) const {
4445   bool IsPic = getTargetMachine().getRelocationModel() == Reloc::PIC_;
4446   bool ExtraLoadRequired =
4447     Subtarget->GVRequiresExtraLoad(GV, getTargetMachine(), false);
4448
4449   // Create the TargetGlobalAddress node, folding in the constant
4450   // offset if it is legal.
4451   SDValue Result;
4452   if (!IsPic && !ExtraLoadRequired && isInt32(Offset)) {
4453     Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), Offset);
4454     Offset = 0;
4455   } else
4456     Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), 0);
4457   Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4458
4459   // With PIC, the address is actually $g + Offset.
4460   if (IsPic && !Subtarget->isPICStyleRIPRel()) {
4461     Result = DAG.getNode(ISD::ADD, getPointerTy(),
4462                          DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4463                          Result);
4464   }
4465   
4466   // For Darwin & Mingw32, external and weak symbols are indirect, so we want to
4467   // load the value at address GV, not the value of GV itself. This means that
4468   // the GlobalAddress must be in the base or index register of the address, not
4469   // the GV offset field. Platform check is inside GVRequiresExtraLoad() call
4470   // The same applies for external symbols during PIC codegen
4471   if (ExtraLoadRequired)
4472     Result = DAG.getLoad(getPointerTy(), DAG.getEntryNode(), Result,
4473                          PseudoSourceValue::getGOT(), 0);
4474
4475   // If there was a non-zero offset that we didn't fold, create an explicit
4476   // addition for it.
4477   if (Offset != 0)
4478     Result = DAG.getNode(ISD::ADD, getPointerTy(), Result,
4479                          DAG.getConstant(Offset, getPointerTy()));
4480
4481   return Result;
4482 }
4483
4484 SDValue
4485 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) {
4486   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4487   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
4488   return LowerGlobalAddress(GV, Offset, DAG);
4489 }
4490
4491 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
4492 static SDValue
4493 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4494                                 const MVT PtrVT) {
4495   SDValue InFlag;
4496   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), X86::EBX,
4497                                      DAG.getNode(X86ISD::GlobalBaseReg,
4498                                                  PtrVT), InFlag);
4499   InFlag = Chain.getValue(1);
4500
4501   // emit leal symbol@TLSGD(,%ebx,1), %eax
4502   SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
4503   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4504                                              GA->getValueType(0),
4505                                              GA->getOffset());
4506   SDValue Ops[] = { Chain,  TGA, InFlag };
4507   SDValue Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 3);
4508   InFlag = Result.getValue(2);
4509   Chain = Result.getValue(1);
4510
4511   // call ___tls_get_addr. This function receives its argument in
4512   // the register EAX.
4513   Chain = DAG.getCopyToReg(Chain, X86::EAX, Result, InFlag);
4514   InFlag = Chain.getValue(1);
4515
4516   NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4517   SDValue Ops1[] = { Chain,
4518                       DAG.getTargetExternalSymbol("___tls_get_addr",
4519                                                   PtrVT),
4520                       DAG.getRegister(X86::EAX, PtrVT),
4521                       DAG.getRegister(X86::EBX, PtrVT),
4522                       InFlag };
4523   Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 5);
4524   InFlag = Chain.getValue(1);
4525
4526   return DAG.getCopyFromReg(Chain, X86::EAX, PtrVT, InFlag);
4527 }
4528
4529 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
4530 static SDValue
4531 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4532                                 const MVT PtrVT) {
4533   SDValue InFlag, Chain;
4534
4535   // emit leaq symbol@TLSGD(%rip), %rdi
4536   SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
4537   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4538                                              GA->getValueType(0),
4539                                              GA->getOffset());
4540   SDValue Ops[]  = { DAG.getEntryNode(), TGA};
4541   SDValue Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 2);
4542   Chain  = Result.getValue(1);
4543   InFlag = Result.getValue(2);
4544
4545   // call __tls_get_addr. This function receives its argument in
4546   // the register RDI.
4547   Chain = DAG.getCopyToReg(Chain, X86::RDI, Result, InFlag);
4548   InFlag = Chain.getValue(1);
4549
4550   NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4551   SDValue Ops1[] = { Chain,
4552                       DAG.getTargetExternalSymbol("__tls_get_addr",
4553                                                   PtrVT),
4554                       DAG.getRegister(X86::RDI, PtrVT),
4555                       InFlag };
4556   Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 4);
4557   InFlag = Chain.getValue(1);
4558
4559   return DAG.getCopyFromReg(Chain, X86::RAX, PtrVT, InFlag);
4560 }
4561
4562 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
4563 // "local exec" model.
4564 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4565                                      const MVT PtrVT) {
4566   // Get the Thread Pointer
4567   SDValue ThreadPointer = DAG.getNode(X86ISD::THREAD_POINTER, PtrVT);
4568   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
4569   // exec)
4570   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4571                                              GA->getValueType(0),
4572                                              GA->getOffset());
4573   SDValue Offset = DAG.getNode(X86ISD::Wrapper, PtrVT, TGA);
4574
4575   if (GA->getGlobal()->isDeclaration()) // initial exec TLS model
4576     Offset = DAG.getLoad(PtrVT, DAG.getEntryNode(), Offset,
4577                          PseudoSourceValue::getGOT(), 0);
4578
4579   // The address of the thread local variable is the add of the thread
4580   // pointer with the offset of the variable.
4581   return DAG.getNode(ISD::ADD, PtrVT, ThreadPointer, Offset);
4582 }
4583
4584 SDValue
4585 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) {
4586   // TODO: implement the "local dynamic" model
4587   // TODO: implement the "initial exec"model for pic executables
4588   assert(Subtarget->isTargetELF() &&
4589          "TLS not implemented for non-ELF targets");
4590   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4591   // If the relocation model is PIC, use the "General Dynamic" TLS Model,
4592   // otherwise use the "Local Exec"TLS Model
4593   if (Subtarget->is64Bit()) {
4594     return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
4595   } else {
4596     if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
4597       return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
4598     else
4599       return LowerToTLSExecModel(GA, DAG, getPointerTy());
4600   }
4601 }
4602
4603 SDValue
4604 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) {
4605   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
4606   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy());
4607   Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4608   // With PIC, the address is actually $g + Offset.
4609   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4610       !Subtarget->isPICStyleRIPRel()) {
4611     Result = DAG.getNode(ISD::ADD, getPointerTy(),
4612                          DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4613                          Result);
4614   }
4615
4616   return Result;
4617 }
4618
4619 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) {
4620   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4621   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), 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 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
4635 /// take a 2 x i32 value to shift plus a shift amount. 
4636 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) {
4637   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4638   MVT VT = Op.getValueType();
4639   unsigned VTBits = VT.getSizeInBits();
4640   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
4641   SDValue ShOpLo = Op.getOperand(0);
4642   SDValue ShOpHi = Op.getOperand(1);
4643   SDValue ShAmt  = Op.getOperand(2);
4644   SDValue Tmp1 = isSRA ?
4645     DAG.getNode(ISD::SRA, VT, ShOpHi, DAG.getConstant(VTBits - 1, MVT::i8)) :
4646     DAG.getConstant(0, VT);
4647
4648   SDValue Tmp2, Tmp3;
4649   if (Op.getOpcode() == ISD::SHL_PARTS) {
4650     Tmp2 = DAG.getNode(X86ISD::SHLD, VT, ShOpHi, ShOpLo, ShAmt);
4651     Tmp3 = DAG.getNode(ISD::SHL, VT, ShOpLo, ShAmt);
4652   } else {
4653     Tmp2 = DAG.getNode(X86ISD::SHRD, VT, ShOpLo, ShOpHi, ShAmt);
4654     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, VT, ShOpHi, ShAmt);
4655   }
4656
4657   SDValue AndNode = DAG.getNode(ISD::AND, MVT::i8, ShAmt,
4658                                   DAG.getConstant(VTBits, MVT::i8));
4659   SDValue Cond = DAG.getNode(X86ISD::CMP, VT,
4660                                AndNode, DAG.getConstant(0, MVT::i8));
4661
4662   SDValue Hi, Lo;
4663   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4664   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
4665   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
4666
4667   if (Op.getOpcode() == ISD::SHL_PARTS) {
4668     Hi = DAG.getNode(X86ISD::CMOV, VT, Ops0, 4);
4669     Lo = DAG.getNode(X86ISD::CMOV, VT, Ops1, 4);
4670   } else {
4671     Lo = DAG.getNode(X86ISD::CMOV, VT, Ops0, 4);
4672     Hi = DAG.getNode(X86ISD::CMOV, VT, Ops1, 4);
4673   }
4674
4675   SDValue Ops[2] = { Lo, Hi };
4676   return DAG.getMergeValues(Ops, 2);
4677 }
4678
4679 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4680   MVT SrcVT = Op.getOperand(0).getValueType();
4681   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
4682          "Unknown SINT_TO_FP to lower!");
4683   
4684   // These are really Legal; caller falls through into that case.
4685   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
4686     return SDValue();
4687   if (SrcVT == MVT::i64 && Op.getValueType() != MVT::f80 && 
4688       Subtarget->is64Bit())
4689     return SDValue();
4690   
4691   unsigned Size = SrcVT.getSizeInBits()/8;
4692   MachineFunction &MF = DAG.getMachineFunction();
4693   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
4694   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4695   SDValue Chain = DAG.getStore(DAG.getEntryNode(), Op.getOperand(0),
4696                                  StackSlot,
4697                                  PseudoSourceValue::getFixedStack(SSFI), 0);
4698
4699   // Build the FILD
4700   SDVTList Tys;
4701   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
4702   if (useSSE)
4703     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
4704   else
4705     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
4706   SmallVector<SDValue, 8> Ops;
4707   Ops.push_back(Chain);
4708   Ops.push_back(StackSlot);
4709   Ops.push_back(DAG.getValueType(SrcVT));
4710   SDValue Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD,
4711                                  Tys, &Ops[0], Ops.size());
4712
4713   if (useSSE) {
4714     Chain = Result.getValue(1);
4715     SDValue InFlag = Result.getValue(2);
4716
4717     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
4718     // shouldn't be necessary except that RFP cannot be live across
4719     // multiple blocks. When stackifier is fixed, they can be uncoupled.
4720     MachineFunction &MF = DAG.getMachineFunction();
4721     int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
4722     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4723     Tys = DAG.getVTList(MVT::Other);
4724     SmallVector<SDValue, 8> Ops;
4725     Ops.push_back(Chain);
4726     Ops.push_back(Result);
4727     Ops.push_back(StackSlot);
4728     Ops.push_back(DAG.getValueType(Op.getValueType()));
4729     Ops.push_back(InFlag);
4730     Chain = DAG.getNode(X86ISD::FST, Tys, &Ops[0], Ops.size());
4731     Result = DAG.getLoad(Op.getValueType(), Chain, StackSlot,
4732                          PseudoSourceValue::getFixedStack(SSFI), 0);
4733   }
4734
4735   return Result;
4736 }
4737
4738 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4739   MVT SrcVT = Op.getOperand(0).getValueType();
4740   assert(SrcVT.getSimpleVT() == MVT::i64 && "Unknown UINT_TO_FP to lower!");
4741   
4742   // We only handle SSE2 f64 target here; caller can handle the rest.
4743   if (Op.getValueType() != MVT::f64 || !X86ScalarSSEf64)
4744     return SDValue();
4745   
4746   // This algorithm is not obvious.  Here it is in C code, more or less:
4747 /*
4748  double uint64_to_double( uint32_t hi, uint32_t lo )
4749   {
4750     static const __m128i exp = { 0x4330000045300000ULL, 0 };
4751     static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
4752
4753     // copy ints to xmm registers
4754     __m128i xh = _mm_cvtsi32_si128( hi );
4755     __m128i xl = _mm_cvtsi32_si128( lo );
4756
4757     // combine into low half of a single xmm register
4758     __m128i x = _mm_unpacklo_epi32( xh, xl );
4759     __m128d d;
4760     double sd;
4761
4762     // merge in appropriate exponents to give the integer bits the 
4763     // right magnitude
4764     x = _mm_unpacklo_epi32( x, exp );
4765
4766     // subtract away the biases to deal with the IEEE-754 double precision
4767     // implicit 1
4768     d = _mm_sub_pd( (__m128d) x, bias );
4769
4770     // All conversions up to here are exact. The correctly rounded result is 
4771     // calculated using the
4772     // current rounding mode using the following horizontal add.
4773     d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
4774     _mm_store_sd( &sd, d );   //since we are returning doubles in XMM, this
4775     // store doesn't really need to be here (except maybe to zero the other
4776     // double)
4777     return sd;
4778   }
4779 */
4780
4781   // Build some magic constants.
4782   std::vector<Constant*>CV0;
4783   CV0.push_back(ConstantInt::get(APInt(32, 0x45300000)));
4784   CV0.push_back(ConstantInt::get(APInt(32, 0x43300000)));
4785   CV0.push_back(ConstantInt::get(APInt(32, 0)));
4786   CV0.push_back(ConstantInt::get(APInt(32, 0)));
4787   Constant *C0 = ConstantVector::get(CV0);
4788   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 4);
4789
4790   std::vector<Constant*>CV1;
4791   CV1.push_back(ConstantFP::get(APFloat(APInt(64, 0x4530000000000000ULL))));
4792   CV1.push_back(ConstantFP::get(APFloat(APInt(64, 0x4330000000000000ULL))));
4793   Constant *C1 = ConstantVector::get(CV1);
4794   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 4);
4795
4796   SmallVector<SDValue, 4> MaskVec;
4797   MaskVec.push_back(DAG.getConstant(0, MVT::i32));
4798   MaskVec.push_back(DAG.getConstant(4, MVT::i32));
4799   MaskVec.push_back(DAG.getConstant(1, MVT::i32));
4800   MaskVec.push_back(DAG.getConstant(5, MVT::i32));
4801   SDValue UnpcklMask = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, &MaskVec[0],
4802                                    MaskVec.size());
4803   SmallVector<SDValue, 4> MaskVec2;
4804   MaskVec2.push_back(DAG.getConstant(1, MVT::i32));
4805   MaskVec2.push_back(DAG.getConstant(0, MVT::i32));
4806   SDValue ShufMask = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, &MaskVec2[0],
4807                                  MaskVec2.size());
4808
4809   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v4i32,
4810                             DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32,
4811                                         Op.getOperand(0),
4812                                         DAG.getIntPtrConstant(1)));
4813   SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v4i32,
4814                             DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32,
4815                                         Op.getOperand(0),
4816                                         DAG.getIntPtrConstant(0)));
4817   SDValue Unpck1 = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v4i32,
4818                                 XR1, XR2, UnpcklMask);
4819   SDValue CLod0 = DAG.getLoad(MVT::v4i32, DAG.getEntryNode(), CPIdx0,
4820                          PseudoSourceValue::getConstantPool(), 0, false, 16);
4821   SDValue Unpck2 = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v4i32,
4822                                 Unpck1, CLod0, UnpcklMask);
4823   SDValue XR2F = DAG.getNode(ISD::BIT_CONVERT, MVT::v2f64, Unpck2);
4824   SDValue CLod1 = DAG.getLoad(MVT::v2f64, CLod0.getValue(1), CPIdx1,
4825                          PseudoSourceValue::getConstantPool(), 0, false, 16);
4826   SDValue Sub = DAG.getNode(ISD::FSUB, MVT::v2f64, XR2F, CLod1);
4827   // Add the halves; easiest way is to swap them into another reg first.
4828   SDValue Shuf = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v2f64,
4829                              Sub, Sub, ShufMask);
4830   SDValue Add = DAG.getNode(ISD::FADD, MVT::v2f64, Shuf, Sub);
4831   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::f64, Add,
4832                      DAG.getIntPtrConstant(0));
4833 }
4834
4835 std::pair<SDValue,SDValue> X86TargetLowering::
4836 FP_TO_SINTHelper(SDValue Op, SelectionDAG &DAG) {
4837   assert(Op.getValueType().getSimpleVT() <= MVT::i64 &&
4838          Op.getValueType().getSimpleVT() >= MVT::i16 &&
4839          "Unknown FP_TO_SINT to lower!");
4840
4841   // These are really Legal.
4842   if (Op.getValueType() == MVT::i32 && 
4843       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
4844     return std::make_pair(SDValue(), SDValue());
4845   if (Subtarget->is64Bit() &&
4846       Op.getValueType() == MVT::i64 &&
4847       Op.getOperand(0).getValueType() != MVT::f80)
4848     return std::make_pair(SDValue(), SDValue());
4849
4850   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
4851   // stack slot.
4852   MachineFunction &MF = DAG.getMachineFunction();
4853   unsigned MemSize = Op.getValueType().getSizeInBits()/8;
4854   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4855   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4856   unsigned Opc;
4857   switch (Op.getValueType().getSimpleVT()) {
4858   default: assert(0 && "Invalid FP_TO_SINT to lower!");
4859   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
4860   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
4861   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
4862   }
4863
4864   SDValue Chain = DAG.getEntryNode();
4865   SDValue Value = Op.getOperand(0);
4866   if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
4867     assert(Op.getValueType() == MVT::i64 && "Invalid FP_TO_SINT to lower!");
4868     Chain = DAG.getStore(Chain, Value, StackSlot,
4869                          PseudoSourceValue::getFixedStack(SSFI), 0);
4870     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
4871     SDValue Ops[] = {
4872       Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
4873     };
4874     Value = DAG.getNode(X86ISD::FLD, Tys, Ops, 3);
4875     Chain = Value.getValue(1);
4876     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4877     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4878   }
4879
4880   // Build the FP_TO_INT*_IN_MEM
4881   SDValue Ops[] = { Chain, Value, StackSlot };
4882   SDValue FIST = DAG.getNode(Opc, MVT::Other, Ops, 3);
4883
4884   return std::make_pair(FIST, StackSlot);
4885 }
4886
4887 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) {
4888   std::pair<SDValue,SDValue> Vals = FP_TO_SINTHelper(Op, DAG);
4889   SDValue FIST = Vals.first, StackSlot = Vals.second;
4890   if (FIST.getNode() == 0) return SDValue();
4891   
4892   // Load the result.
4893   return DAG.getLoad(Op.getValueType(), FIST, StackSlot, NULL, 0);
4894 }
4895
4896 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) {
4897   MVT VT = Op.getValueType();
4898   MVT EltVT = VT;
4899   if (VT.isVector())
4900     EltVT = VT.getVectorElementType();
4901   std::vector<Constant*> CV;
4902   if (EltVT == MVT::f64) {
4903     Constant *C = ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63))));
4904     CV.push_back(C);
4905     CV.push_back(C);
4906   } else {
4907     Constant *C = ConstantFP::get(APFloat(APInt(32, ~(1U << 31))));
4908     CV.push_back(C);
4909     CV.push_back(C);
4910     CV.push_back(C);
4911     CV.push_back(C);
4912   }
4913   Constant *C = ConstantVector::get(CV);
4914   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4915   SDValue Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4916                                PseudoSourceValue::getConstantPool(), 0,
4917                                false, 16);
4918   return DAG.getNode(X86ISD::FAND, VT, Op.getOperand(0), Mask);
4919 }
4920
4921 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) {
4922   MVT VT = Op.getValueType();
4923   MVT EltVT = VT;
4924   unsigned EltNum = 1;
4925   if (VT.isVector()) {
4926     EltVT = VT.getVectorElementType();
4927     EltNum = VT.getVectorNumElements();
4928   }
4929   std::vector<Constant*> CV;
4930   if (EltVT == MVT::f64) {
4931     Constant *C = ConstantFP::get(APFloat(APInt(64, 1ULL << 63)));
4932     CV.push_back(C);
4933     CV.push_back(C);
4934   } else {
4935     Constant *C = ConstantFP::get(APFloat(APInt(32, 1U << 31)));
4936     CV.push_back(C);
4937     CV.push_back(C);
4938     CV.push_back(C);
4939     CV.push_back(C);
4940   }
4941   Constant *C = ConstantVector::get(CV);
4942   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4943   SDValue Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4944                                PseudoSourceValue::getConstantPool(), 0,
4945                                false, 16);
4946   if (VT.isVector()) {
4947     return DAG.getNode(ISD::BIT_CONVERT, VT,
4948                        DAG.getNode(ISD::XOR, MVT::v2i64,
4949                     DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Op.getOperand(0)),
4950                     DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Mask)));
4951   } else {
4952     return DAG.getNode(X86ISD::FXOR, VT, Op.getOperand(0), Mask);
4953   }
4954 }
4955
4956 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
4957   SDValue Op0 = Op.getOperand(0);
4958   SDValue Op1 = Op.getOperand(1);
4959   MVT VT = Op.getValueType();
4960   MVT SrcVT = Op1.getValueType();
4961
4962   // If second operand is smaller, extend it first.
4963   if (SrcVT.bitsLT(VT)) {
4964     Op1 = DAG.getNode(ISD::FP_EXTEND, VT, Op1);
4965     SrcVT = VT;
4966   }
4967   // And if it is bigger, shrink it first.
4968   if (SrcVT.bitsGT(VT)) {
4969     Op1 = DAG.getNode(ISD::FP_ROUND, VT, Op1, DAG.getIntPtrConstant(1));
4970     SrcVT = VT;
4971   }
4972
4973   // At this point the operands and the result should have the same
4974   // type, and that won't be f80 since that is not custom lowered.
4975
4976   // First get the sign bit of second operand.
4977   std::vector<Constant*> CV;
4978   if (SrcVT == MVT::f64) {
4979     CV.push_back(ConstantFP::get(APFloat(APInt(64, 1ULL << 63))));
4980     CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
4981   } else {
4982     CV.push_back(ConstantFP::get(APFloat(APInt(32, 1U << 31))));
4983     CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4984     CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4985     CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4986   }
4987   Constant *C = ConstantVector::get(CV);
4988   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4989   SDValue Mask1 = DAG.getLoad(SrcVT, DAG.getEntryNode(), CPIdx,
4990                                 PseudoSourceValue::getConstantPool(), 0,
4991                                 false, 16);
4992   SDValue SignBit = DAG.getNode(X86ISD::FAND, SrcVT, Op1, Mask1);
4993
4994   // Shift sign bit right or left if the two operands have different types.
4995   if (SrcVT.bitsGT(VT)) {
4996     // Op0 is MVT::f32, Op1 is MVT::f64.
4997     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2f64, SignBit);
4998     SignBit = DAG.getNode(X86ISD::FSRL, MVT::v2f64, SignBit,
4999                           DAG.getConstant(32, MVT::i32));
5000     SignBit = DAG.getNode(ISD::BIT_CONVERT, MVT::v4f32, SignBit);
5001     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::f32, SignBit,
5002                           DAG.getIntPtrConstant(0));
5003   }
5004
5005   // Clear first operand sign bit.
5006   CV.clear();
5007   if (VT == MVT::f64) {
5008     CV.push_back(ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63)))));
5009     CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
5010   } else {
5011     CV.push_back(ConstantFP::get(APFloat(APInt(32, ~(1U << 31)))));
5012     CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5013     CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5014     CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5015   }
5016   C = ConstantVector::get(CV);
5017   CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
5018   SDValue Mask2 = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
5019                                 PseudoSourceValue::getConstantPool(), 0,
5020                                 false, 16);
5021   SDValue Val = DAG.getNode(X86ISD::FAND, VT, Op0, Mask2);
5022
5023   // Or the value with the sign bit.
5024   return DAG.getNode(X86ISD::FOR, VT, Val, SignBit);
5025 }
5026
5027 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) {
5028   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
5029   SDValue Op0 = Op.getOperand(0);
5030   SDValue Op1 = Op.getOperand(1);
5031   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
5032   
5033   // Lower (X & (1 << N)) == 0 to BT.
5034   // Lower ((X >>u N) & 1) != 0 to BT.
5035   // Lower ((X >>s N) & 1) != 0 to BT.
5036   // FIXME: Is i386 or later or available only on some chips?
5037   if (Op0.getOpcode() == ISD::AND &&
5038       Op0.hasOneUse() &&
5039       Op1.getOpcode() == ISD::Constant &&
5040       Op0.getOperand(1).getOpcode() == ISD::Constant &&
5041       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
5042     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op0.getOperand(1));
5043     ConstantSDNode *CmpRHS = cast<ConstantSDNode>(Op1);
5044     SDValue AndLHS = Op0.getOperand(0);
5045     if (CmpRHS->getZExtValue() == 0 && AndRHS->getZExtValue() == 1 &&
5046         AndLHS.getOpcode() == ISD::SRL) {
5047       SDValue LHS = AndLHS.getOperand(0);
5048       SDValue RHS = AndLHS.getOperand(1);
5049
5050       // If LHS is i8, promote it to i16 with any_extend.  There is no i8 BT
5051       // instruction.  Since the shift amount is in-range-or-undefined, we know
5052       // that doing a bittest on the i16 value is ok.  We extend to i32 because
5053       // the encoding for the i16 version is larger than the i32 version.
5054       if (LHS.getValueType() == MVT::i8)
5055         LHS = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, LHS);
5056
5057       // If the operand types disagree, extend the shift amount to match.  Since
5058       // BT ignores high bits (like shifts) we can use anyextend.
5059       if (LHS.getValueType() != RHS.getValueType())
5060         RHS = DAG.getNode(ISD::ANY_EXTEND, LHS.getValueType(), RHS);
5061       
5062       SDValue BT = DAG.getNode(X86ISD::BT, MVT::i32, LHS, RHS);
5063       unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
5064       return DAG.getNode(X86ISD::SETCC, MVT::i8, 
5065                          DAG.getConstant(Cond, MVT::i8), BT);
5066     }
5067   }
5068
5069   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5070   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
5071     
5072   SDValue Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
5073   return DAG.getNode(X86ISD::SETCC, MVT::i8,
5074                      DAG.getConstant(X86CC, MVT::i8), Cond);
5075 }
5076
5077 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
5078   SDValue Cond;
5079   SDValue Op0 = Op.getOperand(0);
5080   SDValue Op1 = Op.getOperand(1);
5081   SDValue CC = Op.getOperand(2);
5082   MVT VT = Op.getValueType();
5083   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
5084   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5085
5086   if (isFP) {
5087     unsigned SSECC = 8;
5088     MVT VT0 = Op0.getValueType();
5089     assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
5090     unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
5091     bool Swap = false;
5092
5093     switch (SetCCOpcode) {
5094     default: break;
5095     case ISD::SETOEQ:
5096     case ISD::SETEQ:  SSECC = 0; break;
5097     case ISD::SETOGT: 
5098     case ISD::SETGT: Swap = true; // Fallthrough
5099     case ISD::SETLT:
5100     case ISD::SETOLT: SSECC = 1; break;
5101     case ISD::SETOGE:
5102     case ISD::SETGE: Swap = true; // Fallthrough
5103     case ISD::SETLE:
5104     case ISD::SETOLE: SSECC = 2; break;
5105     case ISD::SETUO:  SSECC = 3; break;
5106     case ISD::SETUNE:
5107     case ISD::SETNE:  SSECC = 4; break;
5108     case ISD::SETULE: Swap = true;
5109     case ISD::SETUGE: SSECC = 5; break;
5110     case ISD::SETULT: Swap = true;
5111     case ISD::SETUGT: SSECC = 6; break;
5112     case ISD::SETO:   SSECC = 7; break;
5113     }
5114     if (Swap)
5115       std::swap(Op0, Op1);
5116
5117     // In the two special cases we can't handle, emit two comparisons.
5118     if (SSECC == 8) {
5119       if (SetCCOpcode == ISD::SETUEQ) {
5120         SDValue UNORD, EQ;
5121         UNORD = DAG.getNode(Opc, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
5122         EQ = DAG.getNode(Opc, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
5123         return DAG.getNode(ISD::OR, VT, UNORD, EQ);
5124       }
5125       else if (SetCCOpcode == ISD::SETONE) {
5126         SDValue ORD, NEQ;
5127         ORD = DAG.getNode(Opc, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
5128         NEQ = DAG.getNode(Opc, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
5129         return DAG.getNode(ISD::AND, VT, ORD, NEQ);
5130       }
5131       assert(0 && "Illegal FP comparison");
5132     }
5133     // Handle all other FP comparisons here.
5134     return DAG.getNode(Opc, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
5135   }
5136   
5137   // We are handling one of the integer comparisons here.  Since SSE only has
5138   // GT and EQ comparisons for integer, swapping operands and multiple
5139   // operations may be required for some comparisons.
5140   unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
5141   bool Swap = false, Invert = false, FlipSigns = false;
5142   
5143   switch (VT.getSimpleVT()) {
5144   default: break;
5145   case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
5146   case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
5147   case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
5148   case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
5149   }
5150   
5151   switch (SetCCOpcode) {
5152   default: break;
5153   case ISD::SETNE:  Invert = true;
5154   case ISD::SETEQ:  Opc = EQOpc; break;
5155   case ISD::SETLT:  Swap = true;
5156   case ISD::SETGT:  Opc = GTOpc; break;
5157   case ISD::SETGE:  Swap = true;
5158   case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
5159   case ISD::SETULT: Swap = true;
5160   case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
5161   case ISD::SETUGE: Swap = true;
5162   case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
5163   }
5164   if (Swap)
5165     std::swap(Op0, Op1);
5166   
5167   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
5168   // bits of the inputs before performing those operations.
5169   if (FlipSigns) {
5170     MVT EltVT = VT.getVectorElementType();
5171     SDValue SignBit = DAG.getConstant(EltVT.getIntegerVTSignBit(), EltVT);
5172     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
5173     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, VT, &SignBits[0],
5174                                     SignBits.size());
5175     Op0 = DAG.getNode(ISD::XOR, VT, Op0, SignVec);
5176     Op1 = DAG.getNode(ISD::XOR, VT, Op1, SignVec);
5177   }
5178   
5179   SDValue Result = DAG.getNode(Opc, VT, Op0, Op1);
5180
5181   // If the logical-not of the result is required, perform that now.
5182   if (Invert) {
5183     MVT EltVT = VT.getVectorElementType();
5184     SDValue NegOne = DAG.getConstant(EltVT.getIntegerVTBitMask(), EltVT);
5185     std::vector<SDValue> NegOnes(VT.getVectorNumElements(), NegOne);
5186     SDValue NegOneV = DAG.getNode(ISD::BUILD_VECTOR, VT, &NegOnes[0],
5187                                     NegOnes.size());
5188     Result = DAG.getNode(ISD::XOR, VT, Result, NegOneV);
5189   }
5190   return Result;
5191 }
5192
5193 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
5194 static bool isX86LogicalCmp(unsigned Opc) {
5195   return Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI;
5196 }
5197
5198 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) {
5199   bool addTest = true;
5200   SDValue Cond  = Op.getOperand(0);
5201   SDValue CC;
5202
5203   if (Cond.getOpcode() == ISD::SETCC)
5204     Cond = LowerSETCC(Cond, DAG);
5205
5206   // If condition flag is set by a X86ISD::CMP, then use it as the condition
5207   // setting operand in place of the X86ISD::SETCC.
5208   if (Cond.getOpcode() == X86ISD::SETCC) {
5209     CC = Cond.getOperand(0);
5210
5211     SDValue Cmp = Cond.getOperand(1);
5212     unsigned Opc = Cmp.getOpcode();
5213     MVT VT = Op.getValueType();
5214     
5215     bool IllegalFPCMov = false;
5216     if (VT.isFloatingPoint() && !VT.isVector() &&
5217         !isScalarFPTypeInSSEReg(VT))  // FPStack?
5218       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
5219     
5220     if (isX86LogicalCmp(Opc) && !IllegalFPCMov) {
5221       Cond = Cmp;
5222       addTest = false;
5223     }
5224   }
5225
5226   if (addTest) {
5227     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5228     Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
5229   }
5230
5231   const MVT *VTs = DAG.getNodeValueTypes(Op.getValueType(),
5232                                                     MVT::Flag);
5233   SmallVector<SDValue, 4> Ops;
5234   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
5235   // condition is true.
5236   Ops.push_back(Op.getOperand(2));
5237   Ops.push_back(Op.getOperand(1));
5238   Ops.push_back(CC);
5239   Ops.push_back(Cond);
5240   return DAG.getNode(X86ISD::CMOV, VTs, 2, &Ops[0], Ops.size());
5241 }
5242
5243 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
5244 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
5245 // from the AND / OR.
5246 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
5247   Opc = Op.getOpcode();
5248   if (Opc != ISD::OR && Opc != ISD::AND)
5249     return false;
5250   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
5251           Op.getOperand(0).hasOneUse() &&
5252           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
5253           Op.getOperand(1).hasOneUse());
5254 }
5255
5256 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) {
5257   bool addTest = true;
5258   SDValue Chain = Op.getOperand(0);
5259   SDValue Cond  = Op.getOperand(1);
5260   SDValue Dest  = Op.getOperand(2);
5261   SDValue CC;
5262
5263   if (Cond.getOpcode() == ISD::SETCC)
5264     Cond = LowerSETCC(Cond, DAG);
5265 #if 0
5266   // FIXME: LowerXALUO doesn't handle these!!
5267   else if (Cond.getOpcode() == X86ISD::ADD  ||
5268            Cond.getOpcode() == X86ISD::SUB  ||
5269            Cond.getOpcode() == X86ISD::SMUL ||
5270            Cond.getOpcode() == X86ISD::UMUL)
5271     Cond = LowerXALUO(Cond, DAG);
5272 #endif
5273   
5274   // If condition flag is set by a X86ISD::CMP, then use it as the condition
5275   // setting operand in place of the X86ISD::SETCC.
5276   if (Cond.getOpcode() == X86ISD::SETCC) {
5277     CC = Cond.getOperand(0);
5278
5279     SDValue Cmp = Cond.getOperand(1);
5280     unsigned Opc = Cmp.getOpcode();
5281     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
5282     if (isX86LogicalCmp(Opc) || Opc == X86ISD::BT) {
5283       Cond = Cmp;
5284       addTest = false;
5285     } else {
5286       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
5287       default: break;
5288       case X86::COND_O:
5289       case X86::COND_B:
5290         // These can only come from an arithmetic instruction with overflow,
5291         // e.g. SADDO, UADDO.
5292         Cond = Cond.getNode()->getOperand(1);
5293         addTest = false;
5294         break;
5295       }
5296     }
5297   } else {
5298     unsigned CondOpc;
5299     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
5300       SDValue Cmp = Cond.getOperand(0).getOperand(1);
5301       unsigned Opc = Cmp.getOpcode();
5302       if (CondOpc == ISD::OR) {
5303         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
5304         // two branches instead of an explicit OR instruction with a
5305         // separate test.
5306         if (Cmp == Cond.getOperand(1).getOperand(1) &&
5307             isX86LogicalCmp(Opc)) {
5308           CC = Cond.getOperand(0).getOperand(0);
5309           Chain = DAG.getNode(X86ISD::BRCOND, Op.getValueType(),
5310                               Chain, Dest, CC, Cmp);
5311           CC = Cond.getOperand(1).getOperand(0);
5312           Cond = Cmp;
5313           addTest = false;
5314         }
5315       } else { // ISD::AND
5316         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
5317         // two branches instead of an explicit AND instruction with a
5318         // separate test. However, we only do this if this block doesn't
5319         // have a fall-through edge, because this requires an explicit
5320         // jmp when the condition is false.
5321         if (Cmp == Cond.getOperand(1).getOperand(1) &&
5322             isX86LogicalCmp(Opc) &&
5323             Op.getNode()->hasOneUse()) {
5324           X86::CondCode CCode =
5325             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
5326           CCode = X86::GetOppositeBranchCondition(CCode);
5327           CC = DAG.getConstant(CCode, MVT::i8);
5328           SDValue User = SDValue(*Op.getNode()->use_begin(), 0);
5329           // Look for an unconditional branch following this conditional branch.
5330           // We need this because we need to reverse the successors in order
5331           // to implement FCMP_OEQ.
5332           if (User.getOpcode() == ISD::BR) {
5333             SDValue FalseBB = User.getOperand(1);
5334             SDValue NewBR =
5335               DAG.UpdateNodeOperands(User, User.getOperand(0), Dest);
5336             assert(NewBR == User);
5337             Dest = FalseBB;
5338
5339             Chain = DAG.getNode(X86ISD::BRCOND, Op.getValueType(),
5340                                 Chain, Dest, CC, Cmp);
5341             X86::CondCode CCode =
5342               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
5343             CCode = X86::GetOppositeBranchCondition(CCode);
5344             CC = DAG.getConstant(CCode, MVT::i8);
5345             Cond = Cmp;
5346             addTest = false;
5347           }
5348         }
5349       }
5350     }
5351   }
5352
5353   if (addTest) {
5354     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5355     Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
5356   }
5357   return DAG.getNode(X86ISD::BRCOND, Op.getValueType(),
5358                      Chain, Dest, CC, Cond);
5359 }
5360
5361
5362 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
5363 // Calls to _alloca is needed to probe the stack when allocating more than 4k
5364 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
5365 // that the guard pages used by the OS virtual memory manager are allocated in
5366 // correct sequence.
5367 SDValue
5368 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
5369                                            SelectionDAG &DAG) {
5370   assert(Subtarget->isTargetCygMing() &&
5371          "This should be used only on Cygwin/Mingw targets");
5372
5373   // Get the inputs.
5374   SDValue Chain = Op.getOperand(0);
5375   SDValue Size  = Op.getOperand(1);
5376   // FIXME: Ensure alignment here
5377
5378   SDValue Flag;
5379
5380   MVT IntPtr = getPointerTy();
5381   MVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
5382
5383   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true));
5384
5385   Chain = DAG.getCopyToReg(Chain, X86::EAX, Size, Flag);
5386   Flag = Chain.getValue(1);
5387
5388   SDVTList  NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
5389   SDValue Ops[] = { Chain,
5390                       DAG.getTargetExternalSymbol("_alloca", IntPtr),
5391                       DAG.getRegister(X86::EAX, IntPtr),
5392                       DAG.getRegister(X86StackPtr, SPTy),
5393                       Flag };
5394   Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops, 5);
5395   Flag = Chain.getValue(1);
5396
5397   Chain = DAG.getCALLSEQ_END(Chain,
5398                              DAG.getIntPtrConstant(0, true),
5399                              DAG.getIntPtrConstant(0, true),
5400                              Flag);
5401
5402   Chain = DAG.getCopyFromReg(Chain, X86StackPtr, SPTy).getValue(1);
5403
5404   SDValue Ops1[2] = { Chain.getValue(0), Chain };
5405   return DAG.getMergeValues(Ops1, 2);
5406 }
5407
5408 SDValue
5409 X86TargetLowering::EmitTargetCodeForMemset(SelectionDAG &DAG,
5410                                            SDValue Chain,
5411                                            SDValue Dst, SDValue Src,
5412                                            SDValue Size, unsigned Align,
5413                                            const Value *DstSV,
5414                                            uint64_t DstSVOff) {
5415   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5416
5417   // If not DWORD aligned or size is more than the threshold, call the library.
5418   // The libc version is likely to be faster for these cases. It can use the
5419   // address value and run time information about the CPU.
5420   if ((Align & 3) != 0 ||
5421       !ConstantSize ||
5422       ConstantSize->getZExtValue() >
5423         getSubtarget()->getMaxInlineSizeThreshold()) {
5424     SDValue InFlag(0, 0);
5425
5426     // Check to see if there is a specialized entry-point for memory zeroing.
5427     ConstantSDNode *V = dyn_cast<ConstantSDNode>(Src);
5428
5429     if (const char *bzeroEntry =  V &&
5430         V->isNullValue() ? Subtarget->getBZeroEntry() : 0) {
5431       MVT IntPtr = getPointerTy();
5432       const Type *IntPtrTy = TD->getIntPtrType();
5433       TargetLowering::ArgListTy Args; 
5434       TargetLowering::ArgListEntry Entry;
5435       Entry.Node = Dst;
5436       Entry.Ty = IntPtrTy;
5437       Args.push_back(Entry);
5438       Entry.Node = Size;
5439       Args.push_back(Entry);
5440       std::pair<SDValue,SDValue> CallResult =
5441         LowerCallTo(Chain, Type::VoidTy, false, false, false, false, 
5442                     CallingConv::C, false, 
5443                     DAG.getExternalSymbol(bzeroEntry, IntPtr), Args, DAG);
5444       return CallResult.second;
5445     }
5446
5447     // Otherwise have the target-independent code call memset.
5448     return SDValue();
5449   }
5450
5451   uint64_t SizeVal = ConstantSize->getZExtValue();
5452   SDValue InFlag(0, 0);
5453   MVT AVT;
5454   SDValue Count;
5455   ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Src);
5456   unsigned BytesLeft = 0;
5457   bool TwoRepStos = false;
5458   if (ValC) {
5459     unsigned ValReg;
5460     uint64_t Val = ValC->getZExtValue() & 255;
5461
5462     // If the value is a constant, then we can potentially use larger sets.
5463     switch (Align & 3) {
5464     case 2:   // WORD aligned
5465       AVT = MVT::i16;
5466       ValReg = X86::AX;
5467       Val = (Val << 8) | Val;
5468       break;
5469     case 0:  // DWORD aligned
5470       AVT = MVT::i32;
5471       ValReg = X86::EAX;
5472       Val = (Val << 8)  | Val;
5473       Val = (Val << 16) | Val;
5474       if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) {  // QWORD aligned
5475         AVT = MVT::i64;
5476         ValReg = X86::RAX;
5477         Val = (Val << 32) | Val;
5478       }
5479       break;
5480     default:  // Byte aligned
5481       AVT = MVT::i8;
5482       ValReg = X86::AL;
5483       Count = DAG.getIntPtrConstant(SizeVal);
5484       break;
5485     }
5486
5487     if (AVT.bitsGT(MVT::i8)) {
5488       unsigned UBytes = AVT.getSizeInBits() / 8;
5489       Count = DAG.getIntPtrConstant(SizeVal / UBytes);
5490       BytesLeft = SizeVal % UBytes;
5491     }
5492
5493     Chain  = DAG.getCopyToReg(Chain, ValReg, DAG.getConstant(Val, AVT),
5494                               InFlag);
5495     InFlag = Chain.getValue(1);
5496   } else {
5497     AVT = MVT::i8;
5498     Count  = DAG.getIntPtrConstant(SizeVal);
5499     Chain  = DAG.getCopyToReg(Chain, X86::AL, Src, InFlag);
5500     InFlag = Chain.getValue(1);
5501   }
5502
5503   Chain  = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
5504                             Count, InFlag);
5505   InFlag = Chain.getValue(1);
5506   Chain  = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
5507                             Dst, InFlag);
5508   InFlag = Chain.getValue(1);
5509
5510   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5511   SmallVector<SDValue, 8> Ops;
5512   Ops.push_back(Chain);
5513   Ops.push_back(DAG.getValueType(AVT));
5514   Ops.push_back(InFlag);
5515   Chain  = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
5516
5517   if (TwoRepStos) {
5518     InFlag = Chain.getValue(1);
5519     Count  = Size;
5520     MVT CVT = Count.getValueType();
5521     SDValue Left = DAG.getNode(ISD::AND, CVT, Count,
5522                                DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
5523     Chain  = DAG.getCopyToReg(Chain, (CVT == MVT::i64) ? X86::RCX : X86::ECX,
5524                               Left, InFlag);
5525     InFlag = Chain.getValue(1);
5526     Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5527     Ops.clear();
5528     Ops.push_back(Chain);
5529     Ops.push_back(DAG.getValueType(MVT::i8));
5530     Ops.push_back(InFlag);
5531     Chain  = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
5532   } else if (BytesLeft) {
5533     // Handle the last 1 - 7 bytes.
5534     unsigned Offset = SizeVal - BytesLeft;
5535     MVT AddrVT = Dst.getValueType();
5536     MVT SizeVT = Size.getValueType();
5537
5538     Chain = DAG.getMemset(Chain,
5539                           DAG.getNode(ISD::ADD, AddrVT, Dst,
5540                                       DAG.getConstant(Offset, AddrVT)),
5541                           Src,
5542                           DAG.getConstant(BytesLeft, SizeVT),
5543                           Align, DstSV, DstSVOff + Offset);
5544   }
5545
5546   // TODO: Use a Tokenfactor, as in memcpy, instead of a single chain.
5547   return Chain;
5548 }
5549
5550 SDValue
5551 X86TargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG,
5552                                       SDValue Chain, SDValue Dst, SDValue Src,
5553                                       SDValue Size, unsigned Align,
5554                                       bool AlwaysInline,
5555                                       const Value *DstSV, uint64_t DstSVOff,
5556                                       const Value *SrcSV, uint64_t SrcSVOff) {  
5557   // This requires the copy size to be a constant, preferrably
5558   // within a subtarget-specific limit.
5559   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5560   if (!ConstantSize)
5561     return SDValue();
5562   uint64_t SizeVal = ConstantSize->getZExtValue();
5563   if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
5564     return SDValue();
5565
5566   /// If not DWORD aligned, call the library.
5567   if ((Align & 3) != 0)
5568     return SDValue();
5569
5570   // DWORD aligned
5571   MVT AVT = MVT::i32;
5572   if (Subtarget->is64Bit() && ((Align & 0x7) == 0))  // QWORD aligned
5573     AVT = MVT::i64;
5574
5575   unsigned UBytes = AVT.getSizeInBits() / 8;
5576   unsigned CountVal = SizeVal / UBytes;
5577   SDValue Count = DAG.getIntPtrConstant(CountVal);
5578   unsigned BytesLeft = SizeVal % UBytes;
5579
5580   SDValue InFlag(0, 0);
5581   Chain  = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
5582                             Count, InFlag);
5583   InFlag = Chain.getValue(1);
5584   Chain  = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
5585                             Dst, InFlag);
5586   InFlag = Chain.getValue(1);
5587   Chain  = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RSI : X86::ESI,
5588                             Src, InFlag);
5589   InFlag = Chain.getValue(1);
5590
5591   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5592   SmallVector<SDValue, 8> Ops;
5593   Ops.push_back(Chain);
5594   Ops.push_back(DAG.getValueType(AVT));
5595   Ops.push_back(InFlag);
5596   SDValue RepMovs = DAG.getNode(X86ISD::REP_MOVS, Tys, &Ops[0], Ops.size());
5597
5598   SmallVector<SDValue, 4> Results;
5599   Results.push_back(RepMovs);
5600   if (BytesLeft) {
5601     // Handle the last 1 - 7 bytes.
5602     unsigned Offset = SizeVal - BytesLeft;
5603     MVT DstVT = Dst.getValueType();
5604     MVT SrcVT = Src.getValueType();
5605     MVT SizeVT = Size.getValueType();
5606     Results.push_back(DAG.getMemcpy(Chain,
5607                                     DAG.getNode(ISD::ADD, DstVT, Dst,
5608                                                 DAG.getConstant(Offset, DstVT)),
5609                                     DAG.getNode(ISD::ADD, SrcVT, Src,
5610                                                 DAG.getConstant(Offset, SrcVT)),
5611                                     DAG.getConstant(BytesLeft, SizeVT),
5612                                     Align, AlwaysInline,
5613                                     DstSV, DstSVOff + Offset,
5614                                     SrcSV, SrcSVOff + Offset));
5615   }
5616
5617   return DAG.getNode(ISD::TokenFactor, MVT::Other, &Results[0], Results.size());
5618 }
5619
5620 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) {
5621   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5622
5623   if (!Subtarget->is64Bit()) {
5624     // vastart just stores the address of the VarArgsFrameIndex slot into the
5625     // memory location argument.
5626     SDValue FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
5627     return DAG.getStore(Op.getOperand(0), FR,Op.getOperand(1), SV, 0);
5628   }
5629
5630   // __va_list_tag:
5631   //   gp_offset         (0 - 6 * 8)
5632   //   fp_offset         (48 - 48 + 8 * 16)
5633   //   overflow_arg_area (point to parameters coming in memory).
5634   //   reg_save_area
5635   SmallVector<SDValue, 8> MemOps;
5636   SDValue FIN = Op.getOperand(1);
5637   // Store gp_offset
5638   SDValue Store = DAG.getStore(Op.getOperand(0),
5639                                  DAG.getConstant(VarArgsGPOffset, MVT::i32),
5640                                  FIN, SV, 0);
5641   MemOps.push_back(Store);
5642
5643   // Store fp_offset
5644   FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(4));
5645   Store = DAG.getStore(Op.getOperand(0),
5646                        DAG.getConstant(VarArgsFPOffset, MVT::i32),
5647                        FIN, SV, 0);
5648   MemOps.push_back(Store);
5649
5650   // Store ptr to overflow_arg_area
5651   FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(4));
5652   SDValue OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
5653   Store = DAG.getStore(Op.getOperand(0), OVFIN, FIN, SV, 0);
5654   MemOps.push_back(Store);
5655
5656   // Store ptr to reg_save_area.
5657   FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(8));
5658   SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
5659   Store = DAG.getStore(Op.getOperand(0), RSFIN, FIN, SV, 0);
5660   MemOps.push_back(Store);
5661   return DAG.getNode(ISD::TokenFactor, MVT::Other, &MemOps[0], MemOps.size());
5662 }
5663
5664 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) {
5665   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
5666   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
5667   SDValue Chain = Op.getOperand(0);
5668   SDValue SrcPtr = Op.getOperand(1);
5669   SDValue SrcSV = Op.getOperand(2);
5670
5671   assert(0 && "VAArgInst is not yet implemented for x86-64!");
5672   abort();
5673   return SDValue();
5674 }
5675
5676 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) {
5677   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
5678   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
5679   SDValue Chain = Op.getOperand(0);
5680   SDValue DstPtr = Op.getOperand(1);
5681   SDValue SrcPtr = Op.getOperand(2);
5682   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
5683   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5684
5685   return DAG.getMemcpy(Chain, DstPtr, SrcPtr,
5686                        DAG.getIntPtrConstant(24), 8, false,
5687                        DstSV, 0, SrcSV, 0);
5688 }
5689
5690 SDValue
5691 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
5692   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5693   switch (IntNo) {
5694   default: return SDValue();    // Don't custom lower most intrinsics.
5695   // Comparison intrinsics.
5696   case Intrinsic::x86_sse_comieq_ss:
5697   case Intrinsic::x86_sse_comilt_ss:
5698   case Intrinsic::x86_sse_comile_ss:
5699   case Intrinsic::x86_sse_comigt_ss:
5700   case Intrinsic::x86_sse_comige_ss:
5701   case Intrinsic::x86_sse_comineq_ss:
5702   case Intrinsic::x86_sse_ucomieq_ss:
5703   case Intrinsic::x86_sse_ucomilt_ss:
5704   case Intrinsic::x86_sse_ucomile_ss:
5705   case Intrinsic::x86_sse_ucomigt_ss:
5706   case Intrinsic::x86_sse_ucomige_ss:
5707   case Intrinsic::x86_sse_ucomineq_ss:
5708   case Intrinsic::x86_sse2_comieq_sd:
5709   case Intrinsic::x86_sse2_comilt_sd:
5710   case Intrinsic::x86_sse2_comile_sd:
5711   case Intrinsic::x86_sse2_comigt_sd:
5712   case Intrinsic::x86_sse2_comige_sd:
5713   case Intrinsic::x86_sse2_comineq_sd:
5714   case Intrinsic::x86_sse2_ucomieq_sd:
5715   case Intrinsic::x86_sse2_ucomilt_sd:
5716   case Intrinsic::x86_sse2_ucomile_sd:
5717   case Intrinsic::x86_sse2_ucomigt_sd:
5718   case Intrinsic::x86_sse2_ucomige_sd:
5719   case Intrinsic::x86_sse2_ucomineq_sd: {
5720     unsigned Opc = 0;
5721     ISD::CondCode CC = ISD::SETCC_INVALID;
5722     switch (IntNo) {
5723     default: break;
5724     case Intrinsic::x86_sse_comieq_ss:
5725     case Intrinsic::x86_sse2_comieq_sd:
5726       Opc = X86ISD::COMI;
5727       CC = ISD::SETEQ;
5728       break;
5729     case Intrinsic::x86_sse_comilt_ss:
5730     case Intrinsic::x86_sse2_comilt_sd:
5731       Opc = X86ISD::COMI;
5732       CC = ISD::SETLT;
5733       break;
5734     case Intrinsic::x86_sse_comile_ss:
5735     case Intrinsic::x86_sse2_comile_sd:
5736       Opc = X86ISD::COMI;
5737       CC = ISD::SETLE;
5738       break;
5739     case Intrinsic::x86_sse_comigt_ss:
5740     case Intrinsic::x86_sse2_comigt_sd:
5741       Opc = X86ISD::COMI;
5742       CC = ISD::SETGT;
5743       break;
5744     case Intrinsic::x86_sse_comige_ss:
5745     case Intrinsic::x86_sse2_comige_sd:
5746       Opc = X86ISD::COMI;
5747       CC = ISD::SETGE;
5748       break;
5749     case Intrinsic::x86_sse_comineq_ss:
5750     case Intrinsic::x86_sse2_comineq_sd:
5751       Opc = X86ISD::COMI;
5752       CC = ISD::SETNE;
5753       break;
5754     case Intrinsic::x86_sse_ucomieq_ss:
5755     case Intrinsic::x86_sse2_ucomieq_sd:
5756       Opc = X86ISD::UCOMI;
5757       CC = ISD::SETEQ;
5758       break;
5759     case Intrinsic::x86_sse_ucomilt_ss:
5760     case Intrinsic::x86_sse2_ucomilt_sd:
5761       Opc = X86ISD::UCOMI;
5762       CC = ISD::SETLT;
5763       break;
5764     case Intrinsic::x86_sse_ucomile_ss:
5765     case Intrinsic::x86_sse2_ucomile_sd:
5766       Opc = X86ISD::UCOMI;
5767       CC = ISD::SETLE;
5768       break;
5769     case Intrinsic::x86_sse_ucomigt_ss:
5770     case Intrinsic::x86_sse2_ucomigt_sd:
5771       Opc = X86ISD::UCOMI;
5772       CC = ISD::SETGT;
5773       break;
5774     case Intrinsic::x86_sse_ucomige_ss:
5775     case Intrinsic::x86_sse2_ucomige_sd:
5776       Opc = X86ISD::UCOMI;
5777       CC = ISD::SETGE;
5778       break;
5779     case Intrinsic::x86_sse_ucomineq_ss:
5780     case Intrinsic::x86_sse2_ucomineq_sd:
5781       Opc = X86ISD::UCOMI;
5782       CC = ISD::SETNE;
5783       break;
5784     }
5785
5786     SDValue LHS = Op.getOperand(1);
5787     SDValue RHS = Op.getOperand(2);
5788     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
5789     SDValue Cond = DAG.getNode(Opc, MVT::i32, LHS, RHS);
5790     SDValue SetCC = DAG.getNode(X86ISD::SETCC, MVT::i8,
5791                                 DAG.getConstant(X86CC, MVT::i8), Cond);
5792     return DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, SetCC);
5793   }
5794
5795   // Fix vector shift instructions where the last operand is a non-immediate
5796   // i32 value.
5797   case Intrinsic::x86_sse2_pslli_w:
5798   case Intrinsic::x86_sse2_pslli_d:
5799   case Intrinsic::x86_sse2_pslli_q:
5800   case Intrinsic::x86_sse2_psrli_w:
5801   case Intrinsic::x86_sse2_psrli_d:
5802   case Intrinsic::x86_sse2_psrli_q:
5803   case Intrinsic::x86_sse2_psrai_w:
5804   case Intrinsic::x86_sse2_psrai_d:
5805   case Intrinsic::x86_mmx_pslli_w:
5806   case Intrinsic::x86_mmx_pslli_d:
5807   case Intrinsic::x86_mmx_pslli_q:
5808   case Intrinsic::x86_mmx_psrli_w:
5809   case Intrinsic::x86_mmx_psrli_d:
5810   case Intrinsic::x86_mmx_psrli_q:
5811   case Intrinsic::x86_mmx_psrai_w:
5812   case Intrinsic::x86_mmx_psrai_d: {
5813     SDValue ShAmt = Op.getOperand(2);
5814     if (isa<ConstantSDNode>(ShAmt))
5815       return SDValue();
5816
5817     unsigned NewIntNo = 0;
5818     MVT ShAmtVT = MVT::v4i32;
5819     switch (IntNo) {
5820     case Intrinsic::x86_sse2_pslli_w:
5821       NewIntNo = Intrinsic::x86_sse2_psll_w;
5822       break;
5823     case Intrinsic::x86_sse2_pslli_d:
5824       NewIntNo = Intrinsic::x86_sse2_psll_d;
5825       break;
5826     case Intrinsic::x86_sse2_pslli_q:
5827       NewIntNo = Intrinsic::x86_sse2_psll_q;
5828       break;
5829     case Intrinsic::x86_sse2_psrli_w:
5830       NewIntNo = Intrinsic::x86_sse2_psrl_w;
5831       break;
5832     case Intrinsic::x86_sse2_psrli_d:
5833       NewIntNo = Intrinsic::x86_sse2_psrl_d;
5834       break;
5835     case Intrinsic::x86_sse2_psrli_q:
5836       NewIntNo = Intrinsic::x86_sse2_psrl_q;
5837       break;
5838     case Intrinsic::x86_sse2_psrai_w:
5839       NewIntNo = Intrinsic::x86_sse2_psra_w;
5840       break;
5841     case Intrinsic::x86_sse2_psrai_d:
5842       NewIntNo = Intrinsic::x86_sse2_psra_d;
5843       break;
5844     default: {
5845       ShAmtVT = MVT::v2i32;
5846       switch (IntNo) {
5847       case Intrinsic::x86_mmx_pslli_w:
5848         NewIntNo = Intrinsic::x86_mmx_psll_w;
5849         break;
5850       case Intrinsic::x86_mmx_pslli_d:
5851         NewIntNo = Intrinsic::x86_mmx_psll_d;
5852         break;
5853       case Intrinsic::x86_mmx_pslli_q:
5854         NewIntNo = Intrinsic::x86_mmx_psll_q;
5855         break;
5856       case Intrinsic::x86_mmx_psrli_w:
5857         NewIntNo = Intrinsic::x86_mmx_psrl_w;
5858         break;
5859       case Intrinsic::x86_mmx_psrli_d:
5860         NewIntNo = Intrinsic::x86_mmx_psrl_d;
5861         break;
5862       case Intrinsic::x86_mmx_psrli_q:
5863         NewIntNo = Intrinsic::x86_mmx_psrl_q;
5864         break;
5865       case Intrinsic::x86_mmx_psrai_w:
5866         NewIntNo = Intrinsic::x86_mmx_psra_w;
5867         break;
5868       case Intrinsic::x86_mmx_psrai_d:
5869         NewIntNo = Intrinsic::x86_mmx_psra_d;
5870         break;
5871       default: abort();  // Can't reach here.
5872       }
5873       break;
5874     }
5875     }
5876     MVT VT = Op.getValueType();
5877     ShAmt = DAG.getNode(ISD::BIT_CONVERT, VT,
5878                         DAG.getNode(ISD::SCALAR_TO_VECTOR, ShAmtVT, ShAmt));
5879     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
5880                        DAG.getConstant(NewIntNo, MVT::i32),
5881                        Op.getOperand(1), ShAmt);
5882   }
5883   }
5884 }
5885
5886 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) {
5887   // Depths > 0 not supported yet!
5888   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
5889     return SDValue();
5890   
5891   // Just load the return address
5892   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
5893   return DAG.getLoad(getPointerTy(), DAG.getEntryNode(), RetAddrFI, NULL, 0);
5894 }
5895
5896 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
5897   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5898   MFI->setFrameAddressIsTaken(true);
5899   MVT VT = Op.getValueType();
5900   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5901   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
5902   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), FrameReg, VT);
5903   while (Depth--)
5904     FrameAddr = DAG.getLoad(VT, DAG.getEntryNode(), FrameAddr, NULL, 0);
5905   return FrameAddr;
5906 }
5907
5908 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
5909                                                      SelectionDAG &DAG) {
5910   return DAG.getIntPtrConstant(2*TD->getPointerSize());
5911 }
5912
5913 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
5914 {
5915   MachineFunction &MF = DAG.getMachineFunction();
5916   SDValue Chain     = Op.getOperand(0);
5917   SDValue Offset    = Op.getOperand(1);
5918   SDValue Handler   = Op.getOperand(2);
5919
5920   SDValue Frame = DAG.getRegister(Subtarget->is64Bit() ? X86::RBP : X86::EBP,
5921                                   getPointerTy());
5922   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
5923
5924   SDValue StoreAddr = DAG.getNode(ISD::SUB, getPointerTy(), Frame,
5925                                   DAG.getIntPtrConstant(-TD->getPointerSize()));
5926   StoreAddr = DAG.getNode(ISD::ADD, getPointerTy(), StoreAddr, Offset);
5927   Chain = DAG.getStore(Chain, Handler, StoreAddr, NULL, 0);
5928   Chain = DAG.getCopyToReg(Chain, StoreAddrReg, StoreAddr);
5929   MF.getRegInfo().addLiveOut(StoreAddrReg);
5930
5931   return DAG.getNode(X86ISD::EH_RETURN,
5932                      MVT::Other,
5933                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
5934 }
5935
5936 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
5937                                              SelectionDAG &DAG) {
5938   SDValue Root = Op.getOperand(0);
5939   SDValue Trmp = Op.getOperand(1); // trampoline
5940   SDValue FPtr = Op.getOperand(2); // nested function
5941   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
5942
5943   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5944
5945   const X86InstrInfo *TII =
5946     ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
5947
5948   if (Subtarget->is64Bit()) {
5949     SDValue OutChains[6];
5950
5951     // Large code-model.
5952
5953     const unsigned char JMP64r  = TII->getBaseOpcodeFor(X86::JMP64r);
5954     const unsigned char MOV64ri = TII->getBaseOpcodeFor(X86::MOV64ri);
5955
5956     const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
5957     const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
5958
5959     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
5960
5961     // Load the pointer to the nested function into R11.
5962     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
5963     SDValue Addr = Trmp;
5964     OutChains[0] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5965                                 TrmpAddr, 0);
5966
5967     Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(2, MVT::i64));
5968     OutChains[1] = DAG.getStore(Root, FPtr, Addr, TrmpAddr, 2, false, 2);
5969
5970     // Load the 'nest' parameter value into R10.
5971     // R10 is specified in X86CallingConv.td
5972     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
5973     Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(10, MVT::i64));
5974     OutChains[2] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5975                                 TrmpAddr, 10);
5976
5977     Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(12, MVT::i64));
5978     OutChains[3] = DAG.getStore(Root, Nest, Addr, TrmpAddr, 12, false, 2);
5979
5980     // Jump to the nested function.
5981     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
5982     Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(20, MVT::i64));
5983     OutChains[4] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5984                                 TrmpAddr, 20);
5985
5986     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
5987     Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(22, MVT::i64));
5988     OutChains[5] = DAG.getStore(Root, DAG.getConstant(ModRM, MVT::i8), Addr,
5989                                 TrmpAddr, 22);
5990
5991     SDValue Ops[] =
5992       { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 6) };
5993     return DAG.getMergeValues(Ops, 2);
5994   } else {
5995     const Function *Func =
5996       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
5997     unsigned CC = Func->getCallingConv();
5998     unsigned NestReg;
5999
6000     switch (CC) {
6001     default:
6002       assert(0 && "Unsupported calling convention");
6003     case CallingConv::C:
6004     case CallingConv::X86_StdCall: {
6005       // Pass 'nest' parameter in ECX.
6006       // Must be kept in sync with X86CallingConv.td
6007       NestReg = X86::ECX;
6008
6009       // Check that ECX wasn't needed by an 'inreg' parameter.
6010       const FunctionType *FTy = Func->getFunctionType();
6011       const AttrListPtr &Attrs = Func->getAttributes();
6012
6013       if (!Attrs.isEmpty() && !Func->isVarArg()) {
6014         unsigned InRegCount = 0;
6015         unsigned Idx = 1;
6016
6017         for (FunctionType::param_iterator I = FTy->param_begin(),
6018              E = FTy->param_end(); I != E; ++I, ++Idx)
6019           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
6020             // FIXME: should only count parameters that are lowered to integers.
6021             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
6022
6023         if (InRegCount > 2) {
6024           cerr << "Nest register in use - reduce number of inreg parameters!\n";
6025           abort();
6026         }
6027       }
6028       break;
6029     }
6030     case CallingConv::X86_FastCall:
6031     case CallingConv::Fast:
6032       // Pass 'nest' parameter in EAX.
6033       // Must be kept in sync with X86CallingConv.td
6034       NestReg = X86::EAX;
6035       break;
6036     }
6037
6038     SDValue OutChains[4];
6039     SDValue Addr, Disp;
6040
6041     Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(10, MVT::i32));
6042     Disp = DAG.getNode(ISD::SUB, MVT::i32, FPtr, Addr);
6043
6044     const unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
6045     const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
6046     OutChains[0] = DAG.getStore(Root, DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
6047                                 Trmp, TrmpAddr, 0);
6048
6049     Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(1, MVT::i32));
6050     OutChains[1] = DAG.getStore(Root, Nest, Addr, TrmpAddr, 1, false, 1);
6051
6052     const unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
6053     Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(5, MVT::i32));
6054     OutChains[2] = DAG.getStore(Root, DAG.getConstant(JMP, MVT::i8), Addr,
6055                                 TrmpAddr, 5, false, 1);
6056
6057     Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(6, MVT::i32));
6058     OutChains[3] = DAG.getStore(Root, Disp, Addr, TrmpAddr, 6, false, 1);
6059
6060     SDValue Ops[] =
6061       { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 4) };
6062     return DAG.getMergeValues(Ops, 2);
6063   }
6064 }
6065
6066 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op, SelectionDAG &DAG) {
6067   /*
6068    The rounding mode is in bits 11:10 of FPSR, and has the following
6069    settings:
6070      00 Round to nearest
6071      01 Round to -inf
6072      10 Round to +inf
6073      11 Round to 0
6074
6075   FLT_ROUNDS, on the other hand, expects the following:
6076     -1 Undefined
6077      0 Round to 0
6078      1 Round to nearest
6079      2 Round to +inf
6080      3 Round to -inf
6081
6082   To perform the conversion, we do:
6083     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
6084   */
6085
6086   MachineFunction &MF = DAG.getMachineFunction();
6087   const TargetMachine &TM = MF.getTarget();
6088   const TargetFrameInfo &TFI = *TM.getFrameInfo();
6089   unsigned StackAlignment = TFI.getStackAlignment();
6090   MVT VT = Op.getValueType();
6091
6092   // Save FP Control Word to stack slot
6093   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment);
6094   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6095
6096   SDValue Chain = DAG.getNode(X86ISD::FNSTCW16m, MVT::Other,
6097                               DAG.getEntryNode(), StackSlot);
6098
6099   // Load FP Control Word from stack slot
6100   SDValue CWD = DAG.getLoad(MVT::i16, Chain, StackSlot, NULL, 0);
6101
6102   // Transform as necessary
6103   SDValue CWD1 =
6104     DAG.getNode(ISD::SRL, MVT::i16,
6105                 DAG.getNode(ISD::AND, MVT::i16,
6106                             CWD, DAG.getConstant(0x800, MVT::i16)),
6107                 DAG.getConstant(11, MVT::i8));
6108   SDValue CWD2 =
6109     DAG.getNode(ISD::SRL, MVT::i16,
6110                 DAG.getNode(ISD::AND, MVT::i16,
6111                             CWD, DAG.getConstant(0x400, MVT::i16)),
6112                 DAG.getConstant(9, MVT::i8));
6113
6114   SDValue RetVal =
6115     DAG.getNode(ISD::AND, MVT::i16,
6116                 DAG.getNode(ISD::ADD, MVT::i16,
6117                             DAG.getNode(ISD::OR, MVT::i16, CWD1, CWD2),
6118                             DAG.getConstant(1, MVT::i16)),
6119                 DAG.getConstant(3, MVT::i16));
6120
6121
6122   return DAG.getNode((VT.getSizeInBits() < 16 ?
6123                       ISD::TRUNCATE : ISD::ZERO_EXTEND), VT, RetVal);
6124 }
6125
6126 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
6127   MVT VT = Op.getValueType();
6128   MVT OpVT = VT;
6129   unsigned NumBits = VT.getSizeInBits();
6130
6131   Op = Op.getOperand(0);
6132   if (VT == MVT::i8) {
6133     // Zero extend to i32 since there is not an i8 bsr.
6134     OpVT = MVT::i32;
6135     Op = DAG.getNode(ISD::ZERO_EXTEND, OpVT, Op);
6136   }
6137
6138   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
6139   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
6140   Op = DAG.getNode(X86ISD::BSR, VTs, Op);
6141
6142   // If src is zero (i.e. bsr sets ZF), returns NumBits.
6143   SmallVector<SDValue, 4> Ops;
6144   Ops.push_back(Op);
6145   Ops.push_back(DAG.getConstant(NumBits+NumBits-1, OpVT));
6146   Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
6147   Ops.push_back(Op.getValue(1));
6148   Op = DAG.getNode(X86ISD::CMOV, OpVT, &Ops[0], 4);
6149
6150   // Finally xor with NumBits-1.
6151   Op = DAG.getNode(ISD::XOR, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
6152
6153   if (VT == MVT::i8)
6154     Op = DAG.getNode(ISD::TRUNCATE, MVT::i8, Op);
6155   return Op;
6156 }
6157
6158 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
6159   MVT VT = Op.getValueType();
6160   MVT OpVT = VT;
6161   unsigned NumBits = VT.getSizeInBits();
6162
6163   Op = Op.getOperand(0);
6164   if (VT == MVT::i8) {
6165     OpVT = MVT::i32;
6166     Op = DAG.getNode(ISD::ZERO_EXTEND, OpVT, Op);
6167   }
6168
6169   // Issue a bsf (scan bits forward) which also sets EFLAGS.
6170   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
6171   Op = DAG.getNode(X86ISD::BSF, VTs, Op);
6172
6173   // If src is zero (i.e. bsf sets ZF), returns NumBits.
6174   SmallVector<SDValue, 4> Ops;
6175   Ops.push_back(Op);
6176   Ops.push_back(DAG.getConstant(NumBits, OpVT));
6177   Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
6178   Ops.push_back(Op.getValue(1));
6179   Op = DAG.getNode(X86ISD::CMOV, OpVT, &Ops[0], 4);
6180
6181   if (VT == MVT::i8)
6182     Op = DAG.getNode(ISD::TRUNCATE, MVT::i8, Op);
6183   return Op;
6184 }
6185
6186 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) {
6187   MVT VT = Op.getValueType();
6188   assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
6189   
6190   //  ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
6191   //  ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
6192   //  ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
6193   //  ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
6194   //  ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
6195   //
6196   //  AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
6197   //  AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
6198   //  return AloBlo + AloBhi + AhiBlo;
6199
6200   SDValue A = Op.getOperand(0);
6201   SDValue B = Op.getOperand(1);
6202   
6203   SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
6204                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
6205                        A, DAG.getConstant(32, MVT::i32));
6206   SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
6207                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
6208                        B, DAG.getConstant(32, MVT::i32));
6209   SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
6210                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6211                        A, B);
6212   SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
6213                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6214                        A, Bhi);
6215   SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
6216                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6217                        Ahi, B);
6218   AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
6219                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
6220                        AloBhi, DAG.getConstant(32, MVT::i32));
6221   AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
6222                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
6223                        AhiBlo, DAG.getConstant(32, MVT::i32));
6224   SDValue Res = DAG.getNode(ISD::ADD, VT, AloBlo, AloBhi);
6225   Res = DAG.getNode(ISD::ADD, VT, Res, AhiBlo);
6226   return Res;
6227 }
6228
6229
6230 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) {
6231   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
6232   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
6233   // looks for this combo and may remove the "setcc" instruction if the "setcc"
6234   // has only one use.
6235   SDNode *N = Op.getNode();
6236   SDValue LHS = N->getOperand(0);
6237   SDValue RHS = N->getOperand(1);
6238   unsigned BaseOp = 0;
6239   unsigned Cond = 0;
6240
6241   switch (Op.getOpcode()) {
6242   default: assert(0 && "Unknown ovf instruction!");
6243   case ISD::SADDO:
6244     BaseOp = X86ISD::ADD;
6245     Cond = X86::COND_O;
6246     break;
6247   case ISD::UADDO:
6248     BaseOp = X86ISD::ADD;
6249     Cond = X86::COND_B;
6250     break;
6251   case ISD::SSUBO:
6252     BaseOp = X86ISD::SUB;
6253     Cond = X86::COND_O;
6254     break;
6255   case ISD::USUBO:
6256     BaseOp = X86ISD::SUB;
6257     Cond = X86::COND_B;
6258     break;
6259   case ISD::SMULO:
6260     BaseOp = X86ISD::SMUL;
6261     Cond = X86::COND_O;
6262     break;
6263   case ISD::UMULO:
6264     BaseOp = X86ISD::UMUL;
6265     Cond = X86::COND_B;
6266     break;
6267   }
6268
6269   // Also sets EFLAGS.
6270   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
6271   SDValue Sum = DAG.getNode(BaseOp, VTs, LHS, RHS);
6272
6273   SDValue SetCC =
6274     DAG.getNode(X86ISD::SETCC, N->getValueType(1),
6275                 DAG.getConstant(Cond, MVT::i32), SDValue(Sum.getNode(), 1));
6276
6277   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
6278   return Sum;
6279 }
6280
6281 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) {
6282   MVT T = Op.getValueType();
6283   unsigned Reg = 0;
6284   unsigned size = 0;
6285   switch(T.getSimpleVT()) {
6286   default:
6287     assert(false && "Invalid value type!");
6288   case MVT::i8:  Reg = X86::AL;  size = 1; break;
6289   case MVT::i16: Reg = X86::AX;  size = 2; break;
6290   case MVT::i32: Reg = X86::EAX; size = 4; break;
6291   case MVT::i64: 
6292     assert(Subtarget->is64Bit() && "Node not type legal!");
6293     Reg = X86::RAX; size = 8;
6294     break;
6295   }
6296   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), Reg,
6297                                     Op.getOperand(2), SDValue());
6298   SDValue Ops[] = { cpIn.getValue(0),
6299                     Op.getOperand(1),
6300                     Op.getOperand(3),
6301                     DAG.getTargetConstant(size, MVT::i8),
6302                     cpIn.getValue(1) };
6303   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6304   SDValue Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, Tys, Ops, 5);
6305   SDValue cpOut = 
6306     DAG.getCopyFromReg(Result.getValue(0), Reg, T, Result.getValue(1));
6307   return cpOut;
6308 }
6309
6310 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
6311                                                  SelectionDAG &DAG) {
6312   assert(Subtarget->is64Bit() && "Result not type legalized?");
6313   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6314   SDValue TheChain = Op.getOperand(0);
6315   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, Tys, &TheChain, 1);
6316   SDValue rax = DAG.getCopyFromReg(rd, X86::RAX, MVT::i64, rd.getValue(1));
6317   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), X86::RDX, MVT::i64,
6318                                    rax.getValue(2));
6319   SDValue Tmp = DAG.getNode(ISD::SHL, MVT::i64, rdx,
6320                             DAG.getConstant(32, MVT::i8));
6321   SDValue Ops[] = {
6322     DAG.getNode(ISD::OR, MVT::i64, rax, Tmp),
6323     rdx.getValue(1)
6324   };
6325   return DAG.getMergeValues(Ops, 2);
6326 }
6327
6328 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
6329   SDNode *Node = Op.getNode();
6330   MVT T = Node->getValueType(0);
6331   SDValue negOp = DAG.getNode(ISD::SUB, T,
6332                                 DAG.getConstant(0, T), Node->getOperand(2));
6333   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD,
6334                        cast<AtomicSDNode>(Node)->getMemoryVT(),
6335                        Node->getOperand(0),
6336                        Node->getOperand(1), negOp,
6337                        cast<AtomicSDNode>(Node)->getSrcValue(),
6338                        cast<AtomicSDNode>(Node)->getAlignment());
6339 }
6340
6341 /// LowerOperation - Provide custom lowering hooks for some operations.
6342 ///
6343 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
6344   switch (Op.getOpcode()) {
6345   default: assert(0 && "Should not custom lower this!");
6346   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
6347   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
6348   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
6349   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
6350   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6351   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
6352   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
6353   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
6354   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
6355   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
6356   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
6357   case ISD::SHL_PARTS:
6358   case ISD::SRA_PARTS:
6359   case ISD::SRL_PARTS:          return LowerShift(Op, DAG);
6360   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
6361   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
6362   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
6363   case ISD::FABS:               return LowerFABS(Op, DAG);
6364   case ISD::FNEG:               return LowerFNEG(Op, DAG);
6365   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
6366   case ISD::SETCC:              return LowerSETCC(Op, DAG);
6367   case ISD::VSETCC:             return LowerVSETCC(Op, DAG);
6368   case ISD::SELECT:             return LowerSELECT(Op, DAG);
6369   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
6370   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
6371   case ISD::CALL:               return LowerCALL(Op, DAG);
6372   case ISD::RET:                return LowerRET(Op, DAG);
6373   case ISD::FORMAL_ARGUMENTS:   return LowerFORMAL_ARGUMENTS(Op, DAG);
6374   case ISD::VASTART:            return LowerVASTART(Op, DAG);
6375   case ISD::VAARG:              return LowerVAARG(Op, DAG);
6376   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
6377   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
6378   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
6379   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
6380   case ISD::FRAME_TO_ARGS_OFFSET:
6381                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
6382   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
6383   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
6384   case ISD::TRAMPOLINE:         return LowerTRAMPOLINE(Op, DAG);
6385   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
6386   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
6387   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
6388   case ISD::MUL:                return LowerMUL_V2I64(Op, DAG);
6389   case ISD::SADDO:
6390   case ISD::UADDO:
6391   case ISD::SSUBO:
6392   case ISD::USUBO:
6393   case ISD::SMULO:
6394   case ISD::UMULO:              return LowerXALUO(Op, DAG);
6395   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
6396   }
6397 }
6398
6399 void X86TargetLowering::
6400 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
6401                         SelectionDAG &DAG, unsigned NewOp) {
6402   MVT T = Node->getValueType(0);
6403   assert (T == MVT::i64 && "Only know how to expand i64 atomics");
6404
6405   SDValue Chain = Node->getOperand(0);
6406   SDValue In1 = Node->getOperand(1);
6407   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32,
6408                              Node->getOperand(2), DAG.getIntPtrConstant(0));
6409   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32,
6410                              Node->getOperand(2), DAG.getIntPtrConstant(1));
6411   // This is a generalized SDNode, not an AtomicSDNode, so it doesn't
6412   // have a MemOperand.  Pass the info through as a normal operand.
6413   SDValue LSI = DAG.getMemOperand(cast<MemSDNode>(Node)->getMemOperand());
6414   SDValue Ops[] = { Chain, In1, In2L, In2H, LSI };
6415   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6416   SDValue Result = DAG.getNode(NewOp, Tys, Ops, 5);
6417   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
6418   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, MVT::i64, OpsF, 2));
6419   Results.push_back(Result.getValue(2));
6420 }
6421
6422 /// ReplaceNodeResults - Replace a node with an illegal result type
6423 /// with a new node built out of custom code.
6424 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
6425                                            SmallVectorImpl<SDValue>&Results,
6426                                            SelectionDAG &DAG) {
6427   switch (N->getOpcode()) {
6428   default:
6429     assert(false && "Do not know how to custom type legalize this operation!");
6430     return;
6431   case ISD::FP_TO_SINT: {
6432     std::pair<SDValue,SDValue> Vals = FP_TO_SINTHelper(SDValue(N, 0), DAG);
6433     SDValue FIST = Vals.first, StackSlot = Vals.second;
6434     if (FIST.getNode() != 0) {
6435       MVT VT = N->getValueType(0);
6436       // Return a load from the stack slot.
6437       Results.push_back(DAG.getLoad(VT, FIST, StackSlot, NULL, 0));
6438     }
6439     return;
6440   }
6441   case ISD::READCYCLECOUNTER: {
6442     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6443     SDValue TheChain = N->getOperand(0);
6444     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, Tys, &TheChain, 1);
6445     SDValue eax = DAG.getCopyFromReg(rd, X86::EAX, MVT::i32, rd.getValue(1));
6446     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), X86::EDX, MVT::i32,
6447                                      eax.getValue(2));
6448     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
6449     SDValue Ops[] = { eax, edx };
6450     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, MVT::i64, Ops, 2));
6451     Results.push_back(edx.getValue(1));
6452     return;
6453   }
6454   case ISD::ATOMIC_CMP_SWAP: {
6455     MVT T = N->getValueType(0);
6456     assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
6457     SDValue cpInL, cpInH;
6458     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, N->getOperand(2),
6459                         DAG.getConstant(0, MVT::i32));
6460     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, N->getOperand(2),
6461                         DAG.getConstant(1, MVT::i32));
6462     cpInL = DAG.getCopyToReg(N->getOperand(0), X86::EAX, cpInL, SDValue());
6463     cpInH = DAG.getCopyToReg(cpInL.getValue(0), X86::EDX, cpInH,
6464                              cpInL.getValue(1));
6465     SDValue swapInL, swapInH;
6466     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, N->getOperand(3),
6467                           DAG.getConstant(0, MVT::i32));
6468     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, N->getOperand(3),
6469                           DAG.getConstant(1, MVT::i32));
6470     swapInL = DAG.getCopyToReg(cpInH.getValue(0), X86::EBX, swapInL,
6471                                cpInH.getValue(1));
6472     swapInH = DAG.getCopyToReg(swapInL.getValue(0), X86::ECX, swapInH,
6473                                swapInL.getValue(1));
6474     SDValue Ops[] = { swapInH.getValue(0),
6475                       N->getOperand(1),
6476                       swapInH.getValue(1) };
6477     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6478     SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, Tys, Ops, 3);
6479     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), X86::EAX, MVT::i32,
6480                                         Result.getValue(1));
6481     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), X86::EDX, MVT::i32,
6482                                         cpOutL.getValue(2));
6483     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
6484     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, MVT::i64, OpsF, 2));
6485     Results.push_back(cpOutH.getValue(1));
6486     return;
6487   }
6488   case ISD::ATOMIC_LOAD_ADD:
6489     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
6490     return;
6491   case ISD::ATOMIC_LOAD_AND:
6492     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
6493     return;
6494   case ISD::ATOMIC_LOAD_NAND:
6495     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
6496     return;
6497   case ISD::ATOMIC_LOAD_OR:
6498     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
6499     return;
6500   case ISD::ATOMIC_LOAD_SUB:
6501     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
6502     return;
6503   case ISD::ATOMIC_LOAD_XOR:
6504     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
6505     return;
6506   case ISD::ATOMIC_SWAP:
6507     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
6508     return;
6509   }
6510 }
6511
6512 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
6513   switch (Opcode) {
6514   default: return NULL;
6515   case X86ISD::BSF:                return "X86ISD::BSF";
6516   case X86ISD::BSR:                return "X86ISD::BSR";
6517   case X86ISD::SHLD:               return "X86ISD::SHLD";
6518   case X86ISD::SHRD:               return "X86ISD::SHRD";
6519   case X86ISD::FAND:               return "X86ISD::FAND";
6520   case X86ISD::FOR:                return "X86ISD::FOR";
6521   case X86ISD::FXOR:               return "X86ISD::FXOR";
6522   case X86ISD::FSRL:               return "X86ISD::FSRL";
6523   case X86ISD::FILD:               return "X86ISD::FILD";
6524   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
6525   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
6526   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
6527   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
6528   case X86ISD::FLD:                return "X86ISD::FLD";
6529   case X86ISD::FST:                return "X86ISD::FST";
6530   case X86ISD::CALL:               return "X86ISD::CALL";
6531   case X86ISD::TAILCALL:           return "X86ISD::TAILCALL";
6532   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
6533   case X86ISD::BT:                 return "X86ISD::BT";
6534   case X86ISD::CMP:                return "X86ISD::CMP";
6535   case X86ISD::COMI:               return "X86ISD::COMI";
6536   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
6537   case X86ISD::SETCC:              return "X86ISD::SETCC";
6538   case X86ISD::CMOV:               return "X86ISD::CMOV";
6539   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
6540   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
6541   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
6542   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
6543   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
6544   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
6545   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
6546   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
6547   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
6548   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
6549   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
6550   case X86ISD::FMAX:               return "X86ISD::FMAX";
6551   case X86ISD::FMIN:               return "X86ISD::FMIN";
6552   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
6553   case X86ISD::FRCP:               return "X86ISD::FRCP";
6554   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
6555   case X86ISD::THREAD_POINTER:     return "X86ISD::THREAD_POINTER";
6556   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
6557   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
6558   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
6559   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
6560   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
6561   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
6562   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
6563   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
6564   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
6565   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
6566   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
6567   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
6568   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
6569   case X86ISD::VSHL:               return "X86ISD::VSHL";
6570   case X86ISD::VSRL:               return "X86ISD::VSRL";
6571   case X86ISD::CMPPD:              return "X86ISD::CMPPD";
6572   case X86ISD::CMPPS:              return "X86ISD::CMPPS";
6573   case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
6574   case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
6575   case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
6576   case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
6577   case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
6578   case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
6579   case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
6580   case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
6581   case X86ISD::ADD:                return "X86ISD::ADD";
6582   case X86ISD::SUB:                return "X86ISD::SUB";
6583   case X86ISD::SMUL:               return "X86ISD::SMUL";
6584   case X86ISD::UMUL:               return "X86ISD::UMUL";
6585   }
6586 }
6587
6588 // isLegalAddressingMode - Return true if the addressing mode represented
6589 // by AM is legal for this target, for a load/store of the specified type.
6590 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM, 
6591                                               const Type *Ty) const {
6592   // X86 supports extremely general addressing modes.
6593   
6594   // X86 allows a sign-extended 32-bit immediate field as a displacement.
6595   if (AM.BaseOffs <= -(1LL << 32) || AM.BaseOffs >= (1LL << 32)-1)
6596     return false;
6597   
6598   if (AM.BaseGV) {
6599     // We can only fold this if we don't need an extra load.
6600     if (Subtarget->GVRequiresExtraLoad(AM.BaseGV, getTargetMachine(), false))
6601       return false;
6602     // If BaseGV requires a register, we cannot also have a BaseReg.
6603     if (Subtarget->GVRequiresRegister(AM.BaseGV, getTargetMachine(), false) &&
6604         AM.HasBaseReg)
6605       return false;
6606
6607     // X86-64 only supports addr of globals in small code model.
6608     if (Subtarget->is64Bit()) {
6609       if (getTargetMachine().getCodeModel() != CodeModel::Small)
6610         return false;
6611       // If lower 4G is not available, then we must use rip-relative addressing.
6612       if (AM.BaseOffs || AM.Scale > 1)
6613         return false;
6614     }
6615   }
6616   
6617   switch (AM.Scale) {
6618   case 0:
6619   case 1:
6620   case 2:
6621   case 4:
6622   case 8:
6623     // These scales always work.
6624     break;
6625   case 3:
6626   case 5:
6627   case 9:
6628     // These scales are formed with basereg+scalereg.  Only accept if there is
6629     // no basereg yet.
6630     if (AM.HasBaseReg)
6631       return false;
6632     break;
6633   default:  // Other stuff never works.
6634     return false;
6635   }
6636   
6637   return true;
6638 }
6639
6640
6641 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
6642   if (!Ty1->isInteger() || !Ty2->isInteger())
6643     return false;
6644   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6645   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
6646   if (NumBits1 <= NumBits2)
6647     return false;
6648   return Subtarget->is64Bit() || NumBits1 < 64;
6649 }
6650
6651 bool X86TargetLowering::isTruncateFree(MVT VT1, MVT VT2) const {
6652   if (!VT1.isInteger() || !VT2.isInteger())
6653     return false;
6654   unsigned NumBits1 = VT1.getSizeInBits();
6655   unsigned NumBits2 = VT2.getSizeInBits();
6656   if (NumBits1 <= NumBits2)
6657     return false;
6658   return Subtarget->is64Bit() || NumBits1 < 64;
6659 }
6660
6661 /// isShuffleMaskLegal - Targets can use this to indicate that they only
6662 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
6663 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
6664 /// are assumed to be legal.
6665 bool
6666 X86TargetLowering::isShuffleMaskLegal(SDValue Mask, MVT VT) const {
6667   // Only do shuffles on 128-bit vector types for now.
6668   if (VT.getSizeInBits() == 64) return false;
6669   return (Mask.getNode()->getNumOperands() <= 4 ||
6670           isIdentityMask(Mask.getNode()) ||
6671           isIdentityMask(Mask.getNode(), true) ||
6672           isSplatMask(Mask.getNode())  ||
6673           isPSHUFHW_PSHUFLWMask(Mask.getNode()) ||
6674           X86::isUNPCKLMask(Mask.getNode()) ||
6675           X86::isUNPCKHMask(Mask.getNode()) ||
6676           X86::isUNPCKL_v_undef_Mask(Mask.getNode()) ||
6677           X86::isUNPCKH_v_undef_Mask(Mask.getNode()));
6678 }
6679
6680 bool
6681 X86TargetLowering::isVectorClearMaskLegal(const std::vector<SDValue> &BVOps,
6682                                           MVT EVT, SelectionDAG &DAG) const {
6683   unsigned NumElts = BVOps.size();
6684   // Only do shuffles on 128-bit vector types for now.
6685   if (EVT.getSizeInBits() * NumElts == 64) return false;
6686   if (NumElts == 2) return true;
6687   if (NumElts == 4) {
6688     return (isMOVLMask(&BVOps[0], 4)  ||
6689             isCommutedMOVL(&BVOps[0], 4, true) ||
6690             isSHUFPMask(&BVOps[0], 4) || 
6691             isCommutedSHUFP(&BVOps[0], 4));
6692   }
6693   return false;
6694 }
6695
6696 //===----------------------------------------------------------------------===//
6697 //                           X86 Scheduler Hooks
6698 //===----------------------------------------------------------------------===//
6699
6700 // private utility function
6701 MachineBasicBlock *
6702 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
6703                                                        MachineBasicBlock *MBB,
6704                                                        unsigned regOpc,
6705                                                        unsigned immOpc,
6706                                                        unsigned LoadOpc,
6707                                                        unsigned CXchgOpc,
6708                                                        unsigned copyOpc,
6709                                                        unsigned notOpc,
6710                                                        unsigned EAXreg,
6711                                                        TargetRegisterClass *RC,
6712                                                        bool invSrc) {
6713   // For the atomic bitwise operator, we generate
6714   //   thisMBB:
6715   //   newMBB:
6716   //     ld  t1 = [bitinstr.addr]
6717   //     op  t2 = t1, [bitinstr.val]
6718   //     mov EAX = t1
6719   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
6720   //     bz  newMBB
6721   //     fallthrough -->nextMBB
6722   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6723   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
6724   MachineFunction::iterator MBBIter = MBB;
6725   ++MBBIter;
6726   
6727   /// First build the CFG
6728   MachineFunction *F = MBB->getParent();
6729   MachineBasicBlock *thisMBB = MBB;
6730   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
6731   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
6732   F->insert(MBBIter, newMBB);
6733   F->insert(MBBIter, nextMBB);
6734   
6735   // Move all successors to thisMBB to nextMBB
6736   nextMBB->transferSuccessors(thisMBB);
6737     
6738   // Update thisMBB to fall through to newMBB
6739   thisMBB->addSuccessor(newMBB);
6740   
6741   // newMBB jumps to itself and fall through to nextMBB
6742   newMBB->addSuccessor(nextMBB);
6743   newMBB->addSuccessor(newMBB);
6744   
6745   // Insert instructions into newMBB based on incoming instruction
6746   assert(bInstr->getNumOperands() < 8 && "unexpected number of operands");
6747   MachineOperand& destOper = bInstr->getOperand(0);
6748   MachineOperand* argOpers[6];
6749   int numArgs = bInstr->getNumOperands() - 1;
6750   for (int i=0; i < numArgs; ++i)
6751     argOpers[i] = &bInstr->getOperand(i+1);
6752
6753   // x86 address has 4 operands: base, index, scale, and displacement
6754   int lastAddrIndx = 3; // [0,3]
6755   int valArgIndx = 4;
6756   
6757   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
6758   MachineInstrBuilder MIB = BuildMI(newMBB, TII->get(LoadOpc), t1);
6759   for (int i=0; i <= lastAddrIndx; ++i)
6760     (*MIB).addOperand(*argOpers[i]);
6761
6762   unsigned tt = F->getRegInfo().createVirtualRegister(RC);
6763   if (invSrc) {
6764     MIB = BuildMI(newMBB, TII->get(notOpc), tt).addReg(t1);
6765   }
6766   else 
6767     tt = t1;
6768
6769   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
6770   assert((argOpers[valArgIndx]->isReg() ||
6771           argOpers[valArgIndx]->isImm()) &&
6772          "invalid operand");
6773   if (argOpers[valArgIndx]->isReg())
6774     MIB = BuildMI(newMBB, TII->get(regOpc), t2);
6775   else
6776     MIB = BuildMI(newMBB, TII->get(immOpc), t2);
6777   MIB.addReg(tt);
6778   (*MIB).addOperand(*argOpers[valArgIndx]);
6779
6780   MIB = BuildMI(newMBB, TII->get(copyOpc), EAXreg);
6781   MIB.addReg(t1);
6782   
6783   MIB = BuildMI(newMBB, TII->get(CXchgOpc));
6784   for (int i=0; i <= lastAddrIndx; ++i)
6785     (*MIB).addOperand(*argOpers[i]);
6786   MIB.addReg(t2);
6787   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
6788   (*MIB).addMemOperand(*F, *bInstr->memoperands_begin());
6789
6790   MIB = BuildMI(newMBB, TII->get(copyOpc), destOper.getReg());
6791   MIB.addReg(EAXreg);
6792   
6793   // insert branch
6794   BuildMI(newMBB, TII->get(X86::JNE)).addMBB(newMBB);
6795
6796   F->DeleteMachineInstr(bInstr);   // The pseudo instruction is gone now.
6797   return nextMBB;
6798 }
6799
6800 // private utility function:  64 bit atomics on 32 bit host.
6801 MachineBasicBlock *
6802 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
6803                                                        MachineBasicBlock *MBB,
6804                                                        unsigned regOpcL,
6805                                                        unsigned regOpcH,
6806                                                        unsigned immOpcL,
6807                                                        unsigned immOpcH,
6808                                                        bool invSrc) {
6809   // For the atomic bitwise operator, we generate
6810   //   thisMBB (instructions are in pairs, except cmpxchg8b)
6811   //     ld t1,t2 = [bitinstr.addr]
6812   //   newMBB:
6813   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
6814   //     op  t5, t6 <- out1, out2, [bitinstr.val]
6815   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
6816   //     mov ECX, EBX <- t5, t6
6817   //     mov EAX, EDX <- t1, t2
6818   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
6819   //     mov t3, t4 <- EAX, EDX
6820   //     bz  newMBB
6821   //     result in out1, out2
6822   //     fallthrough -->nextMBB
6823
6824   const TargetRegisterClass *RC = X86::GR32RegisterClass;
6825   const unsigned LoadOpc = X86::MOV32rm;
6826   const unsigned copyOpc = X86::MOV32rr;
6827   const unsigned NotOpc = X86::NOT32r;
6828   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6829   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
6830   MachineFunction::iterator MBBIter = MBB;
6831   ++MBBIter;
6832   
6833   /// First build the CFG
6834   MachineFunction *F = MBB->getParent();
6835   MachineBasicBlock *thisMBB = MBB;
6836   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
6837   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
6838   F->insert(MBBIter, newMBB);
6839   F->insert(MBBIter, nextMBB);
6840   
6841   // Move all successors to thisMBB to nextMBB
6842   nextMBB->transferSuccessors(thisMBB);
6843     
6844   // Update thisMBB to fall through to newMBB
6845   thisMBB->addSuccessor(newMBB);
6846   
6847   // newMBB jumps to itself and fall through to nextMBB
6848   newMBB->addSuccessor(nextMBB);
6849   newMBB->addSuccessor(newMBB);
6850   
6851   // Insert instructions into newMBB based on incoming instruction
6852   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
6853   assert(bInstr->getNumOperands() < 18 && "unexpected number of operands");
6854   MachineOperand& dest1Oper = bInstr->getOperand(0);
6855   MachineOperand& dest2Oper = bInstr->getOperand(1);
6856   MachineOperand* argOpers[6];
6857   for (int i=0; i < 6; ++i)
6858     argOpers[i] = &bInstr->getOperand(i+2);
6859
6860   // x86 address has 4 operands: base, index, scale, and displacement
6861   int lastAddrIndx = 3; // [0,3]
6862   
6863   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
6864   MachineInstrBuilder MIB = BuildMI(thisMBB, TII->get(LoadOpc), t1);
6865   for (int i=0; i <= lastAddrIndx; ++i)
6866     (*MIB).addOperand(*argOpers[i]);
6867   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
6868   MIB = BuildMI(thisMBB, TII->get(LoadOpc), t2);
6869   // add 4 to displacement.
6870   for (int i=0; i <= lastAddrIndx-1; ++i)
6871     (*MIB).addOperand(*argOpers[i]);
6872   MachineOperand newOp3 = *(argOpers[3]);
6873   if (newOp3.isImm())
6874     newOp3.setImm(newOp3.getImm()+4);
6875   else
6876     newOp3.setOffset(newOp3.getOffset()+4);
6877   (*MIB).addOperand(newOp3);
6878
6879   // t3/4 are defined later, at the bottom of the loop
6880   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
6881   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
6882   BuildMI(newMBB, TII->get(X86::PHI), dest1Oper.getReg())
6883     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
6884   BuildMI(newMBB, TII->get(X86::PHI), dest2Oper.getReg())
6885     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
6886
6887   unsigned tt1 = F->getRegInfo().createVirtualRegister(RC);
6888   unsigned tt2 = F->getRegInfo().createVirtualRegister(RC);
6889   if (invSrc) {  
6890     MIB = BuildMI(newMBB, TII->get(NotOpc), tt1).addReg(t1);
6891     MIB = BuildMI(newMBB, TII->get(NotOpc), tt2).addReg(t2);
6892   } else {
6893     tt1 = t1;
6894     tt2 = t2;
6895   }
6896
6897   assert((argOpers[4]->isReg() || argOpers[4]->isImm()) &&
6898          "invalid operand");
6899   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
6900   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
6901   if (argOpers[4]->isReg())
6902     MIB = BuildMI(newMBB, TII->get(regOpcL), t5);
6903   else
6904     MIB = BuildMI(newMBB, TII->get(immOpcL), t5);
6905   if (regOpcL != X86::MOV32rr)
6906     MIB.addReg(tt1);
6907   (*MIB).addOperand(*argOpers[4]);
6908   assert(argOpers[5]->isReg() == argOpers[4]->isReg());
6909   assert(argOpers[5]->isImm() == argOpers[4]->isImm());
6910   if (argOpers[5]->isReg())
6911     MIB = BuildMI(newMBB, TII->get(regOpcH), t6);
6912   else
6913     MIB = BuildMI(newMBB, TII->get(immOpcH), t6);
6914   if (regOpcH != X86::MOV32rr)
6915     MIB.addReg(tt2);
6916   (*MIB).addOperand(*argOpers[5]);
6917
6918   MIB = BuildMI(newMBB, TII->get(copyOpc), X86::EAX);
6919   MIB.addReg(t1);
6920   MIB = BuildMI(newMBB, TII->get(copyOpc), X86::EDX);
6921   MIB.addReg(t2);
6922
6923   MIB = BuildMI(newMBB, TII->get(copyOpc), X86::EBX);
6924   MIB.addReg(t5);
6925   MIB = BuildMI(newMBB, TII->get(copyOpc), X86::ECX);
6926   MIB.addReg(t6);
6927   
6928   MIB = BuildMI(newMBB, TII->get(X86::LCMPXCHG8B));
6929   for (int i=0; i <= lastAddrIndx; ++i)
6930     (*MIB).addOperand(*argOpers[i]);
6931
6932   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
6933   (*MIB).addMemOperand(*F, *bInstr->memoperands_begin());
6934
6935   MIB = BuildMI(newMBB, TII->get(copyOpc), t3);
6936   MIB.addReg(X86::EAX);
6937   MIB = BuildMI(newMBB, TII->get(copyOpc), t4);
6938   MIB.addReg(X86::EDX);
6939   
6940   // insert branch
6941   BuildMI(newMBB, TII->get(X86::JNE)).addMBB(newMBB);
6942
6943   F->DeleteMachineInstr(bInstr);   // The pseudo instruction is gone now.
6944   return nextMBB;
6945 }
6946
6947 // private utility function
6948 MachineBasicBlock *
6949 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
6950                                                       MachineBasicBlock *MBB,
6951                                                       unsigned cmovOpc) {
6952   // For the atomic min/max operator, we generate
6953   //   thisMBB:
6954   //   newMBB:
6955   //     ld t1 = [min/max.addr]
6956   //     mov t2 = [min/max.val] 
6957   //     cmp  t1, t2
6958   //     cmov[cond] t2 = t1
6959   //     mov EAX = t1
6960   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
6961   //     bz   newMBB
6962   //     fallthrough -->nextMBB
6963   //
6964   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6965   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
6966   MachineFunction::iterator MBBIter = MBB;
6967   ++MBBIter;
6968   
6969   /// First build the CFG
6970   MachineFunction *F = MBB->getParent();
6971   MachineBasicBlock *thisMBB = MBB;
6972   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
6973   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
6974   F->insert(MBBIter, newMBB);
6975   F->insert(MBBIter, nextMBB);
6976   
6977   // Move all successors to thisMBB to nextMBB
6978   nextMBB->transferSuccessors(thisMBB);
6979   
6980   // Update thisMBB to fall through to newMBB
6981   thisMBB->addSuccessor(newMBB);
6982   
6983   // newMBB jumps to newMBB and fall through to nextMBB
6984   newMBB->addSuccessor(nextMBB);
6985   newMBB->addSuccessor(newMBB);
6986   
6987   // Insert instructions into newMBB based on incoming instruction
6988   assert(mInstr->getNumOperands() < 8 && "unexpected number of operands");
6989   MachineOperand& destOper = mInstr->getOperand(0);
6990   MachineOperand* argOpers[6];
6991   int numArgs = mInstr->getNumOperands() - 1;
6992   for (int i=0; i < numArgs; ++i)
6993     argOpers[i] = &mInstr->getOperand(i+1);
6994   
6995   // x86 address has 4 operands: base, index, scale, and displacement
6996   int lastAddrIndx = 3; // [0,3]
6997   int valArgIndx = 4;
6998   
6999   unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7000   MachineInstrBuilder MIB = BuildMI(newMBB, TII->get(X86::MOV32rm), t1);
7001   for (int i=0; i <= lastAddrIndx; ++i)
7002     (*MIB).addOperand(*argOpers[i]);
7003
7004   // We only support register and immediate values
7005   assert((argOpers[valArgIndx]->isReg() ||
7006           argOpers[valArgIndx]->isImm()) &&
7007          "invalid operand");
7008   
7009   unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);  
7010   if (argOpers[valArgIndx]->isReg())
7011     MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), t2);
7012   else 
7013     MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), t2);
7014   (*MIB).addOperand(*argOpers[valArgIndx]);
7015
7016   MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), X86::EAX);
7017   MIB.addReg(t1);
7018
7019   MIB = BuildMI(newMBB, TII->get(X86::CMP32rr));
7020   MIB.addReg(t1);
7021   MIB.addReg(t2);
7022
7023   // Generate movc
7024   unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7025   MIB = BuildMI(newMBB, TII->get(cmovOpc),t3);
7026   MIB.addReg(t2);
7027   MIB.addReg(t1);
7028
7029   // Cmp and exchange if none has modified the memory location
7030   MIB = BuildMI(newMBB, TII->get(X86::LCMPXCHG32));
7031   for (int i=0; i <= lastAddrIndx; ++i)
7032     (*MIB).addOperand(*argOpers[i]);
7033   MIB.addReg(t3);
7034   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7035   (*MIB).addMemOperand(*F, *mInstr->memoperands_begin());
7036   
7037   MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), destOper.getReg());
7038   MIB.addReg(X86::EAX);
7039   
7040   // insert branch
7041   BuildMI(newMBB, TII->get(X86::JNE)).addMBB(newMBB);
7042
7043   F->DeleteMachineInstr(mInstr);   // The pseudo instruction is gone now.
7044   return nextMBB;
7045 }
7046
7047
7048 MachineBasicBlock *
7049 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7050                                                MachineBasicBlock *BB) {
7051   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7052   switch (MI->getOpcode()) {
7053   default: assert(false && "Unexpected instr type to insert");
7054   case X86::CMOV_V1I64:
7055   case X86::CMOV_FR32:
7056   case X86::CMOV_FR64:
7057   case X86::CMOV_V4F32:
7058   case X86::CMOV_V2F64:
7059   case X86::CMOV_V2I64: {
7060     // To "insert" a SELECT_CC instruction, we actually have to insert the
7061     // diamond control-flow pattern.  The incoming instruction knows the
7062     // destination vreg to set, the condition code register to branch on, the
7063     // true/false values to select between, and a branch opcode to use.
7064     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7065     MachineFunction::iterator It = BB;
7066     ++It;
7067
7068     //  thisMBB:
7069     //  ...
7070     //   TrueVal = ...
7071     //   cmpTY ccX, r1, r2
7072     //   bCC copy1MBB
7073     //   fallthrough --> copy0MBB
7074     MachineBasicBlock *thisMBB = BB;
7075     MachineFunction *F = BB->getParent();
7076     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7077     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7078     unsigned Opc =
7079       X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
7080     BuildMI(BB, TII->get(Opc)).addMBB(sinkMBB);
7081     F->insert(It, copy0MBB);
7082     F->insert(It, sinkMBB);
7083     // Update machine-CFG edges by transferring all successors of the current
7084     // block to the new block which will contain the Phi node for the select.
7085     sinkMBB->transferSuccessors(BB);
7086
7087     // Add the true and fallthrough blocks as its successors.
7088     BB->addSuccessor(copy0MBB);
7089     BB->addSuccessor(sinkMBB);
7090
7091     //  copy0MBB:
7092     //   %FalseValue = ...
7093     //   # fallthrough to sinkMBB
7094     BB = copy0MBB;
7095
7096     // Update machine-CFG edges
7097     BB->addSuccessor(sinkMBB);
7098
7099     //  sinkMBB:
7100     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7101     //  ...
7102     BB = sinkMBB;
7103     BuildMI(BB, TII->get(X86::PHI), MI->getOperand(0).getReg())
7104       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7105       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7106
7107     F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
7108     return BB;
7109   }
7110
7111   case X86::FP32_TO_INT16_IN_MEM:
7112   case X86::FP32_TO_INT32_IN_MEM:
7113   case X86::FP32_TO_INT64_IN_MEM:
7114   case X86::FP64_TO_INT16_IN_MEM:
7115   case X86::FP64_TO_INT32_IN_MEM:
7116   case X86::FP64_TO_INT64_IN_MEM:
7117   case X86::FP80_TO_INT16_IN_MEM:
7118   case X86::FP80_TO_INT32_IN_MEM:
7119   case X86::FP80_TO_INT64_IN_MEM: {
7120     // Change the floating point control register to use "round towards zero"
7121     // mode when truncating to an integer value.
7122     MachineFunction *F = BB->getParent();
7123     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
7124     addFrameReference(BuildMI(BB, TII->get(X86::FNSTCW16m)), CWFrameIdx);
7125
7126     // Load the old value of the high byte of the control word...
7127     unsigned OldCW =
7128       F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
7129     addFrameReference(BuildMI(BB, TII->get(X86::MOV16rm), OldCW), CWFrameIdx);
7130
7131     // Set the high part to be round to zero...
7132     addFrameReference(BuildMI(BB, TII->get(X86::MOV16mi)), CWFrameIdx)
7133       .addImm(0xC7F);
7134
7135     // Reload the modified control word now...
7136     addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
7137
7138     // Restore the memory image of control word to original value
7139     addFrameReference(BuildMI(BB, TII->get(X86::MOV16mr)), CWFrameIdx)
7140       .addReg(OldCW);
7141
7142     // Get the X86 opcode to use.
7143     unsigned Opc;
7144     switch (MI->getOpcode()) {
7145     default: assert(0 && "illegal opcode!");
7146     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
7147     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
7148     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
7149     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
7150     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
7151     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
7152     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
7153     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
7154     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
7155     }
7156
7157     X86AddressMode AM;
7158     MachineOperand &Op = MI->getOperand(0);
7159     if (Op.isReg()) {
7160       AM.BaseType = X86AddressMode::RegBase;
7161       AM.Base.Reg = Op.getReg();
7162     } else {
7163       AM.BaseType = X86AddressMode::FrameIndexBase;
7164       AM.Base.FrameIndex = Op.getIndex();
7165     }
7166     Op = MI->getOperand(1);
7167     if (Op.isImm())
7168       AM.Scale = Op.getImm();
7169     Op = MI->getOperand(2);
7170     if (Op.isImm())
7171       AM.IndexReg = Op.getImm();
7172     Op = MI->getOperand(3);
7173     if (Op.isGlobal()) {
7174       AM.GV = Op.getGlobal();
7175     } else {
7176       AM.Disp = Op.getImm();
7177     }
7178     addFullAddress(BuildMI(BB, TII->get(Opc)), AM)
7179                       .addReg(MI->getOperand(4).getReg());
7180
7181     // Reload the original control word now.
7182     addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
7183
7184     F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
7185     return BB;
7186   }
7187   case X86::ATOMAND32:
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);
7193   case X86::ATOMOR32:
7194     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr, 
7195                                                X86::OR32ri, X86::MOV32rm, 
7196                                                X86::LCMPXCHG32, X86::MOV32rr,
7197                                                X86::NOT32r, X86::EAX,
7198                                                X86::GR32RegisterClass);
7199   case X86::ATOMXOR32:
7200     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
7201                                                X86::XOR32ri, X86::MOV32rm, 
7202                                                X86::LCMPXCHG32, X86::MOV32rr,
7203                                                X86::NOT32r, X86::EAX,
7204                                                X86::GR32RegisterClass);
7205   case X86::ATOMNAND32:
7206     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
7207                                                X86::AND32ri, X86::MOV32rm,
7208                                                X86::LCMPXCHG32, X86::MOV32rr,
7209                                                X86::NOT32r, X86::EAX,
7210                                                X86::GR32RegisterClass, true);
7211   case X86::ATOMMIN32:
7212     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
7213   case X86::ATOMMAX32:
7214     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
7215   case X86::ATOMUMIN32:
7216     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
7217   case X86::ATOMUMAX32:
7218     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
7219
7220   case X86::ATOMAND16:
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);
7226   case X86::ATOMOR16:
7227     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr, 
7228                                                X86::OR16ri, X86::MOV16rm,
7229                                                X86::LCMPXCHG16, X86::MOV16rr,
7230                                                X86::NOT16r, X86::AX,
7231                                                X86::GR16RegisterClass);
7232   case X86::ATOMXOR16:
7233     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
7234                                                X86::XOR16ri, X86::MOV16rm,
7235                                                X86::LCMPXCHG16, X86::MOV16rr,
7236                                                X86::NOT16r, X86::AX,
7237                                                X86::GR16RegisterClass);
7238   case X86::ATOMNAND16:
7239     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
7240                                                X86::AND16ri, X86::MOV16rm,
7241                                                X86::LCMPXCHG16, X86::MOV16rr,
7242                                                X86::NOT16r, X86::AX,
7243                                                X86::GR16RegisterClass, true);
7244   case X86::ATOMMIN16:
7245     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
7246   case X86::ATOMMAX16:
7247     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
7248   case X86::ATOMUMIN16:
7249     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
7250   case X86::ATOMUMAX16:
7251     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
7252
7253   case X86::ATOMAND8:
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);
7259   case X86::ATOMOR8:
7260     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr, 
7261                                                X86::OR8ri, X86::MOV8rm,
7262                                                X86::LCMPXCHG8, X86::MOV8rr,
7263                                                X86::NOT8r, X86::AL,
7264                                                X86::GR8RegisterClass);
7265   case X86::ATOMXOR8:
7266     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
7267                                                X86::XOR8ri, X86::MOV8rm,
7268                                                X86::LCMPXCHG8, X86::MOV8rr,
7269                                                X86::NOT8r, X86::AL,
7270                                                X86::GR8RegisterClass);
7271   case X86::ATOMNAND8:
7272     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
7273                                                X86::AND8ri, X86::MOV8rm,
7274                                                X86::LCMPXCHG8, X86::MOV8rr,
7275                                                X86::NOT8r, X86::AL,
7276                                                X86::GR8RegisterClass, true);
7277   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
7278   // This group is for 64-bit host.
7279   case X86::ATOMAND64:
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);
7285   case X86::ATOMOR64:
7286     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr, 
7287                                                X86::OR64ri32, X86::MOV64rm, 
7288                                                X86::LCMPXCHG64, X86::MOV64rr,
7289                                                X86::NOT64r, X86::RAX,
7290                                                X86::GR64RegisterClass);
7291   case X86::ATOMXOR64:
7292     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
7293                                                X86::XOR64ri32, X86::MOV64rm, 
7294                                                X86::LCMPXCHG64, X86::MOV64rr,
7295                                                X86::NOT64r, X86::RAX,
7296                                                X86::GR64RegisterClass);
7297   case X86::ATOMNAND64:
7298     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
7299                                                X86::AND64ri32, X86::MOV64rm,
7300                                                X86::LCMPXCHG64, X86::MOV64rr,
7301                                                X86::NOT64r, X86::RAX,
7302                                                X86::GR64RegisterClass, true);
7303   case X86::ATOMMIN64:
7304     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
7305   case X86::ATOMMAX64:
7306     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
7307   case X86::ATOMUMIN64:
7308     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
7309   case X86::ATOMUMAX64:
7310     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
7311
7312   // This group does 64-bit operations on a 32-bit host.
7313   case X86::ATOMAND6432:
7314     return EmitAtomicBit6432WithCustomInserter(MI, BB, 
7315                                                X86::AND32rr, X86::AND32rr,
7316                                                X86::AND32ri, X86::AND32ri,
7317                                                false);
7318   case X86::ATOMOR6432:
7319     return EmitAtomicBit6432WithCustomInserter(MI, BB, 
7320                                                X86::OR32rr, X86::OR32rr,
7321                                                X86::OR32ri, X86::OR32ri,
7322                                                false);
7323   case X86::ATOMXOR6432:
7324     return EmitAtomicBit6432WithCustomInserter(MI, BB, 
7325                                                X86::XOR32rr, X86::XOR32rr,
7326                                                X86::XOR32ri, X86::XOR32ri,
7327                                                false);
7328   case X86::ATOMNAND6432:
7329     return EmitAtomicBit6432WithCustomInserter(MI, BB, 
7330                                                X86::AND32rr, X86::AND32rr,
7331                                                X86::AND32ri, X86::AND32ri,
7332                                                true);
7333   case X86::ATOMADD6432:
7334     return EmitAtomicBit6432WithCustomInserter(MI, BB, 
7335                                                X86::ADD32rr, X86::ADC32rr,
7336                                                X86::ADD32ri, X86::ADC32ri,
7337                                                false);
7338   case X86::ATOMSUB6432:
7339     return EmitAtomicBit6432WithCustomInserter(MI, BB, 
7340                                                X86::SUB32rr, X86::SBB32rr,
7341                                                X86::SUB32ri, X86::SBB32ri,
7342                                                false);
7343   case X86::ATOMSWAP6432:
7344     return EmitAtomicBit6432WithCustomInserter(MI, BB, 
7345                                                X86::MOV32rr, X86::MOV32rr,
7346                                                X86::MOV32ri, X86::MOV32ri,
7347                                                false);
7348   }
7349 }
7350
7351 //===----------------------------------------------------------------------===//
7352 //                           X86 Optimization Hooks
7353 //===----------------------------------------------------------------------===//
7354
7355 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
7356                                                        const APInt &Mask,
7357                                                        APInt &KnownZero,
7358                                                        APInt &KnownOne,
7359                                                        const SelectionDAG &DAG,
7360                                                        unsigned Depth) const {
7361   unsigned Opc = Op.getOpcode();
7362   assert((Opc >= ISD::BUILTIN_OP_END ||
7363           Opc == ISD::INTRINSIC_WO_CHAIN ||
7364           Opc == ISD::INTRINSIC_W_CHAIN ||
7365           Opc == ISD::INTRINSIC_VOID) &&
7366          "Should use MaskedValueIsZero if you don't know whether Op"
7367          " is a target node!");
7368
7369   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
7370   switch (Opc) {
7371   default: break;
7372   case X86ISD::SETCC:
7373     KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
7374                                        Mask.getBitWidth() - 1);
7375     break;
7376   }
7377 }
7378
7379 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
7380 /// node is a GlobalAddress + offset.
7381 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
7382                                        GlobalValue* &GA, int64_t &Offset) const{
7383   if (N->getOpcode() == X86ISD::Wrapper) {
7384     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
7385       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
7386       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
7387       return true;
7388     }
7389   }
7390   return TargetLowering::isGAPlusOffset(N, GA, Offset);
7391 }
7392
7393 static bool isBaseAlignmentOfN(unsigned N, SDNode *Base,
7394                                const TargetLowering &TLI) {
7395   GlobalValue *GV;
7396   int64_t Offset = 0;
7397   if (TLI.isGAPlusOffset(Base, GV, Offset))
7398     return (GV->getAlignment() >= N && (Offset % N) == 0);
7399   // DAG combine handles the stack object case.
7400   return false;
7401 }
7402
7403 static bool EltsFromConsecutiveLoads(SDNode *N, SDValue PermMask,
7404                                      unsigned NumElems, MVT EVT,
7405                                      SDNode *&Base,
7406                                      SelectionDAG &DAG, MachineFrameInfo *MFI,
7407                                      const TargetLowering &TLI) {
7408   Base = NULL;
7409   for (unsigned i = 0; i < NumElems; ++i) {
7410     SDValue Idx = PermMask.getOperand(i);
7411     if (Idx.getOpcode() == ISD::UNDEF) {
7412       if (!Base)
7413         return false;
7414       continue;
7415     }
7416
7417     SDValue Elt = DAG.getShuffleScalarElt(N, i);
7418     if (!Elt.getNode() ||
7419         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
7420       return false;
7421     if (!Base) {
7422       Base = Elt.getNode();
7423       if (Base->getOpcode() == ISD::UNDEF)
7424         return false;
7425       continue;
7426     }
7427     if (Elt.getOpcode() == ISD::UNDEF)
7428       continue;
7429
7430     if (!TLI.isConsecutiveLoad(Elt.getNode(), Base,
7431                                EVT.getSizeInBits()/8, i, MFI))
7432       return false;
7433   }
7434   return true;
7435 }
7436
7437 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
7438 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
7439 /// if the load addresses are consecutive, non-overlapping, and in the right
7440 /// order.
7441 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
7442                                        const TargetLowering &TLI) {
7443   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7444   MVT VT = N->getValueType(0);
7445   MVT EVT = VT.getVectorElementType();
7446   SDValue PermMask = N->getOperand(2);
7447   unsigned NumElems = PermMask.getNumOperands();
7448   SDNode *Base = NULL;
7449   if (!EltsFromConsecutiveLoads(N, PermMask, NumElems, EVT, Base,
7450                                 DAG, MFI, TLI))
7451     return SDValue();
7452
7453   LoadSDNode *LD = cast<LoadSDNode>(Base);
7454   if (isBaseAlignmentOfN(16, Base->getOperand(1).getNode(), TLI))
7455     return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
7456                        LD->getSrcValueOffset(), LD->isVolatile());
7457   return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
7458                      LD->getSrcValueOffset(), LD->isVolatile(),
7459                      LD->getAlignment());
7460 }
7461
7462 /// PerformBuildVectorCombine - build_vector 0,(load i64 / f64) -> movq / movsd.
7463 static SDValue PerformBuildVectorCombine(SDNode *N, SelectionDAG &DAG,
7464                                          const X86Subtarget *Subtarget,
7465                                          const TargetLowering &TLI) {
7466   unsigned NumOps = N->getNumOperands();
7467
7468   // Ignore single operand BUILD_VECTOR.
7469   if (NumOps == 1)
7470     return SDValue();
7471
7472   MVT VT = N->getValueType(0);
7473   MVT EVT = VT.getVectorElementType();
7474   if ((EVT != MVT::i64 && EVT != MVT::f64) || Subtarget->is64Bit())
7475     // We are looking for load i64 and zero extend. We want to transform
7476     // it before legalizer has a chance to expand it. Also look for i64
7477     // BUILD_PAIR bit casted to f64.
7478     return SDValue();
7479   // This must be an insertion into a zero vector.
7480   SDValue HighElt = N->getOperand(1);
7481   if (!isZeroNode(HighElt))
7482     return SDValue();
7483
7484   // Value must be a load.
7485   SDNode *Base = N->getOperand(0).getNode();
7486   if (!isa<LoadSDNode>(Base)) {
7487     if (Base->getOpcode() != ISD::BIT_CONVERT)
7488       return SDValue();
7489     Base = Base->getOperand(0).getNode();
7490     if (!isa<LoadSDNode>(Base))
7491       return SDValue();
7492   }
7493
7494   // Transform it into VZEXT_LOAD addr.
7495   LoadSDNode *LD = cast<LoadSDNode>(Base);
7496   
7497   // Load must not be an extload.
7498   if (LD->getExtensionType() != ISD::NON_EXTLOAD)
7499     return SDValue();
7500   
7501   SDVTList Tys = DAG.getVTList(VT, MVT::Other);
7502   SDValue Ops[] = { LD->getChain(), LD->getBasePtr() };
7503   SDValue ResNode = DAG.getNode(X86ISD::VZEXT_LOAD, Tys, Ops, 2);
7504   DAG.ReplaceAllUsesOfValueWith(SDValue(Base, 1), ResNode.getValue(1));
7505   return ResNode;
7506 }                                           
7507
7508 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
7509 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
7510                                       const X86Subtarget *Subtarget) {
7511   SDValue Cond = N->getOperand(0);
7512
7513   // If we have SSE[12] support, try to form min/max nodes.
7514   if (Subtarget->hasSSE2() &&
7515       (N->getValueType(0) == MVT::f32 || N->getValueType(0) == MVT::f64)) {
7516     if (Cond.getOpcode() == ISD::SETCC) {
7517       // Get the LHS/RHS of the select.
7518       SDValue LHS = N->getOperand(1);
7519       SDValue RHS = N->getOperand(2);
7520       ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
7521
7522       unsigned Opcode = 0;
7523       if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
7524         switch (CC) {
7525         default: break;
7526         case ISD::SETOLE: // (X <= Y) ? X : Y -> min
7527         case ISD::SETULE:
7528         case ISD::SETLE:
7529           if (!UnsafeFPMath) break;
7530           // FALL THROUGH.
7531         case ISD::SETOLT:  // (X olt/lt Y) ? X : Y -> min
7532         case ISD::SETLT:
7533           Opcode = X86ISD::FMIN;
7534           break;
7535
7536         case ISD::SETOGT: // (X > Y) ? X : Y -> max
7537         case ISD::SETUGT:
7538         case ISD::SETGT:
7539           if (!UnsafeFPMath) break;
7540           // FALL THROUGH.
7541         case ISD::SETUGE:  // (X uge/ge Y) ? X : Y -> max
7542         case ISD::SETGE:
7543           Opcode = X86ISD::FMAX;
7544           break;
7545         }
7546       } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
7547         switch (CC) {
7548         default: break;
7549         case ISD::SETOGT: // (X > Y) ? Y : X -> min
7550         case ISD::SETUGT:
7551         case ISD::SETGT:
7552           if (!UnsafeFPMath) break;
7553           // FALL THROUGH.
7554         case ISD::SETUGE:  // (X uge/ge Y) ? Y : X -> min
7555         case ISD::SETGE:
7556           Opcode = X86ISD::FMIN;
7557           break;
7558
7559         case ISD::SETOLE:   // (X <= Y) ? Y : X -> max
7560         case ISD::SETULE:
7561         case ISD::SETLE:
7562           if (!UnsafeFPMath) break;
7563           // FALL THROUGH.
7564         case ISD::SETOLT:   // (X olt/lt Y) ? Y : X -> max
7565         case ISD::SETLT:
7566           Opcode = X86ISD::FMAX;
7567           break;
7568         }
7569       }
7570
7571       if (Opcode)
7572         return DAG.getNode(Opcode, N->getValueType(0), LHS, RHS);
7573     }
7574
7575   }
7576
7577   return SDValue();
7578 }
7579
7580 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
7581 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
7582                                      const X86Subtarget *Subtarget) {
7583   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
7584   // the FP state in cases where an emms may be missing.
7585   // A preferable solution to the general problem is to figure out the right
7586   // places to insert EMMS.  This qualifies as a quick hack.
7587   StoreSDNode *St = cast<StoreSDNode>(N);
7588   if (St->getValue().getValueType().isVector() &&
7589       St->getValue().getValueType().getSizeInBits() == 64 &&
7590       isa<LoadSDNode>(St->getValue()) &&
7591       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
7592       St->getChain().hasOneUse() && !St->isVolatile()) {
7593     SDNode* LdVal = St->getValue().getNode();
7594     LoadSDNode *Ld = 0;
7595     int TokenFactorIndex = -1;
7596     SmallVector<SDValue, 8> Ops;
7597     SDNode* ChainVal = St->getChain().getNode();
7598     // Must be a store of a load.  We currently handle two cases:  the load
7599     // is a direct child, and it's under an intervening TokenFactor.  It is
7600     // possible to dig deeper under nested TokenFactors.
7601     if (ChainVal == LdVal)
7602       Ld = cast<LoadSDNode>(St->getChain());
7603     else if (St->getValue().hasOneUse() &&
7604              ChainVal->getOpcode() == ISD::TokenFactor) {
7605       for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
7606         if (ChainVal->getOperand(i).getNode() == LdVal) {
7607           TokenFactorIndex = i;
7608           Ld = cast<LoadSDNode>(St->getValue());
7609         } else
7610           Ops.push_back(ChainVal->getOperand(i));
7611       }
7612     }
7613     if (Ld) {
7614       // If we are a 64-bit capable x86, lower to a single movq load/store pair.
7615       if (Subtarget->is64Bit()) {
7616         SDValue NewLd = DAG.getLoad(MVT::i64, Ld->getChain(), 
7617                                       Ld->getBasePtr(), Ld->getSrcValue(), 
7618                                       Ld->getSrcValueOffset(), Ld->isVolatile(),
7619                                       Ld->getAlignment());
7620         SDValue NewChain = NewLd.getValue(1);
7621         if (TokenFactorIndex != -1) {
7622           Ops.push_back(NewChain);
7623           NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0], 
7624                                  Ops.size());
7625         }
7626         return DAG.getStore(NewChain, NewLd, St->getBasePtr(),
7627                             St->getSrcValue(), St->getSrcValueOffset(),
7628                             St->isVolatile(), St->getAlignment());
7629       }
7630
7631       // Otherwise, lower to two 32-bit copies.
7632       SDValue LoAddr = Ld->getBasePtr();
7633       SDValue HiAddr = DAG.getNode(ISD::ADD, MVT::i32, LoAddr,
7634                                      DAG.getConstant(4, MVT::i32));
7635
7636       SDValue LoLd = DAG.getLoad(MVT::i32, Ld->getChain(), LoAddr,
7637                                    Ld->getSrcValue(), Ld->getSrcValueOffset(),
7638                                    Ld->isVolatile(), Ld->getAlignment());
7639       SDValue HiLd = DAG.getLoad(MVT::i32, Ld->getChain(), HiAddr,
7640                                    Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
7641                                    Ld->isVolatile(), 
7642                                    MinAlign(Ld->getAlignment(), 4));
7643
7644       SDValue NewChain = LoLd.getValue(1);
7645       if (TokenFactorIndex != -1) {
7646         Ops.push_back(LoLd);
7647         Ops.push_back(HiLd);
7648         NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0], 
7649                                Ops.size());
7650       }
7651
7652       LoAddr = St->getBasePtr();
7653       HiAddr = DAG.getNode(ISD::ADD, MVT::i32, LoAddr,
7654                            DAG.getConstant(4, MVT::i32));
7655
7656       SDValue LoSt = DAG.getStore(NewChain, LoLd, LoAddr,
7657                           St->getSrcValue(), St->getSrcValueOffset(),
7658                           St->isVolatile(), St->getAlignment());
7659       SDValue HiSt = DAG.getStore(NewChain, HiLd, HiAddr,
7660                                     St->getSrcValue(),
7661                                     St->getSrcValueOffset() + 4,
7662                                     St->isVolatile(), 
7663                                     MinAlign(St->getAlignment(), 4));
7664       return DAG.getNode(ISD::TokenFactor, MVT::Other, LoSt, HiSt);
7665     }
7666   }
7667   return SDValue();
7668 }
7669
7670 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
7671 /// X86ISD::FXOR nodes.
7672 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
7673   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
7674   // F[X]OR(0.0, x) -> x
7675   // F[X]OR(x, 0.0) -> x
7676   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
7677     if (C->getValueAPF().isPosZero())
7678       return N->getOperand(1);
7679   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
7680     if (C->getValueAPF().isPosZero())
7681       return N->getOperand(0);
7682   return SDValue();
7683 }
7684
7685 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
7686 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
7687   // FAND(0.0, x) -> 0.0
7688   // FAND(x, 0.0) -> 0.0
7689   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
7690     if (C->getValueAPF().isPosZero())
7691       return N->getOperand(0);
7692   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
7693     if (C->getValueAPF().isPosZero())
7694       return N->getOperand(1);
7695   return SDValue();
7696 }
7697
7698
7699 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
7700                                              DAGCombinerInfo &DCI) const {
7701   SelectionDAG &DAG = DCI.DAG;
7702   switch (N->getOpcode()) {
7703   default: break;
7704   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
7705   case ISD::BUILD_VECTOR:
7706     return PerformBuildVectorCombine(N, DAG, Subtarget, *this);
7707   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
7708   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
7709   case X86ISD::FXOR:
7710   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
7711   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
7712   }
7713
7714   return SDValue();
7715 }
7716
7717 //===----------------------------------------------------------------------===//
7718 //                           X86 Inline Assembly Support
7719 //===----------------------------------------------------------------------===//
7720
7721 /// getConstraintType - Given a constraint letter, return the type of
7722 /// constraint it is for this target.
7723 X86TargetLowering::ConstraintType
7724 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
7725   if (Constraint.size() == 1) {
7726     switch (Constraint[0]) {
7727     case 'A':
7728       return C_Register;
7729     case 'f':
7730     case 'r':
7731     case 'R':
7732     case 'l':
7733     case 'q':
7734     case 'Q':
7735     case 'x':
7736     case 'y':
7737     case 'Y':
7738       return C_RegisterClass;
7739     default:
7740       break;
7741     }
7742   }
7743   return TargetLowering::getConstraintType(Constraint);
7744 }
7745
7746 /// LowerXConstraint - try to replace an X constraint, which matches anything,
7747 /// with another that has more specific requirements based on the type of the
7748 /// corresponding operand.
7749 const char *X86TargetLowering::
7750 LowerXConstraint(MVT ConstraintVT) const {
7751   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
7752   // 'f' like normal targets.
7753   if (ConstraintVT.isFloatingPoint()) {
7754     if (Subtarget->hasSSE2())
7755       return "Y";
7756     if (Subtarget->hasSSE1())
7757       return "x";
7758   }
7759   
7760   return TargetLowering::LowerXConstraint(ConstraintVT);
7761 }
7762
7763 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
7764 /// vector.  If it is invalid, don't add anything to Ops.
7765 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
7766                                                      char Constraint,
7767                                                      bool hasMemory,
7768                                                      std::vector<SDValue>&Ops,
7769                                                      SelectionDAG &DAG) const {
7770   SDValue Result(0, 0);
7771   
7772   switch (Constraint) {
7773   default: break;
7774   case 'I':
7775     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
7776       if (C->getZExtValue() <= 31) {
7777         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
7778         break;
7779       }
7780     }
7781     return;
7782   case 'J':
7783     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
7784       if (C->getZExtValue() <= 63) {
7785         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
7786         break;
7787       }
7788     }
7789     return;
7790   case 'N':
7791     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
7792       if (C->getZExtValue() <= 255) {
7793         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
7794         break;
7795       }
7796     }
7797     return;
7798   case 'i': {
7799     // Literal immediates are always ok.
7800     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
7801       Result = DAG.getTargetConstant(CST->getZExtValue(), Op.getValueType());
7802       break;
7803     }
7804
7805     // If we are in non-pic codegen mode, we allow the address of a global (with
7806     // an optional displacement) to be used with 'i'.
7807     GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
7808     int64_t Offset = 0;
7809     
7810     // Match either (GA) or (GA+C)
7811     if (GA) {
7812       Offset = GA->getOffset();
7813     } else if (Op.getOpcode() == ISD::ADD) {
7814       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7815       GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
7816       if (C && GA) {
7817         Offset = GA->getOffset()+C->getZExtValue();
7818       } else {
7819         C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7820         GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
7821         if (C && GA)
7822           Offset = GA->getOffset()+C->getZExtValue();
7823         else
7824           C = 0, GA = 0;
7825       }
7826     }
7827     
7828     if (GA) {
7829       if (hasMemory) 
7830         Op = LowerGlobalAddress(GA->getGlobal(), Offset, DAG);
7831       else
7832         Op = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
7833                                         Offset);
7834       Result = Op;
7835       break;
7836     }
7837
7838     // Otherwise, not valid for this mode.
7839     return;
7840   }
7841   }
7842   
7843   if (Result.getNode()) {
7844     Ops.push_back(Result);
7845     return;
7846   }
7847   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, hasMemory,
7848                                                       Ops, DAG);
7849 }
7850
7851 std::vector<unsigned> X86TargetLowering::
7852 getRegClassForInlineAsmConstraint(const std::string &Constraint,
7853                                   MVT VT) const {
7854   if (Constraint.size() == 1) {
7855     // FIXME: not handling fp-stack yet!
7856     switch (Constraint[0]) {      // GCC X86 Constraint Letters
7857     default: break;  // Unknown constraint letter
7858     case 'q':   // Q_REGS (GENERAL_REGS in 64-bit mode)
7859     case 'Q':   // Q_REGS
7860       if (VT == MVT::i32)
7861         return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
7862       else if (VT == MVT::i16)
7863         return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
7864       else if (VT == MVT::i8)
7865         return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
7866       else if (VT == MVT::i64)
7867         return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
7868       break;
7869     }
7870   }
7871
7872   return std::vector<unsigned>();
7873 }
7874
7875 std::pair<unsigned, const TargetRegisterClass*>
7876 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
7877                                                 MVT VT) const {
7878   // First, see if this is a constraint that directly corresponds to an LLVM
7879   // register class.
7880   if (Constraint.size() == 1) {
7881     // GCC Constraint Letters
7882     switch (Constraint[0]) {
7883     default: break;
7884     case 'r':   // GENERAL_REGS
7885     case 'R':   // LEGACY_REGS
7886     case 'l':   // INDEX_REGS
7887       if (VT == MVT::i8)
7888         return std::make_pair(0U, X86::GR8RegisterClass);
7889       if (VT == MVT::i16)
7890         return std::make_pair(0U, X86::GR16RegisterClass);
7891       if (VT == MVT::i32 || !Subtarget->is64Bit())
7892         return std::make_pair(0U, X86::GR32RegisterClass);  
7893       return std::make_pair(0U, X86::GR64RegisterClass);
7894     case 'f':  // FP Stack registers.
7895       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
7896       // value to the correct fpstack register class.
7897       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
7898         return std::make_pair(0U, X86::RFP32RegisterClass);
7899       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
7900         return std::make_pair(0U, X86::RFP64RegisterClass);
7901       return std::make_pair(0U, X86::RFP80RegisterClass);
7902     case 'y':   // MMX_REGS if MMX allowed.
7903       if (!Subtarget->hasMMX()) break;
7904       return std::make_pair(0U, X86::VR64RegisterClass);
7905     case 'Y':   // SSE_REGS if SSE2 allowed
7906       if (!Subtarget->hasSSE2()) break;
7907       // FALL THROUGH.
7908     case 'x':   // SSE_REGS if SSE1 allowed
7909       if (!Subtarget->hasSSE1()) break;
7910
7911       switch (VT.getSimpleVT()) {
7912       default: break;
7913       // Scalar SSE types.
7914       case MVT::f32:
7915       case MVT::i32:
7916         return std::make_pair(0U, X86::FR32RegisterClass);
7917       case MVT::f64:
7918       case MVT::i64:
7919         return std::make_pair(0U, X86::FR64RegisterClass);
7920       // Vector types.
7921       case MVT::v16i8:
7922       case MVT::v8i16:
7923       case MVT::v4i32:
7924       case MVT::v2i64:
7925       case MVT::v4f32:
7926       case MVT::v2f64:
7927         return std::make_pair(0U, X86::VR128RegisterClass);
7928       }
7929       break;
7930     }
7931   }
7932   
7933   // Use the default implementation in TargetLowering to convert the register
7934   // constraint into a member of a register class.
7935   std::pair<unsigned, const TargetRegisterClass*> Res;
7936   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
7937
7938   // Not found as a standard register?
7939   if (Res.second == 0) {
7940     // GCC calls "st(0)" just plain "st".
7941     if (StringsEqualNoCase("{st}", Constraint)) {
7942       Res.first = X86::ST0;
7943       Res.second = X86::RFP80RegisterClass;
7944     }
7945     // 'A' means EAX + EDX.
7946     if (Constraint == "A") {
7947       Res.first = X86::EAX;
7948       Res.second = X86::GRADRegisterClass;
7949     }
7950     return Res;
7951   }
7952
7953   // Otherwise, check to see if this is a register class of the wrong value
7954   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
7955   // turn into {ax},{dx}.
7956   if (Res.second->hasType(VT))
7957     return Res;   // Correct type already, nothing to do.
7958
7959   // All of the single-register GCC register classes map their values onto
7960   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
7961   // really want an 8-bit or 32-bit register, map to the appropriate register
7962   // class and return the appropriate register.
7963   if (Res.second == X86::GR16RegisterClass) {
7964     if (VT == MVT::i8) {
7965       unsigned DestReg = 0;
7966       switch (Res.first) {
7967       default: break;
7968       case X86::AX: DestReg = X86::AL; break;
7969       case X86::DX: DestReg = X86::DL; break;
7970       case X86::CX: DestReg = X86::CL; break;
7971       case X86::BX: DestReg = X86::BL; break;
7972       }
7973       if (DestReg) {
7974         Res.first = DestReg;
7975         Res.second = Res.second = X86::GR8RegisterClass;
7976       }
7977     } else if (VT == MVT::i32) {
7978       unsigned DestReg = 0;
7979       switch (Res.first) {
7980       default: break;
7981       case X86::AX: DestReg = X86::EAX; break;
7982       case X86::DX: DestReg = X86::EDX; break;
7983       case X86::CX: DestReg = X86::ECX; break;
7984       case X86::BX: DestReg = X86::EBX; break;
7985       case X86::SI: DestReg = X86::ESI; break;
7986       case X86::DI: DestReg = X86::EDI; break;
7987       case X86::BP: DestReg = X86::EBP; break;
7988       case X86::SP: DestReg = X86::ESP; break;
7989       }
7990       if (DestReg) {
7991         Res.first = DestReg;
7992         Res.second = Res.second = X86::GR32RegisterClass;
7993       }
7994     } else if (VT == MVT::i64) {
7995       unsigned DestReg = 0;
7996       switch (Res.first) {
7997       default: break;
7998       case X86::AX: DestReg = X86::RAX; break;
7999       case X86::DX: DestReg = X86::RDX; break;
8000       case X86::CX: DestReg = X86::RCX; break;
8001       case X86::BX: DestReg = X86::RBX; break;
8002       case X86::SI: DestReg = X86::RSI; break;
8003       case X86::DI: DestReg = X86::RDI; break;
8004       case X86::BP: DestReg = X86::RBP; break;
8005       case X86::SP: DestReg = X86::RSP; break;
8006       }
8007       if (DestReg) {
8008         Res.first = DestReg;
8009         Res.second = Res.second = X86::GR64RegisterClass;
8010       }
8011     }
8012   } else if (Res.second == X86::FR32RegisterClass ||
8013              Res.second == X86::FR64RegisterClass ||
8014              Res.second == X86::VR128RegisterClass) {
8015     // Handle references to XMM physical registers that got mapped into the
8016     // wrong class.  This can happen with constraints like {xmm0} where the
8017     // target independent register mapper will just pick the first match it can
8018     // find, ignoring the required type.
8019     if (VT == MVT::f32)
8020       Res.second = X86::FR32RegisterClass;
8021     else if (VT == MVT::f64)
8022       Res.second = X86::FR64RegisterClass;
8023     else if (X86::VR128RegisterClass->hasType(VT))
8024       Res.second = X86::VR128RegisterClass;
8025   }
8026
8027   return Res;
8028 }
8029
8030 //===----------------------------------------------------------------------===//
8031 //                           X86 Widen vector type
8032 //===----------------------------------------------------------------------===//
8033
8034 /// getWidenVectorType: given a vector type, returns the type to widen
8035 /// to (e.g., v7i8 to v8i8). If the vector type is legal, it returns itself.
8036 /// If there is no vector type that we want to widen to, returns MVT::Other
8037 /// When and where to widen is target dependent based on the cost of
8038 /// scalarizing vs using the wider vector type.
8039
8040 MVT X86TargetLowering::getWidenVectorType(MVT VT) {
8041   assert(VT.isVector());
8042   if (isTypeLegal(VT))
8043     return VT;
8044   
8045   // TODO: In computeRegisterProperty, we can compute the list of legal vector
8046   //       type based on element type.  This would speed up our search (though
8047   //       it may not be worth it since the size of the list is relatively
8048   //       small).
8049   MVT EltVT = VT.getVectorElementType();
8050   unsigned NElts = VT.getVectorNumElements();
8051   
8052   // On X86, it make sense to widen any vector wider than 1
8053   if (NElts <= 1)
8054     return MVT::Other;
8055   
8056   for (unsigned nVT = MVT::FIRST_VECTOR_VALUETYPE; 
8057        nVT <= MVT::LAST_VECTOR_VALUETYPE; ++nVT) {
8058     MVT SVT = (MVT::SimpleValueType)nVT;
8059     
8060     if (isTypeLegal(SVT) && 
8061         SVT.getVectorElementType() == EltVT && 
8062         SVT.getVectorNumElements() > NElts)
8063       return SVT;
8064   }
8065   return MVT::Other;
8066 }