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