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