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