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