~40% faster vector shl <4 x i32> on SSE 4.1 Larger improvements for smaller types...
[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 #define DEBUG_TYPE "x86-isel"
16 #include "X86.h"
17 #include "X86InstrBuilder.h"
18 #include "X86ISelLowering.h"
19 #include "X86TargetMachine.h"
20 #include "X86TargetObjectFile.h"
21 #include "llvm/CallingConv.h"
22 #include "llvm/Constants.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/GlobalAlias.h"
25 #include "llvm/GlobalVariable.h"
26 #include "llvm/Function.h"
27 #include "llvm/Instructions.h"
28 #include "llvm/Intrinsics.h"
29 #include "llvm/LLVMContext.h"
30 #include "llvm/CodeGen/MachineFrameInfo.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineJumpTableInfo.h"
34 #include "llvm/CodeGen/MachineModuleInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/PseudoSourceValue.h"
37 #include "llvm/MC/MCAsmInfo.h"
38 #include "llvm/MC/MCContext.h"
39 #include "llvm/MC/MCExpr.h"
40 #include "llvm/MC/MCSymbol.h"
41 #include "llvm/ADT/BitVector.h"
42 #include "llvm/ADT/SmallSet.h"
43 #include "llvm/ADT/Statistic.h"
44 #include "llvm/ADT/StringExtras.h"
45 #include "llvm/ADT/VectorExtras.h"
46 #include "llvm/Support/CommandLine.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/Dwarf.h"
49 #include "llvm/Support/ErrorHandling.h"
50 #include "llvm/Support/MathExtras.h"
51 #include "llvm/Support/raw_ostream.h"
52 using namespace llvm;
53 using namespace dwarf;
54
55 STATISTIC(NumTailCalls, "Number of tail calls");
56
57 static cl::opt<bool>
58 DisableMMX("disable-mmx", cl::Hidden, cl::desc("Disable use of MMX"));
59
60 // Forward declarations.
61 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
62                        SDValue V2);
63
64 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
65   
66   bool is64Bit = TM.getSubtarget<X86Subtarget>().is64Bit();
67   
68   if (TM.getSubtarget<X86Subtarget>().isTargetDarwin()) {
69     if (is64Bit) return new X8664_MachoTargetObjectFile();
70     return new TargetLoweringObjectFileMachO();
71   } else if (TM.getSubtarget<X86Subtarget>().isTargetELF() ){
72     if (is64Bit) return new X8664_ELFTargetObjectFile(TM);
73     return new X8632_ELFTargetObjectFile(TM);
74   } else if (TM.getSubtarget<X86Subtarget>().isTargetCOFF()) {
75     return new TargetLoweringObjectFileCOFF();
76   }  
77   llvm_unreachable("unknown subtarget type");
78 }
79
80 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
81   : TargetLowering(TM, createTLOF(TM)) {
82   Subtarget = &TM.getSubtarget<X86Subtarget>();
83   X86ScalarSSEf64 = Subtarget->hasSSE2();
84   X86ScalarSSEf32 = Subtarget->hasSSE1();
85   X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
86
87   RegInfo = TM.getRegisterInfo();
88   TD = getTargetData();
89
90   // Set up the TargetLowering object.
91
92   // X86 is weird, it always uses i8 for shift amounts and setcc results.
93   setShiftAmountType(MVT::i8);
94   setBooleanContents(ZeroOrOneBooleanContent);
95   setSchedulingPreference(Sched::RegPressure);
96   setStackPointerRegisterToSaveRestore(X86StackPtr);
97
98   if (Subtarget->isTargetDarwin()) {
99     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
100     setUseUnderscoreSetJmp(false);
101     setUseUnderscoreLongJmp(false);
102   } else if (Subtarget->isTargetMingw()) {
103     // MS runtime is weird: it exports _setjmp, but longjmp!
104     setUseUnderscoreSetJmp(true);
105     setUseUnderscoreLongJmp(false);
106   } else {
107     setUseUnderscoreSetJmp(true);
108     setUseUnderscoreLongJmp(true);
109   }
110
111   // Set up the register classes.
112   addRegisterClass(MVT::i8, X86::GR8RegisterClass);
113   addRegisterClass(MVT::i16, X86::GR16RegisterClass);
114   addRegisterClass(MVT::i32, X86::GR32RegisterClass);
115   if (Subtarget->is64Bit())
116     addRegisterClass(MVT::i64, X86::GR64RegisterClass);
117
118   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
119
120   // We don't accept any truncstore of integer registers.
121   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
122   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
123   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
124   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
125   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
126   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
127
128   // SETOEQ and SETUNE require checking two conditions.
129   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
130   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
131   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
132   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
133   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
134   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
135
136   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
137   // operation.
138   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
139   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
140   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
141
142   if (Subtarget->is64Bit()) {
143     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
144     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Expand);
145   } else if (!UseSoftFloat) {
146     // We have an algorithm for SSE2->double, and we turn this into a
147     // 64-bit FILD followed by conditional FADD for other targets.
148     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
149     // We have an algorithm for SSE2, and we turn this into a 64-bit
150     // FILD for other targets.
151     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
152   }
153
154   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
155   // this operation.
156   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
157   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
158
159   if (!UseSoftFloat) {
160     // SSE has no i16 to fp conversion, only i32
161     if (X86ScalarSSEf32) {
162       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
163       // f32 and f64 cases are Legal, f80 case is not
164       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
165     } else {
166       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
167       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
168     }
169   } else {
170     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
171     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
172   }
173
174   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
175   // are Legal, f80 is custom lowered.
176   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
177   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
178
179   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
180   // this operation.
181   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
182   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
183
184   if (X86ScalarSSEf32) {
185     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
186     // f32 and f64 cases are Legal, f80 case is not
187     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
188   } else {
189     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
190     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
191   }
192
193   // Handle FP_TO_UINT by promoting the destination to a larger signed
194   // conversion.
195   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
196   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
197   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
198
199   if (Subtarget->is64Bit()) {
200     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
201     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
202   } else if (!UseSoftFloat) {
203     if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
204       // Expand FP_TO_UINT into a select.
205       // FIXME: We would like to use a Custom expander here eventually to do
206       // the optimal thing for SSE vs. the default expansion in the legalizer.
207       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
208     else
209       // With SSE3 we can use fisttpll to convert to a signed i64; without
210       // SSE, we're stuck with a fistpll.
211       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
212   }
213
214   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
215   if (!X86ScalarSSEf64) { 
216     setOperationAction(ISD::BIT_CONVERT      , MVT::f32  , Expand);
217     setOperationAction(ISD::BIT_CONVERT      , MVT::i32  , Expand);
218     if (Subtarget->is64Bit()) {
219       setOperationAction(ISD::BIT_CONVERT    , MVT::f64  , Expand);
220       // Without SSE, i64->f64 goes through memory; i64->MMX is Legal.
221       if (Subtarget->hasMMX() && !DisableMMX)
222         setOperationAction(ISD::BIT_CONVERT    , MVT::i64  , Custom);
223       else 
224         setOperationAction(ISD::BIT_CONVERT    , MVT::i64  , Expand);
225     }
226   }
227
228   // Scalar integer divide and remainder are lowered to use operations that
229   // produce two results, to match the available instructions. This exposes
230   // the two-result form to trivial CSE, which is able to combine x/y and x%y
231   // into a single instruction.
232   //
233   // Scalar integer multiply-high is also lowered to use two-result
234   // operations, to match the available instructions. However, plain multiply
235   // (low) operations are left as Legal, as there are single-result
236   // instructions for this in x86. Using the two-result multiply instructions
237   // when both high and low results are needed must be arranged by dagcombine.
238   setOperationAction(ISD::MULHS           , MVT::i8    , Expand);
239   setOperationAction(ISD::MULHU           , MVT::i8    , Expand);
240   setOperationAction(ISD::SDIV            , MVT::i8    , Expand);
241   setOperationAction(ISD::UDIV            , MVT::i8    , Expand);
242   setOperationAction(ISD::SREM            , MVT::i8    , Expand);
243   setOperationAction(ISD::UREM            , MVT::i8    , Expand);
244   setOperationAction(ISD::MULHS           , MVT::i16   , Expand);
245   setOperationAction(ISD::MULHU           , MVT::i16   , Expand);
246   setOperationAction(ISD::SDIV            , MVT::i16   , Expand);
247   setOperationAction(ISD::UDIV            , MVT::i16   , Expand);
248   setOperationAction(ISD::SREM            , MVT::i16   , Expand);
249   setOperationAction(ISD::UREM            , MVT::i16   , Expand);
250   setOperationAction(ISD::MULHS           , MVT::i32   , Expand);
251   setOperationAction(ISD::MULHU           , MVT::i32   , Expand);
252   setOperationAction(ISD::SDIV            , MVT::i32   , Expand);
253   setOperationAction(ISD::UDIV            , MVT::i32   , Expand);
254   setOperationAction(ISD::SREM            , MVT::i32   , Expand);
255   setOperationAction(ISD::UREM            , MVT::i32   , Expand);
256   setOperationAction(ISD::MULHS           , MVT::i64   , Expand);
257   setOperationAction(ISD::MULHU           , MVT::i64   , Expand);
258   setOperationAction(ISD::SDIV            , MVT::i64   , Expand);
259   setOperationAction(ISD::UDIV            , MVT::i64   , Expand);
260   setOperationAction(ISD::SREM            , MVT::i64   , Expand);
261   setOperationAction(ISD::UREM            , MVT::i64   , Expand);
262
263   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
264   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
265   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
266   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
267   if (Subtarget->is64Bit())
268     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
269   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
270   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
271   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
272   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
273   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
274   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
275   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
276   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
277
278   setOperationAction(ISD::CTPOP            , MVT::i8   , Expand);
279   setOperationAction(ISD::CTTZ             , MVT::i8   , Custom);
280   setOperationAction(ISD::CTLZ             , MVT::i8   , Custom);
281   setOperationAction(ISD::CTPOP            , MVT::i16  , Expand);
282   setOperationAction(ISD::CTTZ             , MVT::i16  , Custom);
283   setOperationAction(ISD::CTLZ             , MVT::i16  , Custom);
284   setOperationAction(ISD::CTPOP            , MVT::i32  , Expand);
285   setOperationAction(ISD::CTTZ             , MVT::i32  , Custom);
286   setOperationAction(ISD::CTLZ             , MVT::i32  , Custom);
287   if (Subtarget->is64Bit()) {
288     setOperationAction(ISD::CTPOP          , MVT::i64  , Expand);
289     setOperationAction(ISD::CTTZ           , MVT::i64  , Custom);
290     setOperationAction(ISD::CTLZ           , MVT::i64  , Custom);
291   }
292
293   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
294   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
295
296   // These should be promoted to a larger select which is supported.
297   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
298   // X86 wants to expand cmov itself.
299   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
300   setOperationAction(ISD::SELECT        , MVT::i16  , Custom);
301   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
302   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
303   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
304   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
305   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
306   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
307   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
308   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
309   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
310   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
311   if (Subtarget->is64Bit()) {
312     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
313     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
314   }
315   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
316
317   // Darwin ABI issue.
318   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
319   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
320   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
321   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
322   if (Subtarget->is64Bit())
323     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
324   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
325   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
326   if (Subtarget->is64Bit()) {
327     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
328     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
329     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
330     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
331     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
332   }
333   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
334   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
335   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
336   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
337   if (Subtarget->is64Bit()) {
338     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
339     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
340     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
341   }
342
343   if (Subtarget->hasSSE1())
344     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
345
346   // We may not have a libcall for MEMBARRIER so we should lower this.
347   setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
348   
349   // On X86 and X86-64, atomic operations are lowered to locked instructions.
350   // Locked instructions, in turn, have implicit fence semantics (all memory
351   // operations are flushed before issuing the locked instruction, and they
352   // are not buffered), so we can fold away the common pattern of
353   // fence-atomic-fence.
354   setShouldFoldAtomicFences(true);
355
356   // Expand certain atomics
357   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i8, Custom);
358   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i16, Custom);
359   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
360   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
361
362   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i8, Custom);
363   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i16, Custom);
364   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
365   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
366
367   if (!Subtarget->is64Bit()) {
368     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
369     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
370     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
371     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
372     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
373     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
374     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
375   }
376
377   // FIXME - use subtarget debug flags
378   if (!Subtarget->isTargetDarwin() &&
379       !Subtarget->isTargetELF() &&
380       !Subtarget->isTargetCygMing()) {
381     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
382   }
383
384   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
385   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
386   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
387   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
388   if (Subtarget->is64Bit()) {
389     setExceptionPointerRegister(X86::RAX);
390     setExceptionSelectorRegister(X86::RDX);
391   } else {
392     setExceptionPointerRegister(X86::EAX);
393     setExceptionSelectorRegister(X86::EDX);
394   }
395   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
396   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
397
398   setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
399
400   setOperationAction(ISD::TRAP, MVT::Other, Legal);
401
402   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
403   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
404   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
405   if (Subtarget->is64Bit()) {
406     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
407     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
408   } else {
409     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
410     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
411   }
412
413   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
414   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
415   if (Subtarget->is64Bit())
416     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
417   if (Subtarget->isTargetCygMing())
418     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
419   else
420     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
421
422   if (!UseSoftFloat && X86ScalarSSEf64) {
423     // f32 and f64 use SSE.
424     // Set up the FP register classes.
425     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
426     addRegisterClass(MVT::f64, X86::FR64RegisterClass);
427
428     // Use ANDPD to simulate FABS.
429     setOperationAction(ISD::FABS , MVT::f64, Custom);
430     setOperationAction(ISD::FABS , MVT::f32, Custom);
431
432     // Use XORP to simulate FNEG.
433     setOperationAction(ISD::FNEG , MVT::f64, Custom);
434     setOperationAction(ISD::FNEG , MVT::f32, Custom);
435
436     // Use ANDPD and ORPD to simulate FCOPYSIGN.
437     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
438     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
439
440     // We don't support sin/cos/fmod
441     setOperationAction(ISD::FSIN , MVT::f64, Expand);
442     setOperationAction(ISD::FCOS , MVT::f64, Expand);
443     setOperationAction(ISD::FSIN , MVT::f32, Expand);
444     setOperationAction(ISD::FCOS , MVT::f32, Expand);
445
446     // Expand FP immediates into loads from the stack, except for the special
447     // cases we handle.
448     addLegalFPImmediate(APFloat(+0.0)); // xorpd
449     addLegalFPImmediate(APFloat(+0.0f)); // xorps
450   } else if (!UseSoftFloat && X86ScalarSSEf32) {
451     // Use SSE for f32, x87 for f64.
452     // Set up the FP register classes.
453     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
454     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
455
456     // Use ANDPS to simulate FABS.
457     setOperationAction(ISD::FABS , MVT::f32, Custom);
458
459     // Use XORP to simulate FNEG.
460     setOperationAction(ISD::FNEG , MVT::f32, Custom);
461
462     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
463
464     // Use ANDPS and ORPS to simulate FCOPYSIGN.
465     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
466     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
467
468     // We don't support sin/cos/fmod
469     setOperationAction(ISD::FSIN , MVT::f32, Expand);
470     setOperationAction(ISD::FCOS , MVT::f32, Expand);
471
472     // Special cases we handle for FP constants.
473     addLegalFPImmediate(APFloat(+0.0f)); // xorps
474     addLegalFPImmediate(APFloat(+0.0)); // FLD0
475     addLegalFPImmediate(APFloat(+1.0)); // FLD1
476     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
477     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
478
479     if (!UnsafeFPMath) {
480       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
481       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
482     }
483   } else if (!UseSoftFloat) {
484     // f32 and f64 in x87.
485     // Set up the FP register classes.
486     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
487     addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
488
489     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
490     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
491     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
492     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
493
494     if (!UnsafeFPMath) {
495       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
496       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
497     }
498     addLegalFPImmediate(APFloat(+0.0)); // FLD0
499     addLegalFPImmediate(APFloat(+1.0)); // FLD1
500     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
501     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
502     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
503     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
504     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
505     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
506   }
507
508   // Long double always uses X87.
509   if (!UseSoftFloat) {
510     addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
511     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
512     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
513     {
514       bool ignored;
515       APFloat TmpFlt(+0.0);
516       TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
517                      &ignored);
518       addLegalFPImmediate(TmpFlt);  // FLD0
519       TmpFlt.changeSign();
520       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
521       APFloat TmpFlt2(+1.0);
522       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
523                       &ignored);
524       addLegalFPImmediate(TmpFlt2);  // FLD1
525       TmpFlt2.changeSign();
526       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
527     }
528
529     if (!UnsafeFPMath) {
530       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
531       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
532     }
533   }
534
535   // Always use a library call for pow.
536   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
537   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
538   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
539
540   setOperationAction(ISD::FLOG, MVT::f80, Expand);
541   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
542   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
543   setOperationAction(ISD::FEXP, MVT::f80, Expand);
544   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
545
546   // First set operation action for all vector types to either promote
547   // (for widening) or expand (for scalarization). Then we will selectively
548   // turn on ones that can be effectively codegen'd.
549   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
550        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
551     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
552     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
553     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
554     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
555     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
556     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
557     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
558     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
559     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
560     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
561     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
562     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
563     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
564     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
565     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
566     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
567     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
568     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
569     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
570     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
571     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
572     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
573     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
574     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
575     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
576     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
577     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
578     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
579     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
580     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
581     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
582     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
583     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
584     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
585     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
586     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
587     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
588     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
589     setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
590     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
591     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
592     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
593     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
594     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
595     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
596     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
597     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
598     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
599     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
600     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
601     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
602     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
603     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
604     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
605          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
606       setTruncStoreAction((MVT::SimpleValueType)VT,
607                           (MVT::SimpleValueType)InnerVT, Expand);
608     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
609     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
610     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
611   }
612
613   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
614   // with -msoft-float, disable use of MMX as well.
615   if (!UseSoftFloat && !DisableMMX && Subtarget->hasMMX()) {
616     addRegisterClass(MVT::v8i8,  X86::VR64RegisterClass, false);
617     addRegisterClass(MVT::v4i16, X86::VR64RegisterClass, false);
618     addRegisterClass(MVT::v2i32, X86::VR64RegisterClass, false);
619     
620     addRegisterClass(MVT::v1i64, X86::VR64RegisterClass, false);
621
622     setOperationAction(ISD::ADD,                MVT::v8i8,  Legal);
623     setOperationAction(ISD::ADD,                MVT::v4i16, Legal);
624     setOperationAction(ISD::ADD,                MVT::v2i32, Legal);
625     setOperationAction(ISD::ADD,                MVT::v1i64, Legal);
626
627     setOperationAction(ISD::SUB,                MVT::v8i8,  Legal);
628     setOperationAction(ISD::SUB,                MVT::v4i16, Legal);
629     setOperationAction(ISD::SUB,                MVT::v2i32, Legal);
630     setOperationAction(ISD::SUB,                MVT::v1i64, Legal);
631
632     setOperationAction(ISD::MULHS,              MVT::v4i16, Legal);
633     setOperationAction(ISD::MUL,                MVT::v4i16, Legal);
634
635     setOperationAction(ISD::AND,                MVT::v8i8,  Promote);
636     AddPromotedToType (ISD::AND,                MVT::v8i8,  MVT::v1i64);
637     setOperationAction(ISD::AND,                MVT::v4i16, Promote);
638     AddPromotedToType (ISD::AND,                MVT::v4i16, MVT::v1i64);
639     setOperationAction(ISD::AND,                MVT::v2i32, Promote);
640     AddPromotedToType (ISD::AND,                MVT::v2i32, MVT::v1i64);
641     setOperationAction(ISD::AND,                MVT::v1i64, Legal);
642
643     setOperationAction(ISD::OR,                 MVT::v8i8,  Promote);
644     AddPromotedToType (ISD::OR,                 MVT::v8i8,  MVT::v1i64);
645     setOperationAction(ISD::OR,                 MVT::v4i16, Promote);
646     AddPromotedToType (ISD::OR,                 MVT::v4i16, MVT::v1i64);
647     setOperationAction(ISD::OR,                 MVT::v2i32, Promote);
648     AddPromotedToType (ISD::OR,                 MVT::v2i32, MVT::v1i64);
649     setOperationAction(ISD::OR,                 MVT::v1i64, Legal);
650
651     setOperationAction(ISD::XOR,                MVT::v8i8,  Promote);
652     AddPromotedToType (ISD::XOR,                MVT::v8i8,  MVT::v1i64);
653     setOperationAction(ISD::XOR,                MVT::v4i16, Promote);
654     AddPromotedToType (ISD::XOR,                MVT::v4i16, MVT::v1i64);
655     setOperationAction(ISD::XOR,                MVT::v2i32, Promote);
656     AddPromotedToType (ISD::XOR,                MVT::v2i32, MVT::v1i64);
657     setOperationAction(ISD::XOR,                MVT::v1i64, Legal);
658
659     setOperationAction(ISD::LOAD,               MVT::v8i8,  Promote);
660     AddPromotedToType (ISD::LOAD,               MVT::v8i8,  MVT::v1i64);
661     setOperationAction(ISD::LOAD,               MVT::v4i16, Promote);
662     AddPromotedToType (ISD::LOAD,               MVT::v4i16, MVT::v1i64);
663     setOperationAction(ISD::LOAD,               MVT::v2i32, Promote);
664     AddPromotedToType (ISD::LOAD,               MVT::v2i32, MVT::v1i64);
665     setOperationAction(ISD::LOAD,               MVT::v1i64, Legal);
666
667     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i8,  Custom);
668     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i16, Custom);
669     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i32, Custom);
670     setOperationAction(ISD::BUILD_VECTOR,       MVT::v1i64, Custom);
671
672     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8i8,  Custom);
673     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i16, Custom);
674     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i32, Custom);
675     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v1i64, Custom);
676
677     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Custom);
678     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Custom);
679     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Custom);
680
681     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i16, Custom);
682
683     setOperationAction(ISD::SELECT,             MVT::v8i8, Promote);
684     setOperationAction(ISD::SELECT,             MVT::v4i16, Promote);
685     setOperationAction(ISD::SELECT,             MVT::v2i32, Promote);
686     setOperationAction(ISD::SELECT,             MVT::v1i64, Custom);
687     setOperationAction(ISD::VSETCC,             MVT::v8i8, Custom);
688     setOperationAction(ISD::VSETCC,             MVT::v4i16, Custom);
689     setOperationAction(ISD::VSETCC,             MVT::v2i32, Custom);
690
691     if (!X86ScalarSSEf64 && Subtarget->is64Bit()) {
692       setOperationAction(ISD::BIT_CONVERT,        MVT::v8i8,  Custom);
693       setOperationAction(ISD::BIT_CONVERT,        MVT::v4i16, Custom);
694       setOperationAction(ISD::BIT_CONVERT,        MVT::v2i32, Custom);
695       setOperationAction(ISD::BIT_CONVERT,        MVT::v1i64, Custom);
696     }
697   }
698
699   if (!UseSoftFloat && Subtarget->hasSSE1()) {
700     addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
701
702     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
703     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
704     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
705     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
706     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
707     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
708     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
709     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
710     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
711     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
712     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
713     setOperationAction(ISD::VSETCC,             MVT::v4f32, Custom);
714   }
715
716   if (!UseSoftFloat && Subtarget->hasSSE2()) {
717     addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
718
719     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
720     // registers cannot be used even for integer operations.
721     addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
722     addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
723     addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
724     addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
725
726     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
727     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
728     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
729     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
730     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
731     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
732     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
733     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
734     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
735     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
736     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
737     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
738     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
739     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
740     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
741     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
742
743     setOperationAction(ISD::VSETCC,             MVT::v2f64, Custom);
744     setOperationAction(ISD::VSETCC,             MVT::v16i8, Custom);
745     setOperationAction(ISD::VSETCC,             MVT::v8i16, Custom);
746     setOperationAction(ISD::VSETCC,             MVT::v4i32, Custom);
747
748     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
749     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
750     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
751     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
752     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
753
754     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2f64, Custom);
755     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2i64, Custom);
756     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i8, Custom);
757     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i16, Custom);
758     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i32, Custom);
759
760     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
761     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
762       EVT VT = (MVT::SimpleValueType)i;
763       // Do not attempt to custom lower non-power-of-2 vectors
764       if (!isPowerOf2_32(VT.getVectorNumElements()))
765         continue;
766       // Do not attempt to custom lower non-128-bit vectors
767       if (!VT.is128BitVector())
768         continue;
769       setOperationAction(ISD::BUILD_VECTOR,
770                          VT.getSimpleVT().SimpleTy, Custom);
771       setOperationAction(ISD::VECTOR_SHUFFLE,
772                          VT.getSimpleVT().SimpleTy, Custom);
773       setOperationAction(ISD::EXTRACT_VECTOR_ELT,
774                          VT.getSimpleVT().SimpleTy, Custom);
775     }
776
777     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
778     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
779     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
780     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
781     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
782     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
783
784     if (Subtarget->is64Bit()) {
785       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
786       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
787     }
788
789     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
790     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
791       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
792       EVT VT = SVT;
793
794       // Do not attempt to promote non-128-bit vectors
795       if (!VT.is128BitVector())
796         continue;
797       
798       setOperationAction(ISD::AND,    SVT, Promote);
799       AddPromotedToType (ISD::AND,    SVT, MVT::v2i64);
800       setOperationAction(ISD::OR,     SVT, Promote);
801       AddPromotedToType (ISD::OR,     SVT, MVT::v2i64);
802       setOperationAction(ISD::XOR,    SVT, Promote);
803       AddPromotedToType (ISD::XOR,    SVT, MVT::v2i64);
804       setOperationAction(ISD::LOAD,   SVT, Promote);
805       AddPromotedToType (ISD::LOAD,   SVT, MVT::v2i64);
806       setOperationAction(ISD::SELECT, SVT, Promote);
807       AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
808     }
809
810     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
811
812     // Custom lower v2i64 and v2f64 selects.
813     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
814     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
815     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
816     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
817
818     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
819     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
820     if (!DisableMMX && Subtarget->hasMMX()) {
821       setOperationAction(ISD::FP_TO_SINT,         MVT::v2i32, Custom);
822       setOperationAction(ISD::SINT_TO_FP,         MVT::v2i32, Custom);
823     }
824   }
825
826   if (Subtarget->hasSSE41()) {
827     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
828     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
829     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
830     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
831     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
832     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
833     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
834     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
835     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
836     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
837
838     // FIXME: Do we need to handle scalar-to-vector here?
839     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
840
841     // Can turn SHL into an integer multiply.
842     setOperationAction(ISD::SHL,                MVT::v4i32, Custom);
843
844     // i8 and i16 vectors are custom , because the source register and source
845     // source memory operand types are not the same width.  f32 vectors are
846     // custom since the immediate controlling the insert encodes additional
847     // information.
848     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
849     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
850     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
851     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
852
853     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
854     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
855     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
856     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
857
858     if (Subtarget->is64Bit()) {
859       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Legal);
860       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
861     }
862   }
863
864   if (Subtarget->hasSSE42()) {
865     setOperationAction(ISD::VSETCC,             MVT::v2i64, Custom);
866   }
867
868   if (!UseSoftFloat && Subtarget->hasAVX()) {
869     addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
870     addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
871     addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
872     addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
873
874     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
875     setOperationAction(ISD::LOAD,               MVT::v8i32, Legal);
876     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
877     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
878     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
879     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
880     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
881     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
882     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
883     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
884     //setOperationAction(ISD::BUILD_VECTOR,       MVT::v8f32, Custom);
885     //setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8f32, Custom);
886     //setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8f32, Custom);
887     //setOperationAction(ISD::SELECT,             MVT::v8f32, Custom);
888     //setOperationAction(ISD::VSETCC,             MVT::v8f32, Custom);
889
890     // Operations to consider commented out -v16i16 v32i8
891     //setOperationAction(ISD::ADD,                MVT::v16i16, Legal);
892     setOperationAction(ISD::ADD,                MVT::v8i32, Custom);
893     setOperationAction(ISD::ADD,                MVT::v4i64, Custom);
894     //setOperationAction(ISD::SUB,                MVT::v32i8, Legal);
895     //setOperationAction(ISD::SUB,                MVT::v16i16, Legal);
896     setOperationAction(ISD::SUB,                MVT::v8i32, Custom);
897     setOperationAction(ISD::SUB,                MVT::v4i64, Custom);
898     //setOperationAction(ISD::MUL,                MVT::v16i16, Legal);
899     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
900     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
901     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
902     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
903     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
904     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
905
906     setOperationAction(ISD::VSETCC,             MVT::v4f64, Custom);
907     // setOperationAction(ISD::VSETCC,             MVT::v32i8, Custom);
908     // setOperationAction(ISD::VSETCC,             MVT::v16i16, Custom);
909     setOperationAction(ISD::VSETCC,             MVT::v8i32, Custom);
910
911     // setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v32i8, Custom);
912     // setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i16, Custom);
913     // setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i16, Custom);
914     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i32, Custom);
915     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8f32, Custom);
916
917     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f64, Custom);
918     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i64, Custom);
919     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f64, Custom);
920     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i64, Custom);
921     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f64, Custom);
922     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f64, Custom);
923
924 #if 0
925     // Not sure we want to do this since there are no 256-bit integer
926     // operations in AVX
927
928     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
929     // This includes 256-bit vectors
930     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; ++i) {
931       EVT VT = (MVT::SimpleValueType)i;
932
933       // Do not attempt to custom lower non-power-of-2 vectors
934       if (!isPowerOf2_32(VT.getVectorNumElements()))
935         continue;
936
937       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
938       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
939       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
940     }
941
942     if (Subtarget->is64Bit()) {
943       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i64, Custom);
944       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i64, Custom);
945     }
946 #endif
947
948 #if 0
949     // Not sure we want to do this since there are no 256-bit integer
950     // operations in AVX
951
952     // Promote v32i8, v16i16, v8i32 load, select, and, or, xor to v4i64.
953     // Including 256-bit vectors
954     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; i++) {
955       EVT VT = (MVT::SimpleValueType)i;
956
957       if (!VT.is256BitVector()) {
958         continue;
959       }
960       setOperationAction(ISD::AND,    VT, Promote);
961       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
962       setOperationAction(ISD::OR,     VT, Promote);
963       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
964       setOperationAction(ISD::XOR,    VT, Promote);
965       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
966       setOperationAction(ISD::LOAD,   VT, Promote);
967       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
968       setOperationAction(ISD::SELECT, VT, Promote);
969       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
970     }
971
972     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
973 #endif
974   }
975
976   // We want to custom lower some of our intrinsics.
977   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
978
979   // Add/Sub/Mul with overflow operations are custom lowered.
980   setOperationAction(ISD::SADDO, MVT::i32, Custom);
981   setOperationAction(ISD::UADDO, MVT::i32, Custom);
982   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
983   setOperationAction(ISD::USUBO, MVT::i32, Custom);
984   setOperationAction(ISD::SMULO, MVT::i32, Custom);
985
986   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
987   // handle type legalization for these operations here.
988   //
989   // FIXME: We really should do custom legalization for addition and
990   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
991   // than generic legalization for 64-bit multiplication-with-overflow, though.
992   if (Subtarget->is64Bit()) {
993     setOperationAction(ISD::SADDO, MVT::i64, Custom);
994     setOperationAction(ISD::UADDO, MVT::i64, Custom);
995     setOperationAction(ISD::SSUBO, MVT::i64, Custom);
996     setOperationAction(ISD::USUBO, MVT::i64, Custom);
997     setOperationAction(ISD::SMULO, MVT::i64, Custom);
998   }
999
1000   if (!Subtarget->is64Bit()) {
1001     // These libcalls are not available in 32-bit.
1002     setLibcallName(RTLIB::SHL_I128, 0);
1003     setLibcallName(RTLIB::SRL_I128, 0);
1004     setLibcallName(RTLIB::SRA_I128, 0);
1005   }
1006
1007   // We have target-specific dag combine patterns for the following nodes:
1008   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1009   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1010   setTargetDAGCombine(ISD::BUILD_VECTOR);
1011   setTargetDAGCombine(ISD::SELECT);
1012   setTargetDAGCombine(ISD::SHL);
1013   setTargetDAGCombine(ISD::SRA);
1014   setTargetDAGCombine(ISD::SRL);
1015   setTargetDAGCombine(ISD::OR);
1016   setTargetDAGCombine(ISD::STORE);
1017   setTargetDAGCombine(ISD::ZERO_EXTEND);
1018   if (Subtarget->is64Bit())
1019     setTargetDAGCombine(ISD::MUL);
1020
1021   computeRegisterProperties();
1022
1023   // FIXME: These should be based on subtarget info. Plus, the values should
1024   // be smaller when we are in optimizing for size mode.
1025   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1026   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1027   maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
1028   setPrefLoopAlignment(16);
1029   benefitFromCodePlacementOpt = true;
1030 }
1031
1032
1033 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
1034   return MVT::i8;
1035 }
1036
1037
1038 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1039 /// the desired ByVal argument alignment.
1040 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
1041   if (MaxAlign == 16)
1042     return;
1043   if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1044     if (VTy->getBitWidth() == 128)
1045       MaxAlign = 16;
1046   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1047     unsigned EltAlign = 0;
1048     getMaxByValAlign(ATy->getElementType(), EltAlign);
1049     if (EltAlign > MaxAlign)
1050       MaxAlign = EltAlign;
1051   } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1052     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1053       unsigned EltAlign = 0;
1054       getMaxByValAlign(STy->getElementType(i), EltAlign);
1055       if (EltAlign > MaxAlign)
1056         MaxAlign = EltAlign;
1057       if (MaxAlign == 16)
1058         break;
1059     }
1060   }
1061   return;
1062 }
1063
1064 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1065 /// function arguments in the caller parameter area. For X86, aggregates
1066 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1067 /// are at 4-byte boundaries.
1068 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1069   if (Subtarget->is64Bit()) {
1070     // Max of 8 and alignment of type.
1071     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1072     if (TyAlign > 8)
1073       return TyAlign;
1074     return 8;
1075   }
1076
1077   unsigned Align = 4;
1078   if (Subtarget->hasSSE1())
1079     getMaxByValAlign(Ty, Align);
1080   return Align;
1081 }
1082
1083 /// getOptimalMemOpType - Returns the target specific optimal type for load
1084 /// and store operations as a result of memset, memcpy, and memmove
1085 /// lowering. If DstAlign is zero that means it's safe to destination
1086 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1087 /// means there isn't a need to check it against alignment requirement,
1088 /// probably because the source does not need to be loaded. If
1089 /// 'NonScalarIntSafe' is true, that means it's safe to return a
1090 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1091 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1092 /// constant so it does not need to be loaded.
1093 /// It returns EVT::Other if the type should be determined using generic
1094 /// target-independent logic.
1095 EVT
1096 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1097                                        unsigned DstAlign, unsigned SrcAlign,
1098                                        bool NonScalarIntSafe,
1099                                        bool MemcpyStrSrc,
1100                                        MachineFunction &MF) const {
1101   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1102   // linux.  This is because the stack realignment code can't handle certain
1103   // cases like PR2962.  This should be removed when PR2962 is fixed.
1104   const Function *F = MF.getFunction();
1105   if (NonScalarIntSafe &&
1106       !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1107     if (Size >= 16 &&
1108         (Subtarget->isUnalignedMemAccessFast() ||
1109          ((DstAlign == 0 || DstAlign >= 16) &&
1110           (SrcAlign == 0 || SrcAlign >= 16))) &&
1111         Subtarget->getStackAlignment() >= 16) {
1112       if (Subtarget->hasSSE2())
1113         return MVT::v4i32;
1114       if (Subtarget->hasSSE1())
1115         return MVT::v4f32;
1116     } else if (!MemcpyStrSrc && Size >= 8 &&
1117                !Subtarget->is64Bit() &&
1118                Subtarget->getStackAlignment() >= 8 &&
1119                Subtarget->hasSSE2()) {
1120       // Do not use f64 to lower memcpy if source is string constant. It's
1121       // better to use i32 to avoid the loads.
1122       return MVT::f64;
1123     }
1124   }
1125   if (Subtarget->is64Bit() && Size >= 8)
1126     return MVT::i64;
1127   return MVT::i32;
1128 }
1129
1130 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1131 /// current function.  The returned value is a member of the
1132 /// MachineJumpTableInfo::JTEntryKind enum.
1133 unsigned X86TargetLowering::getJumpTableEncoding() const {
1134   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1135   // symbol.
1136   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1137       Subtarget->isPICStyleGOT())
1138     return MachineJumpTableInfo::EK_Custom32;
1139   
1140   // Otherwise, use the normal jump table encoding heuristics.
1141   return TargetLowering::getJumpTableEncoding();
1142 }
1143
1144 /// getPICBaseSymbol - Return the X86-32 PIC base.
1145 MCSymbol *
1146 X86TargetLowering::getPICBaseSymbol(const MachineFunction *MF,
1147                                     MCContext &Ctx) const {
1148   const MCAsmInfo &MAI = *getTargetMachine().getMCAsmInfo();
1149   return Ctx.GetOrCreateSymbol(Twine(MAI.getPrivateGlobalPrefix())+
1150                                Twine(MF->getFunctionNumber())+"$pb");
1151 }
1152
1153
1154 const MCExpr *
1155 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1156                                              const MachineBasicBlock *MBB,
1157                                              unsigned uid,MCContext &Ctx) const{
1158   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1159          Subtarget->isPICStyleGOT());
1160   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1161   // entries.
1162   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1163                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1164 }
1165
1166 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1167 /// jumptable.
1168 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1169                                                     SelectionDAG &DAG) const {
1170   if (!Subtarget->is64Bit())
1171     // This doesn't have DebugLoc associated with it, but is not really the
1172     // same as a Register.
1173     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1174   return Table;
1175 }
1176
1177 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1178 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1179 /// MCExpr.
1180 const MCExpr *X86TargetLowering::
1181 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1182                              MCContext &Ctx) const {
1183   // X86-64 uses RIP relative addressing based on the jump table label.
1184   if (Subtarget->isPICStyleRIPRel())
1185     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1186
1187   // Otherwise, the reference is relative to the PIC base.
1188   return MCSymbolRefExpr::Create(getPICBaseSymbol(MF, Ctx), Ctx);
1189 }
1190
1191 /// getFunctionAlignment - Return the Log2 alignment of this function.
1192 unsigned X86TargetLowering::getFunctionAlignment(const Function *F) const {
1193   return F->hasFnAttr(Attribute::OptimizeForSize) ? 0 : 4;
1194 }
1195
1196 std::pair<const TargetRegisterClass*, uint8_t>
1197 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1198   const TargetRegisterClass *RRC = 0;
1199   uint8_t Cost = 1;
1200   switch (VT.getSimpleVT().SimpleTy) {
1201   default:
1202     return TargetLowering::findRepresentativeClass(VT);
1203   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1204     RRC = (Subtarget->is64Bit()
1205            ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1206     break;
1207   case MVT::v8i8: case MVT::v4i16:
1208   case MVT::v2i32: case MVT::v1i64: 
1209     RRC = X86::VR64RegisterClass;
1210     break;
1211   case MVT::f32: case MVT::f64:
1212   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1213   case MVT::v4f32: case MVT::v2f64:
1214   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1215   case MVT::v4f64:
1216     RRC = X86::VR128RegisterClass;
1217     break;
1218   }
1219   return std::make_pair(RRC, Cost);
1220 }
1221
1222 unsigned
1223 X86TargetLowering::getRegPressureLimit(const TargetRegisterClass *RC,
1224                                        MachineFunction &MF) const {
1225   unsigned FPDiff = RegInfo->hasFP(MF) ? 1 : 0;
1226   switch (RC->getID()) {
1227   default:
1228     return 0;
1229   case X86::GR32RegClassID:
1230     return 4 - FPDiff;
1231   case X86::GR64RegClassID:
1232     return 8 - FPDiff;
1233   case X86::VR128RegClassID:
1234     return Subtarget->is64Bit() ? 10 : 4;
1235   case X86::VR64RegClassID:
1236     return 4;
1237   }
1238 }
1239
1240 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1241                                                unsigned &Offset) const {
1242   if (!Subtarget->isTargetLinux())
1243     return false;
1244
1245   if (Subtarget->is64Bit()) {
1246     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1247     Offset = 0x28;
1248     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1249       AddressSpace = 256;
1250     else
1251       AddressSpace = 257;
1252   } else {
1253     // %gs:0x14 on i386
1254     Offset = 0x14;
1255     AddressSpace = 256;
1256   }
1257   return true;
1258 }
1259
1260
1261 //===----------------------------------------------------------------------===//
1262 //               Return Value Calling Convention Implementation
1263 //===----------------------------------------------------------------------===//
1264
1265 #include "X86GenCallingConv.inc"
1266
1267 bool 
1268 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv, bool isVarArg,
1269                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1270                         LLVMContext &Context) const {
1271   SmallVector<CCValAssign, 16> RVLocs;
1272   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1273                  RVLocs, Context);
1274   return CCInfo.CheckReturn(Outs, RetCC_X86);
1275 }
1276
1277 SDValue
1278 X86TargetLowering::LowerReturn(SDValue Chain,
1279                                CallingConv::ID CallConv, bool isVarArg,
1280                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1281                                const SmallVectorImpl<SDValue> &OutVals,
1282                                DebugLoc dl, SelectionDAG &DAG) const {
1283   MachineFunction &MF = DAG.getMachineFunction();
1284   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1285
1286   SmallVector<CCValAssign, 16> RVLocs;
1287   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1288                  RVLocs, *DAG.getContext());
1289   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1290
1291   // Add the regs to the liveout set for the function.
1292   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1293   for (unsigned i = 0; i != RVLocs.size(); ++i)
1294     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1295       MRI.addLiveOut(RVLocs[i].getLocReg());
1296
1297   SDValue Flag;
1298
1299   SmallVector<SDValue, 6> RetOps;
1300   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1301   // Operand #1 = Bytes To Pop
1302   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1303                    MVT::i16));
1304
1305   // Copy the result values into the output registers.
1306   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1307     CCValAssign &VA = RVLocs[i];
1308     assert(VA.isRegLoc() && "Can only return in registers!");
1309     SDValue ValToCopy = OutVals[i];
1310     EVT ValVT = ValToCopy.getValueType();
1311
1312     // If this is x86-64, and we disabled SSE, we can't return FP values
1313     if ((ValVT == MVT::f32 || ValVT == MVT::f64) &&
1314         (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1315       report_fatal_error("SSE register return with SSE disabled");
1316     }
1317     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1318     // llvm-gcc has never done it right and no one has noticed, so this
1319     // should be OK for now.
1320     if (ValVT == MVT::f64 &&
1321         (Subtarget->is64Bit() && !Subtarget->hasSSE2())) {
1322       report_fatal_error("SSE2 register return with SSE2 disabled");
1323     }
1324
1325     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1326     // the RET instruction and handled by the FP Stackifier.
1327     if (VA.getLocReg() == X86::ST0 ||
1328         VA.getLocReg() == X86::ST1) {
1329       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1330       // change the value to the FP stack register class.
1331       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1332         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1333       RetOps.push_back(ValToCopy);
1334       // Don't emit a copytoreg.
1335       continue;
1336     }
1337
1338     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1339     // which is returned in RAX / RDX.
1340     if (Subtarget->is64Bit()) {
1341       if (ValVT.isVector() && ValVT.getSizeInBits() == 64) {
1342         ValToCopy = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, ValToCopy);
1343         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1)
1344           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1345                                   ValToCopy);
1346       }
1347     }
1348
1349     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1350     Flag = Chain.getValue(1);
1351   }
1352
1353   // The x86-64 ABI for returning structs by value requires that we copy
1354   // the sret argument into %rax for the return. We saved the argument into
1355   // a virtual register in the entry block, so now we copy the value out
1356   // and into %rax.
1357   if (Subtarget->is64Bit() &&
1358       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1359     MachineFunction &MF = DAG.getMachineFunction();
1360     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1361     unsigned Reg = FuncInfo->getSRetReturnReg();
1362     assert(Reg && 
1363            "SRetReturnReg should have been set in LowerFormalArguments().");
1364     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1365
1366     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1367     Flag = Chain.getValue(1);
1368
1369     // RAX now acts like a return value.
1370     MRI.addLiveOut(X86::RAX);
1371   }
1372
1373   RetOps[0] = Chain;  // Update chain.
1374
1375   // Add the flag if we have it.
1376   if (Flag.getNode())
1377     RetOps.push_back(Flag);
1378
1379   return DAG.getNode(X86ISD::RET_FLAG, dl,
1380                      MVT::Other, &RetOps[0], RetOps.size());
1381 }
1382
1383 /// LowerCallResult - Lower the result values of a call into the
1384 /// appropriate copies out of appropriate physical registers.
1385 ///
1386 SDValue
1387 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1388                                    CallingConv::ID CallConv, bool isVarArg,
1389                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1390                                    DebugLoc dl, SelectionDAG &DAG,
1391                                    SmallVectorImpl<SDValue> &InVals) const {
1392
1393   // Assign locations to each value returned by this call.
1394   SmallVector<CCValAssign, 16> RVLocs;
1395   bool Is64Bit = Subtarget->is64Bit();
1396   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1397                  RVLocs, *DAG.getContext());
1398   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1399
1400   // Copy all of the result registers out of their specified physreg.
1401   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1402     CCValAssign &VA = RVLocs[i];
1403     EVT CopyVT = VA.getValVT();
1404
1405     // If this is x86-64, and we disabled SSE, we can't return FP values
1406     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1407         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1408       report_fatal_error("SSE register return with SSE disabled");
1409     }
1410
1411     SDValue Val;
1412
1413     // If this is a call to a function that returns an fp value on the floating
1414     // point stack, we must guarantee the the value is popped from the stack, so
1415     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1416     // if the return value is not used. We use the FpGET_ST0 instructions
1417     // instead.
1418     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1419       // If we prefer to use the value in xmm registers, copy it out as f80 and
1420       // use a truncate to move it from fp stack reg to xmm reg.
1421       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1422       bool isST0 = VA.getLocReg() == X86::ST0;
1423       unsigned Opc = 0;
1424       if (CopyVT == MVT::f32) Opc = isST0 ? X86::FpGET_ST0_32:X86::FpGET_ST1_32;
1425       if (CopyVT == MVT::f64) Opc = isST0 ? X86::FpGET_ST0_64:X86::FpGET_ST1_64;
1426       if (CopyVT == MVT::f80) Opc = isST0 ? X86::FpGET_ST0_80:X86::FpGET_ST1_80;
1427       SDValue Ops[] = { Chain, InFlag };
1428       Chain = SDValue(DAG.getMachineNode(Opc, dl, CopyVT, MVT::Other, MVT::Flag,
1429                                          Ops, 2), 1);
1430       Val = Chain.getValue(0);
1431
1432       // Round the f80 to the right size, which also moves it to the appropriate
1433       // xmm register.
1434       if (CopyVT != VA.getValVT())
1435         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1436                           // This truncation won't change the value.
1437                           DAG.getIntPtrConstant(1));
1438     } else if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1439       // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1440       if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1441         Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1442                                    MVT::v2i64, InFlag).getValue(1);
1443         Val = Chain.getValue(0);
1444         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1445                           Val, DAG.getConstant(0, MVT::i64));
1446       } else {
1447         Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1448                                    MVT::i64, InFlag).getValue(1);
1449         Val = Chain.getValue(0);
1450       }
1451       Val = DAG.getNode(ISD::BIT_CONVERT, dl, CopyVT, Val);
1452     } else {
1453       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1454                                  CopyVT, InFlag).getValue(1);
1455       Val = Chain.getValue(0);
1456     }
1457     InFlag = Chain.getValue(2);
1458     InVals.push_back(Val);
1459   }
1460
1461   return Chain;
1462 }
1463
1464
1465 //===----------------------------------------------------------------------===//
1466 //                C & StdCall & Fast Calling Convention implementation
1467 //===----------------------------------------------------------------------===//
1468 //  StdCall calling convention seems to be standard for many Windows' API
1469 //  routines and around. It differs from C calling convention just a little:
1470 //  callee should clean up the stack, not caller. Symbols should be also
1471 //  decorated in some fancy way :) It doesn't support any vector arguments.
1472 //  For info on fast calling convention see Fast Calling Convention (tail call)
1473 //  implementation LowerX86_32FastCCCallTo.
1474
1475 /// CallIsStructReturn - Determines whether a call uses struct return
1476 /// semantics.
1477 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1478   if (Outs.empty())
1479     return false;
1480
1481   return Outs[0].Flags.isSRet();
1482 }
1483
1484 /// ArgsAreStructReturn - Determines whether a function uses struct
1485 /// return semantics.
1486 static bool
1487 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1488   if (Ins.empty())
1489     return false;
1490
1491   return Ins[0].Flags.isSRet();
1492 }
1493
1494 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1495 /// given CallingConvention value.
1496 CCAssignFn *X86TargetLowering::CCAssignFnForNode(CallingConv::ID CC) const {
1497   if (Subtarget->is64Bit()) {
1498     if (CC == CallingConv::GHC)
1499       return CC_X86_64_GHC;
1500     else if (Subtarget->isTargetWin64())
1501       return CC_X86_Win64_C;
1502     else
1503       return CC_X86_64_C;
1504   }
1505
1506   if (CC == CallingConv::X86_FastCall)
1507     return CC_X86_32_FastCall;
1508   else if (CC == CallingConv::X86_ThisCall)
1509     return CC_X86_32_ThisCall;
1510   else if (CC == CallingConv::Fast)
1511     return CC_X86_32_FastCC;
1512   else if (CC == CallingConv::GHC)
1513     return CC_X86_32_GHC;
1514   else
1515     return CC_X86_32_C;
1516 }
1517
1518 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1519 /// by "Src" to address "Dst" with size and alignment information specified by
1520 /// the specific parameter attribute. The copy will be passed as a byval
1521 /// function parameter.
1522 static SDValue
1523 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1524                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1525                           DebugLoc dl) {
1526   SDValue SizeNode     = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1527   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1528                        /*isVolatile*/false, /*AlwaysInline=*/true,
1529                        NULL, 0, NULL, 0);
1530 }
1531
1532 /// IsTailCallConvention - Return true if the calling convention is one that
1533 /// supports tail call optimization.
1534 static bool IsTailCallConvention(CallingConv::ID CC) {
1535   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1536 }
1537
1538 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1539 /// a tailcall target by changing its ABI.
1540 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1541   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1542 }
1543
1544 SDValue
1545 X86TargetLowering::LowerMemArgument(SDValue Chain,
1546                                     CallingConv::ID CallConv,
1547                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1548                                     DebugLoc dl, SelectionDAG &DAG,
1549                                     const CCValAssign &VA,
1550                                     MachineFrameInfo *MFI,
1551                                     unsigned i) const {
1552   // Create the nodes corresponding to a load from this parameter slot.
1553   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1554   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1555   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1556   EVT ValVT;
1557
1558   // If value is passed by pointer we have address passed instead of the value
1559   // itself.
1560   if (VA.getLocInfo() == CCValAssign::Indirect)
1561     ValVT = VA.getLocVT();
1562   else
1563     ValVT = VA.getValVT();
1564
1565   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1566   // changed with more analysis.
1567   // In case of tail call optimization mark all arguments mutable. Since they
1568   // could be overwritten by lowering of arguments in case of a tail call.
1569   if (Flags.isByVal()) {
1570     int FI = MFI->CreateFixedObject(Flags.getByValSize(),
1571                                     VA.getLocMemOffset(), isImmutable);
1572     return DAG.getFrameIndex(FI, getPointerTy());
1573   } else {
1574     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1575                                     VA.getLocMemOffset(), isImmutable);
1576     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1577     return DAG.getLoad(ValVT, dl, Chain, FIN,
1578                        PseudoSourceValue::getFixedStack(FI), 0,
1579                        false, false, 0);
1580   }
1581 }
1582
1583 SDValue
1584 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1585                                         CallingConv::ID CallConv,
1586                                         bool isVarArg,
1587                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1588                                         DebugLoc dl,
1589                                         SelectionDAG &DAG,
1590                                         SmallVectorImpl<SDValue> &InVals)
1591                                           const {
1592   MachineFunction &MF = DAG.getMachineFunction();
1593   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1594
1595   const Function* Fn = MF.getFunction();
1596   if (Fn->hasExternalLinkage() &&
1597       Subtarget->isTargetCygMing() &&
1598       Fn->getName() == "main")
1599     FuncInfo->setForceFramePointer(true);
1600
1601   MachineFrameInfo *MFI = MF.getFrameInfo();
1602   bool Is64Bit = Subtarget->is64Bit();
1603   bool IsWin64 = Subtarget->isTargetWin64();
1604
1605   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1606          "Var args not supported with calling convention fastcc or ghc");
1607
1608   // Assign locations to all of the incoming arguments.
1609   SmallVector<CCValAssign, 16> ArgLocs;
1610   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1611                  ArgLocs, *DAG.getContext());
1612   CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForNode(CallConv));
1613
1614   unsigned LastVal = ~0U;
1615   SDValue ArgValue;
1616   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1617     CCValAssign &VA = ArgLocs[i];
1618     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1619     // places.
1620     assert(VA.getValNo() != LastVal &&
1621            "Don't support value assigned to multiple locs yet");
1622     LastVal = VA.getValNo();
1623
1624     if (VA.isRegLoc()) {
1625       EVT RegVT = VA.getLocVT();
1626       TargetRegisterClass *RC = NULL;
1627       if (RegVT == MVT::i32)
1628         RC = X86::GR32RegisterClass;
1629       else if (Is64Bit && RegVT == MVT::i64)
1630         RC = X86::GR64RegisterClass;
1631       else if (RegVT == MVT::f32)
1632         RC = X86::FR32RegisterClass;
1633       else if (RegVT == MVT::f64)
1634         RC = X86::FR64RegisterClass;
1635       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1636         RC = X86::VR128RegisterClass;
1637       else if (RegVT.isVector() && RegVT.getSizeInBits() == 64)
1638         RC = X86::VR64RegisterClass;
1639       else
1640         llvm_unreachable("Unknown argument type!");
1641
1642       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1643       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1644
1645       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1646       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1647       // right size.
1648       if (VA.getLocInfo() == CCValAssign::SExt)
1649         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1650                                DAG.getValueType(VA.getValVT()));
1651       else if (VA.getLocInfo() == CCValAssign::ZExt)
1652         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1653                                DAG.getValueType(VA.getValVT()));
1654       else if (VA.getLocInfo() == CCValAssign::BCvt)
1655         ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1656
1657       if (VA.isExtInLoc()) {
1658         // Handle MMX values passed in XMM regs.
1659         if (RegVT.isVector()) {
1660           ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1661                                  ArgValue, DAG.getConstant(0, MVT::i64));
1662           ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1663         } else
1664           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1665       }
1666     } else {
1667       assert(VA.isMemLoc());
1668       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1669     }
1670
1671     // If value is passed via pointer - do a load.
1672     if (VA.getLocInfo() == CCValAssign::Indirect)
1673       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue, NULL, 0,
1674                              false, false, 0);
1675
1676     InVals.push_back(ArgValue);
1677   }
1678
1679   // The x86-64 ABI for returning structs by value requires that we copy
1680   // the sret argument into %rax for the return. Save the argument into
1681   // a virtual register so that we can access it from the return points.
1682   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1683     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1684     unsigned Reg = FuncInfo->getSRetReturnReg();
1685     if (!Reg) {
1686       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1687       FuncInfo->setSRetReturnReg(Reg);
1688     }
1689     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1690     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1691   }
1692
1693   unsigned StackSize = CCInfo.getNextStackOffset();
1694   // Align stack specially for tail calls.
1695   if (FuncIsMadeTailCallSafe(CallConv))
1696     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1697
1698   // If the function takes variable number of arguments, make a frame index for
1699   // the start of the first vararg value... for expansion of llvm.va_start.
1700   if (isVarArg) {
1701     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1702                     CallConv != CallingConv::X86_ThisCall)) {
1703       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1704     }
1705     if (Is64Bit) {
1706       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1707
1708       // FIXME: We should really autogenerate these arrays
1709       static const unsigned GPR64ArgRegsWin64[] = {
1710         X86::RCX, X86::RDX, X86::R8,  X86::R9
1711       };
1712       static const unsigned XMMArgRegsWin64[] = {
1713         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1714       };
1715       static const unsigned GPR64ArgRegs64Bit[] = {
1716         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1717       };
1718       static const unsigned XMMArgRegs64Bit[] = {
1719         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1720         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1721       };
1722       const unsigned *GPR64ArgRegs, *XMMArgRegs;
1723
1724       if (IsWin64) {
1725         TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1726         GPR64ArgRegs = GPR64ArgRegsWin64;
1727         XMMArgRegs = XMMArgRegsWin64;
1728       } else {
1729         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1730         GPR64ArgRegs = GPR64ArgRegs64Bit;
1731         XMMArgRegs = XMMArgRegs64Bit;
1732       }
1733       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1734                                                        TotalNumIntRegs);
1735       unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1736                                                        TotalNumXMMRegs);
1737
1738       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1739       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1740              "SSE register cannot be used when SSE is disabled!");
1741       assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1742              "SSE register cannot be used when SSE is disabled!");
1743       if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
1744         // Kernel mode asks for SSE to be disabled, so don't push them
1745         // on the stack.
1746         TotalNumXMMRegs = 0;
1747
1748       // For X86-64, if there are vararg parameters that are passed via
1749       // registers, then we must store them to their spots on the stack so they
1750       // may be loaded by deferencing the result of va_next.
1751       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1752       FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1753       FuncInfo->setRegSaveFrameIndex(
1754         MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1755                                false));
1756
1757       // Store the integer parameter registers.
1758       SmallVector<SDValue, 8> MemOps;
1759       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1760                                         getPointerTy());
1761       unsigned Offset = FuncInfo->getVarArgsGPOffset();
1762       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1763         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1764                                   DAG.getIntPtrConstant(Offset));
1765         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1766                                      X86::GR64RegisterClass);
1767         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1768         SDValue Store =
1769           DAG.getStore(Val.getValue(1), dl, Val, FIN,
1770                        PseudoSourceValue::getFixedStack(
1771                          FuncInfo->getRegSaveFrameIndex()),
1772                        Offset, false, false, 0);
1773         MemOps.push_back(Store);
1774         Offset += 8;
1775       }
1776
1777       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1778         // Now store the XMM (fp + vector) parameter registers.
1779         SmallVector<SDValue, 11> SaveXMMOps;
1780         SaveXMMOps.push_back(Chain);
1781
1782         unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1783         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1784         SaveXMMOps.push_back(ALVal);
1785
1786         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1787                                FuncInfo->getRegSaveFrameIndex()));
1788         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1789                                FuncInfo->getVarArgsFPOffset()));
1790
1791         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1792           unsigned VReg = MF.addLiveIn(XMMArgRegs[NumXMMRegs],
1793                                        X86::VR128RegisterClass);
1794           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1795           SaveXMMOps.push_back(Val);
1796         }
1797         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1798                                      MVT::Other,
1799                                      &SaveXMMOps[0], SaveXMMOps.size()));
1800       }
1801
1802       if (!MemOps.empty())
1803         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1804                             &MemOps[0], MemOps.size());
1805     }
1806   }
1807
1808   // Some CCs need callee pop.
1809   if (Subtarget->IsCalleePop(isVarArg, CallConv)) {
1810     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1811   } else {
1812     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1813     // If this is an sret function, the return should pop the hidden pointer.
1814     if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1815       FuncInfo->setBytesToPopOnReturn(4);
1816   }
1817
1818   if (!Is64Bit) {
1819     // RegSaveFrameIndex is X86-64 only.
1820     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1821     if (CallConv == CallingConv::X86_FastCall ||
1822         CallConv == CallingConv::X86_ThisCall)
1823       // fastcc functions can't have varargs.
1824       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1825   }
1826
1827   return Chain;
1828 }
1829
1830 SDValue
1831 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1832                                     SDValue StackPtr, SDValue Arg,
1833                                     DebugLoc dl, SelectionDAG &DAG,
1834                                     const CCValAssign &VA,
1835                                     ISD::ArgFlagsTy Flags) const {
1836   const unsigned FirstStackArgOffset = (Subtarget->isTargetWin64() ? 32 : 0);
1837   unsigned LocMemOffset = FirstStackArgOffset + VA.getLocMemOffset();
1838   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1839   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1840   if (Flags.isByVal()) {
1841     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1842   }
1843   return DAG.getStore(Chain, dl, Arg, PtrOff,
1844                       PseudoSourceValue::getStack(), LocMemOffset,
1845                       false, false, 0);
1846 }
1847
1848 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1849 /// optimization is performed and it is required.
1850 SDValue
1851 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1852                                            SDValue &OutRetAddr, SDValue Chain,
1853                                            bool IsTailCall, bool Is64Bit,
1854                                            int FPDiff, DebugLoc dl) const {
1855   // Adjust the Return address stack slot.
1856   EVT VT = getPointerTy();
1857   OutRetAddr = getReturnAddressFrameIndex(DAG);
1858
1859   // Load the "old" Return address.
1860   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, NULL, 0, false, false, 0);
1861   return SDValue(OutRetAddr.getNode(), 1);
1862 }
1863
1864 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1865 /// optimization is performed and it is required (FPDiff!=0).
1866 static SDValue
1867 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1868                          SDValue Chain, SDValue RetAddrFrIdx,
1869                          bool Is64Bit, int FPDiff, DebugLoc dl) {
1870   // Store the return address to the appropriate stack slot.
1871   if (!FPDiff) return Chain;
1872   // Calculate the new stack slot for the return address.
1873   int SlotSize = Is64Bit ? 8 : 4;
1874   int NewReturnAddrFI =
1875     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
1876   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1877   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1878   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1879                        PseudoSourceValue::getFixedStack(NewReturnAddrFI), 0,
1880                        false, false, 0);
1881   return Chain;
1882 }
1883
1884 SDValue
1885 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1886                              CallingConv::ID CallConv, bool isVarArg,
1887                              bool &isTailCall,
1888                              const SmallVectorImpl<ISD::OutputArg> &Outs,
1889                              const SmallVectorImpl<SDValue> &OutVals,
1890                              const SmallVectorImpl<ISD::InputArg> &Ins,
1891                              DebugLoc dl, SelectionDAG &DAG,
1892                              SmallVectorImpl<SDValue> &InVals) const {
1893   MachineFunction &MF = DAG.getMachineFunction();
1894   bool Is64Bit        = Subtarget->is64Bit();
1895   bool IsStructRet    = CallIsStructReturn(Outs);
1896   bool IsSibcall      = false;
1897
1898   if (isTailCall) {
1899     // Check if it's really possible to do a tail call.
1900     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1901                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1902                                                    Outs, OutVals, Ins, DAG);
1903
1904     // Sibcalls are automatically detected tailcalls which do not require
1905     // ABI changes.
1906     if (!GuaranteedTailCallOpt && isTailCall)
1907       IsSibcall = true;
1908
1909     if (isTailCall)
1910       ++NumTailCalls;
1911   }
1912
1913   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1914          "Var args not supported with calling convention fastcc or ghc");
1915
1916   // Analyze operands of the call, assigning locations to each operand.
1917   SmallVector<CCValAssign, 16> ArgLocs;
1918   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1919                  ArgLocs, *DAG.getContext());
1920   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CallConv));
1921
1922   // Get a count of how many bytes are to be pushed on the stack.
1923   unsigned NumBytes = CCInfo.getNextStackOffset();
1924   if (IsSibcall)
1925     // This is a sibcall. The memory operands are available in caller's
1926     // own caller's stack.
1927     NumBytes = 0;
1928   else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
1929     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1930
1931   int FPDiff = 0;
1932   if (isTailCall && !IsSibcall) {
1933     // Lower arguments at fp - stackoffset + fpdiff.
1934     unsigned NumBytesCallerPushed =
1935       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1936     FPDiff = NumBytesCallerPushed - NumBytes;
1937
1938     // Set the delta of movement of the returnaddr stackslot.
1939     // But only set if delta is greater than previous delta.
1940     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1941       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1942   }
1943
1944   if (!IsSibcall)
1945     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1946
1947   SDValue RetAddrFrIdx;
1948   // Load return adress for tail calls.
1949   if (isTailCall && FPDiff)
1950     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
1951                                     Is64Bit, FPDiff, dl);
1952
1953   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1954   SmallVector<SDValue, 8> MemOpChains;
1955   SDValue StackPtr;
1956
1957   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1958   // of tail call optimization arguments are handle later.
1959   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1960     CCValAssign &VA = ArgLocs[i];
1961     EVT RegVT = VA.getLocVT();
1962     SDValue Arg = OutVals[i];
1963     ISD::ArgFlagsTy Flags = Outs[i].Flags;
1964     bool isByVal = Flags.isByVal();
1965
1966     // Promote the value if needed.
1967     switch (VA.getLocInfo()) {
1968     default: llvm_unreachable("Unknown loc info!");
1969     case CCValAssign::Full: break;
1970     case CCValAssign::SExt:
1971       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
1972       break;
1973     case CCValAssign::ZExt:
1974       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
1975       break;
1976     case CCValAssign::AExt:
1977       if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
1978         // Special case: passing MMX values in XMM registers.
1979         Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1980         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
1981         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
1982       } else
1983         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
1984       break;
1985     case CCValAssign::BCvt:
1986       Arg = DAG.getNode(ISD::BIT_CONVERT, dl, RegVT, Arg);
1987       break;
1988     case CCValAssign::Indirect: {
1989       // Store the argument.
1990       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
1991       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1992       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
1993                            PseudoSourceValue::getFixedStack(FI), 0,
1994                            false, false, 0);
1995       Arg = SpillSlot;
1996       break;
1997     }
1998     }
1999
2000     if (VA.isRegLoc()) {
2001       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2002     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2003       assert(VA.isMemLoc());
2004       if (StackPtr.getNode() == 0)
2005         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2006       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2007                                              dl, DAG, VA, Flags));
2008     }
2009   }
2010
2011   if (!MemOpChains.empty())
2012     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2013                         &MemOpChains[0], MemOpChains.size());
2014
2015   // Build a sequence of copy-to-reg nodes chained together with token chain
2016   // and flag operands which copy the outgoing args into registers.
2017   SDValue InFlag;
2018   // Tail call byval lowering might overwrite argument registers so in case of
2019   // tail call optimization the copies to registers are lowered later.
2020   if (!isTailCall)
2021     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2022       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2023                                RegsToPass[i].second, InFlag);
2024       InFlag = Chain.getValue(1);
2025     }
2026
2027   if (Subtarget->isPICStyleGOT()) {
2028     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2029     // GOT pointer.
2030     if (!isTailCall) {
2031       Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2032                                DAG.getNode(X86ISD::GlobalBaseReg,
2033                                            DebugLoc(), getPointerTy()),
2034                                InFlag);
2035       InFlag = Chain.getValue(1);
2036     } else {
2037       // If we are tail calling and generating PIC/GOT style code load the
2038       // address of the callee into ECX. The value in ecx is used as target of
2039       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2040       // for tail calls on PIC/GOT architectures. Normally we would just put the
2041       // address of GOT into ebx and then call target@PLT. But for tail calls
2042       // ebx would be restored (since ebx is callee saved) before jumping to the
2043       // target@PLT.
2044
2045       // Note: The actual moving to ECX is done further down.
2046       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2047       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2048           !G->getGlobal()->hasProtectedVisibility())
2049         Callee = LowerGlobalAddress(Callee, DAG);
2050       else if (isa<ExternalSymbolSDNode>(Callee))
2051         Callee = LowerExternalSymbol(Callee, DAG);
2052     }
2053   }
2054
2055   if (Is64Bit && isVarArg && !Subtarget->isTargetWin64()) {
2056     // From AMD64 ABI document:
2057     // For calls that may call functions that use varargs or stdargs
2058     // (prototype-less calls or calls to functions containing ellipsis (...) in
2059     // the declaration) %al is used as hidden argument to specify the number
2060     // of SSE registers used. The contents of %al do not need to match exactly
2061     // the number of registers, but must be an ubound on the number of SSE
2062     // registers used and is in the range 0 - 8 inclusive.
2063
2064     // Count the number of XMM registers allocated.
2065     static const unsigned XMMArgRegs[] = {
2066       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2067       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2068     };
2069     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2070     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2071            && "SSE registers cannot be used when SSE is disabled");
2072
2073     Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2074                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2075     InFlag = Chain.getValue(1);
2076   }
2077
2078
2079   // For tail calls lower the arguments to the 'real' stack slot.
2080   if (isTailCall) {
2081     // Force all the incoming stack arguments to be loaded from the stack
2082     // before any new outgoing arguments are stored to the stack, because the
2083     // outgoing stack slots may alias the incoming argument stack slots, and
2084     // the alias isn't otherwise explicit. This is slightly more conservative
2085     // than necessary, because it means that each store effectively depends
2086     // on every argument instead of just those arguments it would clobber.
2087     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2088
2089     SmallVector<SDValue, 8> MemOpChains2;
2090     SDValue FIN;
2091     int FI = 0;
2092     // Do not flag preceeding copytoreg stuff together with the following stuff.
2093     InFlag = SDValue();
2094     if (GuaranteedTailCallOpt) {
2095       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2096         CCValAssign &VA = ArgLocs[i];
2097         if (VA.isRegLoc())
2098           continue;
2099         assert(VA.isMemLoc());
2100         SDValue Arg = OutVals[i];
2101         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2102         // Create frame index.
2103         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2104         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2105         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2106         FIN = DAG.getFrameIndex(FI, getPointerTy());
2107
2108         if (Flags.isByVal()) {
2109           // Copy relative to framepointer.
2110           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2111           if (StackPtr.getNode() == 0)
2112             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2113                                           getPointerTy());
2114           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2115
2116           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2117                                                            ArgChain,
2118                                                            Flags, DAG, dl));
2119         } else {
2120           // Store relative to framepointer.
2121           MemOpChains2.push_back(
2122             DAG.getStore(ArgChain, dl, Arg, FIN,
2123                          PseudoSourceValue::getFixedStack(FI), 0,
2124                          false, false, 0));
2125         }
2126       }
2127     }
2128
2129     if (!MemOpChains2.empty())
2130       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2131                           &MemOpChains2[0], MemOpChains2.size());
2132
2133     // Copy arguments to their registers.
2134     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2135       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2136                                RegsToPass[i].second, InFlag);
2137       InFlag = Chain.getValue(1);
2138     }
2139     InFlag =SDValue();
2140
2141     // Store the return address to the appropriate stack slot.
2142     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2143                                      FPDiff, dl);
2144   }
2145
2146   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2147     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2148     // In the 64-bit large code model, we have to make all calls
2149     // through a register, since the call instruction's 32-bit
2150     // pc-relative offset may not be large enough to hold the whole
2151     // address.
2152   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2153     // If the callee is a GlobalAddress node (quite common, every direct call
2154     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2155     // it.
2156
2157     // We should use extra load for direct calls to dllimported functions in
2158     // non-JIT mode.
2159     const GlobalValue *GV = G->getGlobal();
2160     if (!GV->hasDLLImportLinkage()) {
2161       unsigned char OpFlags = 0;
2162
2163       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2164       // external symbols most go through the PLT in PIC mode.  If the symbol
2165       // has hidden or protected visibility, or if it is static or local, then
2166       // we don't need to use the PLT - we can directly call it.
2167       if (Subtarget->isTargetELF() &&
2168           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2169           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2170         OpFlags = X86II::MO_PLT;
2171       } else if (Subtarget->isPICStyleStubAny() &&
2172                (GV->isDeclaration() || GV->isWeakForLinker()) &&
2173                Subtarget->getDarwinVers() < 9) {
2174         // PC-relative references to external symbols should go through $stub,
2175         // unless we're building with the leopard linker or later, which
2176         // automatically synthesizes these stubs.
2177         OpFlags = X86II::MO_DARWIN_STUB;
2178       }
2179
2180       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2181                                           G->getOffset(), OpFlags);
2182     }
2183   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2184     unsigned char OpFlags = 0;
2185
2186     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to external
2187     // symbols should go through the PLT.
2188     if (Subtarget->isTargetELF() &&
2189         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2190       OpFlags = X86II::MO_PLT;
2191     } else if (Subtarget->isPICStyleStubAny() &&
2192              Subtarget->getDarwinVers() < 9) {
2193       // PC-relative references to external symbols should go through $stub,
2194       // unless we're building with the leopard linker or later, which
2195       // automatically synthesizes these stubs.
2196       OpFlags = X86II::MO_DARWIN_STUB;
2197     }
2198
2199     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2200                                          OpFlags);
2201   }
2202
2203   // Returns a chain & a flag for retval copy to use.
2204   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
2205   SmallVector<SDValue, 8> Ops;
2206
2207   if (!IsSibcall && isTailCall) {
2208     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2209                            DAG.getIntPtrConstant(0, true), InFlag);
2210     InFlag = Chain.getValue(1);
2211   }
2212
2213   Ops.push_back(Chain);
2214   Ops.push_back(Callee);
2215
2216   if (isTailCall)
2217     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2218
2219   // Add argument registers to the end of the list so that they are known live
2220   // into the call.
2221   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2222     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2223                                   RegsToPass[i].second.getValueType()));
2224
2225   // Add an implicit use GOT pointer in EBX.
2226   if (!isTailCall && Subtarget->isPICStyleGOT())
2227     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2228
2229   // Add an implicit use of AL for x86 vararg functions.
2230   if (Is64Bit && isVarArg)
2231     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2232
2233   if (InFlag.getNode())
2234     Ops.push_back(InFlag);
2235
2236   if (isTailCall) {
2237     // We used to do:
2238     //// If this is the first return lowered for this function, add the regs
2239     //// to the liveout set for the function.
2240     // This isn't right, although it's probably harmless on x86; liveouts
2241     // should be computed from returns not tail calls.  Consider a void
2242     // function making a tail call to a function returning int.
2243     return DAG.getNode(X86ISD::TC_RETURN, dl,
2244                        NodeTys, &Ops[0], Ops.size());
2245   }
2246
2247   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2248   InFlag = Chain.getValue(1);
2249
2250   // Create the CALLSEQ_END node.
2251   unsigned NumBytesForCalleeToPush;
2252   if (Subtarget->IsCalleePop(isVarArg, CallConv))
2253     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2254   else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2255     // If this is a call to a struct-return function, the callee
2256     // pops the hidden struct pointer, so we have to push it back.
2257     // This is common for Darwin/X86, Linux & Mingw32 targets.
2258     NumBytesForCalleeToPush = 4;
2259   else
2260     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2261
2262   // Returns a flag for retval copy to use.
2263   if (!IsSibcall) {
2264     Chain = DAG.getCALLSEQ_END(Chain,
2265                                DAG.getIntPtrConstant(NumBytes, true),
2266                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2267                                                      true),
2268                                InFlag);
2269     InFlag = Chain.getValue(1);
2270   }
2271
2272   // Handle result values, copying them out of physregs into vregs that we
2273   // return.
2274   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2275                          Ins, dl, DAG, InVals);
2276 }
2277
2278
2279 //===----------------------------------------------------------------------===//
2280 //                Fast Calling Convention (tail call) implementation
2281 //===----------------------------------------------------------------------===//
2282
2283 //  Like std call, callee cleans arguments, convention except that ECX is
2284 //  reserved for storing the tail called function address. Only 2 registers are
2285 //  free for argument passing (inreg). Tail call optimization is performed
2286 //  provided:
2287 //                * tailcallopt is enabled
2288 //                * caller/callee are fastcc
2289 //  On X86_64 architecture with GOT-style position independent code only local
2290 //  (within module) calls are supported at the moment.
2291 //  To keep the stack aligned according to platform abi the function
2292 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2293 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2294 //  If a tail called function callee has more arguments than the caller the
2295 //  caller needs to make sure that there is room to move the RETADDR to. This is
2296 //  achieved by reserving an area the size of the argument delta right after the
2297 //  original REtADDR, but before the saved framepointer or the spilled registers
2298 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2299 //  stack layout:
2300 //    arg1
2301 //    arg2
2302 //    RETADDR
2303 //    [ new RETADDR
2304 //      move area ]
2305 //    (possible EBP)
2306 //    ESI
2307 //    EDI
2308 //    local1 ..
2309
2310 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2311 /// for a 16 byte align requirement.
2312 unsigned
2313 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2314                                                SelectionDAG& DAG) const {
2315   MachineFunction &MF = DAG.getMachineFunction();
2316   const TargetMachine &TM = MF.getTarget();
2317   const TargetFrameInfo &TFI = *TM.getFrameInfo();
2318   unsigned StackAlignment = TFI.getStackAlignment();
2319   uint64_t AlignMask = StackAlignment - 1;
2320   int64_t Offset = StackSize;
2321   uint64_t SlotSize = TD->getPointerSize();
2322   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2323     // Number smaller than 12 so just add the difference.
2324     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2325   } else {
2326     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2327     Offset = ((~AlignMask) & Offset) + StackAlignment +
2328       (StackAlignment-SlotSize);
2329   }
2330   return Offset;
2331 }
2332
2333 /// MatchingStackOffset - Return true if the given stack call argument is
2334 /// already available in the same position (relatively) of the caller's
2335 /// incoming argument stack.
2336 static
2337 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2338                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2339                          const X86InstrInfo *TII) {
2340   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2341   int FI = INT_MAX;
2342   if (Arg.getOpcode() == ISD::CopyFromReg) {
2343     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2344     if (!VR || TargetRegisterInfo::isPhysicalRegister(VR))
2345       return false;
2346     MachineInstr *Def = MRI->getVRegDef(VR);
2347     if (!Def)
2348       return false;
2349     if (!Flags.isByVal()) {
2350       if (!TII->isLoadFromStackSlot(Def, FI))
2351         return false;
2352     } else {
2353       unsigned Opcode = Def->getOpcode();
2354       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2355           Def->getOperand(1).isFI()) {
2356         FI = Def->getOperand(1).getIndex();
2357         Bytes = Flags.getByValSize();
2358       } else
2359         return false;
2360     }
2361   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2362     if (Flags.isByVal())
2363       // ByVal argument is passed in as a pointer but it's now being
2364       // dereferenced. e.g.
2365       // define @foo(%struct.X* %A) {
2366       //   tail call @bar(%struct.X* byval %A)
2367       // }
2368       return false;
2369     SDValue Ptr = Ld->getBasePtr();
2370     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2371     if (!FINode)
2372       return false;
2373     FI = FINode->getIndex();
2374   } else
2375     return false;
2376
2377   assert(FI != INT_MAX);
2378   if (!MFI->isFixedObjectIndex(FI))
2379     return false;
2380   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2381 }
2382
2383 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2384 /// for tail call optimization. Targets which want to do tail call
2385 /// optimization should implement this function.
2386 bool
2387 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2388                                                      CallingConv::ID CalleeCC,
2389                                                      bool isVarArg,
2390                                                      bool isCalleeStructRet,
2391                                                      bool isCallerStructRet,
2392                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2393                                     const SmallVectorImpl<SDValue> &OutVals,
2394                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2395                                                      SelectionDAG& DAG) const {
2396   if (!IsTailCallConvention(CalleeCC) &&
2397       CalleeCC != CallingConv::C)
2398     return false;
2399
2400   // If -tailcallopt is specified, make fastcc functions tail-callable.
2401   const MachineFunction &MF = DAG.getMachineFunction();
2402   const Function *CallerF = DAG.getMachineFunction().getFunction();
2403   CallingConv::ID CallerCC = CallerF->getCallingConv();
2404   bool CCMatch = CallerCC == CalleeCC;
2405
2406   if (GuaranteedTailCallOpt) {
2407     if (IsTailCallConvention(CalleeCC) && CCMatch)
2408       return true;
2409     return false;
2410   }
2411
2412   // Look for obvious safe cases to perform tail call optimization that do not
2413   // require ABI changes. This is what gcc calls sibcall.
2414
2415   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2416   // emit a special epilogue.
2417   if (RegInfo->needsStackRealignment(MF))
2418     return false;
2419
2420   // Do not sibcall optimize vararg calls unless the call site is not passing
2421   // any arguments.
2422   if (isVarArg && !Outs.empty())
2423     return false;
2424
2425   // Also avoid sibcall optimization if either caller or callee uses struct
2426   // return semantics.
2427   if (isCalleeStructRet || isCallerStructRet)
2428     return false;
2429
2430   // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2431   // Therefore if it's not used by the call it is not safe to optimize this into
2432   // a sibcall.
2433   bool Unused = false;
2434   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2435     if (!Ins[i].Used) {
2436       Unused = true;
2437       break;
2438     }
2439   }
2440   if (Unused) {
2441     SmallVector<CCValAssign, 16> RVLocs;
2442     CCState CCInfo(CalleeCC, false, getTargetMachine(),
2443                    RVLocs, *DAG.getContext());
2444     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2445     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2446       CCValAssign &VA = RVLocs[i];
2447       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2448         return false;
2449     }
2450   }
2451
2452   // If the calling conventions do not match, then we'd better make sure the
2453   // results are returned in the same way as what the caller expects.
2454   if (!CCMatch) {
2455     SmallVector<CCValAssign, 16> RVLocs1;
2456     CCState CCInfo1(CalleeCC, false, getTargetMachine(),
2457                     RVLocs1, *DAG.getContext());
2458     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2459
2460     SmallVector<CCValAssign, 16> RVLocs2;
2461     CCState CCInfo2(CallerCC, false, getTargetMachine(),
2462                     RVLocs2, *DAG.getContext());
2463     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2464
2465     if (RVLocs1.size() != RVLocs2.size())
2466       return false;
2467     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2468       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2469         return false;
2470       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2471         return false;
2472       if (RVLocs1[i].isRegLoc()) {
2473         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2474           return false;
2475       } else {
2476         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2477           return false;
2478       }
2479     }
2480   }
2481
2482   // If the callee takes no arguments then go on to check the results of the
2483   // call.
2484   if (!Outs.empty()) {
2485     // Check if stack adjustment is needed. For now, do not do this if any
2486     // argument is passed on the stack.
2487     SmallVector<CCValAssign, 16> ArgLocs;
2488     CCState CCInfo(CalleeCC, isVarArg, getTargetMachine(),
2489                    ArgLocs, *DAG.getContext());
2490     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CalleeCC));
2491     if (CCInfo.getNextStackOffset()) {
2492       MachineFunction &MF = DAG.getMachineFunction();
2493       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2494         return false;
2495       if (Subtarget->isTargetWin64())
2496         // Win64 ABI has additional complications.
2497         return false;
2498
2499       // Check if the arguments are already laid out in the right way as
2500       // the caller's fixed stack objects.
2501       MachineFrameInfo *MFI = MF.getFrameInfo();
2502       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2503       const X86InstrInfo *TII =
2504         ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2505       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2506         CCValAssign &VA = ArgLocs[i];
2507         SDValue Arg = OutVals[i];
2508         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2509         if (VA.getLocInfo() == CCValAssign::Indirect)
2510           return false;
2511         if (!VA.isRegLoc()) {
2512           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2513                                    MFI, MRI, TII))
2514             return false;
2515         }
2516       }
2517     }
2518
2519     // If the tailcall address may be in a register, then make sure it's
2520     // possible to register allocate for it. In 32-bit, the call address can
2521     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2522     // callee-saved registers are restored. These happen to be the same
2523     // registers used to pass 'inreg' arguments so watch out for those.
2524     if (!Subtarget->is64Bit() &&
2525         !isa<GlobalAddressSDNode>(Callee) &&
2526         !isa<ExternalSymbolSDNode>(Callee)) {
2527       unsigned NumInRegs = 0;
2528       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2529         CCValAssign &VA = ArgLocs[i];
2530         if (!VA.isRegLoc())
2531           continue;
2532         unsigned Reg = VA.getLocReg();
2533         switch (Reg) {
2534         default: break;
2535         case X86::EAX: case X86::EDX: case X86::ECX:
2536           if (++NumInRegs == 3)
2537             return false;
2538           break;
2539         }
2540       }
2541     }
2542   }
2543
2544   return true;
2545 }
2546
2547 FastISel *
2548 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2549   return X86::createFastISel(funcInfo);
2550 }
2551
2552
2553 //===----------------------------------------------------------------------===//
2554 //                           Other Lowering Hooks
2555 //===----------------------------------------------------------------------===//
2556
2557
2558 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2559   MachineFunction &MF = DAG.getMachineFunction();
2560   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2561   int ReturnAddrIndex = FuncInfo->getRAIndex();
2562
2563   if (ReturnAddrIndex == 0) {
2564     // Set up a frame object for the return address.
2565     uint64_t SlotSize = TD->getPointerSize();
2566     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2567                                                            false);
2568     FuncInfo->setRAIndex(ReturnAddrIndex);
2569   }
2570
2571   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2572 }
2573
2574
2575 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2576                                        bool hasSymbolicDisplacement) {
2577   // Offset should fit into 32 bit immediate field.
2578   if (!isInt<32>(Offset))
2579     return false;
2580
2581   // If we don't have a symbolic displacement - we don't have any extra
2582   // restrictions.
2583   if (!hasSymbolicDisplacement)
2584     return true;
2585
2586   // FIXME: Some tweaks might be needed for medium code model.
2587   if (M != CodeModel::Small && M != CodeModel::Kernel)
2588     return false;
2589
2590   // For small code model we assume that latest object is 16MB before end of 31
2591   // bits boundary. We may also accept pretty large negative constants knowing
2592   // that all objects are in the positive half of address space.
2593   if (M == CodeModel::Small && Offset < 16*1024*1024)
2594     return true;
2595
2596   // For kernel code model we know that all object resist in the negative half
2597   // of 32bits address space. We may not accept negative offsets, since they may
2598   // be just off and we may accept pretty large positive ones.
2599   if (M == CodeModel::Kernel && Offset > 0)
2600     return true;
2601
2602   return false;
2603 }
2604
2605 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2606 /// specific condition code, returning the condition code and the LHS/RHS of the
2607 /// comparison to make.
2608 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2609                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2610   if (!isFP) {
2611     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2612       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2613         // X > -1   -> X == 0, jump !sign.
2614         RHS = DAG.getConstant(0, RHS.getValueType());
2615         return X86::COND_NS;
2616       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2617         // X < 0   -> X == 0, jump on sign.
2618         return X86::COND_S;
2619       } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2620         // X < 1   -> X <= 0
2621         RHS = DAG.getConstant(0, RHS.getValueType());
2622         return X86::COND_LE;
2623       }
2624     }
2625
2626     switch (SetCCOpcode) {
2627     default: llvm_unreachable("Invalid integer condition!");
2628     case ISD::SETEQ:  return X86::COND_E;
2629     case ISD::SETGT:  return X86::COND_G;
2630     case ISD::SETGE:  return X86::COND_GE;
2631     case ISD::SETLT:  return X86::COND_L;
2632     case ISD::SETLE:  return X86::COND_LE;
2633     case ISD::SETNE:  return X86::COND_NE;
2634     case ISD::SETULT: return X86::COND_B;
2635     case ISD::SETUGT: return X86::COND_A;
2636     case ISD::SETULE: return X86::COND_BE;
2637     case ISD::SETUGE: return X86::COND_AE;
2638     }
2639   }
2640
2641   // First determine if it is required or is profitable to flip the operands.
2642
2643   // If LHS is a foldable load, but RHS is not, flip the condition.
2644   if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2645       !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2646     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2647     std::swap(LHS, RHS);
2648   }
2649
2650   switch (SetCCOpcode) {
2651   default: break;
2652   case ISD::SETOLT:
2653   case ISD::SETOLE:
2654   case ISD::SETUGT:
2655   case ISD::SETUGE:
2656     std::swap(LHS, RHS);
2657     break;
2658   }
2659
2660   // On a floating point condition, the flags are set as follows:
2661   // ZF  PF  CF   op
2662   //  0 | 0 | 0 | X > Y
2663   //  0 | 0 | 1 | X < Y
2664   //  1 | 0 | 0 | X == Y
2665   //  1 | 1 | 1 | unordered
2666   switch (SetCCOpcode) {
2667   default: llvm_unreachable("Condcode should be pre-legalized away");
2668   case ISD::SETUEQ:
2669   case ISD::SETEQ:   return X86::COND_E;
2670   case ISD::SETOLT:              // flipped
2671   case ISD::SETOGT:
2672   case ISD::SETGT:   return X86::COND_A;
2673   case ISD::SETOLE:              // flipped
2674   case ISD::SETOGE:
2675   case ISD::SETGE:   return X86::COND_AE;
2676   case ISD::SETUGT:              // flipped
2677   case ISD::SETULT:
2678   case ISD::SETLT:   return X86::COND_B;
2679   case ISD::SETUGE:              // flipped
2680   case ISD::SETULE:
2681   case ISD::SETLE:   return X86::COND_BE;
2682   case ISD::SETONE:
2683   case ISD::SETNE:   return X86::COND_NE;
2684   case ISD::SETUO:   return X86::COND_P;
2685   case ISD::SETO:    return X86::COND_NP;
2686   case ISD::SETOEQ:
2687   case ISD::SETUNE:  return X86::COND_INVALID;
2688   }
2689 }
2690
2691 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2692 /// code. Current x86 isa includes the following FP cmov instructions:
2693 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2694 static bool hasFPCMov(unsigned X86CC) {
2695   switch (X86CC) {
2696   default:
2697     return false;
2698   case X86::COND_B:
2699   case X86::COND_BE:
2700   case X86::COND_E:
2701   case X86::COND_P:
2702   case X86::COND_A:
2703   case X86::COND_AE:
2704   case X86::COND_NE:
2705   case X86::COND_NP:
2706     return true;
2707   }
2708 }
2709
2710 /// isFPImmLegal - Returns true if the target can instruction select the
2711 /// specified FP immediate natively. If false, the legalizer will
2712 /// materialize the FP immediate as a load from a constant pool.
2713 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2714   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
2715     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
2716       return true;
2717   }
2718   return false;
2719 }
2720
2721 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2722 /// the specified range (L, H].
2723 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2724   return (Val < 0) || (Val >= Low && Val < Hi);
2725 }
2726
2727 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2728 /// specified value.
2729 static bool isUndefOrEqual(int Val, int CmpVal) {
2730   if (Val < 0 || Val == CmpVal)
2731     return true;
2732   return false;
2733 }
2734
2735 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2736 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
2737 /// the second operand.
2738 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2739   if (VT == MVT::v4f32 || VT == MVT::v4i32 || VT == MVT::v4i16)
2740     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2741   if (VT == MVT::v2f64 || VT == MVT::v2i64)
2742     return (Mask[0] < 2 && Mask[1] < 2);
2743   return false;
2744 }
2745
2746 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2747   SmallVector<int, 8> M;
2748   N->getMask(M);
2749   return ::isPSHUFDMask(M, N->getValueType(0));
2750 }
2751
2752 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2753 /// is suitable for input to PSHUFHW.
2754 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2755   if (VT != MVT::v8i16)
2756     return false;
2757
2758   // Lower quadword copied in order or undef.
2759   for (int i = 0; i != 4; ++i)
2760     if (Mask[i] >= 0 && Mask[i] != i)
2761       return false;
2762
2763   // Upper quadword shuffled.
2764   for (int i = 4; i != 8; ++i)
2765     if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2766       return false;
2767
2768   return true;
2769 }
2770
2771 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2772   SmallVector<int, 8> M;
2773   N->getMask(M);
2774   return ::isPSHUFHWMask(M, N->getValueType(0));
2775 }
2776
2777 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
2778 /// is suitable for input to PSHUFLW.
2779 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2780   if (VT != MVT::v8i16)
2781     return false;
2782
2783   // Upper quadword copied in order.
2784   for (int i = 4; i != 8; ++i)
2785     if (Mask[i] >= 0 && Mask[i] != i)
2786       return false;
2787
2788   // Lower quadword shuffled.
2789   for (int i = 0; i != 4; ++i)
2790     if (Mask[i] >= 4)
2791       return false;
2792
2793   return true;
2794 }
2795
2796 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
2797   SmallVector<int, 8> M;
2798   N->getMask(M);
2799   return ::isPSHUFLWMask(M, N->getValueType(0));
2800 }
2801
2802 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
2803 /// is suitable for input to PALIGNR.
2804 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
2805                           bool hasSSSE3) {
2806   int i, e = VT.getVectorNumElements();
2807   
2808   // Do not handle v2i64 / v2f64 shuffles with palignr.
2809   if (e < 4 || !hasSSSE3)
2810     return false;
2811   
2812   for (i = 0; i != e; ++i)
2813     if (Mask[i] >= 0)
2814       break;
2815   
2816   // All undef, not a palignr.
2817   if (i == e)
2818     return false;
2819
2820   // Determine if it's ok to perform a palignr with only the LHS, since we
2821   // don't have access to the actual shuffle elements to see if RHS is undef.
2822   bool Unary = Mask[i] < (int)e;
2823   bool NeedsUnary = false;
2824
2825   int s = Mask[i] - i;
2826   
2827   // Check the rest of the elements to see if they are consecutive.
2828   for (++i; i != e; ++i) {
2829     int m = Mask[i];
2830     if (m < 0) 
2831       continue;
2832     
2833     Unary = Unary && (m < (int)e);
2834     NeedsUnary = NeedsUnary || (m < s);
2835
2836     if (NeedsUnary && !Unary)
2837       return false;
2838     if (Unary && m != ((s+i) & (e-1)))
2839       return false;
2840     if (!Unary && m != (s+i))
2841       return false;
2842   }
2843   return true;
2844 }
2845
2846 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
2847   SmallVector<int, 8> M;
2848   N->getMask(M);
2849   return ::isPALIGNRMask(M, N->getValueType(0), true);
2850 }
2851
2852 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2853 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2854 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2855   int NumElems = VT.getVectorNumElements();
2856   if (NumElems != 2 && NumElems != 4)
2857     return false;
2858
2859   int Half = NumElems / 2;
2860   for (int i = 0; i < Half; ++i)
2861     if (!isUndefOrInRange(Mask[i], 0, NumElems))
2862       return false;
2863   for (int i = Half; i < NumElems; ++i)
2864     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2865       return false;
2866
2867   return true;
2868 }
2869
2870 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
2871   SmallVector<int, 8> M;
2872   N->getMask(M);
2873   return ::isSHUFPMask(M, N->getValueType(0));
2874 }
2875
2876 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2877 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2878 /// half elements to come from vector 1 (which would equal the dest.) and
2879 /// the upper half to come from vector 2.
2880 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2881   int NumElems = VT.getVectorNumElements();
2882
2883   if (NumElems != 2 && NumElems != 4)
2884     return false;
2885
2886   int Half = NumElems / 2;
2887   for (int i = 0; i < Half; ++i)
2888     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2889       return false;
2890   for (int i = Half; i < NumElems; ++i)
2891     if (!isUndefOrInRange(Mask[i], 0, NumElems))
2892       return false;
2893   return true;
2894 }
2895
2896 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
2897   SmallVector<int, 8> M;
2898   N->getMask(M);
2899   return isCommutedSHUFPMask(M, N->getValueType(0));
2900 }
2901
2902 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2903 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2904 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
2905   if (N->getValueType(0).getVectorNumElements() != 4)
2906     return false;
2907
2908   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2909   return isUndefOrEqual(N->getMaskElt(0), 6) &&
2910          isUndefOrEqual(N->getMaskElt(1), 7) &&
2911          isUndefOrEqual(N->getMaskElt(2), 2) &&
2912          isUndefOrEqual(N->getMaskElt(3), 3);
2913 }
2914
2915 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2916 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2917 /// <2, 3, 2, 3>
2918 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
2919   unsigned NumElems = N->getValueType(0).getVectorNumElements();
2920   
2921   if (NumElems != 4)
2922     return false;
2923   
2924   return isUndefOrEqual(N->getMaskElt(0), 2) &&
2925   isUndefOrEqual(N->getMaskElt(1), 3) &&
2926   isUndefOrEqual(N->getMaskElt(2), 2) &&
2927   isUndefOrEqual(N->getMaskElt(3), 3);
2928 }
2929
2930 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2931 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2932 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
2933   unsigned NumElems = N->getValueType(0).getVectorNumElements();
2934
2935   if (NumElems != 2 && NumElems != 4)
2936     return false;
2937
2938   for (unsigned i = 0; i < NumElems/2; ++i)
2939     if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
2940       return false;
2941
2942   for (unsigned i = NumElems/2; i < NumElems; ++i)
2943     if (!isUndefOrEqual(N->getMaskElt(i), i))
2944       return false;
2945
2946   return true;
2947 }
2948
2949 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
2950 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
2951 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
2952   unsigned NumElems = N->getValueType(0).getVectorNumElements();
2953
2954   if (NumElems != 2 && NumElems != 4)
2955     return false;
2956
2957   for (unsigned i = 0; i < NumElems/2; ++i)
2958     if (!isUndefOrEqual(N->getMaskElt(i), i))
2959       return false;
2960
2961   for (unsigned i = 0; i < NumElems/2; ++i)
2962     if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
2963       return false;
2964
2965   return true;
2966 }
2967
2968 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2969 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2970 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
2971                          bool V2IsSplat = false) {
2972   int NumElts = VT.getVectorNumElements();
2973   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2974     return false;
2975
2976   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2977     int BitI  = Mask[i];
2978     int BitI1 = Mask[i+1];
2979     if (!isUndefOrEqual(BitI, j))
2980       return false;
2981     if (V2IsSplat) {
2982       if (!isUndefOrEqual(BitI1, NumElts))
2983         return false;
2984     } else {
2985       if (!isUndefOrEqual(BitI1, j + NumElts))
2986         return false;
2987     }
2988   }
2989   return true;
2990 }
2991
2992 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2993   SmallVector<int, 8> M;
2994   N->getMask(M);
2995   return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
2996 }
2997
2998 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2999 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3000 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3001                          bool V2IsSplat = false) {
3002   int NumElts = VT.getVectorNumElements();
3003   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3004     return false;
3005
3006   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3007     int BitI  = Mask[i];
3008     int BitI1 = Mask[i+1];
3009     if (!isUndefOrEqual(BitI, j + NumElts/2))
3010       return false;
3011     if (V2IsSplat) {
3012       if (isUndefOrEqual(BitI1, NumElts))
3013         return false;
3014     } else {
3015       if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
3016         return false;
3017     }
3018   }
3019   return true;
3020 }
3021
3022 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3023   SmallVector<int, 8> M;
3024   N->getMask(M);
3025   return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
3026 }
3027
3028 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3029 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3030 /// <0, 0, 1, 1>
3031 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3032   int NumElems = VT.getVectorNumElements();
3033   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3034     return false;
3035
3036   for (int i = 0, j = 0; i != NumElems; i += 2, ++j) {
3037     int BitI  = Mask[i];
3038     int BitI1 = Mask[i+1];
3039     if (!isUndefOrEqual(BitI, j))
3040       return false;
3041     if (!isUndefOrEqual(BitI1, j))
3042       return false;
3043   }
3044   return true;
3045 }
3046
3047 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3048   SmallVector<int, 8> M;
3049   N->getMask(M);
3050   return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3051 }
3052
3053 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3054 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3055 /// <2, 2, 3, 3>
3056 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3057   int NumElems = VT.getVectorNumElements();
3058   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3059     return false;
3060
3061   for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3062     int BitI  = Mask[i];
3063     int BitI1 = Mask[i+1];
3064     if (!isUndefOrEqual(BitI, j))
3065       return false;
3066     if (!isUndefOrEqual(BitI1, j))
3067       return false;
3068   }
3069   return true;
3070 }
3071
3072 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3073   SmallVector<int, 8> M;
3074   N->getMask(M);
3075   return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3076 }
3077
3078 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3079 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3080 /// MOVSD, and MOVD, i.e. setting the lowest element.
3081 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3082   if (VT.getVectorElementType().getSizeInBits() < 32)
3083     return false;
3084
3085   int NumElts = VT.getVectorNumElements();
3086
3087   if (!isUndefOrEqual(Mask[0], NumElts))
3088     return false;
3089
3090   for (int i = 1; i < NumElts; ++i)
3091     if (!isUndefOrEqual(Mask[i], i))
3092       return false;
3093
3094   return true;
3095 }
3096
3097 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3098   SmallVector<int, 8> M;
3099   N->getMask(M);
3100   return ::isMOVLMask(M, N->getValueType(0));
3101 }
3102
3103 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3104 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3105 /// element of vector 2 and the other elements to come from vector 1 in order.
3106 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3107                                bool V2IsSplat = false, bool V2IsUndef = false) {
3108   int NumOps = VT.getVectorNumElements();
3109   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3110     return false;
3111
3112   if (!isUndefOrEqual(Mask[0], 0))
3113     return false;
3114
3115   for (int i = 1; i < NumOps; ++i)
3116     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3117           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3118           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3119       return false;
3120
3121   return true;
3122 }
3123
3124 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3125                            bool V2IsUndef = false) {
3126   SmallVector<int, 8> M;
3127   N->getMask(M);
3128   return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3129 }
3130
3131 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3132 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3133 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
3134   if (N->getValueType(0).getVectorNumElements() != 4)
3135     return false;
3136
3137   // Expect 1, 1, 3, 3
3138   for (unsigned i = 0; i < 2; ++i) {
3139     int Elt = N->getMaskElt(i);
3140     if (Elt >= 0 && Elt != 1)
3141       return false;
3142   }
3143
3144   bool HasHi = false;
3145   for (unsigned i = 2; i < 4; ++i) {
3146     int Elt = N->getMaskElt(i);
3147     if (Elt >= 0 && Elt != 3)
3148       return false;
3149     if (Elt == 3)
3150       HasHi = true;
3151   }
3152   // Don't use movshdup if it can be done with a shufps.
3153   // FIXME: verify that matching u, u, 3, 3 is what we want.
3154   return HasHi;
3155 }
3156
3157 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3158 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3159 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
3160   if (N->getValueType(0).getVectorNumElements() != 4)
3161     return false;
3162
3163   // Expect 0, 0, 2, 2
3164   for (unsigned i = 0; i < 2; ++i)
3165     if (N->getMaskElt(i) > 0)
3166       return false;
3167
3168   bool HasHi = false;
3169   for (unsigned i = 2; i < 4; ++i) {
3170     int Elt = N->getMaskElt(i);
3171     if (Elt >= 0 && Elt != 2)
3172       return false;
3173     if (Elt == 2)
3174       HasHi = true;
3175   }
3176   // Don't use movsldup if it can be done with a shufps.
3177   return HasHi;
3178 }
3179
3180 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3181 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3182 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3183   int e = N->getValueType(0).getVectorNumElements() / 2;
3184
3185   for (int i = 0; i < e; ++i)
3186     if (!isUndefOrEqual(N->getMaskElt(i), i))
3187       return false;
3188   for (int i = 0; i < e; ++i)
3189     if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3190       return false;
3191   return true;
3192 }
3193
3194 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3195 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3196 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3197   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3198   int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3199
3200   unsigned Shift = (NumOperands == 4) ? 2 : 1;
3201   unsigned Mask = 0;
3202   for (int i = 0; i < NumOperands; ++i) {
3203     int Val = SVOp->getMaskElt(NumOperands-i-1);
3204     if (Val < 0) Val = 0;
3205     if (Val >= NumOperands) Val -= NumOperands;
3206     Mask |= Val;
3207     if (i != NumOperands - 1)
3208       Mask <<= Shift;
3209   }
3210   return Mask;
3211 }
3212
3213 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3214 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3215 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3216   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3217   unsigned Mask = 0;
3218   // 8 nodes, but we only care about the last 4.
3219   for (unsigned i = 7; i >= 4; --i) {
3220     int Val = SVOp->getMaskElt(i);
3221     if (Val >= 0)
3222       Mask |= (Val - 4);
3223     if (i != 4)
3224       Mask <<= 2;
3225   }
3226   return Mask;
3227 }
3228
3229 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3230 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3231 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3232   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3233   unsigned Mask = 0;
3234   // 8 nodes, but we only care about the first 4.
3235   for (int i = 3; i >= 0; --i) {
3236     int Val = SVOp->getMaskElt(i);
3237     if (Val >= 0)
3238       Mask |= Val;
3239     if (i != 0)
3240       Mask <<= 2;
3241   }
3242   return Mask;
3243 }
3244
3245 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3246 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3247 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3248   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3249   EVT VVT = N->getValueType(0);
3250   unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3251   int Val = 0;
3252
3253   unsigned i, e;
3254   for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3255     Val = SVOp->getMaskElt(i);
3256     if (Val >= 0)
3257       break;
3258   }
3259   return (Val - i) * EltSize;
3260 }
3261
3262 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3263 /// constant +0.0.
3264 bool X86::isZeroNode(SDValue Elt) {
3265   return ((isa<ConstantSDNode>(Elt) &&
3266            cast<ConstantSDNode>(Elt)->isNullValue()) ||
3267           (isa<ConstantFPSDNode>(Elt) &&
3268            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3269 }
3270
3271 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3272 /// their permute mask.
3273 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3274                                     SelectionDAG &DAG) {
3275   EVT VT = SVOp->getValueType(0);
3276   unsigned NumElems = VT.getVectorNumElements();
3277   SmallVector<int, 8> MaskVec;
3278
3279   for (unsigned i = 0; i != NumElems; ++i) {
3280     int idx = SVOp->getMaskElt(i);
3281     if (idx < 0)
3282       MaskVec.push_back(idx);
3283     else if (idx < (int)NumElems)
3284       MaskVec.push_back(idx + NumElems);
3285     else
3286       MaskVec.push_back(idx - NumElems);
3287   }
3288   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3289                               SVOp->getOperand(0), &MaskVec[0]);
3290 }
3291
3292 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3293 /// the two vector operands have swapped position.
3294 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3295   unsigned NumElems = VT.getVectorNumElements();
3296   for (unsigned i = 0; i != NumElems; ++i) {
3297     int idx = Mask[i];
3298     if (idx < 0)
3299       continue;
3300     else if (idx < (int)NumElems)
3301       Mask[i] = idx + NumElems;
3302     else
3303       Mask[i] = idx - NumElems;
3304   }
3305 }
3306
3307 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3308 /// match movhlps. The lower half elements should come from upper half of
3309 /// V1 (and in order), and the upper half elements should come from the upper
3310 /// half of V2 (and in order).
3311 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3312   if (Op->getValueType(0).getVectorNumElements() != 4)
3313     return false;
3314   for (unsigned i = 0, e = 2; i != e; ++i)
3315     if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3316       return false;
3317   for (unsigned i = 2; i != 4; ++i)
3318     if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3319       return false;
3320   return true;
3321 }
3322
3323 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3324 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3325 /// required.
3326 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3327   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3328     return false;
3329   N = N->getOperand(0).getNode();
3330   if (!ISD::isNON_EXTLoad(N))
3331     return false;
3332   if (LD)
3333     *LD = cast<LoadSDNode>(N);
3334   return true;
3335 }
3336
3337 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3338 /// match movlp{s|d}. The lower half elements should come from lower half of
3339 /// V1 (and in order), and the upper half elements should come from the upper
3340 /// half of V2 (and in order). And since V1 will become the source of the
3341 /// MOVLP, it must be either a vector load or a scalar load to vector.
3342 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3343                                ShuffleVectorSDNode *Op) {
3344   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3345     return false;
3346   // Is V2 is a vector load, don't do this transformation. We will try to use
3347   // load folding shufps op.
3348   if (ISD::isNON_EXTLoad(V2))
3349     return false;
3350
3351   unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3352
3353   if (NumElems != 2 && NumElems != 4)
3354     return false;
3355   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3356     if (!isUndefOrEqual(Op->getMaskElt(i), i))
3357       return false;
3358   for (unsigned i = NumElems/2; i != NumElems; ++i)
3359     if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3360       return false;
3361   return true;
3362 }
3363
3364 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3365 /// all the same.
3366 static bool isSplatVector(SDNode *N) {
3367   if (N->getOpcode() != ISD::BUILD_VECTOR)
3368     return false;
3369
3370   SDValue SplatValue = N->getOperand(0);
3371   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3372     if (N->getOperand(i) != SplatValue)
3373       return false;
3374   return true;
3375 }
3376
3377 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3378 /// to an zero vector.
3379 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3380 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3381   SDValue V1 = N->getOperand(0);
3382   SDValue V2 = N->getOperand(1);
3383   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3384   for (unsigned i = 0; i != NumElems; ++i) {
3385     int Idx = N->getMaskElt(i);
3386     if (Idx >= (int)NumElems) {
3387       unsigned Opc = V2.getOpcode();
3388       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3389         continue;
3390       if (Opc != ISD::BUILD_VECTOR ||
3391           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3392         return false;
3393     } else if (Idx >= 0) {
3394       unsigned Opc = V1.getOpcode();
3395       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3396         continue;
3397       if (Opc != ISD::BUILD_VECTOR ||
3398           !X86::isZeroNode(V1.getOperand(Idx)))
3399         return false;
3400     }
3401   }
3402   return true;
3403 }
3404
3405 /// getZeroVector - Returns a vector of specified type with all zero elements.
3406 ///
3407 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3408                              DebugLoc dl) {
3409   assert(VT.isVector() && "Expected a vector type");
3410
3411   // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3412   // type.  This ensures they get CSE'd.
3413   SDValue Vec;
3414   if (VT.getSizeInBits() == 64) { // MMX
3415     SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3416     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3417   } else if (HasSSE2) {  // SSE2
3418     SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3419     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3420   } else { // SSE1
3421     SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3422     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3423   }
3424   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3425 }
3426
3427 /// getOnesVector - Returns a vector of specified type with all bits set.
3428 ///
3429 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3430   assert(VT.isVector() && "Expected a vector type");
3431
3432   // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3433   // type.  This ensures they get CSE'd.
3434   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3435   SDValue Vec;
3436   if (VT.getSizeInBits() == 64)  // MMX
3437     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3438   else                                              // SSE
3439     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3440   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3441 }
3442
3443
3444 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3445 /// that point to V2 points to its first element.
3446 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3447   EVT VT = SVOp->getValueType(0);
3448   unsigned NumElems = VT.getVectorNumElements();
3449
3450   bool Changed = false;
3451   SmallVector<int, 8> MaskVec;
3452   SVOp->getMask(MaskVec);
3453
3454   for (unsigned i = 0; i != NumElems; ++i) {
3455     if (MaskVec[i] > (int)NumElems) {
3456       MaskVec[i] = NumElems;
3457       Changed = true;
3458     }
3459   }
3460   if (Changed)
3461     return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3462                                 SVOp->getOperand(1), &MaskVec[0]);
3463   return SDValue(SVOp, 0);
3464 }
3465
3466 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3467 /// operation of specified width.
3468 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3469                        SDValue V2) {
3470   unsigned NumElems = VT.getVectorNumElements();
3471   SmallVector<int, 8> Mask;
3472   Mask.push_back(NumElems);
3473   for (unsigned i = 1; i != NumElems; ++i)
3474     Mask.push_back(i);
3475   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3476 }
3477
3478 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3479 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3480                           SDValue V2) {
3481   unsigned NumElems = VT.getVectorNumElements();
3482   SmallVector<int, 8> Mask;
3483   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3484     Mask.push_back(i);
3485     Mask.push_back(i + NumElems);
3486   }
3487   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3488 }
3489
3490 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3491 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3492                           SDValue V2) {
3493   unsigned NumElems = VT.getVectorNumElements();
3494   unsigned Half = NumElems/2;
3495   SmallVector<int, 8> Mask;
3496   for (unsigned i = 0; i != Half; ++i) {
3497     Mask.push_back(i + Half);
3498     Mask.push_back(i + NumElems + Half);
3499   }
3500   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3501 }
3502
3503 /// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
3504 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG,
3505                             bool HasSSE2) {
3506   if (SV->getValueType(0).getVectorNumElements() <= 4)
3507     return SDValue(SV, 0);
3508
3509   EVT PVT = MVT::v4f32;
3510   EVT VT = SV->getValueType(0);
3511   DebugLoc dl = SV->getDebugLoc();
3512   SDValue V1 = SV->getOperand(0);
3513   int NumElems = VT.getVectorNumElements();
3514   int EltNo = SV->getSplatIndex();
3515
3516   // unpack elements to the correct location
3517   while (NumElems > 4) {
3518     if (EltNo < NumElems/2) {
3519       V1 = getUnpackl(DAG, dl, VT, V1, V1);
3520     } else {
3521       V1 = getUnpackh(DAG, dl, VT, V1, V1);
3522       EltNo -= NumElems/2;
3523     }
3524     NumElems >>= 1;
3525   }
3526
3527   // Perform the splat.
3528   int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3529   V1 = DAG.getNode(ISD::BIT_CONVERT, dl, PVT, V1);
3530   V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3531   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, V1);
3532 }
3533
3534 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3535 /// vector of zero or undef vector.  This produces a shuffle where the low
3536 /// element of V2 is swizzled into the zero/undef vector, landing at element
3537 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
3538 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3539                                              bool isZero, bool HasSSE2,
3540                                              SelectionDAG &DAG) {
3541   EVT VT = V2.getValueType();
3542   SDValue V1 = isZero
3543     ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3544   unsigned NumElems = VT.getVectorNumElements();
3545   SmallVector<int, 16> MaskVec;
3546   for (unsigned i = 0; i != NumElems; ++i)
3547     // If this is the insertion idx, put the low elt of V2 here.
3548     MaskVec.push_back(i == Idx ? NumElems : i);
3549   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3550 }
3551
3552 /// getNumOfConsecutiveZeros - Return the number of elements in a result of
3553 /// a shuffle that is zero.
3554 static
3555 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, int NumElems,
3556                                   bool Low, SelectionDAG &DAG) {
3557   unsigned NumZeros = 0;
3558   for (int i = 0; i < NumElems; ++i) {
3559     unsigned Index = Low ? i : NumElems-i-1;
3560     int Idx = SVOp->getMaskElt(Index);
3561     if (Idx < 0) {
3562       ++NumZeros;
3563       continue;
3564     }
3565     SDValue Elt = DAG.getShuffleScalarElt(SVOp, Index);
3566     if (Elt.getNode() && X86::isZeroNode(Elt))
3567       ++NumZeros;
3568     else
3569       break;
3570   }
3571   return NumZeros;
3572 }
3573
3574 /// isVectorShift - Returns true if the shuffle can be implemented as a
3575 /// logical left or right shift of a vector.
3576 /// FIXME: split into pslldqi, psrldqi, palignr variants.
3577 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3578                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3579   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
3580
3581   isLeft = true;
3582   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, true, DAG);
3583   if (!NumZeros) {
3584     isLeft = false;
3585     NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, false, DAG);
3586     if (!NumZeros)
3587       return false;
3588   }
3589   bool SeenV1 = false;
3590   bool SeenV2 = false;
3591   for (unsigned i = NumZeros; i < NumElems; ++i) {
3592     unsigned Val = isLeft ? (i - NumZeros) : i;
3593     int Idx_ = SVOp->getMaskElt(isLeft ? i : (i - NumZeros));
3594     if (Idx_ < 0)
3595       continue;
3596     unsigned Idx = (unsigned) Idx_;
3597     if (Idx < NumElems)
3598       SeenV1 = true;
3599     else {
3600       Idx -= NumElems;
3601       SeenV2 = true;
3602     }
3603     if (Idx != Val)
3604       return false;
3605   }
3606   if (SeenV1 && SeenV2)
3607     return false;
3608
3609   ShVal = SeenV1 ? SVOp->getOperand(0) : SVOp->getOperand(1);
3610   ShAmt = NumZeros;
3611   return true;
3612 }
3613
3614
3615 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3616 ///
3617 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3618                                        unsigned NumNonZero, unsigned NumZero,
3619                                        SelectionDAG &DAG,
3620                                        const TargetLowering &TLI) {
3621   if (NumNonZero > 8)
3622     return SDValue();
3623
3624   DebugLoc dl = Op.getDebugLoc();
3625   SDValue V(0, 0);
3626   bool First = true;
3627   for (unsigned i = 0; i < 16; ++i) {
3628     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3629     if (ThisIsNonZero && First) {
3630       if (NumZero)
3631         V = getZeroVector(MVT::v8i16, true, DAG, dl);
3632       else
3633         V = DAG.getUNDEF(MVT::v8i16);
3634       First = false;
3635     }
3636
3637     if ((i & 1) != 0) {
3638       SDValue ThisElt(0, 0), LastElt(0, 0);
3639       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3640       if (LastIsNonZero) {
3641         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
3642                               MVT::i16, Op.getOperand(i-1));
3643       }
3644       if (ThisIsNonZero) {
3645         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
3646         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
3647                               ThisElt, DAG.getConstant(8, MVT::i8));
3648         if (LastIsNonZero)
3649           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
3650       } else
3651         ThisElt = LastElt;
3652
3653       if (ThisElt.getNode())
3654         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
3655                         DAG.getIntPtrConstant(i/2));
3656     }
3657   }
3658
3659   return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V);
3660 }
3661
3662 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3663 ///
3664 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3665                                      unsigned NumNonZero, unsigned NumZero,
3666                                      SelectionDAG &DAG,
3667                                      const TargetLowering &TLI) {
3668   if (NumNonZero > 4)
3669     return SDValue();
3670
3671   DebugLoc dl = Op.getDebugLoc();
3672   SDValue V(0, 0);
3673   bool First = true;
3674   for (unsigned i = 0; i < 8; ++i) {
3675     bool isNonZero = (NonZeros & (1 << i)) != 0;
3676     if (isNonZero) {
3677       if (First) {
3678         if (NumZero)
3679           V = getZeroVector(MVT::v8i16, true, DAG, dl);
3680         else
3681           V = DAG.getUNDEF(MVT::v8i16);
3682         First = false;
3683       }
3684       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
3685                       MVT::v8i16, V, Op.getOperand(i),
3686                       DAG.getIntPtrConstant(i));
3687     }
3688   }
3689
3690   return V;
3691 }
3692
3693 /// getVShift - Return a vector logical shift node.
3694 ///
3695 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
3696                          unsigned NumBits, SelectionDAG &DAG,
3697                          const TargetLowering &TLI, DebugLoc dl) {
3698   bool isMMX = VT.getSizeInBits() == 64;
3699   EVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
3700   unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3701   SrcOp = DAG.getNode(ISD::BIT_CONVERT, dl, ShVT, SrcOp);
3702   return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3703                      DAG.getNode(Opc, dl, ShVT, SrcOp,
3704                              DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3705 }
3706
3707 SDValue
3708 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
3709                                           SelectionDAG &DAG) const {
3710   
3711   // Check if the scalar load can be widened into a vector load. And if
3712   // the address is "base + cst" see if the cst can be "absorbed" into
3713   // the shuffle mask.
3714   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
3715     SDValue Ptr = LD->getBasePtr();
3716     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
3717       return SDValue();
3718     EVT PVT = LD->getValueType(0);
3719     if (PVT != MVT::i32 && PVT != MVT::f32)
3720       return SDValue();
3721
3722     int FI = -1;
3723     int64_t Offset = 0;
3724     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
3725       FI = FINode->getIndex();
3726       Offset = 0;
3727     } else if (Ptr.getOpcode() == ISD::ADD &&
3728                isa<ConstantSDNode>(Ptr.getOperand(1)) &&
3729                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
3730       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
3731       Offset = Ptr.getConstantOperandVal(1);
3732       Ptr = Ptr.getOperand(0);
3733     } else {
3734       return SDValue();
3735     }
3736
3737     SDValue Chain = LD->getChain();
3738     // Make sure the stack object alignment is at least 16.
3739     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3740     if (DAG.InferPtrAlignment(Ptr) < 16) {
3741       if (MFI->isFixedObjectIndex(FI)) {
3742         // Can't change the alignment. FIXME: It's possible to compute
3743         // the exact stack offset and reference FI + adjust offset instead.
3744         // If someone *really* cares about this. That's the way to implement it.
3745         return SDValue();
3746       } else {
3747         MFI->setObjectAlignment(FI, 16);
3748       }
3749     }
3750
3751     // (Offset % 16) must be multiple of 4. Then address is then
3752     // Ptr + (Offset & ~15).
3753     if (Offset < 0)
3754       return SDValue();
3755     if ((Offset % 16) & 3)
3756       return SDValue();
3757     int64_t StartOffset = Offset & ~15;
3758     if (StartOffset)
3759       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
3760                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
3761
3762     int EltNo = (Offset - StartOffset) >> 2;
3763     int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
3764     EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
3765     SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,LD->getSrcValue(),0,
3766                              false, false, 0);
3767     // Canonicalize it to a v4i32 shuffle.
3768     V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32, V1);
3769     return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3770                        DAG.getVectorShuffle(MVT::v4i32, dl, V1,
3771                                             DAG.getUNDEF(MVT::v4i32), &Mask[0]));
3772   }
3773
3774   return SDValue();
3775 }
3776
3777 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a 
3778 /// vector of type 'VT', see if the elements can be replaced by a single large 
3779 /// load which has the same value as a build_vector whose operands are 'elts'.
3780 ///
3781 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
3782 /// 
3783 /// FIXME: we'd also like to handle the case where the last elements are zero
3784 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
3785 /// There's even a handy isZeroNode for that purpose.
3786 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
3787                                         DebugLoc &dl, SelectionDAG &DAG) {
3788   EVT EltVT = VT.getVectorElementType();
3789   unsigned NumElems = Elts.size();
3790   
3791   LoadSDNode *LDBase = NULL;
3792   unsigned LastLoadedElt = -1U;
3793   
3794   // For each element in the initializer, see if we've found a load or an undef.
3795   // If we don't find an initial load element, or later load elements are 
3796   // non-consecutive, bail out.
3797   for (unsigned i = 0; i < NumElems; ++i) {
3798     SDValue Elt = Elts[i];
3799     
3800     if (!Elt.getNode() ||
3801         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
3802       return SDValue();
3803     if (!LDBase) {
3804       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
3805         return SDValue();
3806       LDBase = cast<LoadSDNode>(Elt.getNode());
3807       LastLoadedElt = i;
3808       continue;
3809     }
3810     if (Elt.getOpcode() == ISD::UNDEF)
3811       continue;
3812
3813     LoadSDNode *LD = cast<LoadSDNode>(Elt);
3814     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
3815       return SDValue();
3816     LastLoadedElt = i;
3817   }
3818
3819   // If we have found an entire vector of loads and undefs, then return a large
3820   // load of the entire vector width starting at the base pointer.  If we found
3821   // consecutive loads for the low half, generate a vzext_load node.
3822   if (LastLoadedElt == NumElems - 1) {
3823     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
3824       return DAG.getLoad(VT, dl, LDBase->getChain(), LDBase->getBasePtr(),
3825                          LDBase->getSrcValue(), LDBase->getSrcValueOffset(),
3826                          LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
3827     return DAG.getLoad(VT, dl, LDBase->getChain(), LDBase->getBasePtr(),
3828                        LDBase->getSrcValue(), LDBase->getSrcValueOffset(),
3829                        LDBase->isVolatile(), LDBase->isNonTemporal(),
3830                        LDBase->getAlignment());
3831   } else if (NumElems == 4 && LastLoadedElt == 1) {
3832     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
3833     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
3834     SDValue ResNode = DAG.getNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2);
3835     return DAG.getNode(ISD::BIT_CONVERT, dl, VT, ResNode);
3836   }
3837   return SDValue();
3838 }
3839
3840 SDValue
3841 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
3842   DebugLoc dl = Op.getDebugLoc();
3843   // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3844   if (ISD::isBuildVectorAllZeros(Op.getNode())
3845       || ISD::isBuildVectorAllOnes(Op.getNode())) {
3846     // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3847     // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3848     // eliminated on x86-32 hosts.
3849     if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3850       return Op;
3851
3852     if (ISD::isBuildVectorAllOnes(Op.getNode()))
3853       return getOnesVector(Op.getValueType(), DAG, dl);
3854     return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
3855   }
3856
3857   EVT VT = Op.getValueType();
3858   EVT ExtVT = VT.getVectorElementType();
3859   unsigned EVTBits = ExtVT.getSizeInBits();
3860
3861   unsigned NumElems = Op.getNumOperands();
3862   unsigned NumZero  = 0;
3863   unsigned NumNonZero = 0;
3864   unsigned NonZeros = 0;
3865   bool IsAllConstants = true;
3866   SmallSet<SDValue, 8> Values;
3867   for (unsigned i = 0; i < NumElems; ++i) {
3868     SDValue Elt = Op.getOperand(i);
3869     if (Elt.getOpcode() == ISD::UNDEF)
3870       continue;
3871     Values.insert(Elt);
3872     if (Elt.getOpcode() != ISD::Constant &&
3873         Elt.getOpcode() != ISD::ConstantFP)
3874       IsAllConstants = false;
3875     if (X86::isZeroNode(Elt))
3876       NumZero++;
3877     else {
3878       NonZeros |= (1 << i);
3879       NumNonZero++;
3880     }
3881   }
3882
3883   if (NumNonZero == 0) {
3884     // All undef vector. Return an UNDEF.  All zero vectors were handled above.
3885     return DAG.getUNDEF(VT);
3886   }
3887
3888   // Special case for single non-zero, non-undef, element.
3889   if (NumNonZero == 1) {
3890     unsigned Idx = CountTrailingZeros_32(NonZeros);
3891     SDValue Item = Op.getOperand(Idx);
3892
3893     // If this is an insertion of an i64 value on x86-32, and if the top bits of
3894     // the value are obviously zero, truncate the value to i32 and do the
3895     // insertion that way.  Only do this if the value is non-constant or if the
3896     // value is a constant being inserted into element 0.  It is cheaper to do
3897     // a constant pool load than it is to do a movd + shuffle.
3898     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
3899         (!IsAllConstants || Idx == 0)) {
3900       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3901         // Handle MMX and SSE both.
3902         EVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3903         unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
3904
3905         // Truncate the value (which may itself be a constant) to i32, and
3906         // convert it to a vector with movd (S2V+shuffle to zero extend).
3907         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
3908         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
3909         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3910                                            Subtarget->hasSSE2(), DAG);
3911
3912         // Now we have our 32-bit value zero extended in the low element of
3913         // a vector.  If Idx != 0, swizzle it into place.
3914         if (Idx != 0) {
3915           SmallVector<int, 4> Mask;
3916           Mask.push_back(Idx);
3917           for (unsigned i = 1; i != VecElts; ++i)
3918             Mask.push_back(i);
3919           Item = DAG.getVectorShuffle(VecVT, dl, Item,
3920                                       DAG.getUNDEF(Item.getValueType()),
3921                                       &Mask[0]);
3922         }
3923         return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Item);
3924       }
3925     }
3926
3927     // If we have a constant or non-constant insertion into the low element of
3928     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3929     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
3930     // depending on what the source datatype is.
3931     if (Idx == 0) {
3932       if (NumZero == 0) {
3933         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3934       } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
3935           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
3936         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3937         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3938         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
3939                                            DAG);
3940       } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
3941         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
3942         EVT MiddleVT = VT.getSizeInBits() == 64 ? MVT::v2i32 : MVT::v4i32;
3943         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
3944         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3945                                            Subtarget->hasSSE2(), DAG);
3946         return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Item);
3947       }
3948     }
3949
3950     // Is it a vector logical left shift?
3951     if (NumElems == 2 && Idx == 1 &&
3952         X86::isZeroNode(Op.getOperand(0)) &&
3953         !X86::isZeroNode(Op.getOperand(1))) {
3954       unsigned NumBits = VT.getSizeInBits();
3955       return getVShift(true, VT,
3956                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
3957                                    VT, Op.getOperand(1)),
3958                        NumBits/2, DAG, *this, dl);
3959     }
3960
3961     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3962       return SDValue();
3963
3964     // Otherwise, if this is a vector with i32 or f32 elements, and the element
3965     // is a non-constant being inserted into an element other than the low one,
3966     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
3967     // movd/movss) to move this into the low element, then shuffle it into
3968     // place.
3969     if (EVTBits == 32) {
3970       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3971
3972       // Turn it into a shuffle of zero and zero-extended scalar to vector.
3973       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3974                                          Subtarget->hasSSE2(), DAG);
3975       SmallVector<int, 8> MaskVec;
3976       for (unsigned i = 0; i < NumElems; i++)
3977         MaskVec.push_back(i == Idx ? 0 : 1);
3978       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
3979     }
3980   }
3981
3982   // Splat is obviously ok. Let legalizer expand it to a shuffle.
3983   if (Values.size() == 1) {
3984     if (EVTBits == 32) {
3985       // Instead of a shuffle like this:
3986       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
3987       // Check if it's possible to issue this instead.
3988       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
3989       unsigned Idx = CountTrailingZeros_32(NonZeros);
3990       SDValue Item = Op.getOperand(Idx);
3991       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
3992         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
3993     }
3994     return SDValue();
3995   }
3996
3997   // A vector full of immediates; various special cases are already
3998   // handled, so this is best done with a single constant-pool load.
3999   if (IsAllConstants)
4000     return SDValue();
4001
4002   // Let legalizer expand 2-wide build_vectors.
4003   if (EVTBits == 64) {
4004     if (NumNonZero == 1) {
4005       // One half is zero or undef.
4006       unsigned Idx = CountTrailingZeros_32(NonZeros);
4007       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
4008                                  Op.getOperand(Idx));
4009       return getShuffleVectorZeroOrUndef(V2, Idx, true,
4010                                          Subtarget->hasSSE2(), DAG);
4011     }
4012     return SDValue();
4013   }
4014
4015   // If element VT is < 32 bits, convert it to inserts into a zero vector.
4016   if (EVTBits == 8 && NumElems == 16) {
4017     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
4018                                         *this);
4019     if (V.getNode()) return V;
4020   }
4021
4022   if (EVTBits == 16 && NumElems == 8) {
4023     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
4024                                         *this);
4025     if (V.getNode()) return V;
4026   }
4027
4028   // If element VT is == 32 bits, turn it into a number of shuffles.
4029   SmallVector<SDValue, 8> V;
4030   V.resize(NumElems);
4031   if (NumElems == 4 && NumZero > 0) {
4032     for (unsigned i = 0; i < 4; ++i) {
4033       bool isZero = !(NonZeros & (1 << i));
4034       if (isZero)
4035         V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4036       else
4037         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4038     }
4039
4040     for (unsigned i = 0; i < 2; ++i) {
4041       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
4042         default: break;
4043         case 0:
4044           V[i] = V[i*2];  // Must be a zero vector.
4045           break;
4046         case 1:
4047           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
4048           break;
4049         case 2:
4050           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
4051           break;
4052         case 3:
4053           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
4054           break;
4055       }
4056     }
4057
4058     SmallVector<int, 8> MaskVec;
4059     bool Reverse = (NonZeros & 0x3) == 2;
4060     for (unsigned i = 0; i < 2; ++i)
4061       MaskVec.push_back(Reverse ? 1-i : i);
4062     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
4063     for (unsigned i = 0; i < 2; ++i)
4064       MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
4065     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
4066   }
4067
4068   if (Values.size() > 1 && VT.getSizeInBits() == 128) {
4069     // Check for a build vector of consecutive loads.
4070     for (unsigned i = 0; i < NumElems; ++i)
4071       V[i] = Op.getOperand(i);
4072     
4073     // Check for elements which are consecutive loads.
4074     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
4075     if (LD.getNode())
4076       return LD;
4077     
4078     // For SSE 4.1, use inserts into undef.  
4079     if (getSubtarget()->hasSSE41()) {
4080       V[0] = DAG.getUNDEF(VT);
4081       for (unsigned i = 0; i < NumElems; ++i)
4082         if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
4083           V[0] = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, V[0],
4084                              Op.getOperand(i), DAG.getIntPtrConstant(i));
4085       return V[0];
4086     }
4087     
4088     // Otherwise, expand into a number of unpckl*
4089     // e.g. for v4f32
4090     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
4091     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
4092     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
4093     for (unsigned i = 0; i < NumElems; ++i)
4094       V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4095     NumElems >>= 1;
4096     while (NumElems != 0) {
4097       for (unsigned i = 0; i < NumElems; ++i)
4098         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + NumElems]);
4099       NumElems >>= 1;
4100     }
4101     return V[0];
4102   }
4103   return SDValue();
4104 }
4105
4106 SDValue
4107 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
4108   // We support concatenate two MMX registers and place them in a MMX
4109   // register.  This is better than doing a stack convert.
4110   DebugLoc dl = Op.getDebugLoc();
4111   EVT ResVT = Op.getValueType();
4112   assert(Op.getNumOperands() == 2);
4113   assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
4114          ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
4115   int Mask[2];
4116   SDValue InVec = DAG.getNode(ISD::BIT_CONVERT,dl, MVT::v1i64, Op.getOperand(0));
4117   SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4118   InVec = Op.getOperand(1);
4119   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4120     unsigned NumElts = ResVT.getVectorNumElements();
4121     VecOp = DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
4122     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
4123                        InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
4124   } else {
4125     InVec = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v1i64, InVec);
4126     SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4127     Mask[0] = 0; Mask[1] = 2;
4128     VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
4129   }
4130   return DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
4131 }
4132
4133 // v8i16 shuffles - Prefer shuffles in the following order:
4134 // 1. [all]   pshuflw, pshufhw, optional move
4135 // 2. [ssse3] 1 x pshufb
4136 // 3. [ssse3] 2 x pshufb + 1 x por
4137 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
4138 static
4139 SDValue LowerVECTOR_SHUFFLEv8i16(ShuffleVectorSDNode *SVOp,
4140                                  SelectionDAG &DAG,
4141                                  const X86TargetLowering &TLI) {
4142   SDValue V1 = SVOp->getOperand(0);
4143   SDValue V2 = SVOp->getOperand(1);
4144   DebugLoc dl = SVOp->getDebugLoc();
4145   SmallVector<int, 8> MaskVals;
4146
4147   // Determine if more than 1 of the words in each of the low and high quadwords
4148   // of the result come from the same quadword of one of the two inputs.  Undef
4149   // mask values count as coming from any quadword, for better codegen.
4150   SmallVector<unsigned, 4> LoQuad(4);
4151   SmallVector<unsigned, 4> HiQuad(4);
4152   BitVector InputQuads(4);
4153   for (unsigned i = 0; i < 8; ++i) {
4154     SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
4155     int EltIdx = SVOp->getMaskElt(i);
4156     MaskVals.push_back(EltIdx);
4157     if (EltIdx < 0) {
4158       ++Quad[0];
4159       ++Quad[1];
4160       ++Quad[2];
4161       ++Quad[3];
4162       continue;
4163     }
4164     ++Quad[EltIdx / 4];
4165     InputQuads.set(EltIdx / 4);
4166   }
4167
4168   int BestLoQuad = -1;
4169   unsigned MaxQuad = 1;
4170   for (unsigned i = 0; i < 4; ++i) {
4171     if (LoQuad[i] > MaxQuad) {
4172       BestLoQuad = i;
4173       MaxQuad = LoQuad[i];
4174     }
4175   }
4176
4177   int BestHiQuad = -1;
4178   MaxQuad = 1;
4179   for (unsigned i = 0; i < 4; ++i) {
4180     if (HiQuad[i] > MaxQuad) {
4181       BestHiQuad = i;
4182       MaxQuad = HiQuad[i];
4183     }
4184   }
4185
4186   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
4187   // of the two input vectors, shuffle them into one input vector so only a
4188   // single pshufb instruction is necessary. If There are more than 2 input
4189   // quads, disable the next transformation since it does not help SSSE3.
4190   bool V1Used = InputQuads[0] || InputQuads[1];
4191   bool V2Used = InputQuads[2] || InputQuads[3];
4192   if (TLI.getSubtarget()->hasSSSE3()) {
4193     if (InputQuads.count() == 2 && V1Used && V2Used) {
4194       BestLoQuad = InputQuads.find_first();
4195       BestHiQuad = InputQuads.find_next(BestLoQuad);
4196     }
4197     if (InputQuads.count() > 2) {
4198       BestLoQuad = -1;
4199       BestHiQuad = -1;
4200     }
4201   }
4202
4203   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
4204   // the shuffle mask.  If a quad is scored as -1, that means that it contains
4205   // words from all 4 input quadwords.
4206   SDValue NewV;
4207   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
4208     SmallVector<int, 8> MaskV;
4209     MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
4210     MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
4211     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
4212                   DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V1),
4213                   DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V2), &MaskV[0]);
4214     NewV = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, NewV);
4215
4216     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
4217     // source words for the shuffle, to aid later transformations.
4218     bool AllWordsInNewV = true;
4219     bool InOrder[2] = { true, true };
4220     for (unsigned i = 0; i != 8; ++i) {
4221       int idx = MaskVals[i];
4222       if (idx != (int)i)
4223         InOrder[i/4] = false;
4224       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
4225         continue;
4226       AllWordsInNewV = false;
4227       break;
4228     }
4229
4230     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
4231     if (AllWordsInNewV) {
4232       for (int i = 0; i != 8; ++i) {
4233         int idx = MaskVals[i];
4234         if (idx < 0)
4235           continue;
4236         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
4237         if ((idx != i) && idx < 4)
4238           pshufhw = false;
4239         if ((idx != i) && idx > 3)
4240           pshuflw = false;
4241       }
4242       V1 = NewV;
4243       V2Used = false;
4244       BestLoQuad = 0;
4245       BestHiQuad = 1;
4246     }
4247
4248     // If we've eliminated the use of V2, and the new mask is a pshuflw or
4249     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
4250     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
4251       return DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
4252                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
4253     }
4254   }
4255
4256   // If we have SSSE3, and all words of the result are from 1 input vector,
4257   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
4258   // is present, fall back to case 4.
4259   if (TLI.getSubtarget()->hasSSSE3()) {
4260     SmallVector<SDValue,16> pshufbMask;
4261
4262     // If we have elements from both input vectors, set the high bit of the
4263     // shuffle mask element to zero out elements that come from V2 in the V1
4264     // mask, and elements that come from V1 in the V2 mask, so that the two
4265     // results can be OR'd together.
4266     bool TwoInputs = V1Used && V2Used;
4267     for (unsigned i = 0; i != 8; ++i) {
4268       int EltIdx = MaskVals[i] * 2;
4269       if (TwoInputs && (EltIdx >= 16)) {
4270         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4271         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4272         continue;
4273       }
4274       pshufbMask.push_back(DAG.getConstant(EltIdx,   MVT::i8));
4275       pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
4276     }
4277     V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V1);
4278     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4279                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4280                                  MVT::v16i8, &pshufbMask[0], 16));
4281     if (!TwoInputs)
4282       return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4283
4284     // Calculate the shuffle mask for the second input, shuffle it, and
4285     // OR it with the first shuffled input.
4286     pshufbMask.clear();
4287     for (unsigned i = 0; i != 8; ++i) {
4288       int EltIdx = MaskVals[i] * 2;
4289       if (EltIdx < 16) {
4290         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4291         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4292         continue;
4293       }
4294       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4295       pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
4296     }
4297     V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V2);
4298     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4299                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4300                                  MVT::v16i8, &pshufbMask[0], 16));
4301     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4302     return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4303   }
4304
4305   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
4306   // and update MaskVals with new element order.
4307   BitVector InOrder(8);
4308   if (BestLoQuad >= 0) {
4309     SmallVector<int, 8> MaskV;
4310     for (int i = 0; i != 4; ++i) {
4311       int idx = MaskVals[i];
4312       if (idx < 0) {
4313         MaskV.push_back(-1);
4314         InOrder.set(i);
4315       } else if ((idx / 4) == BestLoQuad) {
4316         MaskV.push_back(idx & 3);
4317         InOrder.set(i);
4318       } else {
4319         MaskV.push_back(-1);
4320       }
4321     }
4322     for (unsigned i = 4; i != 8; ++i)
4323       MaskV.push_back(i);
4324     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4325                                 &MaskV[0]);
4326   }
4327
4328   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
4329   // and update MaskVals with the new element order.
4330   if (BestHiQuad >= 0) {
4331     SmallVector<int, 8> MaskV;
4332     for (unsigned i = 0; i != 4; ++i)
4333       MaskV.push_back(i);
4334     for (unsigned i = 4; i != 8; ++i) {
4335       int idx = MaskVals[i];
4336       if (idx < 0) {
4337         MaskV.push_back(-1);
4338         InOrder.set(i);
4339       } else if ((idx / 4) == BestHiQuad) {
4340         MaskV.push_back((idx & 3) + 4);
4341         InOrder.set(i);
4342       } else {
4343         MaskV.push_back(-1);
4344       }
4345     }
4346     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4347                                 &MaskV[0]);
4348   }
4349
4350   // In case BestHi & BestLo were both -1, which means each quadword has a word
4351   // from each of the four input quadwords, calculate the InOrder bitvector now
4352   // before falling through to the insert/extract cleanup.
4353   if (BestLoQuad == -1 && BestHiQuad == -1) {
4354     NewV = V1;
4355     for (int i = 0; i != 8; ++i)
4356       if (MaskVals[i] < 0 || MaskVals[i] == i)
4357         InOrder.set(i);
4358   }
4359
4360   // The other elements are put in the right place using pextrw and pinsrw.
4361   for (unsigned i = 0; i != 8; ++i) {
4362     if (InOrder[i])
4363       continue;
4364     int EltIdx = MaskVals[i];
4365     if (EltIdx < 0)
4366       continue;
4367     SDValue ExtOp = (EltIdx < 8)
4368     ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
4369                   DAG.getIntPtrConstant(EltIdx))
4370     : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
4371                   DAG.getIntPtrConstant(EltIdx - 8));
4372     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
4373                        DAG.getIntPtrConstant(i));
4374   }
4375   return NewV;
4376 }
4377
4378 // v16i8 shuffles - Prefer shuffles in the following order:
4379 // 1. [ssse3] 1 x pshufb
4380 // 2. [ssse3] 2 x pshufb + 1 x por
4381 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
4382 static
4383 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
4384                                  SelectionDAG &DAG,
4385                                  const X86TargetLowering &TLI) {
4386   SDValue V1 = SVOp->getOperand(0);
4387   SDValue V2 = SVOp->getOperand(1);
4388   DebugLoc dl = SVOp->getDebugLoc();
4389   SmallVector<int, 16> MaskVals;
4390   SVOp->getMask(MaskVals);
4391
4392   // If we have SSSE3, case 1 is generated when all result bytes come from
4393   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
4394   // present, fall back to case 3.
4395   // FIXME: kill V2Only once shuffles are canonizalized by getNode.
4396   bool V1Only = true;
4397   bool V2Only = true;
4398   for (unsigned i = 0; i < 16; ++i) {
4399     int EltIdx = MaskVals[i];
4400     if (EltIdx < 0)
4401       continue;
4402     if (EltIdx < 16)
4403       V2Only = false;
4404     else
4405       V1Only = false;
4406   }
4407
4408   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
4409   if (TLI.getSubtarget()->hasSSSE3()) {
4410     SmallVector<SDValue,16> pshufbMask;
4411
4412     // If all result elements are from one input vector, then only translate
4413     // undef mask values to 0x80 (zero out result) in the pshufb mask.
4414     //
4415     // Otherwise, we have elements from both input vectors, and must zero out
4416     // elements that come from V2 in the first mask, and V1 in the second mask
4417     // so that we can OR them together.
4418     bool TwoInputs = !(V1Only || V2Only);
4419     for (unsigned i = 0; i != 16; ++i) {
4420       int EltIdx = MaskVals[i];
4421       if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
4422         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4423         continue;
4424       }
4425       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4426     }
4427     // If all the elements are from V2, assign it to V1 and return after
4428     // building the first pshufb.
4429     if (V2Only)
4430       V1 = V2;
4431     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4432                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4433                                  MVT::v16i8, &pshufbMask[0], 16));
4434     if (!TwoInputs)
4435       return V1;
4436
4437     // Calculate the shuffle mask for the second input, shuffle it, and
4438     // OR it with the first shuffled input.
4439     pshufbMask.clear();
4440     for (unsigned i = 0; i != 16; ++i) {
4441       int EltIdx = MaskVals[i];
4442       if (EltIdx < 16) {
4443         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4444         continue;
4445       }
4446       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4447     }
4448     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4449                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4450                                  MVT::v16i8, &pshufbMask[0], 16));
4451     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4452   }
4453
4454   // No SSSE3 - Calculate in place words and then fix all out of place words
4455   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
4456   // the 16 different words that comprise the two doublequadword input vectors.
4457   V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4458   V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V2);
4459   SDValue NewV = V2Only ? V2 : V1;
4460   for (int i = 0; i != 8; ++i) {
4461     int Elt0 = MaskVals[i*2];
4462     int Elt1 = MaskVals[i*2+1];
4463
4464     // This word of the result is all undef, skip it.
4465     if (Elt0 < 0 && Elt1 < 0)
4466       continue;
4467
4468     // This word of the result is already in the correct place, skip it.
4469     if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
4470       continue;
4471     if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
4472       continue;
4473
4474     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
4475     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
4476     SDValue InsElt;
4477
4478     // If Elt0 and Elt1 are defined, are consecutive, and can be load
4479     // using a single extract together, load it and store it.
4480     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
4481       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4482                            DAG.getIntPtrConstant(Elt1 / 2));
4483       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4484                         DAG.getIntPtrConstant(i));
4485       continue;
4486     }
4487
4488     // If Elt1 is defined, extract it from the appropriate source.  If the
4489     // source byte is not also odd, shift the extracted word left 8 bits
4490     // otherwise clear the bottom 8 bits if we need to do an or.
4491     if (Elt1 >= 0) {
4492       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4493                            DAG.getIntPtrConstant(Elt1 / 2));
4494       if ((Elt1 & 1) == 0)
4495         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
4496                              DAG.getConstant(8, TLI.getShiftAmountTy()));
4497       else if (Elt0 >= 0)
4498         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
4499                              DAG.getConstant(0xFF00, MVT::i16));
4500     }
4501     // If Elt0 is defined, extract it from the appropriate source.  If the
4502     // source byte is not also even, shift the extracted word right 8 bits. If
4503     // Elt1 was also defined, OR the extracted values together before
4504     // inserting them in the result.
4505     if (Elt0 >= 0) {
4506       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
4507                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
4508       if ((Elt0 & 1) != 0)
4509         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
4510                               DAG.getConstant(8, TLI.getShiftAmountTy()));
4511       else if (Elt1 >= 0)
4512         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
4513                              DAG.getConstant(0x00FF, MVT::i16));
4514       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
4515                          : InsElt0;
4516     }
4517     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4518                        DAG.getIntPtrConstant(i));
4519   }
4520   return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, NewV);
4521 }
4522
4523 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
4524 /// ones, or rewriting v4i32 / v2i32 as 2 wide ones if possible. This can be
4525 /// done when every pair / quad of shuffle mask elements point to elements in
4526 /// the right sequence. e.g.
4527 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
4528 static
4529 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
4530                                  SelectionDAG &DAG,
4531                                  const TargetLowering &TLI, DebugLoc dl) {
4532   EVT VT = SVOp->getValueType(0);
4533   SDValue V1 = SVOp->getOperand(0);
4534   SDValue V2 = SVOp->getOperand(1);
4535   unsigned NumElems = VT.getVectorNumElements();
4536   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
4537   EVT MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
4538   EVT NewVT = MaskVT;
4539   switch (VT.getSimpleVT().SimpleTy) {
4540   default: assert(false && "Unexpected!");
4541   case MVT::v4f32: NewVT = MVT::v2f64; break;
4542   case MVT::v4i32: NewVT = MVT::v2i64; break;
4543   case MVT::v8i16: NewVT = MVT::v4i32; break;
4544   case MVT::v16i8: NewVT = MVT::v4i32; break;
4545   }
4546
4547   if (NewWidth == 2) {
4548     if (VT.isInteger())
4549       NewVT = MVT::v2i64;
4550     else
4551       NewVT = MVT::v2f64;
4552   }
4553   int Scale = NumElems / NewWidth;
4554   SmallVector<int, 8> MaskVec;
4555   for (unsigned i = 0; i < NumElems; i += Scale) {
4556     int StartIdx = -1;
4557     for (int j = 0; j < Scale; ++j) {
4558       int EltIdx = SVOp->getMaskElt(i+j);
4559       if (EltIdx < 0)
4560         continue;
4561       if (StartIdx == -1)
4562         StartIdx = EltIdx - (EltIdx % Scale);
4563       if (EltIdx != StartIdx + j)
4564         return SDValue();
4565     }
4566     if (StartIdx == -1)
4567       MaskVec.push_back(-1);
4568     else
4569       MaskVec.push_back(StartIdx / Scale);
4570   }
4571
4572   V1 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V1);
4573   V2 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V2);
4574   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
4575 }
4576
4577 /// getVZextMovL - Return a zero-extending vector move low node.
4578 ///
4579 static SDValue getVZextMovL(EVT VT, EVT OpVT,
4580                             SDValue SrcOp, SelectionDAG &DAG,
4581                             const X86Subtarget *Subtarget, DebugLoc dl) {
4582   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
4583     LoadSDNode *LD = NULL;
4584     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
4585       LD = dyn_cast<LoadSDNode>(SrcOp);
4586     if (!LD) {
4587       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
4588       // instead.
4589       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
4590       if ((ExtVT.SimpleTy != MVT::i64 || Subtarget->is64Bit()) &&
4591           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
4592           SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
4593           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
4594         // PR2108
4595         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
4596         return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4597                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4598                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4599                                                    OpVT,
4600                                                    SrcOp.getOperand(0)
4601                                                           .getOperand(0))));
4602       }
4603     }
4604   }
4605
4606   return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4607                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4608                                  DAG.getNode(ISD::BIT_CONVERT, dl,
4609                                              OpVT, SrcOp)));
4610 }
4611
4612 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
4613 /// shuffles.
4614 static SDValue
4615 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4616   SDValue V1 = SVOp->getOperand(0);
4617   SDValue V2 = SVOp->getOperand(1);
4618   DebugLoc dl = SVOp->getDebugLoc();
4619   EVT VT = SVOp->getValueType(0);
4620
4621   SmallVector<std::pair<int, int>, 8> Locs;
4622   Locs.resize(4);
4623   SmallVector<int, 8> Mask1(4U, -1);
4624   SmallVector<int, 8> PermMask;
4625   SVOp->getMask(PermMask);
4626
4627   unsigned NumHi = 0;
4628   unsigned NumLo = 0;
4629   for (unsigned i = 0; i != 4; ++i) {
4630     int Idx = PermMask[i];
4631     if (Idx < 0) {
4632       Locs[i] = std::make_pair(-1, -1);
4633     } else {
4634       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
4635       if (Idx < 4) {
4636         Locs[i] = std::make_pair(0, NumLo);
4637         Mask1[NumLo] = Idx;
4638         NumLo++;
4639       } else {
4640         Locs[i] = std::make_pair(1, NumHi);
4641         if (2+NumHi < 4)
4642           Mask1[2+NumHi] = Idx;
4643         NumHi++;
4644       }
4645     }
4646   }
4647
4648   if (NumLo <= 2 && NumHi <= 2) {
4649     // If no more than two elements come from either vector. This can be
4650     // implemented with two shuffles. First shuffle gather the elements.
4651     // The second shuffle, which takes the first shuffle as both of its
4652     // vector operands, put the elements into the right order.
4653     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4654
4655     SmallVector<int, 8> Mask2(4U, -1);
4656
4657     for (unsigned i = 0; i != 4; ++i) {
4658       if (Locs[i].first == -1)
4659         continue;
4660       else {
4661         unsigned Idx = (i < 2) ? 0 : 4;
4662         Idx += Locs[i].first * 2 + Locs[i].second;
4663         Mask2[i] = Idx;
4664       }
4665     }
4666
4667     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
4668   } else if (NumLo == 3 || NumHi == 3) {
4669     // Otherwise, we must have three elements from one vector, call it X, and
4670     // one element from the other, call it Y.  First, use a shufps to build an
4671     // intermediate vector with the one element from Y and the element from X
4672     // that will be in the same half in the final destination (the indexes don't
4673     // matter). Then, use a shufps to build the final vector, taking the half
4674     // containing the element from Y from the intermediate, and the other half
4675     // from X.
4676     if (NumHi == 3) {
4677       // Normalize it so the 3 elements come from V1.
4678       CommuteVectorShuffleMask(PermMask, VT);
4679       std::swap(V1, V2);
4680     }
4681
4682     // Find the element from V2.
4683     unsigned HiIndex;
4684     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
4685       int Val = PermMask[HiIndex];
4686       if (Val < 0)
4687         continue;
4688       if (Val >= 4)
4689         break;
4690     }
4691
4692     Mask1[0] = PermMask[HiIndex];
4693     Mask1[1] = -1;
4694     Mask1[2] = PermMask[HiIndex^1];
4695     Mask1[3] = -1;
4696     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4697
4698     if (HiIndex >= 2) {
4699       Mask1[0] = PermMask[0];
4700       Mask1[1] = PermMask[1];
4701       Mask1[2] = HiIndex & 1 ? 6 : 4;
4702       Mask1[3] = HiIndex & 1 ? 4 : 6;
4703       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4704     } else {
4705       Mask1[0] = HiIndex & 1 ? 2 : 0;
4706       Mask1[1] = HiIndex & 1 ? 0 : 2;
4707       Mask1[2] = PermMask[2];
4708       Mask1[3] = PermMask[3];
4709       if (Mask1[2] >= 0)
4710         Mask1[2] += 4;
4711       if (Mask1[3] >= 0)
4712         Mask1[3] += 4;
4713       return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
4714     }
4715   }
4716
4717   // Break it into (shuffle shuffle_hi, shuffle_lo).
4718   Locs.clear();
4719   SmallVector<int,8> LoMask(4U, -1);
4720   SmallVector<int,8> HiMask(4U, -1);
4721
4722   SmallVector<int,8> *MaskPtr = &LoMask;
4723   unsigned MaskIdx = 0;
4724   unsigned LoIdx = 0;
4725   unsigned HiIdx = 2;
4726   for (unsigned i = 0; i != 4; ++i) {
4727     if (i == 2) {
4728       MaskPtr = &HiMask;
4729       MaskIdx = 1;
4730       LoIdx = 0;
4731       HiIdx = 2;
4732     }
4733     int Idx = PermMask[i];
4734     if (Idx < 0) {
4735       Locs[i] = std::make_pair(-1, -1);
4736     } else if (Idx < 4) {
4737       Locs[i] = std::make_pair(MaskIdx, LoIdx);
4738       (*MaskPtr)[LoIdx] = Idx;
4739       LoIdx++;
4740     } else {
4741       Locs[i] = std::make_pair(MaskIdx, HiIdx);
4742       (*MaskPtr)[HiIdx] = Idx;
4743       HiIdx++;
4744     }
4745   }
4746
4747   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
4748   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
4749   SmallVector<int, 8> MaskOps;
4750   for (unsigned i = 0; i != 4; ++i) {
4751     if (Locs[i].first == -1) {
4752       MaskOps.push_back(-1);
4753     } else {
4754       unsigned Idx = Locs[i].first * 4 + Locs[i].second;
4755       MaskOps.push_back(Idx);
4756     }
4757   }
4758   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
4759 }
4760
4761 SDValue
4762 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
4763   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4764   SDValue V1 = Op.getOperand(0);
4765   SDValue V2 = Op.getOperand(1);
4766   EVT VT = Op.getValueType();
4767   DebugLoc dl = Op.getDebugLoc();
4768   unsigned NumElems = VT.getVectorNumElements();
4769   bool isMMX = VT.getSizeInBits() == 64;
4770   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
4771   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
4772   bool V1IsSplat = false;
4773   bool V2IsSplat = false;
4774
4775   if (isZeroShuffle(SVOp))
4776     return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4777
4778   // Promote splats to v4f32.
4779   if (SVOp->isSplat()) {
4780     if (isMMX || NumElems < 4)
4781       return Op;
4782     return PromoteSplat(SVOp, DAG, Subtarget->hasSSE2());
4783   }
4784
4785   // If the shuffle can be profitably rewritten as a narrower shuffle, then
4786   // do it!
4787   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
4788     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4789     if (NewOp.getNode())
4790       return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4791                          LowerVECTOR_SHUFFLE(NewOp, DAG));
4792   } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
4793     // FIXME: Figure out a cleaner way to do this.
4794     // Try to make use of movq to zero out the top part.
4795     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
4796       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4797       if (NewOp.getNode()) {
4798         if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
4799           return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
4800                               DAG, Subtarget, dl);
4801       }
4802     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
4803       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4804       if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
4805         return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
4806                             DAG, Subtarget, dl);
4807     }
4808   }
4809
4810   if (X86::isPSHUFDMask(SVOp))
4811     return Op;
4812
4813   // Check if this can be converted into a logical shift.
4814   bool isLeft = false;
4815   unsigned ShAmt = 0;
4816   SDValue ShVal;
4817   bool isShift = getSubtarget()->hasSSE2() &&
4818     isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
4819   if (isShift && ShVal.hasOneUse()) {
4820     // If the shifted value has multiple uses, it may be cheaper to use
4821     // v_set0 + movlhps or movhlps, etc.
4822     EVT EltVT = VT.getVectorElementType();
4823     ShAmt *= EltVT.getSizeInBits();
4824     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4825   }
4826
4827   if (X86::isMOVLMask(SVOp)) {
4828     if (V1IsUndef)
4829       return V2;
4830     if (ISD::isBuildVectorAllZeros(V1.getNode()))
4831       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
4832     if (!isMMX)
4833       return Op;
4834   }
4835
4836   // FIXME: fold these into legal mask.
4837   if (!isMMX && (X86::isMOVSHDUPMask(SVOp) ||
4838                  X86::isMOVSLDUPMask(SVOp) ||
4839                  X86::isMOVHLPSMask(SVOp) ||
4840                  X86::isMOVLHPSMask(SVOp) ||
4841                  X86::isMOVLPMask(SVOp)))
4842     return Op;
4843
4844   if (ShouldXformToMOVHLPS(SVOp) ||
4845       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
4846     return CommuteVectorShuffle(SVOp, DAG);
4847
4848   if (isShift) {
4849     // No better options. Use a vshl / vsrl.
4850     EVT EltVT = VT.getVectorElementType();
4851     ShAmt *= EltVT.getSizeInBits();
4852     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4853   }
4854
4855   bool Commuted = false;
4856   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
4857   // 1,1,1,1 -> v8i16 though.
4858   V1IsSplat = isSplatVector(V1.getNode());
4859   V2IsSplat = isSplatVector(V2.getNode());
4860
4861   // Canonicalize the splat or undef, if present, to be on the RHS.
4862   if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
4863     Op = CommuteVectorShuffle(SVOp, DAG);
4864     SVOp = cast<ShuffleVectorSDNode>(Op);
4865     V1 = SVOp->getOperand(0);
4866     V2 = SVOp->getOperand(1);
4867     std::swap(V1IsSplat, V2IsSplat);
4868     std::swap(V1IsUndef, V2IsUndef);
4869     Commuted = true;
4870   }
4871
4872   if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
4873     // Shuffling low element of v1 into undef, just return v1.
4874     if (V2IsUndef)
4875       return V1;
4876     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
4877     // the instruction selector will not match, so get a canonical MOVL with
4878     // swapped operands to undo the commute.
4879     return getMOVL(DAG, dl, VT, V2, V1);
4880   }
4881
4882   if (X86::isUNPCKL_v_undef_Mask(SVOp) ||
4883       X86::isUNPCKH_v_undef_Mask(SVOp) ||
4884       X86::isUNPCKLMask(SVOp) ||
4885       X86::isUNPCKHMask(SVOp))
4886     return Op;
4887
4888   if (V2IsSplat) {
4889     // Normalize mask so all entries that point to V2 points to its first
4890     // element then try to match unpck{h|l} again. If match, return a
4891     // new vector_shuffle with the corrected mask.
4892     SDValue NewMask = NormalizeMask(SVOp, DAG);
4893     ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
4894     if (NSVOp != SVOp) {
4895       if (X86::isUNPCKLMask(NSVOp, true)) {
4896         return NewMask;
4897       } else if (X86::isUNPCKHMask(NSVOp, true)) {
4898         return NewMask;
4899       }
4900     }
4901   }
4902
4903   if (Commuted) {
4904     // Commute is back and try unpck* again.
4905     // FIXME: this seems wrong.
4906     SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
4907     ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
4908     if (X86::isUNPCKL_v_undef_Mask(NewSVOp) ||
4909         X86::isUNPCKH_v_undef_Mask(NewSVOp) ||
4910         X86::isUNPCKLMask(NewSVOp) ||
4911         X86::isUNPCKHMask(NewSVOp))
4912       return NewOp;
4913   }
4914
4915   // FIXME: for mmx, bitcast v2i32 to v4i16 for shuffle.
4916
4917   // Normalize the node to match x86 shuffle ops if needed
4918   if (!isMMX && V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
4919     return CommuteVectorShuffle(SVOp, DAG);
4920
4921   // Check for legal shuffle and return?
4922   SmallVector<int, 16> PermMask;
4923   SVOp->getMask(PermMask);
4924   if (isShuffleMaskLegal(PermMask, VT))
4925     return Op;
4926
4927   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
4928   if (VT == MVT::v8i16) {
4929     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(SVOp, DAG, *this);
4930     if (NewOp.getNode())
4931       return NewOp;
4932   }
4933
4934   if (VT == MVT::v16i8) {
4935     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
4936     if (NewOp.getNode())
4937       return NewOp;
4938   }
4939
4940   // Handle all 4 wide cases with a number of shuffles except for MMX.
4941   if (NumElems == 4 && !isMMX)
4942     return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
4943
4944   return SDValue();
4945 }
4946
4947 SDValue
4948 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
4949                                                 SelectionDAG &DAG) const {
4950   EVT VT = Op.getValueType();
4951   DebugLoc dl = Op.getDebugLoc();
4952   if (VT.getSizeInBits() == 8) {
4953     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
4954                                     Op.getOperand(0), Op.getOperand(1));
4955     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4956                                     DAG.getValueType(VT));
4957     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4958   } else if (VT.getSizeInBits() == 16) {
4959     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4960     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
4961     if (Idx == 0)
4962       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4963                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4964                                      DAG.getNode(ISD::BIT_CONVERT, dl,
4965                                                  MVT::v4i32,
4966                                                  Op.getOperand(0)),
4967                                      Op.getOperand(1)));
4968     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
4969                                     Op.getOperand(0), Op.getOperand(1));
4970     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4971                                     DAG.getValueType(VT));
4972     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4973   } else if (VT == MVT::f32) {
4974     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
4975     // the result back to FR32 register. It's only worth matching if the
4976     // result has a single use which is a store or a bitcast to i32.  And in
4977     // the case of a store, it's not worth it if the index is a constant 0,
4978     // because a MOVSSmr can be used instead, which is smaller and faster.
4979     if (!Op.hasOneUse())
4980       return SDValue();
4981     SDNode *User = *Op.getNode()->use_begin();
4982     if ((User->getOpcode() != ISD::STORE ||
4983          (isa<ConstantSDNode>(Op.getOperand(1)) &&
4984           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
4985         (User->getOpcode() != ISD::BIT_CONVERT ||
4986          User->getValueType(0) != MVT::i32))
4987       return SDValue();
4988     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4989                                   DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32,
4990                                               Op.getOperand(0)),
4991                                               Op.getOperand(1));
4992     return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Extract);
4993   } else if (VT == MVT::i32) {
4994     // ExtractPS works with constant index.
4995     if (isa<ConstantSDNode>(Op.getOperand(1)))
4996       return Op;
4997   }
4998   return SDValue();
4999 }
5000
5001
5002 SDValue
5003 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
5004                                            SelectionDAG &DAG) const {
5005   if (!isa<ConstantSDNode>(Op.getOperand(1)))
5006     return SDValue();
5007
5008   if (Subtarget->hasSSE41()) {
5009     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
5010     if (Res.getNode())
5011       return Res;
5012   }
5013
5014   EVT VT = Op.getValueType();
5015   DebugLoc dl = Op.getDebugLoc();
5016   // TODO: handle v16i8.
5017   if (VT.getSizeInBits() == 16) {
5018     SDValue Vec = Op.getOperand(0);
5019     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5020     if (Idx == 0)
5021       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
5022                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5023                                      DAG.getNode(ISD::BIT_CONVERT, dl,
5024                                                  MVT::v4i32, Vec),
5025                                      Op.getOperand(1)));
5026     // Transform it so it match pextrw which produces a 32-bit result.
5027     EVT EltVT = MVT::i32;
5028     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
5029                                     Op.getOperand(0), Op.getOperand(1));
5030     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
5031                                     DAG.getValueType(VT));
5032     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5033   } else if (VT.getSizeInBits() == 32) {
5034     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5035     if (Idx == 0)
5036       return Op;
5037
5038     // SHUFPS the element to the lowest double word, then movss.
5039     int Mask[4] = { Idx, -1, -1, -1 };
5040     EVT VVT = Op.getOperand(0).getValueType();
5041     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
5042                                        DAG.getUNDEF(VVT), Mask);
5043     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
5044                        DAG.getIntPtrConstant(0));
5045   } else if (VT.getSizeInBits() == 64) {
5046     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
5047     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
5048     //        to match extract_elt for f64.
5049     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5050     if (Idx == 0)
5051       return Op;
5052
5053     // UNPCKHPD the element to the lowest double word, then movsd.
5054     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
5055     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
5056     int Mask[2] = { 1, -1 };
5057     EVT VVT = Op.getOperand(0).getValueType();
5058     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
5059                                        DAG.getUNDEF(VVT), Mask);
5060     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
5061                        DAG.getIntPtrConstant(0));
5062   }
5063
5064   return SDValue();
5065 }
5066
5067 SDValue
5068 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
5069                                                SelectionDAG &DAG) const {
5070   EVT VT = Op.getValueType();
5071   EVT EltVT = VT.getVectorElementType();
5072   DebugLoc dl = Op.getDebugLoc();
5073
5074   SDValue N0 = Op.getOperand(0);
5075   SDValue N1 = Op.getOperand(1);
5076   SDValue N2 = Op.getOperand(2);
5077
5078   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
5079       isa<ConstantSDNode>(N2)) {
5080     unsigned Opc;
5081     if (VT == MVT::v8i16)
5082       Opc = X86ISD::PINSRW;
5083     else if (VT == MVT::v4i16)
5084       Opc = X86ISD::MMX_PINSRW;
5085     else if (VT == MVT::v16i8)
5086       Opc = X86ISD::PINSRB;
5087     else
5088       Opc = X86ISD::PINSRB;
5089
5090     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
5091     // argument.
5092     if (N1.getValueType() != MVT::i32)
5093       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
5094     if (N2.getValueType() != MVT::i32)
5095       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
5096     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
5097   } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
5098     // Bits [7:6] of the constant are the source select.  This will always be
5099     //  zero here.  The DAG Combiner may combine an extract_elt index into these
5100     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
5101     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
5102     // Bits [5:4] of the constant are the destination select.  This is the
5103     //  value of the incoming immediate.
5104     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
5105     //   combine either bitwise AND or insert of float 0.0 to set these bits.
5106     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
5107     // Create this as a scalar to vector..
5108     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
5109     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
5110   } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
5111     // PINSR* works with constant index.
5112     return Op;
5113   }
5114   return SDValue();
5115 }
5116
5117 SDValue
5118 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
5119   EVT VT = Op.getValueType();
5120   EVT EltVT = VT.getVectorElementType();
5121
5122   if (Subtarget->hasSSE41())
5123     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
5124
5125   if (EltVT == MVT::i8)
5126     return SDValue();
5127
5128   DebugLoc dl = Op.getDebugLoc();
5129   SDValue N0 = Op.getOperand(0);
5130   SDValue N1 = Op.getOperand(1);
5131   SDValue N2 = Op.getOperand(2);
5132
5133   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
5134     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
5135     // as its second argument.
5136     if (N1.getValueType() != MVT::i32)
5137       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
5138     if (N2.getValueType() != MVT::i32)
5139       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
5140     return DAG.getNode(VT == MVT::v8i16 ? X86ISD::PINSRW : X86ISD::MMX_PINSRW,
5141                        dl, VT, N0, N1, N2);
5142   }
5143   return SDValue();
5144 }
5145
5146 SDValue
5147 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5148   DebugLoc dl = Op.getDebugLoc();
5149   
5150   if (Op.getValueType() == MVT::v1i64 &&
5151       Op.getOperand(0).getValueType() == MVT::i64)
5152     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
5153
5154   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
5155   EVT VT = MVT::v2i32;
5156   switch (Op.getValueType().getSimpleVT().SimpleTy) {
5157   default: break;
5158   case MVT::v16i8:
5159   case MVT::v8i16:
5160     VT = MVT::v4i32;
5161     break;
5162   }
5163   return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(),
5164                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, AnyExt));
5165 }
5166
5167 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
5168 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
5169 // one of the above mentioned nodes. It has to be wrapped because otherwise
5170 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
5171 // be used to form addressing mode. These wrapped nodes will be selected
5172 // into MOV32ri.
5173 SDValue
5174 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
5175   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
5176
5177   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5178   // global base reg.
5179   unsigned char OpFlag = 0;
5180   unsigned WrapperKind = X86ISD::Wrapper;
5181   CodeModel::Model M = getTargetMachine().getCodeModel();
5182
5183   if (Subtarget->isPICStyleRIPRel() &&
5184       (M == CodeModel::Small || M == CodeModel::Kernel))
5185     WrapperKind = X86ISD::WrapperRIP;
5186   else if (Subtarget->isPICStyleGOT())
5187     OpFlag = X86II::MO_GOTOFF;
5188   else if (Subtarget->isPICStyleStubPIC())
5189     OpFlag = X86II::MO_PIC_BASE_OFFSET;
5190
5191   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
5192                                              CP->getAlignment(),
5193                                              CP->getOffset(), OpFlag);
5194   DebugLoc DL = CP->getDebugLoc();
5195   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5196   // With PIC, the address is actually $g + Offset.
5197   if (OpFlag) {
5198     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5199                          DAG.getNode(X86ISD::GlobalBaseReg,
5200                                      DebugLoc(), getPointerTy()),
5201                          Result);
5202   }
5203
5204   return Result;
5205 }
5206
5207 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
5208   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
5209
5210   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5211   // global base reg.
5212   unsigned char OpFlag = 0;
5213   unsigned WrapperKind = X86ISD::Wrapper;
5214   CodeModel::Model M = getTargetMachine().getCodeModel();
5215
5216   if (Subtarget->isPICStyleRIPRel() &&
5217       (M == CodeModel::Small || M == CodeModel::Kernel))
5218     WrapperKind = X86ISD::WrapperRIP;
5219   else if (Subtarget->isPICStyleGOT())
5220     OpFlag = X86II::MO_GOTOFF;
5221   else if (Subtarget->isPICStyleStubPIC())
5222     OpFlag = X86II::MO_PIC_BASE_OFFSET;
5223
5224   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
5225                                           OpFlag);
5226   DebugLoc DL = JT->getDebugLoc();
5227   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5228
5229   // With PIC, the address is actually $g + Offset.
5230   if (OpFlag) {
5231     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5232                          DAG.getNode(X86ISD::GlobalBaseReg,
5233                                      DebugLoc(), getPointerTy()),
5234                          Result);
5235   }
5236
5237   return Result;
5238 }
5239
5240 SDValue
5241 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
5242   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
5243
5244   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5245   // global base reg.
5246   unsigned char OpFlag = 0;
5247   unsigned WrapperKind = X86ISD::Wrapper;
5248   CodeModel::Model M = getTargetMachine().getCodeModel();
5249
5250   if (Subtarget->isPICStyleRIPRel() &&
5251       (M == CodeModel::Small || M == CodeModel::Kernel))
5252     WrapperKind = X86ISD::WrapperRIP;
5253   else if (Subtarget->isPICStyleGOT())
5254     OpFlag = X86II::MO_GOTOFF;
5255   else if (Subtarget->isPICStyleStubPIC())
5256     OpFlag = X86II::MO_PIC_BASE_OFFSET;
5257
5258   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
5259
5260   DebugLoc DL = Op.getDebugLoc();
5261   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5262
5263
5264   // With PIC, the address is actually $g + Offset.
5265   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
5266       !Subtarget->is64Bit()) {
5267     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5268                          DAG.getNode(X86ISD::GlobalBaseReg,
5269                                      DebugLoc(), getPointerTy()),
5270                          Result);
5271   }
5272
5273   return Result;
5274 }
5275
5276 SDValue
5277 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
5278   // Create the TargetBlockAddressAddress node.
5279   unsigned char OpFlags =
5280     Subtarget->ClassifyBlockAddressReference();
5281   CodeModel::Model M = getTargetMachine().getCodeModel();
5282   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
5283   DebugLoc dl = Op.getDebugLoc();
5284   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
5285                                        /*isTarget=*/true, OpFlags);
5286
5287   if (Subtarget->isPICStyleRIPRel() &&
5288       (M == CodeModel::Small || M == CodeModel::Kernel))
5289     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
5290   else
5291     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
5292
5293   // With PIC, the address is actually $g + Offset.
5294   if (isGlobalRelativeToPICBase(OpFlags)) {
5295     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5296                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
5297                          Result);
5298   }
5299
5300   return Result;
5301 }
5302
5303 SDValue
5304 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
5305                                       int64_t Offset,
5306                                       SelectionDAG &DAG) const {
5307   // Create the TargetGlobalAddress node, folding in the constant
5308   // offset if it is legal.
5309   unsigned char OpFlags =
5310     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
5311   CodeModel::Model M = getTargetMachine().getCodeModel();
5312   SDValue Result;
5313   if (OpFlags == X86II::MO_NO_FLAG &&
5314       X86::isOffsetSuitableForCodeModel(Offset, M)) {
5315     // A direct static reference to a global.
5316     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
5317     Offset = 0;
5318   } else {
5319     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
5320   }
5321
5322   if (Subtarget->isPICStyleRIPRel() &&
5323       (M == CodeModel::Small || M == CodeModel::Kernel))
5324     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
5325   else
5326     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
5327
5328   // With PIC, the address is actually $g + Offset.
5329   if (isGlobalRelativeToPICBase(OpFlags)) {
5330     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5331                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
5332                          Result);
5333   }
5334
5335   // For globals that require a load from a stub to get the address, emit the
5336   // load.
5337   if (isGlobalStubReference(OpFlags))
5338     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
5339                          PseudoSourceValue::getGOT(), 0, false, false, 0);
5340
5341   // If there was a non-zero offset that we didn't fold, create an explicit
5342   // addition for it.
5343   if (Offset != 0)
5344     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
5345                          DAG.getConstant(Offset, getPointerTy()));
5346
5347   return Result;
5348 }
5349
5350 SDValue
5351 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
5352   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
5353   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
5354   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
5355 }
5356
5357 static SDValue
5358 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
5359            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
5360            unsigned char OperandFlags) {
5361   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5362   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
5363   DebugLoc dl = GA->getDebugLoc();
5364   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
5365                                            GA->getValueType(0),
5366                                            GA->getOffset(),
5367                                            OperandFlags);
5368   if (InFlag) {
5369     SDValue Ops[] = { Chain,  TGA, *InFlag };
5370     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
5371   } else {
5372     SDValue Ops[]  = { Chain, TGA };
5373     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
5374   }
5375
5376   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
5377   MFI->setAdjustsStack(true);
5378
5379   SDValue Flag = Chain.getValue(1);
5380   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
5381 }
5382
5383 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
5384 static SDValue
5385 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5386                                 const EVT PtrVT) {
5387   SDValue InFlag;
5388   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
5389   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
5390                                      DAG.getNode(X86ISD::GlobalBaseReg,
5391                                                  DebugLoc(), PtrVT), InFlag);
5392   InFlag = Chain.getValue(1);
5393
5394   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
5395 }
5396
5397 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
5398 static SDValue
5399 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5400                                 const EVT PtrVT) {
5401   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
5402                     X86::RAX, X86II::MO_TLSGD);
5403 }
5404
5405 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
5406 // "local exec" model.
5407 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5408                                    const EVT PtrVT, TLSModel::Model model,
5409                                    bool is64Bit) {
5410   DebugLoc dl = GA->getDebugLoc();
5411   // Get the Thread Pointer
5412   SDValue Base = DAG.getNode(X86ISD::SegmentBaseAddress,
5413                              DebugLoc(), PtrVT,
5414                              DAG.getRegister(is64Bit? X86::FS : X86::GS,
5415                                              MVT::i32));
5416
5417   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Base,
5418                                       NULL, 0, false, false, 0);
5419
5420   unsigned char OperandFlags = 0;
5421   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
5422   // initialexec.
5423   unsigned WrapperKind = X86ISD::Wrapper;
5424   if (model == TLSModel::LocalExec) {
5425     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
5426   } else if (is64Bit) {
5427     assert(model == TLSModel::InitialExec);
5428     OperandFlags = X86II::MO_GOTTPOFF;
5429     WrapperKind = X86ISD::WrapperRIP;
5430   } else {
5431     assert(model == TLSModel::InitialExec);
5432     OperandFlags = X86II::MO_INDNTPOFF;
5433   }
5434
5435   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
5436   // exec)
5437   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl, 
5438                                            GA->getValueType(0),
5439                                            GA->getOffset(), OperandFlags);
5440   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
5441
5442   if (model == TLSModel::InitialExec)
5443     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
5444                          PseudoSourceValue::getGOT(), 0, false, false, 0);
5445
5446   // The address of the thread local variable is the add of the thread
5447   // pointer with the offset of the variable.
5448   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
5449 }
5450
5451 SDValue
5452 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
5453   
5454   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
5455   const GlobalValue *GV = GA->getGlobal();
5456
5457   if (Subtarget->isTargetELF()) {
5458     // TODO: implement the "local dynamic" model
5459     // TODO: implement the "initial exec"model for pic executables
5460     
5461     // If GV is an alias then use the aliasee for determining
5462     // thread-localness.
5463     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
5464       GV = GA->resolveAliasedGlobal(false);
5465     
5466     TLSModel::Model model 
5467       = getTLSModel(GV, getTargetMachine().getRelocationModel());
5468     
5469     switch (model) {
5470       case TLSModel::GeneralDynamic:
5471       case TLSModel::LocalDynamic: // not implemented
5472         if (Subtarget->is64Bit())
5473           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
5474         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
5475         
5476       case TLSModel::InitialExec:
5477       case TLSModel::LocalExec:
5478         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
5479                                    Subtarget->is64Bit());
5480     }
5481   } else if (Subtarget->isTargetDarwin()) {
5482     // Darwin only has one model of TLS.  Lower to that.
5483     unsigned char OpFlag = 0;
5484     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
5485                            X86ISD::WrapperRIP : X86ISD::Wrapper;
5486     
5487     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5488     // global base reg.
5489     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
5490                   !Subtarget->is64Bit();
5491     if (PIC32)
5492       OpFlag = X86II::MO_TLVP_PIC_BASE;
5493     else
5494       OpFlag = X86II::MO_TLVP;
5495     DebugLoc DL = Op.getDebugLoc();    
5496     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
5497                                                 getPointerTy(),
5498                                                 GA->getOffset(), OpFlag);
5499     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5500   
5501     // With PIC32, the address is actually $g + Offset.
5502     if (PIC32)
5503       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5504                            DAG.getNode(X86ISD::GlobalBaseReg,
5505                                        DebugLoc(), getPointerTy()),
5506                            Offset);
5507     
5508     // Lowering the machine isd will make sure everything is in the right
5509     // location.
5510     SDValue Args[] = { Offset };
5511     SDValue Chain = DAG.getNode(X86ISD::TLSCALL, DL, MVT::Other, Args, 1);
5512     
5513     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
5514     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5515     MFI->setAdjustsStack(true);
5516
5517     // And our return value (tls address) is in the standard call return value
5518     // location.
5519     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
5520     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
5521   }
5522   
5523   assert(false &&
5524          "TLS not implemented for this target.");
5525
5526   llvm_unreachable("Unreachable");
5527   return SDValue();
5528 }
5529
5530
5531 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
5532 /// take a 2 x i32 value to shift plus a shift amount.
5533 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
5534   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5535   EVT VT = Op.getValueType();
5536   unsigned VTBits = VT.getSizeInBits();
5537   DebugLoc dl = Op.getDebugLoc();
5538   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
5539   SDValue ShOpLo = Op.getOperand(0);
5540   SDValue ShOpHi = Op.getOperand(1);
5541   SDValue ShAmt  = Op.getOperand(2);
5542   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
5543                                      DAG.getConstant(VTBits - 1, MVT::i8))
5544                        : DAG.getConstant(0, VT);
5545
5546   SDValue Tmp2, Tmp3;
5547   if (Op.getOpcode() == ISD::SHL_PARTS) {
5548     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
5549     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5550   } else {
5551     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
5552     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
5553   }
5554
5555   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
5556                                 DAG.getConstant(VTBits, MVT::i8));
5557   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
5558                              AndNode, DAG.getConstant(0, MVT::i8));
5559
5560   SDValue Hi, Lo;
5561   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5562   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
5563   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
5564
5565   if (Op.getOpcode() == ISD::SHL_PARTS) {
5566     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
5567     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
5568   } else {
5569     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
5570     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
5571   }
5572
5573   SDValue Ops[2] = { Lo, Hi };
5574   return DAG.getMergeValues(Ops, 2, dl);
5575 }
5576
5577 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
5578                                            SelectionDAG &DAG) const {
5579   EVT SrcVT = Op.getOperand(0).getValueType();
5580
5581   if (SrcVT.isVector()) {
5582     if (SrcVT == MVT::v2i32 && Op.getValueType() == MVT::v2f64) {
5583       return Op;
5584     }
5585     return SDValue();
5586   }
5587
5588   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
5589          "Unknown SINT_TO_FP to lower!");
5590
5591   // These are really Legal; return the operand so the caller accepts it as
5592   // Legal.
5593   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
5594     return Op;
5595   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
5596       Subtarget->is64Bit()) {
5597     return Op;
5598   }
5599
5600   DebugLoc dl = Op.getDebugLoc();
5601   unsigned Size = SrcVT.getSizeInBits()/8;
5602   MachineFunction &MF = DAG.getMachineFunction();
5603   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
5604   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5605   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5606                                StackSlot,
5607                                PseudoSourceValue::getFixedStack(SSFI), 0,
5608                                false, false, 0);
5609   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
5610 }
5611
5612 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
5613                                      SDValue StackSlot, 
5614                                      SelectionDAG &DAG) const {
5615   // Build the FILD
5616   DebugLoc dl = Op.getDebugLoc();
5617   SDVTList Tys;
5618   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
5619   if (useSSE)
5620     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
5621   else
5622     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
5623   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
5624   SDValue Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD, dl,
5625                                Tys, Ops, array_lengthof(Ops));
5626
5627   if (useSSE) {
5628     Chain = Result.getValue(1);
5629     SDValue InFlag = Result.getValue(2);
5630
5631     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
5632     // shouldn't be necessary except that RFP cannot be live across
5633     // multiple blocks. When stackifier is fixed, they can be uncoupled.
5634     MachineFunction &MF = DAG.getMachineFunction();
5635     int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
5636     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5637     Tys = DAG.getVTList(MVT::Other);
5638     SDValue Ops[] = {
5639       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
5640     };
5641     Chain = DAG.getNode(X86ISD::FST, dl, Tys, Ops, array_lengthof(Ops));
5642     Result = DAG.getLoad(Op.getValueType(), dl, Chain, StackSlot,
5643                          PseudoSourceValue::getFixedStack(SSFI), 0,
5644                          false, false, 0);
5645   }
5646
5647   return Result;
5648 }
5649
5650 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
5651 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
5652                                                SelectionDAG &DAG) const {
5653   // This algorithm is not obvious. Here it is in C code, more or less:
5654   /*
5655     double uint64_to_double( uint32_t hi, uint32_t lo ) {
5656       static const __m128i exp = { 0x4330000045300000ULL, 0 };
5657       static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
5658
5659       // Copy ints to xmm registers.
5660       __m128i xh = _mm_cvtsi32_si128( hi );
5661       __m128i xl = _mm_cvtsi32_si128( lo );
5662
5663       // Combine into low half of a single xmm register.
5664       __m128i x = _mm_unpacklo_epi32( xh, xl );
5665       __m128d d;
5666       double sd;
5667
5668       // Merge in appropriate exponents to give the integer bits the right
5669       // magnitude.
5670       x = _mm_unpacklo_epi32( x, exp );
5671
5672       // Subtract away the biases to deal with the IEEE-754 double precision
5673       // implicit 1.
5674       d = _mm_sub_pd( (__m128d) x, bias );
5675
5676       // All conversions up to here are exact. The correctly rounded result is
5677       // calculated using the current rounding mode using the following
5678       // horizontal add.
5679       d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
5680       _mm_store_sd( &sd, d );   // Because we are returning doubles in XMM, this
5681                                 // store doesn't really need to be here (except
5682                                 // maybe to zero the other double)
5683       return sd;
5684     }
5685   */
5686
5687   DebugLoc dl = Op.getDebugLoc();
5688   LLVMContext *Context = DAG.getContext();
5689
5690   // Build some magic constants.
5691   std::vector<Constant*> CV0;
5692   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
5693   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
5694   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
5695   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
5696   Constant *C0 = ConstantVector::get(CV0);
5697   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
5698
5699   std::vector<Constant*> CV1;
5700   CV1.push_back(
5701     ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
5702   CV1.push_back(
5703     ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
5704   Constant *C1 = ConstantVector::get(CV1);
5705   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
5706
5707   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5708                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5709                                         Op.getOperand(0),
5710                                         DAG.getIntPtrConstant(1)));
5711   SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5712                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5713                                         Op.getOperand(0),
5714                                         DAG.getIntPtrConstant(0)));
5715   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
5716   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
5717                               PseudoSourceValue::getConstantPool(), 0,
5718                               false, false, 16);
5719   SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
5720   SDValue XR2F = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Unpck2);
5721   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
5722                               PseudoSourceValue::getConstantPool(), 0,
5723                               false, false, 16);
5724   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
5725
5726   // Add the halves; easiest way is to swap them into another reg first.
5727   int ShufMask[2] = { 1, -1 };
5728   SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
5729                                       DAG.getUNDEF(MVT::v2f64), ShufMask);
5730   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
5731   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
5732                      DAG.getIntPtrConstant(0));
5733 }
5734
5735 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
5736 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
5737                                                SelectionDAG &DAG) const {
5738   DebugLoc dl = Op.getDebugLoc();
5739   // FP constant to bias correct the final result.
5740   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
5741                                    MVT::f64);
5742
5743   // Load the 32-bit value into an XMM register.
5744   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5745                              DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5746                                          Op.getOperand(0),
5747                                          DAG.getIntPtrConstant(0)));
5748
5749   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5750                      DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Load),
5751                      DAG.getIntPtrConstant(0));
5752
5753   // Or the load with the bias.
5754   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
5755                            DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5756                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5757                                                    MVT::v2f64, Load)),
5758                            DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5759                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5760                                                    MVT::v2f64, Bias)));
5761   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5762                    DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Or),
5763                    DAG.getIntPtrConstant(0));
5764
5765   // Subtract the bias.
5766   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
5767
5768   // Handle final rounding.
5769   EVT DestVT = Op.getValueType();
5770
5771   if (DestVT.bitsLT(MVT::f64)) {
5772     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
5773                        DAG.getIntPtrConstant(0));
5774   } else if (DestVT.bitsGT(MVT::f64)) {
5775     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
5776   }
5777
5778   // Handle final rounding.
5779   return Sub;
5780 }
5781
5782 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
5783                                            SelectionDAG &DAG) const {
5784   SDValue N0 = Op.getOperand(0);
5785   DebugLoc dl = Op.getDebugLoc();
5786
5787   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
5788   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
5789   // the optimization here.
5790   if (DAG.SignBitIsZero(N0))
5791     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
5792
5793   EVT SrcVT = N0.getValueType();
5794   EVT DstVT = Op.getValueType();
5795   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
5796     return LowerUINT_TO_FP_i64(Op, DAG);
5797   else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
5798     return LowerUINT_TO_FP_i32(Op, DAG);
5799
5800   // Make a 64-bit buffer, and use it to build an FILD.
5801   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
5802   if (SrcVT == MVT::i32) {
5803     SDValue WordOff = DAG.getConstant(4, getPointerTy());
5804     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
5805                                      getPointerTy(), StackSlot, WordOff);
5806     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5807                                   StackSlot, NULL, 0, false, false, 0);
5808     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
5809                                   OffsetSlot, NULL, 0, false, false, 0);
5810     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
5811     return Fild;
5812   }
5813
5814   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
5815   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5816                                 StackSlot, NULL, 0, false, false, 0);
5817   // For i64 source, we need to add the appropriate power of 2 if the input
5818   // was negative.  This is the same as the optimization in
5819   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
5820   // we must be careful to do the computation in x87 extended precision, not
5821   // in SSE. (The generic code can't know it's OK to do this, or how to.)
5822   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
5823   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
5824   SDValue Fild = DAG.getNode(X86ISD::FILD, dl, Tys, Ops, 3);
5825
5826   APInt FF(32, 0x5F800000ULL);
5827
5828   // Check whether the sign bit is set.
5829   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
5830                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
5831                                  ISD::SETLT);
5832
5833   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
5834   SDValue FudgePtr = DAG.getConstantPool(
5835                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
5836                                          getPointerTy());
5837
5838   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
5839   SDValue Zero = DAG.getIntPtrConstant(0);
5840   SDValue Four = DAG.getIntPtrConstant(4);
5841   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
5842                                Zero, Four);
5843   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
5844
5845   // Load the value out, extending it from f32 to f80.
5846   // FIXME: Avoid the extend by constructing the right constant pool?
5847   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, MVT::f80, dl, DAG.getEntryNode(),
5848                                  FudgePtr, PseudoSourceValue::getConstantPool(),
5849                                  0, MVT::f32, false, false, 4);
5850   // Extend everything to 80 bits to force it to be done on x87.
5851   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
5852   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
5853 }
5854
5855 std::pair<SDValue,SDValue> X86TargetLowering::
5856 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
5857   DebugLoc dl = Op.getDebugLoc();
5858
5859   EVT DstTy = Op.getValueType();
5860
5861   if (!IsSigned) {
5862     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
5863     DstTy = MVT::i64;
5864   }
5865
5866   assert(DstTy.getSimpleVT() <= MVT::i64 &&
5867          DstTy.getSimpleVT() >= MVT::i16 &&
5868          "Unknown FP_TO_SINT to lower!");
5869
5870   // These are really Legal.
5871   if (DstTy == MVT::i32 &&
5872       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5873     return std::make_pair(SDValue(), SDValue());
5874   if (Subtarget->is64Bit() &&
5875       DstTy == MVT::i64 &&
5876       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5877     return std::make_pair(SDValue(), SDValue());
5878
5879   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
5880   // stack slot.
5881   MachineFunction &MF = DAG.getMachineFunction();
5882   unsigned MemSize = DstTy.getSizeInBits()/8;
5883   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
5884   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5885
5886   unsigned Opc;
5887   switch (DstTy.getSimpleVT().SimpleTy) {
5888   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
5889   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
5890   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
5891   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
5892   }
5893
5894   SDValue Chain = DAG.getEntryNode();
5895   SDValue Value = Op.getOperand(0);
5896   if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
5897     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
5898     Chain = DAG.getStore(Chain, dl, Value, StackSlot,
5899                          PseudoSourceValue::getFixedStack(SSFI), 0,
5900                          false, false, 0);
5901     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
5902     SDValue Ops[] = {
5903       Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
5904     };
5905     Value = DAG.getNode(X86ISD::FLD, dl, Tys, Ops, 3);
5906     Chain = Value.getValue(1);
5907     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
5908     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5909   }
5910
5911   // Build the FP_TO_INT*_IN_MEM
5912   SDValue Ops[] = { Chain, Value, StackSlot };
5913   SDValue FIST = DAG.getNode(Opc, dl, MVT::Other, Ops, 3);
5914
5915   return std::make_pair(FIST, StackSlot);
5916 }
5917
5918 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
5919                                            SelectionDAG &DAG) const {
5920   if (Op.getValueType().isVector()) {
5921     if (Op.getValueType() == MVT::v2i32 &&
5922         Op.getOperand(0).getValueType() == MVT::v2f64) {
5923       return Op;
5924     }
5925     return SDValue();
5926   }
5927
5928   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
5929   SDValue FIST = Vals.first, StackSlot = Vals.second;
5930   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
5931   if (FIST.getNode() == 0) return Op;
5932
5933   // Load the result.
5934   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5935                      FIST, StackSlot, NULL, 0, false, false, 0);
5936 }
5937
5938 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
5939                                            SelectionDAG &DAG) const {
5940   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
5941   SDValue FIST = Vals.first, StackSlot = Vals.second;
5942   assert(FIST.getNode() && "Unexpected failure");
5943
5944   // Load the result.
5945   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5946                      FIST, StackSlot, NULL, 0, false, false, 0);
5947 }
5948
5949 SDValue X86TargetLowering::LowerFABS(SDValue Op,
5950                                      SelectionDAG &DAG) const {
5951   LLVMContext *Context = DAG.getContext();
5952   DebugLoc dl = Op.getDebugLoc();
5953   EVT VT = Op.getValueType();
5954   EVT EltVT = VT;
5955   if (VT.isVector())
5956     EltVT = VT.getVectorElementType();
5957   std::vector<Constant*> CV;
5958   if (EltVT == MVT::f64) {
5959     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
5960     CV.push_back(C);
5961     CV.push_back(C);
5962   } else {
5963     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
5964     CV.push_back(C);
5965     CV.push_back(C);
5966     CV.push_back(C);
5967     CV.push_back(C);
5968   }
5969   Constant *C = ConstantVector::get(CV);
5970   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5971   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5972                              PseudoSourceValue::getConstantPool(), 0,
5973                              false, false, 16);
5974   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
5975 }
5976
5977 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
5978   LLVMContext *Context = DAG.getContext();
5979   DebugLoc dl = Op.getDebugLoc();
5980   EVT VT = Op.getValueType();
5981   EVT EltVT = VT;
5982   if (VT.isVector())
5983     EltVT = VT.getVectorElementType();
5984   std::vector<Constant*> CV;
5985   if (EltVT == MVT::f64) {
5986     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
5987     CV.push_back(C);
5988     CV.push_back(C);
5989   } else {
5990     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
5991     CV.push_back(C);
5992     CV.push_back(C);
5993     CV.push_back(C);
5994     CV.push_back(C);
5995   }
5996   Constant *C = ConstantVector::get(CV);
5997   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5998   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5999                              PseudoSourceValue::getConstantPool(), 0,
6000                              false, false, 16);
6001   if (VT.isVector()) {
6002     return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
6003                        DAG.getNode(ISD::XOR, dl, MVT::v2i64,
6004                     DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
6005                                 Op.getOperand(0)),
6006                     DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, Mask)));
6007   } else {
6008     return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
6009   }
6010 }
6011
6012 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
6013   LLVMContext *Context = DAG.getContext();
6014   SDValue Op0 = Op.getOperand(0);
6015   SDValue Op1 = Op.getOperand(1);
6016   DebugLoc dl = Op.getDebugLoc();
6017   EVT VT = Op.getValueType();
6018   EVT SrcVT = Op1.getValueType();
6019
6020   // If second operand is smaller, extend it first.
6021   if (SrcVT.bitsLT(VT)) {
6022     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
6023     SrcVT = VT;
6024   }
6025   // And if it is bigger, shrink it first.
6026   if (SrcVT.bitsGT(VT)) {
6027     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
6028     SrcVT = VT;
6029   }
6030
6031   // At this point the operands and the result should have the same
6032   // type, and that won't be f80 since that is not custom lowered.
6033
6034   // First get the sign bit of second operand.
6035   std::vector<Constant*> CV;
6036   if (SrcVT == MVT::f64) {
6037     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
6038     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
6039   } else {
6040     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
6041     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6042     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6043     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6044   }
6045   Constant *C = ConstantVector::get(CV);
6046   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6047   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
6048                               PseudoSourceValue::getConstantPool(), 0,
6049                               false, false, 16);
6050   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
6051
6052   // Shift sign bit right or left if the two operands have different types.
6053   if (SrcVT.bitsGT(VT)) {
6054     // Op0 is MVT::f32, Op1 is MVT::f64.
6055     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
6056     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
6057                           DAG.getConstant(32, MVT::i32));
6058     SignBit = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, SignBit);
6059     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
6060                           DAG.getIntPtrConstant(0));
6061   }
6062
6063   // Clear first operand sign bit.
6064   CV.clear();
6065   if (VT == MVT::f64) {
6066     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
6067     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
6068   } else {
6069     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
6070     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6071     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6072     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6073   }
6074   C = ConstantVector::get(CV);
6075   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6076   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
6077                               PseudoSourceValue::getConstantPool(), 0,
6078                               false, false, 16);
6079   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
6080
6081   // Or the value with the sign bit.
6082   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
6083 }
6084
6085 /// Emit nodes that will be selected as "test Op0,Op0", or something
6086 /// equivalent.
6087 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
6088                                     SelectionDAG &DAG) const {
6089   DebugLoc dl = Op.getDebugLoc();
6090
6091   // CF and OF aren't always set the way we want. Determine which
6092   // of these we need.
6093   bool NeedCF = false;
6094   bool NeedOF = false;
6095   switch (X86CC) {
6096   default: break;
6097   case X86::COND_A: case X86::COND_AE:
6098   case X86::COND_B: case X86::COND_BE:
6099     NeedCF = true;
6100     break;
6101   case X86::COND_G: case X86::COND_GE:
6102   case X86::COND_L: case X86::COND_LE:
6103   case X86::COND_O: case X86::COND_NO:
6104     NeedOF = true;
6105     break;
6106   }
6107
6108   // See if we can use the EFLAGS value from the operand instead of
6109   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
6110   // we prove that the arithmetic won't overflow, we can't use OF or CF.
6111   if (Op.getResNo() != 0 || NeedOF || NeedCF)
6112     // Emit a CMP with 0, which is the TEST pattern.
6113     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
6114                        DAG.getConstant(0, Op.getValueType()));
6115
6116   unsigned Opcode = 0;
6117   unsigned NumOperands = 0;
6118   switch (Op.getNode()->getOpcode()) {
6119   case ISD::ADD:
6120     // Due to an isel shortcoming, be conservative if this add is likely to be
6121     // selected as part of a load-modify-store instruction. When the root node
6122     // in a match is a store, isel doesn't know how to remap non-chain non-flag
6123     // uses of other nodes in the match, such as the ADD in this case. This
6124     // leads to the ADD being left around and reselected, with the result being
6125     // two adds in the output.  Alas, even if none our users are stores, that
6126     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
6127     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
6128     // climbing the DAG back to the root, and it doesn't seem to be worth the
6129     // effort.
6130     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6131            UE = Op.getNode()->use_end(); UI != UE; ++UI)
6132       if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
6133         goto default_case;
6134
6135     if (ConstantSDNode *C =
6136         dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
6137       // An add of one will be selected as an INC.
6138       if (C->getAPIntValue() == 1) {
6139         Opcode = X86ISD::INC;
6140         NumOperands = 1;
6141         break;
6142       }
6143
6144       // An add of negative one (subtract of one) will be selected as a DEC.
6145       if (C->getAPIntValue().isAllOnesValue()) {
6146         Opcode = X86ISD::DEC;
6147         NumOperands = 1;
6148         break;
6149       }
6150     }
6151
6152     // Otherwise use a regular EFLAGS-setting add.
6153     Opcode = X86ISD::ADD;
6154     NumOperands = 2;
6155     break;
6156   case ISD::AND: {
6157     // If the primary and result isn't used, don't bother using X86ISD::AND,
6158     // because a TEST instruction will be better.
6159     bool NonFlagUse = false;
6160     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6161            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
6162       SDNode *User = *UI;
6163       unsigned UOpNo = UI.getOperandNo();
6164       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
6165         // Look pass truncate.
6166         UOpNo = User->use_begin().getOperandNo();
6167         User = *User->use_begin();
6168       }
6169
6170       if (User->getOpcode() != ISD::BRCOND &&
6171           User->getOpcode() != ISD::SETCC &&
6172           (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
6173         NonFlagUse = true;
6174         break;
6175       }
6176     }
6177
6178     if (!NonFlagUse)
6179       break;
6180   }
6181     // FALL THROUGH
6182   case ISD::SUB:
6183   case ISD::OR:
6184   case ISD::XOR:
6185     // Due to the ISEL shortcoming noted above, be conservative if this op is
6186     // likely to be selected as part of a load-modify-store instruction.
6187     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6188            UE = Op.getNode()->use_end(); UI != UE; ++UI)
6189       if (UI->getOpcode() == ISD::STORE)
6190         goto default_case;
6191
6192     // Otherwise use a regular EFLAGS-setting instruction.
6193     switch (Op.getNode()->getOpcode()) {
6194     default: llvm_unreachable("unexpected operator!");
6195     case ISD::SUB: Opcode = X86ISD::SUB; break;
6196     case ISD::OR:  Opcode = X86ISD::OR;  break;
6197     case ISD::XOR: Opcode = X86ISD::XOR; break;
6198     case ISD::AND: Opcode = X86ISD::AND; break;
6199     }
6200
6201     NumOperands = 2;
6202     break;
6203   case X86ISD::ADD:
6204   case X86ISD::SUB:
6205   case X86ISD::INC:
6206   case X86ISD::DEC:
6207   case X86ISD::OR:
6208   case X86ISD::XOR:
6209   case X86ISD::AND:
6210     return SDValue(Op.getNode(), 1);
6211   default:
6212   default_case:
6213     break;
6214   }
6215
6216   if (Opcode == 0)
6217     // Emit a CMP with 0, which is the TEST pattern.
6218     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
6219                        DAG.getConstant(0, Op.getValueType()));
6220
6221   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
6222   SmallVector<SDValue, 4> Ops;
6223   for (unsigned i = 0; i != NumOperands; ++i)
6224     Ops.push_back(Op.getOperand(i));
6225
6226   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
6227   DAG.ReplaceAllUsesWith(Op, New);
6228   return SDValue(New.getNode(), 1);
6229 }
6230
6231 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
6232 /// equivalent.
6233 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
6234                                    SelectionDAG &DAG) const {
6235   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
6236     if (C->getAPIntValue() == 0)
6237       return EmitTest(Op0, X86CC, DAG);
6238
6239   DebugLoc dl = Op0.getDebugLoc();
6240   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
6241 }
6242
6243 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
6244 /// if it's possible.
6245 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
6246                                      DebugLoc dl, SelectionDAG &DAG) const {
6247   SDValue Op0 = And.getOperand(0);
6248   SDValue Op1 = And.getOperand(1);
6249   if (Op0.getOpcode() == ISD::TRUNCATE)
6250     Op0 = Op0.getOperand(0);
6251   if (Op1.getOpcode() == ISD::TRUNCATE)
6252     Op1 = Op1.getOperand(0);
6253
6254   SDValue LHS, RHS;
6255   if (Op1.getOpcode() == ISD::SHL)
6256     std::swap(Op0, Op1);
6257   if (Op0.getOpcode() == ISD::SHL) {
6258     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
6259       if (And00C->getZExtValue() == 1) {
6260         // If we looked past a truncate, check that it's only truncating away
6261         // known zeros.
6262         unsigned BitWidth = Op0.getValueSizeInBits();
6263         unsigned AndBitWidth = And.getValueSizeInBits();
6264         if (BitWidth > AndBitWidth) {
6265           APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
6266           DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
6267           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
6268             return SDValue();
6269         }
6270         LHS = Op1;
6271         RHS = Op0.getOperand(1);
6272       }
6273   } else if (Op1.getOpcode() == ISD::Constant) {
6274     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
6275     SDValue AndLHS = Op0;
6276     if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
6277       LHS = AndLHS.getOperand(0);
6278       RHS = AndLHS.getOperand(1);
6279     }
6280   }
6281
6282   if (LHS.getNode()) {
6283     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
6284     // instruction.  Since the shift amount is in-range-or-undefined, we know
6285     // that doing a bittest on the i32 value is ok.  We extend to i32 because
6286     // the encoding for the i16 version is larger than the i32 version.
6287     // Also promote i16 to i32 for performance / code size reason.
6288     if (LHS.getValueType() == MVT::i8 ||
6289         LHS.getValueType() == MVT::i16)
6290       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
6291
6292     // If the operand types disagree, extend the shift amount to match.  Since
6293     // BT ignores high bits (like shifts) we can use anyextend.
6294     if (LHS.getValueType() != RHS.getValueType())
6295       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
6296
6297     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
6298     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
6299     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6300                        DAG.getConstant(Cond, MVT::i8), BT);
6301   }
6302
6303   return SDValue();
6304 }
6305
6306 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
6307   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
6308   SDValue Op0 = Op.getOperand(0);
6309   SDValue Op1 = Op.getOperand(1);
6310   DebugLoc dl = Op.getDebugLoc();
6311   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6312
6313   // Optimize to BT if possible.
6314   // Lower (X & (1 << N)) == 0 to BT(X, N).
6315   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
6316   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
6317   if (Op0.getOpcode() == ISD::AND &&
6318       Op0.hasOneUse() &&
6319       Op1.getOpcode() == ISD::Constant &&
6320       cast<ConstantSDNode>(Op1)->isNullValue() &&
6321       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
6322     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
6323     if (NewSetCC.getNode())
6324       return NewSetCC;
6325   }
6326
6327   // Look for "(setcc) == / != 1" to avoid unncessary setcc.
6328   if (Op0.getOpcode() == X86ISD::SETCC &&
6329       Op1.getOpcode() == ISD::Constant &&
6330       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
6331        cast<ConstantSDNode>(Op1)->isNullValue()) &&
6332       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
6333     X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
6334     bool Invert = (CC == ISD::SETNE) ^
6335       cast<ConstantSDNode>(Op1)->isNullValue();
6336     if (Invert)
6337       CCode = X86::GetOppositeBranchCondition(CCode);
6338     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6339                        DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
6340   }
6341
6342   bool isFP = Op1.getValueType().isFloatingPoint();
6343   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
6344   if (X86CC == X86::COND_INVALID)
6345     return SDValue();
6346
6347   SDValue Cond = EmitCmp(Op0, Op1, X86CC, DAG);
6348
6349   // Use sbb x, x to materialize carry bit into a GPR.
6350   if (X86CC == X86::COND_B)
6351     return DAG.getNode(ISD::AND, dl, MVT::i8,
6352                        DAG.getNode(X86ISD::SETCC_CARRY, dl, MVT::i8,
6353                                    DAG.getConstant(X86CC, MVT::i8), Cond),
6354                        DAG.getConstant(1, MVT::i8));
6355
6356   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6357                      DAG.getConstant(X86CC, MVT::i8), Cond);
6358 }
6359
6360 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
6361   SDValue Cond;
6362   SDValue Op0 = Op.getOperand(0);
6363   SDValue Op1 = Op.getOperand(1);
6364   SDValue CC = Op.getOperand(2);
6365   EVT VT = Op.getValueType();
6366   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
6367   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
6368   DebugLoc dl = Op.getDebugLoc();
6369
6370   if (isFP) {
6371     unsigned SSECC = 8;
6372     EVT VT0 = Op0.getValueType();
6373     assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
6374     unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
6375     bool Swap = false;
6376
6377     switch (SetCCOpcode) {
6378     default: break;
6379     case ISD::SETOEQ:
6380     case ISD::SETEQ:  SSECC = 0; break;
6381     case ISD::SETOGT:
6382     case ISD::SETGT: Swap = true; // Fallthrough
6383     case ISD::SETLT:
6384     case ISD::SETOLT: SSECC = 1; break;
6385     case ISD::SETOGE:
6386     case ISD::SETGE: Swap = true; // Fallthrough
6387     case ISD::SETLE:
6388     case ISD::SETOLE: SSECC = 2; break;
6389     case ISD::SETUO:  SSECC = 3; break;
6390     case ISD::SETUNE:
6391     case ISD::SETNE:  SSECC = 4; break;
6392     case ISD::SETULE: Swap = true;
6393     case ISD::SETUGE: SSECC = 5; break;
6394     case ISD::SETULT: Swap = true;
6395     case ISD::SETUGT: SSECC = 6; break;
6396     case ISD::SETO:   SSECC = 7; break;
6397     }
6398     if (Swap)
6399       std::swap(Op0, Op1);
6400
6401     // In the two special cases we can't handle, emit two comparisons.
6402     if (SSECC == 8) {
6403       if (SetCCOpcode == ISD::SETUEQ) {
6404         SDValue UNORD, EQ;
6405         UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
6406         EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
6407         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
6408       }
6409       else if (SetCCOpcode == ISD::SETONE) {
6410         SDValue ORD, NEQ;
6411         ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
6412         NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
6413         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
6414       }
6415       llvm_unreachable("Illegal FP comparison");
6416     }
6417     // Handle all other FP comparisons here.
6418     return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
6419   }
6420
6421   // We are handling one of the integer comparisons here.  Since SSE only has
6422   // GT and EQ comparisons for integer, swapping operands and multiple
6423   // operations may be required for some comparisons.
6424   unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
6425   bool Swap = false, Invert = false, FlipSigns = false;
6426
6427   switch (VT.getSimpleVT().SimpleTy) {
6428   default: break;
6429   case MVT::v8i8:
6430   case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
6431   case MVT::v4i16:
6432   case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
6433   case MVT::v2i32:
6434   case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
6435   case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
6436   }
6437
6438   switch (SetCCOpcode) {
6439   default: break;
6440   case ISD::SETNE:  Invert = true;
6441   case ISD::SETEQ:  Opc = EQOpc; break;
6442   case ISD::SETLT:  Swap = true;
6443   case ISD::SETGT:  Opc = GTOpc; break;
6444   case ISD::SETGE:  Swap = true;
6445   case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
6446   case ISD::SETULT: Swap = true;
6447   case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
6448   case ISD::SETUGE: Swap = true;
6449   case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
6450   }
6451   if (Swap)
6452     std::swap(Op0, Op1);
6453
6454   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
6455   // bits of the inputs before performing those operations.
6456   if (FlipSigns) {
6457     EVT EltVT = VT.getVectorElementType();
6458     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
6459                                       EltVT);
6460     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
6461     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
6462                                     SignBits.size());
6463     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
6464     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
6465   }
6466
6467   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
6468
6469   // If the logical-not of the result is required, perform that now.
6470   if (Invert)
6471     Result = DAG.getNOT(dl, Result, VT);
6472
6473   return Result;
6474 }
6475
6476 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
6477 static bool isX86LogicalCmp(SDValue Op) {
6478   unsigned Opc = Op.getNode()->getOpcode();
6479   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
6480     return true;
6481   if (Op.getResNo() == 1 &&
6482       (Opc == X86ISD::ADD ||
6483        Opc == X86ISD::SUB ||
6484        Opc == X86ISD::SMUL ||
6485        Opc == X86ISD::UMUL ||
6486        Opc == X86ISD::INC ||
6487        Opc == X86ISD::DEC ||
6488        Opc == X86ISD::OR ||
6489        Opc == X86ISD::XOR ||
6490        Opc == X86ISD::AND))
6491     return true;
6492
6493   return false;
6494 }
6495
6496 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
6497   bool addTest = true;
6498   SDValue Cond  = Op.getOperand(0);
6499   DebugLoc dl = Op.getDebugLoc();
6500   SDValue CC;
6501
6502   if (Cond.getOpcode() == ISD::SETCC) {
6503     SDValue NewCond = LowerSETCC(Cond, DAG);
6504     if (NewCond.getNode())
6505       Cond = NewCond;
6506   }
6507
6508   // (select (x == 0), -1, 0) -> (sign_bit (x - 1))
6509   SDValue Op1 = Op.getOperand(1);
6510   SDValue Op2 = Op.getOperand(2);
6511   if (Cond.getOpcode() == X86ISD::SETCC &&
6512       cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue() == X86::COND_E) {
6513     SDValue Cmp = Cond.getOperand(1);
6514     if (Cmp.getOpcode() == X86ISD::CMP) {
6515       ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op1);
6516       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
6517       ConstantSDNode *RHSC =
6518         dyn_cast<ConstantSDNode>(Cmp.getOperand(1).getNode());
6519       if (N1C && N1C->isAllOnesValue() &&
6520           N2C && N2C->isNullValue() &&
6521           RHSC && RHSC->isNullValue()) {
6522         SDValue CmpOp0 = Cmp.getOperand(0);
6523         Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
6524                           CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
6525         return DAG.getNode(X86ISD::SETCC_CARRY, dl, Op.getValueType(),
6526                            DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
6527       }
6528     }
6529   }
6530
6531   // Look pass (and (setcc_carry (cmp ...)), 1).
6532   if (Cond.getOpcode() == ISD::AND &&
6533       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
6534     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
6535     if (C && C->getAPIntValue() == 1) 
6536       Cond = Cond.getOperand(0);
6537   }
6538
6539   // If condition flag is set by a X86ISD::CMP, then use it as the condition
6540   // setting operand in place of the X86ISD::SETCC.
6541   if (Cond.getOpcode() == X86ISD::SETCC ||
6542       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
6543     CC = Cond.getOperand(0);
6544
6545     SDValue Cmp = Cond.getOperand(1);
6546     unsigned Opc = Cmp.getOpcode();
6547     EVT VT = Op.getValueType();
6548
6549     bool IllegalFPCMov = false;
6550     if (VT.isFloatingPoint() && !VT.isVector() &&
6551         !isScalarFPTypeInSSEReg(VT))  // FPStack?
6552       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
6553
6554     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
6555         Opc == X86ISD::BT) { // FIXME
6556       Cond = Cmp;
6557       addTest = false;
6558     }
6559   }
6560
6561   if (addTest) {
6562     // Look pass the truncate.
6563     if (Cond.getOpcode() == ISD::TRUNCATE)
6564       Cond = Cond.getOperand(0);
6565
6566     // We know the result of AND is compared against zero. Try to match
6567     // it to BT.
6568     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) { 
6569       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
6570       if (NewSetCC.getNode()) {
6571         CC = NewSetCC.getOperand(0);
6572         Cond = NewSetCC.getOperand(1);
6573         addTest = false;
6574       }
6575     }
6576   }
6577
6578   if (addTest) {
6579     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6580     Cond = EmitTest(Cond, X86::COND_NE, DAG);
6581   }
6582
6583   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
6584   // condition is true.
6585   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Flag);
6586   SDValue Ops[] = { Op2, Op1, CC, Cond };
6587   return DAG.getNode(X86ISD::CMOV, dl, VTs, Ops, array_lengthof(Ops));
6588 }
6589
6590 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
6591 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
6592 // from the AND / OR.
6593 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
6594   Opc = Op.getOpcode();
6595   if (Opc != ISD::OR && Opc != ISD::AND)
6596     return false;
6597   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
6598           Op.getOperand(0).hasOneUse() &&
6599           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
6600           Op.getOperand(1).hasOneUse());
6601 }
6602
6603 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
6604 // 1 and that the SETCC node has a single use.
6605 static bool isXor1OfSetCC(SDValue Op) {
6606   if (Op.getOpcode() != ISD::XOR)
6607     return false;
6608   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6609   if (N1C && N1C->getAPIntValue() == 1) {
6610     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
6611       Op.getOperand(0).hasOneUse();
6612   }
6613   return false;
6614 }
6615
6616 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
6617   bool addTest = true;
6618   SDValue Chain = Op.getOperand(0);
6619   SDValue Cond  = Op.getOperand(1);
6620   SDValue Dest  = Op.getOperand(2);
6621   DebugLoc dl = Op.getDebugLoc();
6622   SDValue CC;
6623
6624   if (Cond.getOpcode() == ISD::SETCC) {
6625     SDValue NewCond = LowerSETCC(Cond, DAG);
6626     if (NewCond.getNode())
6627       Cond = NewCond;
6628   }
6629 #if 0
6630   // FIXME: LowerXALUO doesn't handle these!!
6631   else if (Cond.getOpcode() == X86ISD::ADD  ||
6632            Cond.getOpcode() == X86ISD::SUB  ||
6633            Cond.getOpcode() == X86ISD::SMUL ||
6634            Cond.getOpcode() == X86ISD::UMUL)
6635     Cond = LowerXALUO(Cond, DAG);
6636 #endif
6637
6638   // Look pass (and (setcc_carry (cmp ...)), 1).
6639   if (Cond.getOpcode() == ISD::AND &&
6640       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
6641     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
6642     if (C && C->getAPIntValue() == 1) 
6643       Cond = Cond.getOperand(0);
6644   }
6645
6646   // If condition flag is set by a X86ISD::CMP, then use it as the condition
6647   // setting operand in place of the X86ISD::SETCC.
6648   if (Cond.getOpcode() == X86ISD::SETCC ||
6649       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
6650     CC = Cond.getOperand(0);
6651
6652     SDValue Cmp = Cond.getOperand(1);
6653     unsigned Opc = Cmp.getOpcode();
6654     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
6655     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
6656       Cond = Cmp;
6657       addTest = false;
6658     } else {
6659       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
6660       default: break;
6661       case X86::COND_O:
6662       case X86::COND_B:
6663         // These can only come from an arithmetic instruction with overflow,
6664         // e.g. SADDO, UADDO.
6665         Cond = Cond.getNode()->getOperand(1);
6666         addTest = false;
6667         break;
6668       }
6669     }
6670   } else {
6671     unsigned CondOpc;
6672     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
6673       SDValue Cmp = Cond.getOperand(0).getOperand(1);
6674       if (CondOpc == ISD::OR) {
6675         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
6676         // two branches instead of an explicit OR instruction with a
6677         // separate test.
6678         if (Cmp == Cond.getOperand(1).getOperand(1) &&
6679             isX86LogicalCmp(Cmp)) {
6680           CC = Cond.getOperand(0).getOperand(0);
6681           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6682                               Chain, Dest, CC, Cmp);
6683           CC = Cond.getOperand(1).getOperand(0);
6684           Cond = Cmp;
6685           addTest = false;
6686         }
6687       } else { // ISD::AND
6688         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
6689         // two branches instead of an explicit AND instruction with a
6690         // separate test. However, we only do this if this block doesn't
6691         // have a fall-through edge, because this requires an explicit
6692         // jmp when the condition is false.
6693         if (Cmp == Cond.getOperand(1).getOperand(1) &&
6694             isX86LogicalCmp(Cmp) &&
6695             Op.getNode()->hasOneUse()) {
6696           X86::CondCode CCode =
6697             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
6698           CCode = X86::GetOppositeBranchCondition(CCode);
6699           CC = DAG.getConstant(CCode, MVT::i8);
6700           SDNode *User = *Op.getNode()->use_begin();
6701           // Look for an unconditional branch following this conditional branch.
6702           // We need this because we need to reverse the successors in order
6703           // to implement FCMP_OEQ.
6704           if (User->getOpcode() == ISD::BR) {
6705             SDValue FalseBB = User->getOperand(1);
6706             SDNode *NewBR =
6707               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
6708             assert(NewBR == User);
6709             (void)NewBR;
6710             Dest = FalseBB;
6711
6712             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6713                                 Chain, Dest, CC, Cmp);
6714             X86::CondCode CCode =
6715               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
6716             CCode = X86::GetOppositeBranchCondition(CCode);
6717             CC = DAG.getConstant(CCode, MVT::i8);
6718             Cond = Cmp;
6719             addTest = false;
6720           }
6721         }
6722       }
6723     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
6724       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
6725       // It should be transformed during dag combiner except when the condition
6726       // is set by a arithmetics with overflow node.
6727       X86::CondCode CCode =
6728         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
6729       CCode = X86::GetOppositeBranchCondition(CCode);
6730       CC = DAG.getConstant(CCode, MVT::i8);
6731       Cond = Cond.getOperand(0).getOperand(1);
6732       addTest = false;
6733     }
6734   }
6735
6736   if (addTest) {
6737     // Look pass the truncate.
6738     if (Cond.getOpcode() == ISD::TRUNCATE)
6739       Cond = Cond.getOperand(0);
6740
6741     // We know the result of AND is compared against zero. Try to match
6742     // it to BT.
6743     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) { 
6744       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
6745       if (NewSetCC.getNode()) {
6746         CC = NewSetCC.getOperand(0);
6747         Cond = NewSetCC.getOperand(1);
6748         addTest = false;
6749       }
6750     }
6751   }
6752
6753   if (addTest) {
6754     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6755     Cond = EmitTest(Cond, X86::COND_NE, DAG);
6756   }
6757   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6758                      Chain, Dest, CC, Cond);
6759 }
6760
6761
6762 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
6763 // Calls to _alloca is needed to probe the stack when allocating more than 4k
6764 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
6765 // that the guard pages used by the OS virtual memory manager are allocated in
6766 // correct sequence.
6767 SDValue
6768 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
6769                                            SelectionDAG &DAG) const {
6770   assert(Subtarget->isTargetCygMing() &&
6771          "This should be used only on Cygwin/Mingw targets");
6772   DebugLoc dl = Op.getDebugLoc();
6773
6774   // Get the inputs.
6775   SDValue Chain = Op.getOperand(0);
6776   SDValue Size  = Op.getOperand(1);
6777   // FIXME: Ensure alignment here
6778
6779   SDValue Flag;
6780
6781   EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
6782
6783   Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
6784   Flag = Chain.getValue(1);
6785
6786   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
6787
6788   Chain = DAG.getNode(X86ISD::MINGW_ALLOCA, dl, NodeTys, Chain, Flag);
6789   Flag = Chain.getValue(1);
6790
6791   Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
6792
6793   SDValue Ops1[2] = { Chain.getValue(0), Chain };
6794   return DAG.getMergeValues(Ops1, 2, dl);
6795 }
6796
6797 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
6798   MachineFunction &MF = DAG.getMachineFunction();
6799   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
6800
6801   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
6802   DebugLoc dl = Op.getDebugLoc();
6803
6804   if (!Subtarget->is64Bit()) {
6805     // vastart just stores the address of the VarArgsFrameIndex slot into the
6806     // memory location argument.
6807     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
6808                                    getPointerTy());
6809     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), SV, 0,
6810                         false, false, 0);
6811   }
6812
6813   // __va_list_tag:
6814   //   gp_offset         (0 - 6 * 8)
6815   //   fp_offset         (48 - 48 + 8 * 16)
6816   //   overflow_arg_area (point to parameters coming in memory).
6817   //   reg_save_area
6818   SmallVector<SDValue, 8> MemOps;
6819   SDValue FIN = Op.getOperand(1);
6820   // Store gp_offset
6821   SDValue Store = DAG.getStore(Op.getOperand(0), dl,
6822                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
6823                                                MVT::i32),
6824                                FIN, SV, 0, false, false, 0);
6825   MemOps.push_back(Store);
6826
6827   // Store fp_offset
6828   FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6829                     FIN, DAG.getIntPtrConstant(4));
6830   Store = DAG.getStore(Op.getOperand(0), dl,
6831                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
6832                                        MVT::i32),
6833                        FIN, SV, 4, false, false, 0);
6834   MemOps.push_back(Store);
6835
6836   // Store ptr to overflow_arg_area
6837   FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6838                     FIN, DAG.getIntPtrConstant(4));
6839   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
6840                                     getPointerTy());
6841   Store = DAG.getStore(Op.getOperand(0), dl, OVFIN, FIN, SV, 8,
6842                        false, false, 0);
6843   MemOps.push_back(Store);
6844
6845   // Store ptr to reg_save_area.
6846   FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6847                     FIN, DAG.getIntPtrConstant(8));
6848   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
6849                                     getPointerTy());
6850   Store = DAG.getStore(Op.getOperand(0), dl, RSFIN, FIN, SV, 16,
6851                        false, false, 0);
6852   MemOps.push_back(Store);
6853   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6854                      &MemOps[0], MemOps.size());
6855 }
6856
6857 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
6858   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6859   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
6860
6861   report_fatal_error("VAArgInst is not yet implemented for x86-64!");
6862   return SDValue();
6863 }
6864
6865 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
6866   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6867   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
6868   SDValue Chain = Op.getOperand(0);
6869   SDValue DstPtr = Op.getOperand(1);
6870   SDValue SrcPtr = Op.getOperand(2);
6871   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
6872   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6873   DebugLoc dl = Op.getDebugLoc();
6874
6875   return DAG.getMemcpy(Chain, dl, DstPtr, SrcPtr,
6876                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
6877                        false, DstSV, 0, SrcSV, 0);
6878 }
6879
6880 SDValue
6881 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
6882   DebugLoc dl = Op.getDebugLoc();
6883   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6884   switch (IntNo) {
6885   default: return SDValue();    // Don't custom lower most intrinsics.
6886   // Comparison intrinsics.
6887   case Intrinsic::x86_sse_comieq_ss:
6888   case Intrinsic::x86_sse_comilt_ss:
6889   case Intrinsic::x86_sse_comile_ss:
6890   case Intrinsic::x86_sse_comigt_ss:
6891   case Intrinsic::x86_sse_comige_ss:
6892   case Intrinsic::x86_sse_comineq_ss:
6893   case Intrinsic::x86_sse_ucomieq_ss:
6894   case Intrinsic::x86_sse_ucomilt_ss:
6895   case Intrinsic::x86_sse_ucomile_ss:
6896   case Intrinsic::x86_sse_ucomigt_ss:
6897   case Intrinsic::x86_sse_ucomige_ss:
6898   case Intrinsic::x86_sse_ucomineq_ss:
6899   case Intrinsic::x86_sse2_comieq_sd:
6900   case Intrinsic::x86_sse2_comilt_sd:
6901   case Intrinsic::x86_sse2_comile_sd:
6902   case Intrinsic::x86_sse2_comigt_sd:
6903   case Intrinsic::x86_sse2_comige_sd:
6904   case Intrinsic::x86_sse2_comineq_sd:
6905   case Intrinsic::x86_sse2_ucomieq_sd:
6906   case Intrinsic::x86_sse2_ucomilt_sd:
6907   case Intrinsic::x86_sse2_ucomile_sd:
6908   case Intrinsic::x86_sse2_ucomigt_sd:
6909   case Intrinsic::x86_sse2_ucomige_sd:
6910   case Intrinsic::x86_sse2_ucomineq_sd: {
6911     unsigned Opc = 0;
6912     ISD::CondCode CC = ISD::SETCC_INVALID;
6913     switch (IntNo) {
6914     default: break;
6915     case Intrinsic::x86_sse_comieq_ss:
6916     case Intrinsic::x86_sse2_comieq_sd:
6917       Opc = X86ISD::COMI;
6918       CC = ISD::SETEQ;
6919       break;
6920     case Intrinsic::x86_sse_comilt_ss:
6921     case Intrinsic::x86_sse2_comilt_sd:
6922       Opc = X86ISD::COMI;
6923       CC = ISD::SETLT;
6924       break;
6925     case Intrinsic::x86_sse_comile_ss:
6926     case Intrinsic::x86_sse2_comile_sd:
6927       Opc = X86ISD::COMI;
6928       CC = ISD::SETLE;
6929       break;
6930     case Intrinsic::x86_sse_comigt_ss:
6931     case Intrinsic::x86_sse2_comigt_sd:
6932       Opc = X86ISD::COMI;
6933       CC = ISD::SETGT;
6934       break;
6935     case Intrinsic::x86_sse_comige_ss:
6936     case Intrinsic::x86_sse2_comige_sd:
6937       Opc = X86ISD::COMI;
6938       CC = ISD::SETGE;
6939       break;
6940     case Intrinsic::x86_sse_comineq_ss:
6941     case Intrinsic::x86_sse2_comineq_sd:
6942       Opc = X86ISD::COMI;
6943       CC = ISD::SETNE;
6944       break;
6945     case Intrinsic::x86_sse_ucomieq_ss:
6946     case Intrinsic::x86_sse2_ucomieq_sd:
6947       Opc = X86ISD::UCOMI;
6948       CC = ISD::SETEQ;
6949       break;
6950     case Intrinsic::x86_sse_ucomilt_ss:
6951     case Intrinsic::x86_sse2_ucomilt_sd:
6952       Opc = X86ISD::UCOMI;
6953       CC = ISD::SETLT;
6954       break;
6955     case Intrinsic::x86_sse_ucomile_ss:
6956     case Intrinsic::x86_sse2_ucomile_sd:
6957       Opc = X86ISD::UCOMI;
6958       CC = ISD::SETLE;
6959       break;
6960     case Intrinsic::x86_sse_ucomigt_ss:
6961     case Intrinsic::x86_sse2_ucomigt_sd:
6962       Opc = X86ISD::UCOMI;
6963       CC = ISD::SETGT;
6964       break;
6965     case Intrinsic::x86_sse_ucomige_ss:
6966     case Intrinsic::x86_sse2_ucomige_sd:
6967       Opc = X86ISD::UCOMI;
6968       CC = ISD::SETGE;
6969       break;
6970     case Intrinsic::x86_sse_ucomineq_ss:
6971     case Intrinsic::x86_sse2_ucomineq_sd:
6972       Opc = X86ISD::UCOMI;
6973       CC = ISD::SETNE;
6974       break;
6975     }
6976
6977     SDValue LHS = Op.getOperand(1);
6978     SDValue RHS = Op.getOperand(2);
6979     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
6980     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
6981     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
6982     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6983                                 DAG.getConstant(X86CC, MVT::i8), Cond);
6984     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6985   }
6986   // ptest intrinsics. The intrinsic these come from are designed to return
6987   // an integer value, not just an instruction so lower it to the ptest
6988   // pattern and a setcc for the result.
6989   case Intrinsic::x86_sse41_ptestz:
6990   case Intrinsic::x86_sse41_ptestc:
6991   case Intrinsic::x86_sse41_ptestnzc:{
6992     unsigned X86CC = 0;
6993     switch (IntNo) {
6994     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
6995     case Intrinsic::x86_sse41_ptestz:
6996       // ZF = 1
6997       X86CC = X86::COND_E;
6998       break;
6999     case Intrinsic::x86_sse41_ptestc:
7000       // CF = 1
7001       X86CC = X86::COND_B;
7002       break;
7003     case Intrinsic::x86_sse41_ptestnzc:
7004       // ZF and CF = 0
7005       X86CC = X86::COND_A;
7006       break;
7007     }
7008
7009     SDValue LHS = Op.getOperand(1);
7010     SDValue RHS = Op.getOperand(2);
7011     SDValue Test = DAG.getNode(X86ISD::PTEST, dl, MVT::i32, LHS, RHS);
7012     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
7013     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
7014     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
7015   }
7016
7017   // Fix vector shift instructions where the last operand is a non-immediate
7018   // i32 value.
7019   case Intrinsic::x86_sse2_pslli_w:
7020   case Intrinsic::x86_sse2_pslli_d:
7021   case Intrinsic::x86_sse2_pslli_q:
7022   case Intrinsic::x86_sse2_psrli_w:
7023   case Intrinsic::x86_sse2_psrli_d:
7024   case Intrinsic::x86_sse2_psrli_q:
7025   case Intrinsic::x86_sse2_psrai_w:
7026   case Intrinsic::x86_sse2_psrai_d:
7027   case Intrinsic::x86_mmx_pslli_w:
7028   case Intrinsic::x86_mmx_pslli_d:
7029   case Intrinsic::x86_mmx_pslli_q:
7030   case Intrinsic::x86_mmx_psrli_w:
7031   case Intrinsic::x86_mmx_psrli_d:
7032   case Intrinsic::x86_mmx_psrli_q:
7033   case Intrinsic::x86_mmx_psrai_w:
7034   case Intrinsic::x86_mmx_psrai_d: {
7035     SDValue ShAmt = Op.getOperand(2);
7036     if (isa<ConstantSDNode>(ShAmt))
7037       return SDValue();
7038
7039     unsigned NewIntNo = 0;
7040     EVT ShAmtVT = MVT::v4i32;
7041     switch (IntNo) {
7042     case Intrinsic::x86_sse2_pslli_w:
7043       NewIntNo = Intrinsic::x86_sse2_psll_w;
7044       break;
7045     case Intrinsic::x86_sse2_pslli_d:
7046       NewIntNo = Intrinsic::x86_sse2_psll_d;
7047       break;
7048     case Intrinsic::x86_sse2_pslli_q:
7049       NewIntNo = Intrinsic::x86_sse2_psll_q;
7050       break;
7051     case Intrinsic::x86_sse2_psrli_w:
7052       NewIntNo = Intrinsic::x86_sse2_psrl_w;
7053       break;
7054     case Intrinsic::x86_sse2_psrli_d:
7055       NewIntNo = Intrinsic::x86_sse2_psrl_d;
7056       break;
7057     case Intrinsic::x86_sse2_psrli_q:
7058       NewIntNo = Intrinsic::x86_sse2_psrl_q;
7059       break;
7060     case Intrinsic::x86_sse2_psrai_w:
7061       NewIntNo = Intrinsic::x86_sse2_psra_w;
7062       break;
7063     case Intrinsic::x86_sse2_psrai_d:
7064       NewIntNo = Intrinsic::x86_sse2_psra_d;
7065       break;
7066     default: {
7067       ShAmtVT = MVT::v2i32;
7068       switch (IntNo) {
7069       case Intrinsic::x86_mmx_pslli_w:
7070         NewIntNo = Intrinsic::x86_mmx_psll_w;
7071         break;
7072       case Intrinsic::x86_mmx_pslli_d:
7073         NewIntNo = Intrinsic::x86_mmx_psll_d;
7074         break;
7075       case Intrinsic::x86_mmx_pslli_q:
7076         NewIntNo = Intrinsic::x86_mmx_psll_q;
7077         break;
7078       case Intrinsic::x86_mmx_psrli_w:
7079         NewIntNo = Intrinsic::x86_mmx_psrl_w;
7080         break;
7081       case Intrinsic::x86_mmx_psrli_d:
7082         NewIntNo = Intrinsic::x86_mmx_psrl_d;
7083         break;
7084       case Intrinsic::x86_mmx_psrli_q:
7085         NewIntNo = Intrinsic::x86_mmx_psrl_q;
7086         break;
7087       case Intrinsic::x86_mmx_psrai_w:
7088         NewIntNo = Intrinsic::x86_mmx_psra_w;
7089         break;
7090       case Intrinsic::x86_mmx_psrai_d:
7091         NewIntNo = Intrinsic::x86_mmx_psra_d;
7092         break;
7093       default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7094       }
7095       break;
7096     }
7097     }
7098
7099     // The vector shift intrinsics with scalars uses 32b shift amounts but
7100     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
7101     // to be zero.
7102     SDValue ShOps[4];
7103     ShOps[0] = ShAmt;
7104     ShOps[1] = DAG.getConstant(0, MVT::i32);
7105     if (ShAmtVT == MVT::v4i32) {
7106       ShOps[2] = DAG.getUNDEF(MVT::i32);
7107       ShOps[3] = DAG.getUNDEF(MVT::i32);
7108       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
7109     } else {
7110       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
7111     }
7112
7113     EVT VT = Op.getValueType();
7114     ShAmt = DAG.getNode(ISD::BIT_CONVERT, dl, VT, ShAmt);
7115     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7116                        DAG.getConstant(NewIntNo, MVT::i32),
7117                        Op.getOperand(1), ShAmt);
7118   }
7119   }
7120 }
7121
7122 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
7123                                            SelectionDAG &DAG) const {
7124   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7125   MFI->setReturnAddressIsTaken(true);
7126
7127   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7128   DebugLoc dl = Op.getDebugLoc();
7129
7130   if (Depth > 0) {
7131     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
7132     SDValue Offset =
7133       DAG.getConstant(TD->getPointerSize(),
7134                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
7135     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7136                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
7137                                    FrameAddr, Offset),
7138                        NULL, 0, false, false, 0);
7139   }
7140
7141   // Just load the return address.
7142   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
7143   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7144                      RetAddrFI, NULL, 0, false, false, 0);
7145 }
7146
7147 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
7148   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7149   MFI->setFrameAddressIsTaken(true);
7150
7151   EVT VT = Op.getValueType();
7152   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
7153   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7154   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
7155   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
7156   while (Depth--)
7157     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, NULL, 0,
7158                             false, false, 0);
7159   return FrameAddr;
7160 }
7161
7162 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
7163                                                      SelectionDAG &DAG) const {
7164   return DAG.getIntPtrConstant(2*TD->getPointerSize());
7165 }
7166
7167 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
7168   MachineFunction &MF = DAG.getMachineFunction();
7169   SDValue Chain     = Op.getOperand(0);
7170   SDValue Offset    = Op.getOperand(1);
7171   SDValue Handler   = Op.getOperand(2);
7172   DebugLoc dl       = Op.getDebugLoc();
7173
7174   SDValue Frame = DAG.getRegister(Subtarget->is64Bit() ? X86::RBP : X86::EBP,
7175                                   getPointerTy());
7176   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
7177
7178   SDValue StoreAddr = DAG.getNode(ISD::SUB, dl, getPointerTy(), Frame,
7179                                   DAG.getIntPtrConstant(-TD->getPointerSize()));
7180   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
7181   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, NULL, 0, false, false, 0);
7182   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
7183   MF.getRegInfo().addLiveOut(StoreAddrReg);
7184
7185   return DAG.getNode(X86ISD::EH_RETURN, dl,
7186                      MVT::Other,
7187                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
7188 }
7189
7190 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
7191                                              SelectionDAG &DAG) const {
7192   SDValue Root = Op.getOperand(0);
7193   SDValue Trmp = Op.getOperand(1); // trampoline
7194   SDValue FPtr = Op.getOperand(2); // nested function
7195   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
7196   DebugLoc dl  = Op.getDebugLoc();
7197
7198   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
7199
7200   if (Subtarget->is64Bit()) {
7201     SDValue OutChains[6];
7202
7203     // Large code-model.
7204     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
7205     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
7206
7207     const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
7208     const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
7209
7210     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
7211
7212     // Load the pointer to the nested function into R11.
7213     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
7214     SDValue Addr = Trmp;
7215     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7216                                 Addr, TrmpAddr, 0, false, false, 0);
7217
7218     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7219                        DAG.getConstant(2, MVT::i64));
7220     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr, TrmpAddr, 2,
7221                                 false, false, 2);
7222
7223     // Load the 'nest' parameter value into R10.
7224     // R10 is specified in X86CallingConv.td
7225     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
7226     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7227                        DAG.getConstant(10, MVT::i64));
7228     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7229                                 Addr, TrmpAddr, 10, false, false, 0);
7230
7231     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7232                        DAG.getConstant(12, MVT::i64));
7233     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 12,
7234                                 false, false, 2);
7235
7236     // Jump to the nested function.
7237     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
7238     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7239                        DAG.getConstant(20, MVT::i64));
7240     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7241                                 Addr, TrmpAddr, 20, false, false, 0);
7242
7243     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
7244     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7245                        DAG.getConstant(22, MVT::i64));
7246     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
7247                                 TrmpAddr, 22, false, false, 0);
7248
7249     SDValue Ops[] =
7250       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
7251     return DAG.getMergeValues(Ops, 2, dl);
7252   } else {
7253     const Function *Func =
7254       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
7255     CallingConv::ID CC = Func->getCallingConv();
7256     unsigned NestReg;
7257
7258     switch (CC) {
7259     default:
7260       llvm_unreachable("Unsupported calling convention");
7261     case CallingConv::C:
7262     case CallingConv::X86_StdCall: {
7263       // Pass 'nest' parameter in ECX.
7264       // Must be kept in sync with X86CallingConv.td
7265       NestReg = X86::ECX;
7266
7267       // Check that ECX wasn't needed by an 'inreg' parameter.
7268       const FunctionType *FTy = Func->getFunctionType();
7269       const AttrListPtr &Attrs = Func->getAttributes();
7270
7271       if (!Attrs.isEmpty() && !Func->isVarArg()) {
7272         unsigned InRegCount = 0;
7273         unsigned Idx = 1;
7274
7275         for (FunctionType::param_iterator I = FTy->param_begin(),
7276              E = FTy->param_end(); I != E; ++I, ++Idx)
7277           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
7278             // FIXME: should only count parameters that are lowered to integers.
7279             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
7280
7281         if (InRegCount > 2) {
7282           report_fatal_error("Nest register in use - reduce number of inreg"
7283                              " parameters!");
7284         }
7285       }
7286       break;
7287     }
7288     case CallingConv::X86_FastCall:
7289     case CallingConv::X86_ThisCall:
7290     case CallingConv::Fast:
7291       // Pass 'nest' parameter in EAX.
7292       // Must be kept in sync with X86CallingConv.td
7293       NestReg = X86::EAX;
7294       break;
7295     }
7296
7297     SDValue OutChains[4];
7298     SDValue Addr, Disp;
7299
7300     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7301                        DAG.getConstant(10, MVT::i32));
7302     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
7303
7304     // This is storing the opcode for MOV32ri.
7305     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
7306     const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
7307     OutChains[0] = DAG.getStore(Root, dl,
7308                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
7309                                 Trmp, TrmpAddr, 0, false, false, 0);
7310
7311     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7312                        DAG.getConstant(1, MVT::i32));
7313     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 1,
7314                                 false, false, 1);
7315
7316     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
7317     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7318                        DAG.getConstant(5, MVT::i32));
7319     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
7320                                 TrmpAddr, 5, false, false, 1);
7321
7322     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7323                        DAG.getConstant(6, MVT::i32));
7324     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr, TrmpAddr, 6,
7325                                 false, false, 1);
7326
7327     SDValue Ops[] =
7328       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
7329     return DAG.getMergeValues(Ops, 2, dl);
7330   }
7331 }
7332
7333 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
7334                                             SelectionDAG &DAG) const {
7335   /*
7336    The rounding mode is in bits 11:10 of FPSR, and has the following
7337    settings:
7338      00 Round to nearest
7339      01 Round to -inf
7340      10 Round to +inf
7341      11 Round to 0
7342
7343   FLT_ROUNDS, on the other hand, expects the following:
7344     -1 Undefined
7345      0 Round to 0
7346      1 Round to nearest
7347      2 Round to +inf
7348      3 Round to -inf
7349
7350   To perform the conversion, we do:
7351     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
7352   */
7353
7354   MachineFunction &MF = DAG.getMachineFunction();
7355   const TargetMachine &TM = MF.getTarget();
7356   const TargetFrameInfo &TFI = *TM.getFrameInfo();
7357   unsigned StackAlignment = TFI.getStackAlignment();
7358   EVT VT = Op.getValueType();
7359   DebugLoc dl = Op.getDebugLoc();
7360
7361   // Save FP Control Word to stack slot
7362   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
7363   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7364
7365   SDValue Chain = DAG.getNode(X86ISD::FNSTCW16m, dl, MVT::Other,
7366                               DAG.getEntryNode(), StackSlot);
7367
7368   // Load FP Control Word from stack slot
7369   SDValue CWD = DAG.getLoad(MVT::i16, dl, Chain, StackSlot, NULL, 0,
7370                             false, false, 0);
7371
7372   // Transform as necessary
7373   SDValue CWD1 =
7374     DAG.getNode(ISD::SRL, dl, MVT::i16,
7375                 DAG.getNode(ISD::AND, dl, MVT::i16,
7376                             CWD, DAG.getConstant(0x800, MVT::i16)),
7377                 DAG.getConstant(11, MVT::i8));
7378   SDValue CWD2 =
7379     DAG.getNode(ISD::SRL, dl, MVT::i16,
7380                 DAG.getNode(ISD::AND, dl, MVT::i16,
7381                             CWD, DAG.getConstant(0x400, MVT::i16)),
7382                 DAG.getConstant(9, MVT::i8));
7383
7384   SDValue RetVal =
7385     DAG.getNode(ISD::AND, dl, MVT::i16,
7386                 DAG.getNode(ISD::ADD, dl, MVT::i16,
7387                             DAG.getNode(ISD::OR, dl, MVT::i16, CWD1, CWD2),
7388                             DAG.getConstant(1, MVT::i16)),
7389                 DAG.getConstant(3, MVT::i16));
7390
7391
7392   return DAG.getNode((VT.getSizeInBits() < 16 ?
7393                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
7394 }
7395
7396 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
7397   EVT VT = Op.getValueType();
7398   EVT OpVT = VT;
7399   unsigned NumBits = VT.getSizeInBits();
7400   DebugLoc dl = Op.getDebugLoc();
7401
7402   Op = Op.getOperand(0);
7403   if (VT == MVT::i8) {
7404     // Zero extend to i32 since there is not an i8 bsr.
7405     OpVT = MVT::i32;
7406     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
7407   }
7408
7409   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
7410   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
7411   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
7412
7413   // If src is zero (i.e. bsr sets ZF), returns NumBits.
7414   SDValue Ops[] = {
7415     Op,
7416     DAG.getConstant(NumBits+NumBits-1, OpVT),
7417     DAG.getConstant(X86::COND_E, MVT::i8),
7418     Op.getValue(1)
7419   };
7420   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
7421
7422   // Finally xor with NumBits-1.
7423   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
7424
7425   if (VT == MVT::i8)
7426     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
7427   return Op;
7428 }
7429
7430 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
7431   EVT VT = Op.getValueType();
7432   EVT OpVT = VT;
7433   unsigned NumBits = VT.getSizeInBits();
7434   DebugLoc dl = Op.getDebugLoc();
7435
7436   Op = Op.getOperand(0);
7437   if (VT == MVT::i8) {
7438     OpVT = MVT::i32;
7439     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
7440   }
7441
7442   // Issue a bsf (scan bits forward) which also sets EFLAGS.
7443   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
7444   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
7445
7446   // If src is zero (i.e. bsf sets ZF), returns NumBits.
7447   SDValue Ops[] = {
7448     Op,
7449     DAG.getConstant(NumBits, OpVT),
7450     DAG.getConstant(X86::COND_E, MVT::i8),
7451     Op.getValue(1)
7452   };
7453   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
7454
7455   if (VT == MVT::i8)
7456     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
7457   return Op;
7458 }
7459
7460 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) const {
7461   EVT VT = Op.getValueType();
7462   assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
7463   DebugLoc dl = Op.getDebugLoc();
7464
7465   //  ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
7466   //  ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
7467   //  ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
7468   //  ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
7469   //  ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
7470   //
7471   //  AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
7472   //  AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
7473   //  return AloBlo + AloBhi + AhiBlo;
7474
7475   SDValue A = Op.getOperand(0);
7476   SDValue B = Op.getOperand(1);
7477
7478   SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7479                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
7480                        A, DAG.getConstant(32, MVT::i32));
7481   SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7482                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
7483                        B, DAG.getConstant(32, MVT::i32));
7484   SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7485                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7486                        A, B);
7487   SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7488                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7489                        A, Bhi);
7490   SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7491                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7492                        Ahi, B);
7493   AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7494                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
7495                        AloBhi, DAG.getConstant(32, MVT::i32));
7496   AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7497                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
7498                        AhiBlo, DAG.getConstant(32, MVT::i32));
7499   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
7500   Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
7501   return Res;
7502 }
7503
7504 SDValue X86TargetLowering::LowerSHL(SDValue Op, SelectionDAG &DAG) const {
7505   EVT VT = Op.getValueType();
7506   DebugLoc dl = Op.getDebugLoc();
7507   SDValue R = Op.getOperand(0);
7508
7509   assert(Subtarget->hasSSE41() && "Cannot lower SHL without SSE4.1 or later");
7510   assert(VT == MVT::v4i32 && "Only know how to lower v4i32");
7511   
7512   Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7513                    DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
7514                    Op.getOperand(1), DAG.getConstant(23, MVT::i32));
7515
7516   std::vector<Constant*> CV;
7517   LLVMContext *Context = DAG.getContext();
7518   CV.push_back(ConstantInt::get(*Context, APInt(32, 0x3f800000U)));
7519   CV.push_back(ConstantInt::get(*Context, APInt(32, 0x3f800000U)));
7520   CV.push_back(ConstantInt::get(*Context, APInt(32, 0x3f800000U)));
7521   CV.push_back(ConstantInt::get(*Context, APInt(32, 0x3f800000U)));
7522   Constant *C = ConstantVector::get(CV);
7523   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7524   SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7525                                PseudoSourceValue::getConstantPool(), 0,
7526                                false, false, 16);
7527
7528   Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
7529   Op = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, Op);
7530   Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
7531   return DAG.getNode(ISD::MUL, dl, VT, Op, R);
7532 }
7533
7534 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
7535   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
7536   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
7537   // looks for this combo and may remove the "setcc" instruction if the "setcc"
7538   // has only one use.
7539   SDNode *N = Op.getNode();
7540   SDValue LHS = N->getOperand(0);
7541   SDValue RHS = N->getOperand(1);
7542   unsigned BaseOp = 0;
7543   unsigned Cond = 0;
7544   DebugLoc dl = Op.getDebugLoc();
7545
7546   switch (Op.getOpcode()) {
7547   default: llvm_unreachable("Unknown ovf instruction!");
7548   case ISD::SADDO:
7549     // A subtract of one will be selected as a INC. Note that INC doesn't
7550     // set CF, so we can't do this for UADDO.
7551     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
7552       if (C->getAPIntValue() == 1) {
7553         BaseOp = X86ISD::INC;
7554         Cond = X86::COND_O;
7555         break;
7556       }
7557     BaseOp = X86ISD::ADD;
7558     Cond = X86::COND_O;
7559     break;
7560   case ISD::UADDO:
7561     BaseOp = X86ISD::ADD;
7562     Cond = X86::COND_B;
7563     break;
7564   case ISD::SSUBO:
7565     // A subtract of one will be selected as a DEC. Note that DEC doesn't
7566     // set CF, so we can't do this for USUBO.
7567     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
7568       if (C->getAPIntValue() == 1) {
7569         BaseOp = X86ISD::DEC;
7570         Cond = X86::COND_O;
7571         break;
7572       }
7573     BaseOp = X86ISD::SUB;
7574     Cond = X86::COND_O;
7575     break;
7576   case ISD::USUBO:
7577     BaseOp = X86ISD::SUB;
7578     Cond = X86::COND_B;
7579     break;
7580   case ISD::SMULO:
7581     BaseOp = X86ISD::SMUL;
7582     Cond = X86::COND_O;
7583     break;
7584   case ISD::UMULO:
7585     BaseOp = X86ISD::UMUL;
7586     Cond = X86::COND_B;
7587     break;
7588   }
7589
7590   // Also sets EFLAGS.
7591   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
7592   SDValue Sum = DAG.getNode(BaseOp, dl, VTs, LHS, RHS);
7593
7594   SDValue SetCC =
7595     DAG.getNode(X86ISD::SETCC, dl, N->getValueType(1),
7596                 DAG.getConstant(Cond, MVT::i32), SDValue(Sum.getNode(), 1));
7597
7598   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
7599   return Sum;
7600 }
7601
7602 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
7603   DebugLoc dl = Op.getDebugLoc();
7604   
7605   if (!Subtarget->hasSSE2())
7606     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
7607                        DAG.getConstant(0, MVT::i32));
7608   
7609   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
7610   if(!isDev)
7611     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
7612   else {
7613     unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7614     unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
7615     unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
7616     unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
7617     
7618     // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
7619     if (!Op1 && !Op2 && !Op3 && Op4)
7620       return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
7621     
7622     // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
7623     if (Op1 && !Op2 && !Op3 && !Op4)
7624       return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
7625     
7626     // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)), 
7627     //           (MFENCE)>;
7628     return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
7629   }
7630 }
7631
7632 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
7633   EVT T = Op.getValueType();
7634   DebugLoc dl = Op.getDebugLoc();
7635   unsigned Reg = 0;
7636   unsigned size = 0;
7637   switch(T.getSimpleVT().SimpleTy) {
7638   default:
7639     assert(false && "Invalid value type!");
7640   case MVT::i8:  Reg = X86::AL;  size = 1; break;
7641   case MVT::i16: Reg = X86::AX;  size = 2; break;
7642   case MVT::i32: Reg = X86::EAX; size = 4; break;
7643   case MVT::i64:
7644     assert(Subtarget->is64Bit() && "Node not type legal!");
7645     Reg = X86::RAX; size = 8;
7646     break;
7647   }
7648   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), dl, Reg,
7649                                     Op.getOperand(2), SDValue());
7650   SDValue Ops[] = { cpIn.getValue(0),
7651                     Op.getOperand(1),
7652                     Op.getOperand(3),
7653                     DAG.getTargetConstant(size, MVT::i8),
7654                     cpIn.getValue(1) };
7655   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7656   SDValue Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, dl, Tys, Ops, 5);
7657   SDValue cpOut =
7658     DAG.getCopyFromReg(Result.getValue(0), dl, Reg, T, Result.getValue(1));
7659   return cpOut;
7660 }
7661
7662 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
7663                                                  SelectionDAG &DAG) const {
7664   assert(Subtarget->is64Bit() && "Result not type legalized?");
7665   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7666   SDValue TheChain = Op.getOperand(0);
7667   DebugLoc dl = Op.getDebugLoc();
7668   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
7669   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
7670   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
7671                                    rax.getValue(2));
7672   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
7673                             DAG.getConstant(32, MVT::i8));
7674   SDValue Ops[] = {
7675     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
7676     rdx.getValue(1)
7677   };
7678   return DAG.getMergeValues(Ops, 2, dl);
7679 }
7680
7681 SDValue X86TargetLowering::LowerBIT_CONVERT(SDValue Op,
7682                                             SelectionDAG &DAG) const {
7683   EVT SrcVT = Op.getOperand(0).getValueType();
7684   EVT DstVT = Op.getValueType();
7685   assert((Subtarget->is64Bit() && !Subtarget->hasSSE2() && 
7686           Subtarget->hasMMX() && !DisableMMX) &&
7687          "Unexpected custom BIT_CONVERT");
7688   assert((DstVT == MVT::i64 || 
7689           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
7690          "Unexpected custom BIT_CONVERT");
7691   // i64 <=> MMX conversions are Legal.
7692   if (SrcVT==MVT::i64 && DstVT.isVector())
7693     return Op;
7694   if (DstVT==MVT::i64 && SrcVT.isVector())
7695     return Op;
7696   // MMX <=> MMX conversions are Legal.
7697   if (SrcVT.isVector() && DstVT.isVector())
7698     return Op;
7699   // All other conversions need to be expanded.
7700   return SDValue();
7701 }
7702 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
7703   SDNode *Node = Op.getNode();
7704   DebugLoc dl = Node->getDebugLoc();
7705   EVT T = Node->getValueType(0);
7706   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
7707                               DAG.getConstant(0, T), Node->getOperand(2));
7708   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
7709                        cast<AtomicSDNode>(Node)->getMemoryVT(),
7710                        Node->getOperand(0),
7711                        Node->getOperand(1), negOp,
7712                        cast<AtomicSDNode>(Node)->getSrcValue(),
7713                        cast<AtomicSDNode>(Node)->getAlignment());
7714 }
7715
7716 /// LowerOperation - Provide custom lowering hooks for some operations.
7717 ///
7718 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
7719   switch (Op.getOpcode()) {
7720   default: llvm_unreachable("Should not custom lower this!");
7721   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op,DAG);
7722   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
7723   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
7724   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
7725   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
7726   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
7727   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
7728   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
7729   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
7730   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
7731   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
7732   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
7733   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
7734   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
7735   case ISD::SHL_PARTS:
7736   case ISD::SRA_PARTS:
7737   case ISD::SRL_PARTS:          return LowerShift(Op, DAG);
7738   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
7739   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
7740   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
7741   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
7742   case ISD::FABS:               return LowerFABS(Op, DAG);
7743   case ISD::FNEG:               return LowerFNEG(Op, DAG);
7744   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
7745   case ISD::SETCC:              return LowerSETCC(Op, DAG);
7746   case ISD::VSETCC:             return LowerVSETCC(Op, DAG);
7747   case ISD::SELECT:             return LowerSELECT(Op, DAG);
7748   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
7749   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
7750   case ISD::VASTART:            return LowerVASTART(Op, DAG);
7751   case ISD::VAARG:              return LowerVAARG(Op, DAG);
7752   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
7753   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
7754   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
7755   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
7756   case ISD::FRAME_TO_ARGS_OFFSET:
7757                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
7758   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
7759   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
7760   case ISD::TRAMPOLINE:         return LowerTRAMPOLINE(Op, DAG);
7761   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
7762   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
7763   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
7764   case ISD::MUL:                return LowerMUL_V2I64(Op, DAG);
7765   case ISD::SHL:                return LowerSHL(Op, DAG);
7766   case ISD::SADDO:
7767   case ISD::UADDO:
7768   case ISD::SSUBO:
7769   case ISD::USUBO:
7770   case ISD::SMULO:
7771   case ISD::UMULO:              return LowerXALUO(Op, DAG);
7772   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
7773   case ISD::BIT_CONVERT:        return LowerBIT_CONVERT(Op, DAG);
7774   }
7775 }
7776
7777 void X86TargetLowering::
7778 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
7779                         SelectionDAG &DAG, unsigned NewOp) const {
7780   EVT T = Node->getValueType(0);
7781   DebugLoc dl = Node->getDebugLoc();
7782   assert (T == MVT::i64 && "Only know how to expand i64 atomics");
7783
7784   SDValue Chain = Node->getOperand(0);
7785   SDValue In1 = Node->getOperand(1);
7786   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7787                              Node->getOperand(2), DAG.getIntPtrConstant(0));
7788   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7789                              Node->getOperand(2), DAG.getIntPtrConstant(1));
7790   SDValue Ops[] = { Chain, In1, In2L, In2H };
7791   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
7792   SDValue Result =
7793     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
7794                             cast<MemSDNode>(Node)->getMemOperand());
7795   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
7796   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
7797   Results.push_back(Result.getValue(2));
7798 }
7799
7800 /// ReplaceNodeResults - Replace a node with an illegal result type
7801 /// with a new node built out of custom code.
7802 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
7803                                            SmallVectorImpl<SDValue>&Results,
7804                                            SelectionDAG &DAG) const {
7805   DebugLoc dl = N->getDebugLoc();
7806   switch (N->getOpcode()) {
7807   default:
7808     assert(false && "Do not know how to custom type legalize this operation!");
7809     return;
7810   case ISD::FP_TO_SINT: {
7811     std::pair<SDValue,SDValue> Vals =
7812         FP_TO_INTHelper(SDValue(N, 0), DAG, true);
7813     SDValue FIST = Vals.first, StackSlot = Vals.second;
7814     if (FIST.getNode() != 0) {
7815       EVT VT = N->getValueType(0);
7816       // Return a load from the stack slot.
7817       Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot, NULL, 0,
7818                                     false, false, 0));
7819     }
7820     return;
7821   }
7822   case ISD::READCYCLECOUNTER: {
7823     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7824     SDValue TheChain = N->getOperand(0);
7825     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
7826     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
7827                                      rd.getValue(1));
7828     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
7829                                      eax.getValue(2));
7830     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
7831     SDValue Ops[] = { eax, edx };
7832     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
7833     Results.push_back(edx.getValue(1));
7834     return;
7835   }
7836   case ISD::ATOMIC_CMP_SWAP: {
7837     EVT T = N->getValueType(0);
7838     assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
7839     SDValue cpInL, cpInH;
7840     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7841                         DAG.getConstant(0, MVT::i32));
7842     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7843                         DAG.getConstant(1, MVT::i32));
7844     cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
7845     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
7846                              cpInL.getValue(1));
7847     SDValue swapInL, swapInH;
7848     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7849                           DAG.getConstant(0, MVT::i32));
7850     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7851                           DAG.getConstant(1, MVT::i32));
7852     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
7853                                cpInH.getValue(1));
7854     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
7855                                swapInL.getValue(1));
7856     SDValue Ops[] = { swapInH.getValue(0),
7857                       N->getOperand(1),
7858                       swapInH.getValue(1) };
7859     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7860     SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, dl, Tys, Ops, 3);
7861     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
7862                                         MVT::i32, Result.getValue(1));
7863     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
7864                                         MVT::i32, cpOutL.getValue(2));
7865     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
7866     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
7867     Results.push_back(cpOutH.getValue(1));
7868     return;
7869   }
7870   case ISD::ATOMIC_LOAD_ADD:
7871     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
7872     return;
7873   case ISD::ATOMIC_LOAD_AND:
7874     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
7875     return;
7876   case ISD::ATOMIC_LOAD_NAND:
7877     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
7878     return;
7879   case ISD::ATOMIC_LOAD_OR:
7880     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
7881     return;
7882   case ISD::ATOMIC_LOAD_SUB:
7883     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
7884     return;
7885   case ISD::ATOMIC_LOAD_XOR:
7886     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
7887     return;
7888   case ISD::ATOMIC_SWAP:
7889     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
7890     return;
7891   }
7892 }
7893
7894 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
7895   switch (Opcode) {
7896   default: return NULL;
7897   case X86ISD::BSF:                return "X86ISD::BSF";
7898   case X86ISD::BSR:                return "X86ISD::BSR";
7899   case X86ISD::SHLD:               return "X86ISD::SHLD";
7900   case X86ISD::SHRD:               return "X86ISD::SHRD";
7901   case X86ISD::FAND:               return "X86ISD::FAND";
7902   case X86ISD::FOR:                return "X86ISD::FOR";
7903   case X86ISD::FXOR:               return "X86ISD::FXOR";
7904   case X86ISD::FSRL:               return "X86ISD::FSRL";
7905   case X86ISD::FILD:               return "X86ISD::FILD";
7906   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
7907   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
7908   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
7909   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
7910   case X86ISD::FLD:                return "X86ISD::FLD";
7911   case X86ISD::FST:                return "X86ISD::FST";
7912   case X86ISD::CALL:               return "X86ISD::CALL";
7913   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
7914   case X86ISD::BT:                 return "X86ISD::BT";
7915   case X86ISD::CMP:                return "X86ISD::CMP";
7916   case X86ISD::COMI:               return "X86ISD::COMI";
7917   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
7918   case X86ISD::SETCC:              return "X86ISD::SETCC";
7919   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
7920   case X86ISD::CMOV:               return "X86ISD::CMOV";
7921   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
7922   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
7923   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
7924   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
7925   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
7926   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
7927   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
7928   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
7929   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
7930   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
7931   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
7932   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
7933   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
7934   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
7935   case X86ISD::FMAX:               return "X86ISD::FMAX";
7936   case X86ISD::FMIN:               return "X86ISD::FMIN";
7937   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
7938   case X86ISD::FRCP:               return "X86ISD::FRCP";
7939   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
7940   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
7941   case X86ISD::SegmentBaseAddress: return "X86ISD::SegmentBaseAddress";
7942   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
7943   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
7944   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
7945   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
7946   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
7947   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
7948   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
7949   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
7950   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
7951   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
7952   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
7953   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
7954   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
7955   case X86ISD::VSHL:               return "X86ISD::VSHL";
7956   case X86ISD::VSRL:               return "X86ISD::VSRL";
7957   case X86ISD::CMPPD:              return "X86ISD::CMPPD";
7958   case X86ISD::CMPPS:              return "X86ISD::CMPPS";
7959   case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
7960   case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
7961   case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
7962   case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
7963   case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
7964   case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
7965   case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
7966   case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
7967   case X86ISD::ADD:                return "X86ISD::ADD";
7968   case X86ISD::SUB:                return "X86ISD::SUB";
7969   case X86ISD::SMUL:               return "X86ISD::SMUL";
7970   case X86ISD::UMUL:               return "X86ISD::UMUL";
7971   case X86ISD::INC:                return "X86ISD::INC";
7972   case X86ISD::DEC:                return "X86ISD::DEC";
7973   case X86ISD::OR:                 return "X86ISD::OR";
7974   case X86ISD::XOR:                return "X86ISD::XOR";
7975   case X86ISD::AND:                return "X86ISD::AND";
7976   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
7977   case X86ISD::PTEST:              return "X86ISD::PTEST";
7978   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
7979   case X86ISD::MINGW_ALLOCA:       return "X86ISD::MINGW_ALLOCA";
7980   }
7981 }
7982
7983 // isLegalAddressingMode - Return true if the addressing mode represented
7984 // by AM is legal for this target, for a load/store of the specified type.
7985 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
7986                                               const Type *Ty) const {
7987   // X86 supports extremely general addressing modes.
7988   CodeModel::Model M = getTargetMachine().getCodeModel();
7989
7990   // X86 allows a sign-extended 32-bit immediate field as a displacement.
7991   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
7992     return false;
7993
7994   if (AM.BaseGV) {
7995     unsigned GVFlags =
7996       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
7997
7998     // If a reference to this global requires an extra load, we can't fold it.
7999     if (isGlobalStubReference(GVFlags))
8000       return false;
8001
8002     // If BaseGV requires a register for the PIC base, we cannot also have a
8003     // BaseReg specified.
8004     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
8005       return false;
8006
8007     // If lower 4G is not available, then we must use rip-relative addressing.
8008     if (Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
8009       return false;
8010   }
8011
8012   switch (AM.Scale) {
8013   case 0:
8014   case 1:
8015   case 2:
8016   case 4:
8017   case 8:
8018     // These scales always work.
8019     break;
8020   case 3:
8021   case 5:
8022   case 9:
8023     // These scales are formed with basereg+scalereg.  Only accept if there is
8024     // no basereg yet.
8025     if (AM.HasBaseReg)
8026       return false;
8027     break;
8028   default:  // Other stuff never works.
8029     return false;
8030   }
8031
8032   return true;
8033 }
8034
8035
8036 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
8037   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
8038     return false;
8039   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
8040   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
8041   if (NumBits1 <= NumBits2)
8042     return false;
8043   return true;
8044 }
8045
8046 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
8047   if (!VT1.isInteger() || !VT2.isInteger())
8048     return false;
8049   unsigned NumBits1 = VT1.getSizeInBits();
8050   unsigned NumBits2 = VT2.getSizeInBits();
8051   if (NumBits1 <= NumBits2)
8052     return false;
8053   return true;
8054 }
8055
8056 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
8057   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
8058   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
8059 }
8060
8061 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
8062   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
8063   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
8064 }
8065
8066 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
8067   // i16 instructions are longer (0x66 prefix) and potentially slower.
8068   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
8069 }
8070
8071 /// isShuffleMaskLegal - Targets can use this to indicate that they only
8072 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
8073 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
8074 /// are assumed to be legal.
8075 bool
8076 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
8077                                       EVT VT) const {
8078   // Very little shuffling can be done for 64-bit vectors right now.
8079   if (VT.getSizeInBits() == 64)
8080     return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
8081
8082   // FIXME: pshufb, blends, shifts.
8083   return (VT.getVectorNumElements() == 2 ||
8084           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
8085           isMOVLMask(M, VT) ||
8086           isSHUFPMask(M, VT) ||
8087           isPSHUFDMask(M, VT) ||
8088           isPSHUFHWMask(M, VT) ||
8089           isPSHUFLWMask(M, VT) ||
8090           isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
8091           isUNPCKLMask(M, VT) ||
8092           isUNPCKHMask(M, VT) ||
8093           isUNPCKL_v_undef_Mask(M, VT) ||
8094           isUNPCKH_v_undef_Mask(M, VT));
8095 }
8096
8097 bool
8098 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
8099                                           EVT VT) const {
8100   unsigned NumElts = VT.getVectorNumElements();
8101   // FIXME: This collection of masks seems suspect.
8102   if (NumElts == 2)
8103     return true;
8104   if (NumElts == 4 && VT.getSizeInBits() == 128) {
8105     return (isMOVLMask(Mask, VT)  ||
8106             isCommutedMOVLMask(Mask, VT, true) ||
8107             isSHUFPMask(Mask, VT) ||
8108             isCommutedSHUFPMask(Mask, VT));
8109   }
8110   return false;
8111 }
8112
8113 //===----------------------------------------------------------------------===//
8114 //                           X86 Scheduler Hooks
8115 //===----------------------------------------------------------------------===//
8116
8117 // private utility function
8118 MachineBasicBlock *
8119 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
8120                                                        MachineBasicBlock *MBB,
8121                                                        unsigned regOpc,
8122                                                        unsigned immOpc,
8123                                                        unsigned LoadOpc,
8124                                                        unsigned CXchgOpc,
8125                                                        unsigned notOpc,
8126                                                        unsigned EAXreg,
8127                                                        TargetRegisterClass *RC,
8128                                                        bool invSrc) const {
8129   // For the atomic bitwise operator, we generate
8130   //   thisMBB:
8131   //   newMBB:
8132   //     ld  t1 = [bitinstr.addr]
8133   //     op  t2 = t1, [bitinstr.val]
8134   //     mov EAX = t1
8135   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
8136   //     bz  newMBB
8137   //     fallthrough -->nextMBB
8138   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8139   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8140   MachineFunction::iterator MBBIter = MBB;
8141   ++MBBIter;
8142
8143   /// First build the CFG
8144   MachineFunction *F = MBB->getParent();
8145   MachineBasicBlock *thisMBB = MBB;
8146   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
8147   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
8148   F->insert(MBBIter, newMBB);
8149   F->insert(MBBIter, nextMBB);
8150
8151   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
8152   nextMBB->splice(nextMBB->begin(), thisMBB,
8153                   llvm::next(MachineBasicBlock::iterator(bInstr)),
8154                   thisMBB->end());
8155   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
8156
8157   // Update thisMBB to fall through to newMBB
8158   thisMBB->addSuccessor(newMBB);
8159
8160   // newMBB jumps to itself and fall through to nextMBB
8161   newMBB->addSuccessor(nextMBB);
8162   newMBB->addSuccessor(newMBB);
8163
8164   // Insert instructions into newMBB based on incoming instruction
8165   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
8166          "unexpected number of operands");
8167   DebugLoc dl = bInstr->getDebugLoc();
8168   MachineOperand& destOper = bInstr->getOperand(0);
8169   MachineOperand* argOpers[2 + X86::AddrNumOperands];
8170   int numArgs = bInstr->getNumOperands() - 1;
8171   for (int i=0; i < numArgs; ++i)
8172     argOpers[i] = &bInstr->getOperand(i+1);
8173
8174   // x86 address has 4 operands: base, index, scale, and displacement
8175   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
8176   int valArgIndx = lastAddrIndx + 1;
8177
8178   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
8179   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
8180   for (int i=0; i <= lastAddrIndx; ++i)
8181     (*MIB).addOperand(*argOpers[i]);
8182
8183   unsigned tt = F->getRegInfo().createVirtualRegister(RC);
8184   if (invSrc) {
8185     MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
8186   }
8187   else
8188     tt = t1;
8189
8190   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
8191   assert((argOpers[valArgIndx]->isReg() ||
8192           argOpers[valArgIndx]->isImm()) &&
8193          "invalid operand");
8194   if (argOpers[valArgIndx]->isReg())
8195     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
8196   else
8197     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
8198   MIB.addReg(tt);
8199   (*MIB).addOperand(*argOpers[valArgIndx]);
8200
8201   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
8202   MIB.addReg(t1);
8203
8204   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
8205   for (int i=0; i <= lastAddrIndx; ++i)
8206     (*MIB).addOperand(*argOpers[i]);
8207   MIB.addReg(t2);
8208   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
8209   (*MIB).setMemRefs(bInstr->memoperands_begin(),
8210                     bInstr->memoperands_end());
8211
8212   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
8213   MIB.addReg(EAXreg);
8214
8215   // insert branch
8216   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
8217
8218   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
8219   return nextMBB;
8220 }
8221
8222 // private utility function:  64 bit atomics on 32 bit host.
8223 MachineBasicBlock *
8224 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
8225                                                        MachineBasicBlock *MBB,
8226                                                        unsigned regOpcL,
8227                                                        unsigned regOpcH,
8228                                                        unsigned immOpcL,
8229                                                        unsigned immOpcH,
8230                                                        bool invSrc) const {
8231   // For the atomic bitwise operator, we generate
8232   //   thisMBB (instructions are in pairs, except cmpxchg8b)
8233   //     ld t1,t2 = [bitinstr.addr]
8234   //   newMBB:
8235   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
8236   //     op  t5, t6 <- out1, out2, [bitinstr.val]
8237   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
8238   //     mov ECX, EBX <- t5, t6
8239   //     mov EAX, EDX <- t1, t2
8240   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
8241   //     mov t3, t4 <- EAX, EDX
8242   //     bz  newMBB
8243   //     result in out1, out2
8244   //     fallthrough -->nextMBB
8245
8246   const TargetRegisterClass *RC = X86::GR32RegisterClass;
8247   const unsigned LoadOpc = X86::MOV32rm;
8248   const unsigned NotOpc = X86::NOT32r;
8249   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8250   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8251   MachineFunction::iterator MBBIter = MBB;
8252   ++MBBIter;
8253
8254   /// First build the CFG
8255   MachineFunction *F = MBB->getParent();
8256   MachineBasicBlock *thisMBB = MBB;
8257   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
8258   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
8259   F->insert(MBBIter, newMBB);
8260   F->insert(MBBIter, nextMBB);
8261
8262   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
8263   nextMBB->splice(nextMBB->begin(), thisMBB,
8264                   llvm::next(MachineBasicBlock::iterator(bInstr)),
8265                   thisMBB->end());
8266   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
8267
8268   // Update thisMBB to fall through to newMBB
8269   thisMBB->addSuccessor(newMBB);
8270
8271   // newMBB jumps to itself and fall through to nextMBB
8272   newMBB->addSuccessor(nextMBB);
8273   newMBB->addSuccessor(newMBB);
8274
8275   DebugLoc dl = bInstr->getDebugLoc();
8276   // Insert instructions into newMBB based on incoming instruction
8277   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
8278   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
8279          "unexpected number of operands");
8280   MachineOperand& dest1Oper = bInstr->getOperand(0);
8281   MachineOperand& dest2Oper = bInstr->getOperand(1);
8282   MachineOperand* argOpers[2 + X86::AddrNumOperands];
8283   for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
8284     argOpers[i] = &bInstr->getOperand(i+2);
8285
8286     // We use some of the operands multiple times, so conservatively just
8287     // clear any kill flags that might be present.
8288     if (argOpers[i]->isReg() && argOpers[i]->isUse())
8289       argOpers[i]->setIsKill(false);
8290   }
8291
8292   // x86 address has 5 operands: base, index, scale, displacement, and segment.
8293   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
8294
8295   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
8296   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
8297   for (int i=0; i <= lastAddrIndx; ++i)
8298     (*MIB).addOperand(*argOpers[i]);
8299   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
8300   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
8301   // add 4 to displacement.
8302   for (int i=0; i <= lastAddrIndx-2; ++i)
8303     (*MIB).addOperand(*argOpers[i]);
8304   MachineOperand newOp3 = *(argOpers[3]);
8305   if (newOp3.isImm())
8306     newOp3.setImm(newOp3.getImm()+4);
8307   else
8308     newOp3.setOffset(newOp3.getOffset()+4);
8309   (*MIB).addOperand(newOp3);
8310   (*MIB).addOperand(*argOpers[lastAddrIndx]);
8311
8312   // t3/4 are defined later, at the bottom of the loop
8313   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
8314   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
8315   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
8316     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
8317   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
8318     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
8319
8320   // The subsequent operations should be using the destination registers of
8321   //the PHI instructions.
8322   if (invSrc) {
8323     t1 = F->getRegInfo().createVirtualRegister(RC);
8324     t2 = F->getRegInfo().createVirtualRegister(RC);
8325     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
8326     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
8327   } else {
8328     t1 = dest1Oper.getReg();
8329     t2 = dest2Oper.getReg();
8330   }
8331
8332   int valArgIndx = lastAddrIndx + 1;
8333   assert((argOpers[valArgIndx]->isReg() ||
8334           argOpers[valArgIndx]->isImm()) &&
8335          "invalid operand");
8336   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
8337   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
8338   if (argOpers[valArgIndx]->isReg())
8339     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
8340   else
8341     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
8342   if (regOpcL != X86::MOV32rr)
8343     MIB.addReg(t1);
8344   (*MIB).addOperand(*argOpers[valArgIndx]);
8345   assert(argOpers[valArgIndx + 1]->isReg() ==
8346          argOpers[valArgIndx]->isReg());
8347   assert(argOpers[valArgIndx + 1]->isImm() ==
8348          argOpers[valArgIndx]->isImm());
8349   if (argOpers[valArgIndx + 1]->isReg())
8350     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
8351   else
8352     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
8353   if (regOpcH != X86::MOV32rr)
8354     MIB.addReg(t2);
8355   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
8356
8357   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
8358   MIB.addReg(t1);
8359   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
8360   MIB.addReg(t2);
8361
8362   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
8363   MIB.addReg(t5);
8364   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
8365   MIB.addReg(t6);
8366
8367   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
8368   for (int i=0; i <= lastAddrIndx; ++i)
8369     (*MIB).addOperand(*argOpers[i]);
8370
8371   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
8372   (*MIB).setMemRefs(bInstr->memoperands_begin(),
8373                     bInstr->memoperands_end());
8374
8375   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
8376   MIB.addReg(X86::EAX);
8377   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
8378   MIB.addReg(X86::EDX);
8379
8380   // insert branch
8381   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
8382
8383   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
8384   return nextMBB;
8385 }
8386
8387 // private utility function
8388 MachineBasicBlock *
8389 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
8390                                                       MachineBasicBlock *MBB,
8391                                                       unsigned cmovOpc) const {
8392   // For the atomic min/max operator, we generate
8393   //   thisMBB:
8394   //   newMBB:
8395   //     ld t1 = [min/max.addr]
8396   //     mov t2 = [min/max.val]
8397   //     cmp  t1, t2
8398   //     cmov[cond] t2 = t1
8399   //     mov EAX = t1
8400   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
8401   //     bz   newMBB
8402   //     fallthrough -->nextMBB
8403   //
8404   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8405   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8406   MachineFunction::iterator MBBIter = MBB;
8407   ++MBBIter;
8408
8409   /// First build the CFG
8410   MachineFunction *F = MBB->getParent();
8411   MachineBasicBlock *thisMBB = MBB;
8412   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
8413   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
8414   F->insert(MBBIter, newMBB);
8415   F->insert(MBBIter, nextMBB);
8416
8417   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
8418   nextMBB->splice(nextMBB->begin(), thisMBB,
8419                   llvm::next(MachineBasicBlock::iterator(mInstr)),
8420                   thisMBB->end());
8421   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
8422
8423   // Update thisMBB to fall through to newMBB
8424   thisMBB->addSuccessor(newMBB);
8425
8426   // newMBB jumps to newMBB and fall through to nextMBB
8427   newMBB->addSuccessor(nextMBB);
8428   newMBB->addSuccessor(newMBB);
8429
8430   DebugLoc dl = mInstr->getDebugLoc();
8431   // Insert instructions into newMBB based on incoming instruction
8432   assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
8433          "unexpected number of operands");
8434   MachineOperand& destOper = mInstr->getOperand(0);
8435   MachineOperand* argOpers[2 + X86::AddrNumOperands];
8436   int numArgs = mInstr->getNumOperands() - 1;
8437   for (int i=0; i < numArgs; ++i)
8438     argOpers[i] = &mInstr->getOperand(i+1);
8439
8440   // x86 address has 4 operands: base, index, scale, and displacement
8441   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
8442   int valArgIndx = lastAddrIndx + 1;
8443
8444   unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8445   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
8446   for (int i=0; i <= lastAddrIndx; ++i)
8447     (*MIB).addOperand(*argOpers[i]);
8448
8449   // We only support register and immediate values
8450   assert((argOpers[valArgIndx]->isReg() ||
8451           argOpers[valArgIndx]->isImm()) &&
8452          "invalid operand");
8453
8454   unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8455   if (argOpers[valArgIndx]->isReg())
8456     MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
8457   else
8458     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
8459   (*MIB).addOperand(*argOpers[valArgIndx]);
8460
8461   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
8462   MIB.addReg(t1);
8463
8464   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
8465   MIB.addReg(t1);
8466   MIB.addReg(t2);
8467
8468   // Generate movc
8469   unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8470   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
8471   MIB.addReg(t2);
8472   MIB.addReg(t1);
8473
8474   // Cmp and exchange if none has modified the memory location
8475   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
8476   for (int i=0; i <= lastAddrIndx; ++i)
8477     (*MIB).addOperand(*argOpers[i]);
8478   MIB.addReg(t3);
8479   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
8480   (*MIB).setMemRefs(mInstr->memoperands_begin(),
8481                     mInstr->memoperands_end());
8482
8483   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
8484   MIB.addReg(X86::EAX);
8485
8486   // insert branch
8487   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
8488
8489   mInstr->eraseFromParent();   // The pseudo instruction is gone now.
8490   return nextMBB;
8491 }
8492
8493 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
8494 // all of this code can be replaced with that in the .td file.
8495 MachineBasicBlock *
8496 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
8497                             unsigned numArgs, bool memArg) const {
8498
8499   DebugLoc dl = MI->getDebugLoc();
8500   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8501
8502   unsigned Opc;
8503   if (memArg)
8504     Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
8505   else
8506     Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
8507
8508   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(Opc));
8509
8510   for (unsigned i = 0; i < numArgs; ++i) {
8511     MachineOperand &Op = MI->getOperand(i+1);
8512
8513     if (!(Op.isReg() && Op.isImplicit()))
8514       MIB.addOperand(Op);
8515   }
8516
8517   BuildMI(BB, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
8518     .addReg(X86::XMM0);
8519
8520   MI->eraseFromParent();
8521
8522   return BB;
8523 }
8524
8525 MachineBasicBlock *
8526 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
8527                                                  MachineInstr *MI,
8528                                                  MachineBasicBlock *MBB) const {
8529   // Emit code to save XMM registers to the stack. The ABI says that the
8530   // number of registers to save is given in %al, so it's theoretically
8531   // possible to do an indirect jump trick to avoid saving all of them,
8532   // however this code takes a simpler approach and just executes all
8533   // of the stores if %al is non-zero. It's less code, and it's probably
8534   // easier on the hardware branch predictor, and stores aren't all that
8535   // expensive anyway.
8536
8537   // Create the new basic blocks. One block contains all the XMM stores,
8538   // and one block is the final destination regardless of whether any
8539   // stores were performed.
8540   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8541   MachineFunction *F = MBB->getParent();
8542   MachineFunction::iterator MBBIter = MBB;
8543   ++MBBIter;
8544   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
8545   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
8546   F->insert(MBBIter, XMMSaveMBB);
8547   F->insert(MBBIter, EndMBB);
8548
8549   // Transfer the remainder of MBB and its successor edges to EndMBB.
8550   EndMBB->splice(EndMBB->begin(), MBB,
8551                  llvm::next(MachineBasicBlock::iterator(MI)),
8552                  MBB->end());
8553   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
8554
8555   // The original block will now fall through to the XMM save block.
8556   MBB->addSuccessor(XMMSaveMBB);
8557   // The XMMSaveMBB will fall through to the end block.
8558   XMMSaveMBB->addSuccessor(EndMBB);
8559
8560   // Now add the instructions.
8561   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8562   DebugLoc DL = MI->getDebugLoc();
8563
8564   unsigned CountReg = MI->getOperand(0).getReg();
8565   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
8566   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
8567
8568   if (!Subtarget->isTargetWin64()) {
8569     // If %al is 0, branch around the XMM save block.
8570     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
8571     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
8572     MBB->addSuccessor(EndMBB);
8573   }
8574
8575   // In the XMM save block, save all the XMM argument registers.
8576   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
8577     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
8578     MachineMemOperand *MMO =
8579       F->getMachineMemOperand(
8580         PseudoSourceValue::getFixedStack(RegSaveFrameIndex),
8581         MachineMemOperand::MOStore, Offset,
8582         /*Size=*/16, /*Align=*/16);
8583     BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
8584       .addFrameIndex(RegSaveFrameIndex)
8585       .addImm(/*Scale=*/1)
8586       .addReg(/*IndexReg=*/0)
8587       .addImm(/*Disp=*/Offset)
8588       .addReg(/*Segment=*/0)
8589       .addReg(MI->getOperand(i).getReg())
8590       .addMemOperand(MMO);
8591   }
8592
8593   MI->eraseFromParent();   // The pseudo instruction is gone now.
8594
8595   return EndMBB;
8596 }
8597
8598 MachineBasicBlock *
8599 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
8600                                      MachineBasicBlock *BB) const {
8601   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8602   DebugLoc DL = MI->getDebugLoc();
8603
8604   // To "insert" a SELECT_CC instruction, we actually have to insert the
8605   // diamond control-flow pattern.  The incoming instruction knows the
8606   // destination vreg to set, the condition code register to branch on, the
8607   // true/false values to select between, and a branch opcode to use.
8608   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8609   MachineFunction::iterator It = BB;
8610   ++It;
8611
8612   //  thisMBB:
8613   //  ...
8614   //   TrueVal = ...
8615   //   cmpTY ccX, r1, r2
8616   //   bCC copy1MBB
8617   //   fallthrough --> copy0MBB
8618   MachineBasicBlock *thisMBB = BB;
8619   MachineFunction *F = BB->getParent();
8620   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
8621   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8622   F->insert(It, copy0MBB);
8623   F->insert(It, sinkMBB);
8624
8625   // If the EFLAGS register isn't dead in the terminator, then claim that it's
8626   // live into the sink and copy blocks.
8627   const MachineFunction *MF = BB->getParent();
8628   const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
8629   BitVector ReservedRegs = TRI->getReservedRegs(*MF);
8630
8631   for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
8632     const MachineOperand &MO = MI->getOperand(I);
8633     if (!MO.isReg() || !MO.isUse() || MO.isKill()) continue;
8634     unsigned Reg = MO.getReg();
8635     if (Reg != X86::EFLAGS) continue;
8636     copy0MBB->addLiveIn(Reg);
8637     sinkMBB->addLiveIn(Reg);
8638   }
8639
8640   // Transfer the remainder of BB and its successor edges to sinkMBB.
8641   sinkMBB->splice(sinkMBB->begin(), BB,
8642                   llvm::next(MachineBasicBlock::iterator(MI)),
8643                   BB->end());
8644   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
8645
8646   // Add the true and fallthrough blocks as its successors.
8647   BB->addSuccessor(copy0MBB);
8648   BB->addSuccessor(sinkMBB);
8649
8650   // Create the conditional branch instruction.
8651   unsigned Opc =
8652     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
8653   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
8654
8655   //  copy0MBB:
8656   //   %FalseValue = ...
8657   //   # fallthrough to sinkMBB
8658   copy0MBB->addSuccessor(sinkMBB);
8659
8660   //  sinkMBB:
8661   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
8662   //  ...
8663   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
8664           TII->get(X86::PHI), MI->getOperand(0).getReg())
8665     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
8666     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
8667
8668   MI->eraseFromParent();   // The pseudo instruction is gone now.
8669   return sinkMBB;
8670 }
8671
8672 MachineBasicBlock *
8673 X86TargetLowering::EmitLoweredMingwAlloca(MachineInstr *MI,
8674                                           MachineBasicBlock *BB) const {
8675   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8676   DebugLoc DL = MI->getDebugLoc();
8677
8678   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
8679   // non-trivial part is impdef of ESP.
8680   // FIXME: The code should be tweaked as soon as we'll try to do codegen for
8681   // mingw-w64.
8682
8683   BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
8684     .addExternalSymbol("_alloca")
8685     .addReg(X86::EAX, RegState::Implicit)
8686     .addReg(X86::ESP, RegState::Implicit)
8687     .addReg(X86::EAX, RegState::Define | RegState::Implicit)
8688     .addReg(X86::ESP, RegState::Define | RegState::Implicit);
8689
8690   MI->eraseFromParent();   // The pseudo instruction is gone now.
8691   return BB;
8692 }
8693
8694 MachineBasicBlock *
8695 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
8696                                       MachineBasicBlock *BB) const {
8697   // This is pretty easy.  We're taking the value that we received from
8698   // our load from the relocation, sticking it in either RDI (x86-64)
8699   // or EAX and doing an indirect call.  The return value will then
8700   // be in the normal return register.
8701   const X86InstrInfo *TII 
8702     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
8703   DebugLoc DL = MI->getDebugLoc();
8704   MachineFunction *F = BB->getParent();
8705   
8706   assert(MI->getOperand(3).isGlobal() && "This should be a global");
8707   
8708   if (Subtarget->is64Bit()) {
8709     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
8710                                       TII->get(X86::MOV64rm), X86::RDI)
8711     .addReg(X86::RIP)
8712     .addImm(0).addReg(0)
8713     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0, 
8714                       MI->getOperand(3).getTargetFlags())
8715     .addReg(0);
8716     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
8717     addDirectMem(MIB, X86::RDI);
8718   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
8719     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
8720                                       TII->get(X86::MOV32rm), X86::EAX)
8721     .addReg(0)
8722     .addImm(0).addReg(0)
8723     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0, 
8724                       MI->getOperand(3).getTargetFlags())
8725     .addReg(0);
8726     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
8727     addDirectMem(MIB, X86::EAX);
8728   } else {
8729     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
8730                                       TII->get(X86::MOV32rm), X86::EAX)
8731     .addReg(TII->getGlobalBaseReg(F))
8732     .addImm(0).addReg(0)
8733     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0, 
8734                       MI->getOperand(3).getTargetFlags())
8735     .addReg(0);
8736     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
8737     addDirectMem(MIB, X86::EAX);
8738   }
8739   
8740   MI->eraseFromParent(); // The pseudo instruction is gone now.
8741   return BB;
8742 }
8743
8744 MachineBasicBlock *
8745 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
8746                                                MachineBasicBlock *BB) const {
8747   switch (MI->getOpcode()) {
8748   default: assert(false && "Unexpected instr type to insert");
8749   case X86::MINGW_ALLOCA:
8750     return EmitLoweredMingwAlloca(MI, BB);
8751   case X86::TLSCall_32:
8752   case X86::TLSCall_64:
8753     return EmitLoweredTLSCall(MI, BB);
8754   case X86::CMOV_GR8:
8755   case X86::CMOV_V1I64:
8756   case X86::CMOV_FR32:
8757   case X86::CMOV_FR64:
8758   case X86::CMOV_V4F32:
8759   case X86::CMOV_V2F64:
8760   case X86::CMOV_V2I64:
8761   case X86::CMOV_GR16:
8762   case X86::CMOV_GR32:
8763   case X86::CMOV_RFP32:
8764   case X86::CMOV_RFP64:
8765   case X86::CMOV_RFP80:
8766     return EmitLoweredSelect(MI, BB);
8767
8768   case X86::FP32_TO_INT16_IN_MEM:
8769   case X86::FP32_TO_INT32_IN_MEM:
8770   case X86::FP32_TO_INT64_IN_MEM:
8771   case X86::FP64_TO_INT16_IN_MEM:
8772   case X86::FP64_TO_INT32_IN_MEM:
8773   case X86::FP64_TO_INT64_IN_MEM:
8774   case X86::FP80_TO_INT16_IN_MEM:
8775   case X86::FP80_TO_INT32_IN_MEM:
8776   case X86::FP80_TO_INT64_IN_MEM: {
8777     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8778     DebugLoc DL = MI->getDebugLoc();
8779
8780     // Change the floating point control register to use "round towards zero"
8781     // mode when truncating to an integer value.
8782     MachineFunction *F = BB->getParent();
8783     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
8784     addFrameReference(BuildMI(*BB, MI, DL,
8785                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
8786
8787     // Load the old value of the high byte of the control word...
8788     unsigned OldCW =
8789       F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
8790     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
8791                       CWFrameIdx);
8792
8793     // Set the high part to be round to zero...
8794     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
8795       .addImm(0xC7F);
8796
8797     // Reload the modified control word now...
8798     addFrameReference(BuildMI(*BB, MI, DL,
8799                               TII->get(X86::FLDCW16m)), CWFrameIdx);
8800
8801     // Restore the memory image of control word to original value
8802     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
8803       .addReg(OldCW);
8804
8805     // Get the X86 opcode to use.
8806     unsigned Opc;
8807     switch (MI->getOpcode()) {
8808     default: llvm_unreachable("illegal opcode!");
8809     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
8810     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
8811     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
8812     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
8813     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
8814     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
8815     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
8816     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
8817     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
8818     }
8819
8820     X86AddressMode AM;
8821     MachineOperand &Op = MI->getOperand(0);
8822     if (Op.isReg()) {
8823       AM.BaseType = X86AddressMode::RegBase;
8824       AM.Base.Reg = Op.getReg();
8825     } else {
8826       AM.BaseType = X86AddressMode::FrameIndexBase;
8827       AM.Base.FrameIndex = Op.getIndex();
8828     }
8829     Op = MI->getOperand(1);
8830     if (Op.isImm())
8831       AM.Scale = Op.getImm();
8832     Op = MI->getOperand(2);
8833     if (Op.isImm())
8834       AM.IndexReg = Op.getImm();
8835     Op = MI->getOperand(3);
8836     if (Op.isGlobal()) {
8837       AM.GV = Op.getGlobal();
8838     } else {
8839       AM.Disp = Op.getImm();
8840     }
8841     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
8842                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
8843
8844     // Reload the original control word now.
8845     addFrameReference(BuildMI(*BB, MI, DL,
8846                               TII->get(X86::FLDCW16m)), CWFrameIdx);
8847
8848     MI->eraseFromParent();   // The pseudo instruction is gone now.
8849     return BB;
8850   }
8851     // String/text processing lowering.
8852   case X86::PCMPISTRM128REG:
8853     return EmitPCMP(MI, BB, 3, false /* in-mem */);
8854   case X86::PCMPISTRM128MEM:
8855     return EmitPCMP(MI, BB, 3, true /* in-mem */);
8856   case X86::PCMPESTRM128REG:
8857     return EmitPCMP(MI, BB, 5, false /* in mem */);
8858   case X86::PCMPESTRM128MEM:
8859     return EmitPCMP(MI, BB, 5, true /* in mem */);
8860
8861     // Atomic Lowering.
8862   case X86::ATOMAND32:
8863     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
8864                                                X86::AND32ri, X86::MOV32rm,
8865                                                X86::LCMPXCHG32,
8866                                                X86::NOT32r, X86::EAX,
8867                                                X86::GR32RegisterClass);
8868   case X86::ATOMOR32:
8869     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
8870                                                X86::OR32ri, X86::MOV32rm,
8871                                                X86::LCMPXCHG32,
8872                                                X86::NOT32r, X86::EAX,
8873                                                X86::GR32RegisterClass);
8874   case X86::ATOMXOR32:
8875     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
8876                                                X86::XOR32ri, X86::MOV32rm,
8877                                                X86::LCMPXCHG32,
8878                                                X86::NOT32r, X86::EAX,
8879                                                X86::GR32RegisterClass);
8880   case X86::ATOMNAND32:
8881     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
8882                                                X86::AND32ri, X86::MOV32rm,
8883                                                X86::LCMPXCHG32,
8884                                                X86::NOT32r, X86::EAX,
8885                                                X86::GR32RegisterClass, true);
8886   case X86::ATOMMIN32:
8887     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
8888   case X86::ATOMMAX32:
8889     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
8890   case X86::ATOMUMIN32:
8891     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
8892   case X86::ATOMUMAX32:
8893     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
8894
8895   case X86::ATOMAND16:
8896     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
8897                                                X86::AND16ri, X86::MOV16rm,
8898                                                X86::LCMPXCHG16,
8899                                                X86::NOT16r, X86::AX,
8900                                                X86::GR16RegisterClass);
8901   case X86::ATOMOR16:
8902     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
8903                                                X86::OR16ri, X86::MOV16rm,
8904                                                X86::LCMPXCHG16,
8905                                                X86::NOT16r, X86::AX,
8906                                                X86::GR16RegisterClass);
8907   case X86::ATOMXOR16:
8908     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
8909                                                X86::XOR16ri, X86::MOV16rm,
8910                                                X86::LCMPXCHG16,
8911                                                X86::NOT16r, X86::AX,
8912                                                X86::GR16RegisterClass);
8913   case X86::ATOMNAND16:
8914     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
8915                                                X86::AND16ri, X86::MOV16rm,
8916                                                X86::LCMPXCHG16,
8917                                                X86::NOT16r, X86::AX,
8918                                                X86::GR16RegisterClass, true);
8919   case X86::ATOMMIN16:
8920     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
8921   case X86::ATOMMAX16:
8922     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
8923   case X86::ATOMUMIN16:
8924     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
8925   case X86::ATOMUMAX16:
8926     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
8927
8928   case X86::ATOMAND8:
8929     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
8930                                                X86::AND8ri, X86::MOV8rm,
8931                                                X86::LCMPXCHG8,
8932                                                X86::NOT8r, X86::AL,
8933                                                X86::GR8RegisterClass);
8934   case X86::ATOMOR8:
8935     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
8936                                                X86::OR8ri, X86::MOV8rm,
8937                                                X86::LCMPXCHG8,
8938                                                X86::NOT8r, X86::AL,
8939                                                X86::GR8RegisterClass);
8940   case X86::ATOMXOR8:
8941     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
8942                                                X86::XOR8ri, X86::MOV8rm,
8943                                                X86::LCMPXCHG8,
8944                                                X86::NOT8r, X86::AL,
8945                                                X86::GR8RegisterClass);
8946   case X86::ATOMNAND8:
8947     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
8948                                                X86::AND8ri, X86::MOV8rm,
8949                                                X86::LCMPXCHG8,
8950                                                X86::NOT8r, X86::AL,
8951                                                X86::GR8RegisterClass, true);
8952   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
8953   // This group is for 64-bit host.
8954   case X86::ATOMAND64:
8955     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
8956                                                X86::AND64ri32, X86::MOV64rm,
8957                                                X86::LCMPXCHG64,
8958                                                X86::NOT64r, X86::RAX,
8959                                                X86::GR64RegisterClass);
8960   case X86::ATOMOR64:
8961     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
8962                                                X86::OR64ri32, X86::MOV64rm,
8963                                                X86::LCMPXCHG64,
8964                                                X86::NOT64r, X86::RAX,
8965                                                X86::GR64RegisterClass);
8966   case X86::ATOMXOR64:
8967     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
8968                                                X86::XOR64ri32, X86::MOV64rm,
8969                                                X86::LCMPXCHG64,
8970                                                X86::NOT64r, X86::RAX,
8971                                                X86::GR64RegisterClass);
8972   case X86::ATOMNAND64:
8973     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
8974                                                X86::AND64ri32, X86::MOV64rm,
8975                                                X86::LCMPXCHG64,
8976                                                X86::NOT64r, X86::RAX,
8977                                                X86::GR64RegisterClass, true);
8978   case X86::ATOMMIN64:
8979     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
8980   case X86::ATOMMAX64:
8981     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
8982   case X86::ATOMUMIN64:
8983     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
8984   case X86::ATOMUMAX64:
8985     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
8986
8987   // This group does 64-bit operations on a 32-bit host.
8988   case X86::ATOMAND6432:
8989     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8990                                                X86::AND32rr, X86::AND32rr,
8991                                                X86::AND32ri, X86::AND32ri,
8992                                                false);
8993   case X86::ATOMOR6432:
8994     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8995                                                X86::OR32rr, X86::OR32rr,
8996                                                X86::OR32ri, X86::OR32ri,
8997                                                false);
8998   case X86::ATOMXOR6432:
8999     return EmitAtomicBit6432WithCustomInserter(MI, BB,
9000                                                X86::XOR32rr, X86::XOR32rr,
9001                                                X86::XOR32ri, X86::XOR32ri,
9002                                                false);
9003   case X86::ATOMNAND6432:
9004     return EmitAtomicBit6432WithCustomInserter(MI, BB,
9005                                                X86::AND32rr, X86::AND32rr,
9006                                                X86::AND32ri, X86::AND32ri,
9007                                                true);
9008   case X86::ATOMADD6432:
9009     return EmitAtomicBit6432WithCustomInserter(MI, BB,
9010                                                X86::ADD32rr, X86::ADC32rr,
9011                                                X86::ADD32ri, X86::ADC32ri,
9012                                                false);
9013   case X86::ATOMSUB6432:
9014     return EmitAtomicBit6432WithCustomInserter(MI, BB,
9015                                                X86::SUB32rr, X86::SBB32rr,
9016                                                X86::SUB32ri, X86::SBB32ri,
9017                                                false);
9018   case X86::ATOMSWAP6432:
9019     return EmitAtomicBit6432WithCustomInserter(MI, BB,
9020                                                X86::MOV32rr, X86::MOV32rr,
9021                                                X86::MOV32ri, X86::MOV32ri,
9022                                                false);
9023   case X86::VASTART_SAVE_XMM_REGS:
9024     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
9025   }
9026 }
9027
9028 //===----------------------------------------------------------------------===//
9029 //                           X86 Optimization Hooks
9030 //===----------------------------------------------------------------------===//
9031
9032 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
9033                                                        const APInt &Mask,
9034                                                        APInt &KnownZero,
9035                                                        APInt &KnownOne,
9036                                                        const SelectionDAG &DAG,
9037                                                        unsigned Depth) const {
9038   unsigned Opc = Op.getOpcode();
9039   assert((Opc >= ISD::BUILTIN_OP_END ||
9040           Opc == ISD::INTRINSIC_WO_CHAIN ||
9041           Opc == ISD::INTRINSIC_W_CHAIN ||
9042           Opc == ISD::INTRINSIC_VOID) &&
9043          "Should use MaskedValueIsZero if you don't know whether Op"
9044          " is a target node!");
9045
9046   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
9047   switch (Opc) {
9048   default: break;
9049   case X86ISD::ADD:
9050   case X86ISD::SUB:
9051   case X86ISD::SMUL:
9052   case X86ISD::UMUL:
9053   case X86ISD::INC:
9054   case X86ISD::DEC:
9055   case X86ISD::OR:
9056   case X86ISD::XOR:
9057   case X86ISD::AND:
9058     // These nodes' second result is a boolean.
9059     if (Op.getResNo() == 0)
9060       break;
9061     // Fallthrough
9062   case X86ISD::SETCC:
9063     KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
9064                                        Mask.getBitWidth() - 1);
9065     break;
9066   }
9067 }
9068
9069 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
9070 /// node is a GlobalAddress + offset.
9071 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
9072                                        const GlobalValue* &GA,
9073                                        int64_t &Offset) const {
9074   if (N->getOpcode() == X86ISD::Wrapper) {
9075     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
9076       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
9077       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
9078       return true;
9079     }
9080   }
9081   return TargetLowering::isGAPlusOffset(N, GA, Offset);
9082 }
9083
9084 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
9085 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
9086 /// if the load addresses are consecutive, non-overlapping, and in the right
9087 /// order.
9088 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
9089                                      const TargetLowering &TLI) {
9090   DebugLoc dl = N->getDebugLoc();
9091   EVT VT = N->getValueType(0);
9092   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9093
9094   if (VT.getSizeInBits() != 128)
9095     return SDValue();
9096
9097   SmallVector<SDValue, 16> Elts;
9098   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
9099     Elts.push_back(DAG.getShuffleScalarElt(SVN, i));
9100   
9101   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
9102 }
9103
9104 /// PerformShuffleCombine - Detect vector gather/scatter index generation
9105 /// and convert it from being a bunch of shuffles and extracts to a simple
9106 /// store and scalar loads to extract the elements.
9107 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
9108                                                 const TargetLowering &TLI) {
9109   SDValue InputVector = N->getOperand(0);
9110
9111   // Only operate on vectors of 4 elements, where the alternative shuffling
9112   // gets to be more expensive.
9113   if (InputVector.getValueType() != MVT::v4i32)
9114     return SDValue();
9115
9116   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
9117   // single use which is a sign-extend or zero-extend, and all elements are
9118   // used.
9119   SmallVector<SDNode *, 4> Uses;
9120   unsigned ExtractedElements = 0;
9121   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
9122        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
9123     if (UI.getUse().getResNo() != InputVector.getResNo())
9124       return SDValue();
9125
9126     SDNode *Extract = *UI;
9127     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9128       return SDValue();
9129
9130     if (Extract->getValueType(0) != MVT::i32)
9131       return SDValue();
9132     if (!Extract->hasOneUse())
9133       return SDValue();
9134     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
9135         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
9136       return SDValue();
9137     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
9138       return SDValue();
9139
9140     // Record which element was extracted.
9141     ExtractedElements |=
9142       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
9143
9144     Uses.push_back(Extract);
9145   }
9146
9147   // If not all the elements were used, this may not be worthwhile.
9148   if (ExtractedElements != 15)
9149     return SDValue();
9150
9151   // Ok, we've now decided to do the transformation.
9152   DebugLoc dl = InputVector.getDebugLoc();
9153
9154   // Store the value to a temporary stack slot.
9155   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
9156   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr, NULL,
9157                             0, false, false, 0);
9158
9159   // Replace each use (extract) with a load of the appropriate element.
9160   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
9161        UE = Uses.end(); UI != UE; ++UI) {
9162     SDNode *Extract = *UI;
9163
9164     // Compute the element's address.
9165     SDValue Idx = Extract->getOperand(1);
9166     unsigned EltSize =
9167         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
9168     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
9169     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
9170
9171     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(),
9172                                      OffsetVal, StackPtr);
9173
9174     // Load the scalar.
9175     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
9176                                      ScalarAddr, NULL, 0, false, false, 0);
9177
9178     // Replace the exact with the load.
9179     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
9180   }
9181
9182   // The replacement was made in place; don't return anything.
9183   return SDValue();
9184 }
9185
9186 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
9187 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
9188                                     const X86Subtarget *Subtarget) {
9189   DebugLoc DL = N->getDebugLoc();
9190   SDValue Cond = N->getOperand(0);
9191   // Get the LHS/RHS of the select.
9192   SDValue LHS = N->getOperand(1);
9193   SDValue RHS = N->getOperand(2);
9194
9195   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
9196   // instructions match the semantics of the common C idiom x<y?x:y but not
9197   // x<=y?x:y, because of how they handle negative zero (which can be
9198   // ignored in unsafe-math mode).
9199   if (Subtarget->hasSSE2() &&
9200       (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
9201       Cond.getOpcode() == ISD::SETCC) {
9202     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
9203
9204     unsigned Opcode = 0;
9205     // Check for x CC y ? x : y.
9206     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
9207         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
9208       switch (CC) {
9209       default: break;
9210       case ISD::SETULT:
9211         // Converting this to a min would handle NaNs incorrectly, and swapping
9212         // the operands would cause it to handle comparisons between positive
9213         // and negative zero incorrectly.
9214         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
9215           if (!UnsafeFPMath &&
9216               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9217             break;
9218           std::swap(LHS, RHS);
9219         }
9220         Opcode = X86ISD::FMIN;
9221         break;
9222       case ISD::SETOLE:
9223         // Converting this to a min would handle comparisons between positive
9224         // and negative zero incorrectly.
9225         if (!UnsafeFPMath &&
9226             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
9227           break;
9228         Opcode = X86ISD::FMIN;
9229         break;
9230       case ISD::SETULE:
9231         // Converting this to a min would handle both negative zeros and NaNs
9232         // incorrectly, but we can swap the operands to fix both.
9233         std::swap(LHS, RHS);
9234       case ISD::SETOLT:
9235       case ISD::SETLT:
9236       case ISD::SETLE:
9237         Opcode = X86ISD::FMIN;
9238         break;
9239
9240       case ISD::SETOGE:
9241         // Converting this to a max would handle comparisons between positive
9242         // and negative zero incorrectly.
9243         if (!UnsafeFPMath &&
9244             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS))
9245           break;
9246         Opcode = X86ISD::FMAX;
9247         break;
9248       case ISD::SETUGT:
9249         // Converting this to a max would handle NaNs incorrectly, and swapping
9250         // the operands would cause it to handle comparisons between positive
9251         // and negative zero incorrectly.
9252         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
9253           if (!UnsafeFPMath &&
9254               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9255             break;
9256           std::swap(LHS, RHS);
9257         }
9258         Opcode = X86ISD::FMAX;
9259         break;
9260       case ISD::SETUGE:
9261         // Converting this to a max would handle both negative zeros and NaNs
9262         // incorrectly, but we can swap the operands to fix both.
9263         std::swap(LHS, RHS);
9264       case ISD::SETOGT:
9265       case ISD::SETGT:
9266       case ISD::SETGE:
9267         Opcode = X86ISD::FMAX;
9268         break;
9269       }
9270     // Check for x CC y ? y : x -- a min/max with reversed arms.
9271     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
9272                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
9273       switch (CC) {
9274       default: break;
9275       case ISD::SETOGE:
9276         // Converting this to a min would handle comparisons between positive
9277         // and negative zero incorrectly, and swapping the operands would
9278         // cause it to handle NaNs incorrectly.
9279         if (!UnsafeFPMath &&
9280             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
9281           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
9282             break;
9283           std::swap(LHS, RHS);
9284         }
9285         Opcode = X86ISD::FMIN;
9286         break;
9287       case ISD::SETUGT:
9288         // Converting this to a min would handle NaNs incorrectly.
9289         if (!UnsafeFPMath &&
9290             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
9291           break;
9292         Opcode = X86ISD::FMIN;
9293         break;
9294       case ISD::SETUGE:
9295         // Converting this to a min would handle both negative zeros and NaNs
9296         // incorrectly, but we can swap the operands to fix both.
9297         std::swap(LHS, RHS);
9298       case ISD::SETOGT:
9299       case ISD::SETGT:
9300       case ISD::SETGE:
9301         Opcode = X86ISD::FMIN;
9302         break;
9303
9304       case ISD::SETULT:
9305         // Converting this to a max would handle NaNs incorrectly.
9306         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
9307           break;
9308         Opcode = X86ISD::FMAX;
9309         break;
9310       case ISD::SETOLE:
9311         // Converting this to a max would handle comparisons between positive
9312         // and negative zero incorrectly, and swapping the operands would
9313         // cause it to handle NaNs incorrectly.
9314         if (!UnsafeFPMath &&
9315             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
9316           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
9317             break;
9318           std::swap(LHS, RHS);
9319         }
9320         Opcode = X86ISD::FMAX;
9321         break;
9322       case ISD::SETULE:
9323         // Converting this to a max would handle both negative zeros and NaNs
9324         // incorrectly, but we can swap the operands to fix both.
9325         std::swap(LHS, RHS);
9326       case ISD::SETOLT:
9327       case ISD::SETLT:
9328       case ISD::SETLE:
9329         Opcode = X86ISD::FMAX;
9330         break;
9331       }
9332     }
9333
9334     if (Opcode)
9335       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
9336   }
9337
9338   // If this is a select between two integer constants, try to do some
9339   // optimizations.
9340   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
9341     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
9342       // Don't do this for crazy integer types.
9343       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
9344         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
9345         // so that TrueC (the true value) is larger than FalseC.
9346         bool NeedsCondInvert = false;
9347
9348         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
9349             // Efficiently invertible.
9350             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
9351              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
9352               isa<ConstantSDNode>(Cond.getOperand(1))))) {
9353           NeedsCondInvert = true;
9354           std::swap(TrueC, FalseC);
9355         }
9356
9357         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
9358         if (FalseC->getAPIntValue() == 0 &&
9359             TrueC->getAPIntValue().isPowerOf2()) {
9360           if (NeedsCondInvert) // Invert the condition if needed.
9361             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
9362                                DAG.getConstant(1, Cond.getValueType()));
9363
9364           // Zero extend the condition if needed.
9365           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
9366
9367           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
9368           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
9369                              DAG.getConstant(ShAmt, MVT::i8));
9370         }
9371
9372         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
9373         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
9374           if (NeedsCondInvert) // Invert the condition if needed.
9375             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
9376                                DAG.getConstant(1, Cond.getValueType()));
9377
9378           // Zero extend the condition if needed.
9379           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
9380                              FalseC->getValueType(0), Cond);
9381           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9382                              SDValue(FalseC, 0));
9383         }
9384
9385         // Optimize cases that will turn into an LEA instruction.  This requires
9386         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
9387         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
9388           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
9389           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
9390
9391           bool isFastMultiplier = false;
9392           if (Diff < 10) {
9393             switch ((unsigned char)Diff) {
9394               default: break;
9395               case 1:  // result = add base, cond
9396               case 2:  // result = lea base(    , cond*2)
9397               case 3:  // result = lea base(cond, cond*2)
9398               case 4:  // result = lea base(    , cond*4)
9399               case 5:  // result = lea base(cond, cond*4)
9400               case 8:  // result = lea base(    , cond*8)
9401               case 9:  // result = lea base(cond, cond*8)
9402                 isFastMultiplier = true;
9403                 break;
9404             }
9405           }
9406
9407           if (isFastMultiplier) {
9408             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
9409             if (NeedsCondInvert) // Invert the condition if needed.
9410               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
9411                                  DAG.getConstant(1, Cond.getValueType()));
9412
9413             // Zero extend the condition if needed.
9414             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
9415                                Cond);
9416             // Scale the condition by the difference.
9417             if (Diff != 1)
9418               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
9419                                  DAG.getConstant(Diff, Cond.getValueType()));
9420
9421             // Add the base if non-zero.
9422             if (FalseC->getAPIntValue() != 0)
9423               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9424                                  SDValue(FalseC, 0));
9425             return Cond;
9426           }
9427         }
9428       }
9429   }
9430
9431   return SDValue();
9432 }
9433
9434 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
9435 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
9436                                   TargetLowering::DAGCombinerInfo &DCI) {
9437   DebugLoc DL = N->getDebugLoc();
9438
9439   // If the flag operand isn't dead, don't touch this CMOV.
9440   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
9441     return SDValue();
9442
9443   // If this is a select between two integer constants, try to do some
9444   // optimizations.  Note that the operands are ordered the opposite of SELECT
9445   // operands.
9446   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
9447     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9448       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
9449       // larger than FalseC (the false value).
9450       X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
9451
9452       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
9453         CC = X86::GetOppositeBranchCondition(CC);
9454         std::swap(TrueC, FalseC);
9455       }
9456
9457       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
9458       // This is efficient for any integer data type (including i8/i16) and
9459       // shift amount.
9460       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
9461         SDValue Cond = N->getOperand(3);
9462         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9463                            DAG.getConstant(CC, MVT::i8), Cond);
9464
9465         // Zero extend the condition if needed.
9466         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
9467
9468         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
9469         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
9470                            DAG.getConstant(ShAmt, MVT::i8));
9471         if (N->getNumValues() == 2)  // Dead flag value?
9472           return DCI.CombineTo(N, Cond, SDValue());
9473         return Cond;
9474       }
9475
9476       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
9477       // for any integer data type, including i8/i16.
9478       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
9479         SDValue Cond = N->getOperand(3);
9480         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9481                            DAG.getConstant(CC, MVT::i8), Cond);
9482
9483         // Zero extend the condition if needed.
9484         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
9485                            FalseC->getValueType(0), Cond);
9486         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9487                            SDValue(FalseC, 0));
9488
9489         if (N->getNumValues() == 2)  // Dead flag value?
9490           return DCI.CombineTo(N, Cond, SDValue());
9491         return Cond;
9492       }
9493
9494       // Optimize cases that will turn into an LEA instruction.  This requires
9495       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
9496       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
9497         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
9498         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
9499
9500         bool isFastMultiplier = false;
9501         if (Diff < 10) {
9502           switch ((unsigned char)Diff) {
9503           default: break;
9504           case 1:  // result = add base, cond
9505           case 2:  // result = lea base(    , cond*2)
9506           case 3:  // result = lea base(cond, cond*2)
9507           case 4:  // result = lea base(    , cond*4)
9508           case 5:  // result = lea base(cond, cond*4)
9509           case 8:  // result = lea base(    , cond*8)
9510           case 9:  // result = lea base(cond, cond*8)
9511             isFastMultiplier = true;
9512             break;
9513           }
9514         }
9515
9516         if (isFastMultiplier) {
9517           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
9518           SDValue Cond = N->getOperand(3);
9519           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9520                              DAG.getConstant(CC, MVT::i8), Cond);
9521           // Zero extend the condition if needed.
9522           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
9523                              Cond);
9524           // Scale the condition by the difference.
9525           if (Diff != 1)
9526             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
9527                                DAG.getConstant(Diff, Cond.getValueType()));
9528
9529           // Add the base if non-zero.
9530           if (FalseC->getAPIntValue() != 0)
9531             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9532                                SDValue(FalseC, 0));
9533           if (N->getNumValues() == 2)  // Dead flag value?
9534             return DCI.CombineTo(N, Cond, SDValue());
9535           return Cond;
9536         }
9537       }
9538     }
9539   }
9540   return SDValue();
9541 }
9542
9543
9544 /// PerformMulCombine - Optimize a single multiply with constant into two
9545 /// in order to implement it with two cheaper instructions, e.g.
9546 /// LEA + SHL, LEA + LEA.
9547 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
9548                                  TargetLowering::DAGCombinerInfo &DCI) {
9549   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9550     return SDValue();
9551
9552   EVT VT = N->getValueType(0);
9553   if (VT != MVT::i64)
9554     return SDValue();
9555
9556   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
9557   if (!C)
9558     return SDValue();
9559   uint64_t MulAmt = C->getZExtValue();
9560   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
9561     return SDValue();
9562
9563   uint64_t MulAmt1 = 0;
9564   uint64_t MulAmt2 = 0;
9565   if ((MulAmt % 9) == 0) {
9566     MulAmt1 = 9;
9567     MulAmt2 = MulAmt / 9;
9568   } else if ((MulAmt % 5) == 0) {
9569     MulAmt1 = 5;
9570     MulAmt2 = MulAmt / 5;
9571   } else if ((MulAmt % 3) == 0) {
9572     MulAmt1 = 3;
9573     MulAmt2 = MulAmt / 3;
9574   }
9575   if (MulAmt2 &&
9576       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
9577     DebugLoc DL = N->getDebugLoc();
9578
9579     if (isPowerOf2_64(MulAmt2) &&
9580         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
9581       // If second multiplifer is pow2, issue it first. We want the multiply by
9582       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
9583       // is an add.
9584       std::swap(MulAmt1, MulAmt2);
9585
9586     SDValue NewMul;
9587     if (isPowerOf2_64(MulAmt1))
9588       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
9589                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
9590     else
9591       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
9592                            DAG.getConstant(MulAmt1, VT));
9593
9594     if (isPowerOf2_64(MulAmt2))
9595       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
9596                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
9597     else
9598       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
9599                            DAG.getConstant(MulAmt2, VT));
9600
9601     // Do not add new nodes to DAG combiner worklist.
9602     DCI.CombineTo(N, NewMul, false);
9603   }
9604   return SDValue();
9605 }
9606
9607 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
9608   SDValue N0 = N->getOperand(0);
9609   SDValue N1 = N->getOperand(1);
9610   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
9611   EVT VT = N0.getValueType();
9612
9613   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
9614   // since the result of setcc_c is all zero's or all ones.
9615   if (N1C && N0.getOpcode() == ISD::AND &&
9616       N0.getOperand(1).getOpcode() == ISD::Constant) {
9617     SDValue N00 = N0.getOperand(0);
9618     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
9619         ((N00.getOpcode() == ISD::ANY_EXTEND ||
9620           N00.getOpcode() == ISD::ZERO_EXTEND) &&
9621          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
9622       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
9623       APInt ShAmt = N1C->getAPIntValue();
9624       Mask = Mask.shl(ShAmt);
9625       if (Mask != 0)
9626         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
9627                            N00, DAG.getConstant(Mask, VT));
9628     }
9629   }
9630
9631   return SDValue();
9632 }
9633
9634 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
9635 ///                       when possible.
9636 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
9637                                    const X86Subtarget *Subtarget) {
9638   EVT VT = N->getValueType(0);
9639   if (!VT.isVector() && VT.isInteger() &&
9640       N->getOpcode() == ISD::SHL)
9641     return PerformSHLCombine(N, DAG);
9642
9643   // On X86 with SSE2 support, we can transform this to a vector shift if
9644   // all elements are shifted by the same amount.  We can't do this in legalize
9645   // because the a constant vector is typically transformed to a constant pool
9646   // so we have no knowledge of the shift amount.
9647   if (!Subtarget->hasSSE2())
9648     return SDValue();
9649
9650   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
9651     return SDValue();
9652
9653   SDValue ShAmtOp = N->getOperand(1);
9654   EVT EltVT = VT.getVectorElementType();
9655   DebugLoc DL = N->getDebugLoc();
9656   SDValue BaseShAmt = SDValue();
9657   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
9658     unsigned NumElts = VT.getVectorNumElements();
9659     unsigned i = 0;
9660     for (; i != NumElts; ++i) {
9661       SDValue Arg = ShAmtOp.getOperand(i);
9662       if (Arg.getOpcode() == ISD::UNDEF) continue;
9663       BaseShAmt = Arg;
9664       break;
9665     }
9666     for (; i != NumElts; ++i) {
9667       SDValue Arg = ShAmtOp.getOperand(i);
9668       if (Arg.getOpcode() == ISD::UNDEF) continue;
9669       if (Arg != BaseShAmt) {
9670         return SDValue();
9671       }
9672     }
9673   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
9674              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
9675     SDValue InVec = ShAmtOp.getOperand(0);
9676     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
9677       unsigned NumElts = InVec.getValueType().getVectorNumElements();
9678       unsigned i = 0;
9679       for (; i != NumElts; ++i) {
9680         SDValue Arg = InVec.getOperand(i);
9681         if (Arg.getOpcode() == ISD::UNDEF) continue;
9682         BaseShAmt = Arg;
9683         break;
9684       }
9685     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
9686        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
9687          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
9688          if (C->getZExtValue() == SplatIdx)
9689            BaseShAmt = InVec.getOperand(1);
9690        }
9691     }
9692     if (BaseShAmt.getNode() == 0)
9693       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
9694                               DAG.getIntPtrConstant(0));
9695   } else
9696     return SDValue();
9697
9698   // The shift amount is an i32.
9699   if (EltVT.bitsGT(MVT::i32))
9700     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
9701   else if (EltVT.bitsLT(MVT::i32))
9702     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
9703
9704   // The shift amount is identical so we can do a vector shift.
9705   SDValue  ValOp = N->getOperand(0);
9706   switch (N->getOpcode()) {
9707   default:
9708     llvm_unreachable("Unknown shift opcode!");
9709     break;
9710   case ISD::SHL:
9711     if (VT == MVT::v2i64)
9712       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9713                          DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9714                          ValOp, BaseShAmt);
9715     if (VT == MVT::v4i32)
9716       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9717                          DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
9718                          ValOp, BaseShAmt);
9719     if (VT == MVT::v8i16)
9720       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9721                          DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
9722                          ValOp, BaseShAmt);
9723     break;
9724   case ISD::SRA:
9725     if (VT == MVT::v4i32)
9726       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9727                          DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
9728                          ValOp, BaseShAmt);
9729     if (VT == MVT::v8i16)
9730       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9731                          DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
9732                          ValOp, BaseShAmt);
9733     break;
9734   case ISD::SRL:
9735     if (VT == MVT::v2i64)
9736       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9737                          DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9738                          ValOp, BaseShAmt);
9739     if (VT == MVT::v4i32)
9740       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9741                          DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
9742                          ValOp, BaseShAmt);
9743     if (VT ==  MVT::v8i16)
9744       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9745                          DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
9746                          ValOp, BaseShAmt);
9747     break;
9748   }
9749   return SDValue();
9750 }
9751
9752 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
9753                                 TargetLowering::DAGCombinerInfo &DCI,
9754                                 const X86Subtarget *Subtarget) {
9755   if (DCI.isBeforeLegalizeOps())
9756     return SDValue();
9757
9758   EVT VT = N->getValueType(0);
9759   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
9760     return SDValue();
9761
9762   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
9763   SDValue N0 = N->getOperand(0);
9764   SDValue N1 = N->getOperand(1);
9765   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
9766     std::swap(N0, N1);
9767   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
9768     return SDValue();
9769   if (!N0.hasOneUse() || !N1.hasOneUse())
9770     return SDValue();
9771
9772   SDValue ShAmt0 = N0.getOperand(1);
9773   if (ShAmt0.getValueType() != MVT::i8)
9774     return SDValue();
9775   SDValue ShAmt1 = N1.getOperand(1);
9776   if (ShAmt1.getValueType() != MVT::i8)
9777     return SDValue();
9778   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
9779     ShAmt0 = ShAmt0.getOperand(0);
9780   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
9781     ShAmt1 = ShAmt1.getOperand(0);
9782
9783   DebugLoc DL = N->getDebugLoc();
9784   unsigned Opc = X86ISD::SHLD;
9785   SDValue Op0 = N0.getOperand(0);
9786   SDValue Op1 = N1.getOperand(0);
9787   if (ShAmt0.getOpcode() == ISD::SUB) {
9788     Opc = X86ISD::SHRD;
9789     std::swap(Op0, Op1);
9790     std::swap(ShAmt0, ShAmt1);
9791   }
9792
9793   unsigned Bits = VT.getSizeInBits();
9794   if (ShAmt1.getOpcode() == ISD::SUB) {
9795     SDValue Sum = ShAmt1.getOperand(0);
9796     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
9797       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
9798       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
9799         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
9800       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
9801         return DAG.getNode(Opc, DL, VT,
9802                            Op0, Op1,
9803                            DAG.getNode(ISD::TRUNCATE, DL,
9804                                        MVT::i8, ShAmt0));
9805     }
9806   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
9807     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
9808     if (ShAmt0C &&
9809         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
9810       return DAG.getNode(Opc, DL, VT,
9811                          N0.getOperand(0), N1.getOperand(0),
9812                          DAG.getNode(ISD::TRUNCATE, DL,
9813                                        MVT::i8, ShAmt0));
9814   }
9815
9816   return SDValue();
9817 }
9818
9819 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
9820 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
9821                                    const X86Subtarget *Subtarget) {
9822   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
9823   // the FP state in cases where an emms may be missing.
9824   // A preferable solution to the general problem is to figure out the right
9825   // places to insert EMMS.  This qualifies as a quick hack.
9826
9827   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
9828   StoreSDNode *St = cast<StoreSDNode>(N);
9829   EVT VT = St->getValue().getValueType();
9830   if (VT.getSizeInBits() != 64)
9831     return SDValue();
9832
9833   const Function *F = DAG.getMachineFunction().getFunction();
9834   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
9835   bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
9836     && Subtarget->hasSSE2();
9837   if ((VT.isVector() ||
9838        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
9839       isa<LoadSDNode>(St->getValue()) &&
9840       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
9841       St->getChain().hasOneUse() && !St->isVolatile()) {
9842     SDNode* LdVal = St->getValue().getNode();
9843     LoadSDNode *Ld = 0;
9844     int TokenFactorIndex = -1;
9845     SmallVector<SDValue, 8> Ops;
9846     SDNode* ChainVal = St->getChain().getNode();
9847     // Must be a store of a load.  We currently handle two cases:  the load
9848     // is a direct child, and it's under an intervening TokenFactor.  It is
9849     // possible to dig deeper under nested TokenFactors.
9850     if (ChainVal == LdVal)
9851       Ld = cast<LoadSDNode>(St->getChain());
9852     else if (St->getValue().hasOneUse() &&
9853              ChainVal->getOpcode() == ISD::TokenFactor) {
9854       for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
9855         if (ChainVal->getOperand(i).getNode() == LdVal) {
9856           TokenFactorIndex = i;
9857           Ld = cast<LoadSDNode>(St->getValue());
9858         } else
9859           Ops.push_back(ChainVal->getOperand(i));
9860       }
9861     }
9862
9863     if (!Ld || !ISD::isNormalLoad(Ld))
9864       return SDValue();
9865
9866     // If this is not the MMX case, i.e. we are just turning i64 load/store
9867     // into f64 load/store, avoid the transformation if there are multiple
9868     // uses of the loaded value.
9869     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
9870       return SDValue();
9871
9872     DebugLoc LdDL = Ld->getDebugLoc();
9873     DebugLoc StDL = N->getDebugLoc();
9874     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
9875     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
9876     // pair instead.
9877     if (Subtarget->is64Bit() || F64IsLegal) {
9878       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
9879       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(),
9880                                   Ld->getBasePtr(), Ld->getSrcValue(),
9881                                   Ld->getSrcValueOffset(), Ld->isVolatile(),
9882                                   Ld->isNonTemporal(), Ld->getAlignment());
9883       SDValue NewChain = NewLd.getValue(1);
9884       if (TokenFactorIndex != -1) {
9885         Ops.push_back(NewChain);
9886         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
9887                                Ops.size());
9888       }
9889       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
9890                           St->getSrcValue(), St->getSrcValueOffset(),
9891                           St->isVolatile(), St->isNonTemporal(),
9892                           St->getAlignment());
9893     }
9894
9895     // Otherwise, lower to two pairs of 32-bit loads / stores.
9896     SDValue LoAddr = Ld->getBasePtr();
9897     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
9898                                  DAG.getConstant(4, MVT::i32));
9899
9900     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
9901                                Ld->getSrcValue(), Ld->getSrcValueOffset(),
9902                                Ld->isVolatile(), Ld->isNonTemporal(),
9903                                Ld->getAlignment());
9904     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
9905                                Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
9906                                Ld->isVolatile(), Ld->isNonTemporal(),
9907                                MinAlign(Ld->getAlignment(), 4));
9908
9909     SDValue NewChain = LoLd.getValue(1);
9910     if (TokenFactorIndex != -1) {
9911       Ops.push_back(LoLd);
9912       Ops.push_back(HiLd);
9913       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
9914                              Ops.size());
9915     }
9916
9917     LoAddr = St->getBasePtr();
9918     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
9919                          DAG.getConstant(4, MVT::i32));
9920
9921     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
9922                                 St->getSrcValue(), St->getSrcValueOffset(),
9923                                 St->isVolatile(), St->isNonTemporal(),
9924                                 St->getAlignment());
9925     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
9926                                 St->getSrcValue(),
9927                                 St->getSrcValueOffset() + 4,
9928                                 St->isVolatile(),
9929                                 St->isNonTemporal(),
9930                                 MinAlign(St->getAlignment(), 4));
9931     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
9932   }
9933   return SDValue();
9934 }
9935
9936 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
9937 /// X86ISD::FXOR nodes.
9938 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
9939   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
9940   // F[X]OR(0.0, x) -> x
9941   // F[X]OR(x, 0.0) -> x
9942   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
9943     if (C->getValueAPF().isPosZero())
9944       return N->getOperand(1);
9945   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
9946     if (C->getValueAPF().isPosZero())
9947       return N->getOperand(0);
9948   return SDValue();
9949 }
9950
9951 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
9952 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
9953   // FAND(0.0, x) -> 0.0
9954   // FAND(x, 0.0) -> 0.0
9955   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
9956     if (C->getValueAPF().isPosZero())
9957       return N->getOperand(0);
9958   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
9959     if (C->getValueAPF().isPosZero())
9960       return N->getOperand(1);
9961   return SDValue();
9962 }
9963
9964 static SDValue PerformBTCombine(SDNode *N,
9965                                 SelectionDAG &DAG,
9966                                 TargetLowering::DAGCombinerInfo &DCI) {
9967   // BT ignores high bits in the bit index operand.
9968   SDValue Op1 = N->getOperand(1);
9969   if (Op1.hasOneUse()) {
9970     unsigned BitWidth = Op1.getValueSizeInBits();
9971     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
9972     APInt KnownZero, KnownOne;
9973     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
9974                                           !DCI.isBeforeLegalizeOps());
9975     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9976     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
9977         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
9978       DCI.CommitTargetLoweringOpt(TLO);
9979   }
9980   return SDValue();
9981 }
9982
9983 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
9984   SDValue Op = N->getOperand(0);
9985   if (Op.getOpcode() == ISD::BIT_CONVERT)
9986     Op = Op.getOperand(0);
9987   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
9988   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
9989       VT.getVectorElementType().getSizeInBits() ==
9990       OpVT.getVectorElementType().getSizeInBits()) {
9991     return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT, Op);
9992   }
9993   return SDValue();
9994 }
9995
9996 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
9997   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
9998   //           (and (i32 x86isd::setcc_carry), 1)
9999   // This eliminates the zext. This transformation is necessary because
10000   // ISD::SETCC is always legalized to i8.
10001   DebugLoc dl = N->getDebugLoc();
10002   SDValue N0 = N->getOperand(0);
10003   EVT VT = N->getValueType(0);
10004   if (N0.getOpcode() == ISD::AND &&
10005       N0.hasOneUse() &&
10006       N0.getOperand(0).hasOneUse()) {
10007     SDValue N00 = N0.getOperand(0);
10008     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
10009       return SDValue();
10010     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
10011     if (!C || C->getZExtValue() != 1)
10012       return SDValue();
10013     return DAG.getNode(ISD::AND, dl, VT,
10014                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
10015                                    N00.getOperand(0), N00.getOperand(1)),
10016                        DAG.getConstant(1, VT));
10017   }
10018
10019   return SDValue();
10020 }
10021
10022 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
10023                                              DAGCombinerInfo &DCI) const {
10024   SelectionDAG &DAG = DCI.DAG;
10025   switch (N->getOpcode()) {
10026   default: break;
10027   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
10028   case ISD::EXTRACT_VECTOR_ELT:
10029                         return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
10030   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
10031   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
10032   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
10033   case ISD::SHL:
10034   case ISD::SRA:
10035   case ISD::SRL:            return PerformShiftCombine(N, DAG, Subtarget);
10036   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
10037   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
10038   case X86ISD::FXOR:
10039   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
10040   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
10041   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
10042   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
10043   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG);
10044   }
10045
10046   return SDValue();
10047 }
10048
10049 /// isTypeDesirableForOp - Return true if the target has native support for
10050 /// the specified value type and it is 'desirable' to use the type for the
10051 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
10052 /// instruction encodings are longer and some i16 instructions are slow.
10053 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
10054   if (!isTypeLegal(VT))
10055     return false;
10056   if (VT != MVT::i16)
10057     return true;
10058
10059   switch (Opc) {
10060   default:
10061     return true;
10062   case ISD::LOAD:
10063   case ISD::SIGN_EXTEND:
10064   case ISD::ZERO_EXTEND:
10065   case ISD::ANY_EXTEND:
10066   case ISD::SHL:
10067   case ISD::SRL:
10068   case ISD::SUB:
10069   case ISD::ADD:
10070   case ISD::MUL:
10071   case ISD::AND:
10072   case ISD::OR:
10073   case ISD::XOR:
10074     return false;
10075   }
10076 }
10077
10078 static bool MayFoldLoad(SDValue Op) {
10079   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
10080 }
10081
10082 static bool MayFoldIntoStore(SDValue Op) {
10083   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
10084 }
10085
10086 /// IsDesirableToPromoteOp - This method query the target whether it is
10087 /// beneficial for dag combiner to promote the specified node. If true, it
10088 /// should return the desired promotion type by reference.
10089 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
10090   EVT VT = Op.getValueType();
10091   if (VT != MVT::i16)
10092     return false;
10093
10094   bool Promote = false;
10095   bool Commute = false;
10096   switch (Op.getOpcode()) {
10097   default: break;
10098   case ISD::LOAD: {
10099     LoadSDNode *LD = cast<LoadSDNode>(Op);
10100     // If the non-extending load has a single use and it's not live out, then it
10101     // might be folded.
10102     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
10103                                                      Op.hasOneUse()*/) {
10104       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
10105              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
10106         // The only case where we'd want to promote LOAD (rather then it being
10107         // promoted as an operand is when it's only use is liveout.
10108         if (UI->getOpcode() != ISD::CopyToReg)
10109           return false;
10110       }
10111     }
10112     Promote = true;
10113     break;
10114   }
10115   case ISD::SIGN_EXTEND:
10116   case ISD::ZERO_EXTEND:
10117   case ISD::ANY_EXTEND:
10118     Promote = true;
10119     break;
10120   case ISD::SHL:
10121   case ISD::SRL: {
10122     SDValue N0 = Op.getOperand(0);
10123     // Look out for (store (shl (load), x)).
10124     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
10125       return false;
10126     Promote = true;
10127     break;
10128   }
10129   case ISD::ADD:
10130   case ISD::MUL:
10131   case ISD::AND:
10132   case ISD::OR:
10133   case ISD::XOR:
10134     Commute = true;
10135     // fallthrough
10136   case ISD::SUB: {
10137     SDValue N0 = Op.getOperand(0);
10138     SDValue N1 = Op.getOperand(1);
10139     if (!Commute && MayFoldLoad(N1))
10140       return false;
10141     // Avoid disabling potential load folding opportunities.
10142     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
10143       return false;
10144     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
10145       return false;
10146     Promote = true;
10147   }
10148   }
10149
10150   PVT = MVT::i32;
10151   return Promote;
10152 }
10153
10154 //===----------------------------------------------------------------------===//
10155 //                           X86 Inline Assembly Support
10156 //===----------------------------------------------------------------------===//
10157
10158 static bool LowerToBSwap(CallInst *CI) {
10159   // FIXME: this should verify that we are targetting a 486 or better.  If not,
10160   // we will turn this bswap into something that will be lowered to logical ops
10161   // instead of emitting the bswap asm.  For now, we don't support 486 or lower
10162   // so don't worry about this.
10163
10164   // Verify this is a simple bswap.
10165   if (CI->getNumArgOperands() != 1 ||
10166       CI->getType() != CI->getArgOperand(0)->getType() ||
10167       !CI->getType()->isIntegerTy())
10168     return false;
10169
10170   const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10171   if (!Ty || Ty->getBitWidth() % 16 != 0)
10172     return false;
10173
10174   // Okay, we can do this xform, do so now.
10175   const Type *Tys[] = { Ty };
10176   Module *M = CI->getParent()->getParent()->getParent();
10177   Constant *Int = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
10178
10179   Value *Op = CI->getArgOperand(0);
10180   Op = CallInst::Create(Int, Op, CI->getName(), CI);
10181
10182   CI->replaceAllUsesWith(Op);
10183   CI->eraseFromParent();
10184   return true;
10185 }
10186
10187 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
10188   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10189   std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
10190
10191   std::string AsmStr = IA->getAsmString();
10192
10193   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
10194   SmallVector<StringRef, 4> AsmPieces;
10195   SplitString(AsmStr, AsmPieces, "\n");  // ; as separator?
10196
10197   switch (AsmPieces.size()) {
10198   default: return false;
10199   case 1:
10200     AsmStr = AsmPieces[0];
10201     AsmPieces.clear();
10202     SplitString(AsmStr, AsmPieces, " \t");  // Split with whitespace.
10203
10204     // bswap $0
10205     if (AsmPieces.size() == 2 &&
10206         (AsmPieces[0] == "bswap" ||
10207          AsmPieces[0] == "bswapq" ||
10208          AsmPieces[0] == "bswapl") &&
10209         (AsmPieces[1] == "$0" ||
10210          AsmPieces[1] == "${0:q}")) {
10211       // No need to check constraints, nothing other than the equivalent of
10212       // "=r,0" would be valid here.
10213       return LowerToBSwap(CI);
10214     }
10215     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
10216     if (CI->getType()->isIntegerTy(16) &&
10217         AsmPieces.size() == 3 &&
10218         (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
10219         AsmPieces[1] == "$$8," &&
10220         AsmPieces[2] == "${0:w}" &&
10221         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
10222       AsmPieces.clear();
10223       const std::string &Constraints = IA->getConstraintString();
10224       SplitString(StringRef(Constraints).substr(5), AsmPieces, ",");
10225       std::sort(AsmPieces.begin(), AsmPieces.end());
10226       if (AsmPieces.size() == 4 &&
10227           AsmPieces[0] == "~{cc}" &&
10228           AsmPieces[1] == "~{dirflag}" &&
10229           AsmPieces[2] == "~{flags}" &&
10230           AsmPieces[3] == "~{fpsr}") {
10231         return LowerToBSwap(CI);
10232       }
10233     }
10234     break;
10235   case 3:
10236     if (CI->getType()->isIntegerTy(64) &&
10237         Constraints.size() >= 2 &&
10238         Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
10239         Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
10240       // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
10241       SmallVector<StringRef, 4> Words;
10242       SplitString(AsmPieces[0], Words, " \t");
10243       if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
10244         Words.clear();
10245         SplitString(AsmPieces[1], Words, " \t");
10246         if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
10247           Words.clear();
10248           SplitString(AsmPieces[2], Words, " \t,");
10249           if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
10250               Words[2] == "%edx") {
10251             return LowerToBSwap(CI);
10252           }
10253         }
10254       }
10255     }
10256     break;
10257   }
10258   return false;
10259 }
10260
10261
10262
10263 /// getConstraintType - Given a constraint letter, return the type of
10264 /// constraint it is for this target.
10265 X86TargetLowering::ConstraintType
10266 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
10267   if (Constraint.size() == 1) {
10268     switch (Constraint[0]) {
10269     case 'A':
10270       return C_Register;
10271     case 'f':
10272     case 'r':
10273     case 'R':
10274     case 'l':
10275     case 'q':
10276     case 'Q':
10277     case 'x':
10278     case 'y':
10279     case 'Y':
10280       return C_RegisterClass;
10281     case 'e':
10282     case 'Z':
10283       return C_Other;
10284     default:
10285       break;
10286     }
10287   }
10288   return TargetLowering::getConstraintType(Constraint);
10289 }
10290
10291 /// LowerXConstraint - try to replace an X constraint, which matches anything,
10292 /// with another that has more specific requirements based on the type of the
10293 /// corresponding operand.
10294 const char *X86TargetLowering::
10295 LowerXConstraint(EVT ConstraintVT) const {
10296   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
10297   // 'f' like normal targets.
10298   if (ConstraintVT.isFloatingPoint()) {
10299     if (Subtarget->hasSSE2())
10300       return "Y";
10301     if (Subtarget->hasSSE1())
10302       return "x";
10303   }
10304
10305   return TargetLowering::LowerXConstraint(ConstraintVT);
10306 }
10307
10308 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10309 /// vector.  If it is invalid, don't add anything to Ops.
10310 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10311                                                      char Constraint,
10312                                                      std::vector<SDValue>&Ops,
10313                                                      SelectionDAG &DAG) const {
10314   SDValue Result(0, 0);
10315
10316   switch (Constraint) {
10317   default: break;
10318   case 'I':
10319     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10320       if (C->getZExtValue() <= 31) {
10321         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10322         break;
10323       }
10324     }
10325     return;
10326   case 'J':
10327     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10328       if (C->getZExtValue() <= 63) {
10329         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10330         break;
10331       }
10332     }
10333     return;
10334   case 'K':
10335     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10336       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
10337         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10338         break;
10339       }
10340     }
10341     return;
10342   case 'N':
10343     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10344       if (C->getZExtValue() <= 255) {
10345         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10346         break;
10347       }
10348     }
10349     return;
10350   case 'e': {
10351     // 32-bit signed value
10352     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10353       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
10354                                            C->getSExtValue())) {
10355         // Widen to 64 bits here to get it sign extended.
10356         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
10357         break;
10358       }
10359     // FIXME gcc accepts some relocatable values here too, but only in certain
10360     // memory models; it's complicated.
10361     }
10362     return;
10363   }
10364   case 'Z': {
10365     // 32-bit unsigned value
10366     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10367       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
10368                                            C->getZExtValue())) {
10369         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10370         break;
10371       }
10372     }
10373     // FIXME gcc accepts some relocatable values here too, but only in certain
10374     // memory models; it's complicated.
10375     return;
10376   }
10377   case 'i': {
10378     // Literal immediates are always ok.
10379     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
10380       // Widen to 64 bits here to get it sign extended.
10381       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
10382       break;
10383     }
10384
10385     // In any sort of PIC mode addresses need to be computed at runtime by
10386     // adding in a register or some sort of table lookup.  These can't
10387     // be used as immediates.
10388     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
10389       return;
10390
10391     // If we are in non-pic codegen mode, we allow the address of a global (with
10392     // an optional displacement) to be used with 'i'.
10393     GlobalAddressSDNode *GA = 0;
10394     int64_t Offset = 0;
10395
10396     // Match either (GA), (GA+C), (GA+C1+C2), etc.
10397     while (1) {
10398       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
10399         Offset += GA->getOffset();
10400         break;
10401       } else if (Op.getOpcode() == ISD::ADD) {
10402         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
10403           Offset += C->getZExtValue();
10404           Op = Op.getOperand(0);
10405           continue;
10406         }
10407       } else if (Op.getOpcode() == ISD::SUB) {
10408         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
10409           Offset += -C->getZExtValue();
10410           Op = Op.getOperand(0);
10411           continue;
10412         }
10413       }
10414
10415       // Otherwise, this isn't something we can handle, reject it.
10416       return;
10417     }
10418
10419     const GlobalValue *GV = GA->getGlobal();
10420     // If we require an extra load to get this address, as in PIC mode, we
10421     // can't accept it.
10422     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
10423                                                         getTargetMachine())))
10424       return;
10425
10426     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
10427                                         GA->getValueType(0), Offset);
10428     break;
10429   }
10430   }
10431
10432   if (Result.getNode()) {
10433     Ops.push_back(Result);
10434     return;
10435   }
10436   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10437 }
10438
10439 std::vector<unsigned> X86TargetLowering::
10440 getRegClassForInlineAsmConstraint(const std::string &Constraint,
10441                                   EVT VT) const {
10442   if (Constraint.size() == 1) {
10443     // FIXME: not handling fp-stack yet!
10444     switch (Constraint[0]) {      // GCC X86 Constraint Letters
10445     default: break;  // Unknown constraint letter
10446     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
10447       if (Subtarget->is64Bit()) {
10448         if (VT == MVT::i32)
10449           return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
10450                                        X86::ESI, X86::EDI, X86::R8D, X86::R9D,
10451                                        X86::R10D,X86::R11D,X86::R12D,
10452                                        X86::R13D,X86::R14D,X86::R15D,
10453                                        X86::EBP, X86::ESP, 0);
10454         else if (VT == MVT::i16)
10455           return make_vector<unsigned>(X86::AX,  X86::DX,  X86::CX, X86::BX,
10456                                        X86::SI,  X86::DI,  X86::R8W,X86::R9W,
10457                                        X86::R10W,X86::R11W,X86::R12W,
10458                                        X86::R13W,X86::R14W,X86::R15W,
10459                                        X86::BP,  X86::SP, 0);
10460         else if (VT == MVT::i8)
10461           return make_vector<unsigned>(X86::AL,  X86::DL,  X86::CL, X86::BL,
10462                                        X86::SIL, X86::DIL, X86::R8B,X86::R9B,
10463                                        X86::R10B,X86::R11B,X86::R12B,
10464                                        X86::R13B,X86::R14B,X86::R15B,
10465                                        X86::BPL, X86::SPL, 0);
10466
10467         else if (VT == MVT::i64)
10468           return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
10469                                        X86::RSI, X86::RDI, X86::R8,  X86::R9,
10470                                        X86::R10, X86::R11, X86::R12,
10471                                        X86::R13, X86::R14, X86::R15,
10472                                        X86::RBP, X86::RSP, 0);
10473
10474         break;
10475       }
10476       // 32-bit fallthrough
10477     case 'Q':   // Q_REGS
10478       if (VT == MVT::i32)
10479         return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
10480       else if (VT == MVT::i16)
10481         return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
10482       else if (VT == MVT::i8)
10483         return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
10484       else if (VT == MVT::i64)
10485         return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
10486       break;
10487     }
10488   }
10489
10490   return std::vector<unsigned>();
10491 }
10492
10493 std::pair<unsigned, const TargetRegisterClass*>
10494 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10495                                                 EVT VT) const {
10496   // First, see if this is a constraint that directly corresponds to an LLVM
10497   // register class.
10498   if (Constraint.size() == 1) {
10499     // GCC Constraint Letters
10500     switch (Constraint[0]) {
10501     default: break;
10502     case 'r':   // GENERAL_REGS
10503     case 'l':   // INDEX_REGS
10504       if (VT == MVT::i8)
10505         return std::make_pair(0U, X86::GR8RegisterClass);
10506       if (VT == MVT::i16)
10507         return std::make_pair(0U, X86::GR16RegisterClass);
10508       if (VT == MVT::i32 || !Subtarget->is64Bit())
10509         return std::make_pair(0U, X86::GR32RegisterClass);
10510       return std::make_pair(0U, X86::GR64RegisterClass);
10511     case 'R':   // LEGACY_REGS
10512       if (VT == MVT::i8)
10513         return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
10514       if (VT == MVT::i16)
10515         return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
10516       if (VT == MVT::i32 || !Subtarget->is64Bit())
10517         return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
10518       return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
10519     case 'f':  // FP Stack registers.
10520       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
10521       // value to the correct fpstack register class.
10522       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
10523         return std::make_pair(0U, X86::RFP32RegisterClass);
10524       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
10525         return std::make_pair(0U, X86::RFP64RegisterClass);
10526       return std::make_pair(0U, X86::RFP80RegisterClass);
10527     case 'y':   // MMX_REGS if MMX allowed.
10528       if (!Subtarget->hasMMX()) break;
10529       return std::make_pair(0U, X86::VR64RegisterClass);
10530     case 'Y':   // SSE_REGS if SSE2 allowed
10531       if (!Subtarget->hasSSE2()) break;
10532       // FALL THROUGH.
10533     case 'x':   // SSE_REGS if SSE1 allowed
10534       if (!Subtarget->hasSSE1()) break;
10535
10536       switch (VT.getSimpleVT().SimpleTy) {
10537       default: break;
10538       // Scalar SSE types.
10539       case MVT::f32:
10540       case MVT::i32:
10541         return std::make_pair(0U, X86::FR32RegisterClass);
10542       case MVT::f64:
10543       case MVT::i64:
10544         return std::make_pair(0U, X86::FR64RegisterClass);
10545       // Vector types.
10546       case MVT::v16i8:
10547       case MVT::v8i16:
10548       case MVT::v4i32:
10549       case MVT::v2i64:
10550       case MVT::v4f32:
10551       case MVT::v2f64:
10552         return std::make_pair(0U, X86::VR128RegisterClass);
10553       }
10554       break;
10555     }
10556   }
10557
10558   // Use the default implementation in TargetLowering to convert the register
10559   // constraint into a member of a register class.
10560   std::pair<unsigned, const TargetRegisterClass*> Res;
10561   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10562
10563   // Not found as a standard register?
10564   if (Res.second == 0) {
10565     // Map st(0) -> st(7) -> ST0
10566     if (Constraint.size() == 7 && Constraint[0] == '{' &&
10567         tolower(Constraint[1]) == 's' &&
10568         tolower(Constraint[2]) == 't' &&
10569         Constraint[3] == '(' &&
10570         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
10571         Constraint[5] == ')' &&
10572         Constraint[6] == '}') {
10573
10574       Res.first = X86::ST0+Constraint[4]-'0';
10575       Res.second = X86::RFP80RegisterClass;
10576       return Res;
10577     }
10578
10579     // GCC allows "st(0)" to be called just plain "st".
10580     if (StringRef("{st}").equals_lower(Constraint)) {
10581       Res.first = X86::ST0;
10582       Res.second = X86::RFP80RegisterClass;
10583       return Res;
10584     }
10585
10586     // flags -> EFLAGS
10587     if (StringRef("{flags}").equals_lower(Constraint)) {
10588       Res.first = X86::EFLAGS;
10589       Res.second = X86::CCRRegisterClass;
10590       return Res;
10591     }
10592
10593     // 'A' means EAX + EDX.
10594     if (Constraint == "A") {
10595       Res.first = X86::EAX;
10596       Res.second = X86::GR32_ADRegisterClass;
10597       return Res;
10598     }
10599     return Res;
10600   }
10601
10602   // Otherwise, check to see if this is a register class of the wrong value
10603   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
10604   // turn into {ax},{dx}.
10605   if (Res.second->hasType(VT))
10606     return Res;   // Correct type already, nothing to do.
10607
10608   // All of the single-register GCC register classes map their values onto
10609   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
10610   // really want an 8-bit or 32-bit register, map to the appropriate register
10611   // class and return the appropriate register.
10612   if (Res.second == X86::GR16RegisterClass) {
10613     if (VT == MVT::i8) {
10614       unsigned DestReg = 0;
10615       switch (Res.first) {
10616       default: break;
10617       case X86::AX: DestReg = X86::AL; break;
10618       case X86::DX: DestReg = X86::DL; break;
10619       case X86::CX: DestReg = X86::CL; break;
10620       case X86::BX: DestReg = X86::BL; break;
10621       }
10622       if (DestReg) {
10623         Res.first = DestReg;
10624         Res.second = X86::GR8RegisterClass;
10625       }
10626     } else if (VT == MVT::i32) {
10627       unsigned DestReg = 0;
10628       switch (Res.first) {
10629       default: break;
10630       case X86::AX: DestReg = X86::EAX; break;
10631       case X86::DX: DestReg = X86::EDX; break;
10632       case X86::CX: DestReg = X86::ECX; break;
10633       case X86::BX: DestReg = X86::EBX; break;
10634       case X86::SI: DestReg = X86::ESI; break;
10635       case X86::DI: DestReg = X86::EDI; break;
10636       case X86::BP: DestReg = X86::EBP; break;
10637       case X86::SP: DestReg = X86::ESP; break;
10638       }
10639       if (DestReg) {
10640         Res.first = DestReg;
10641         Res.second = X86::GR32RegisterClass;
10642       }
10643     } else if (VT == MVT::i64) {
10644       unsigned DestReg = 0;
10645       switch (Res.first) {
10646       default: break;
10647       case X86::AX: DestReg = X86::RAX; break;
10648       case X86::DX: DestReg = X86::RDX; break;
10649       case X86::CX: DestReg = X86::RCX; break;
10650       case X86::BX: DestReg = X86::RBX; break;
10651       case X86::SI: DestReg = X86::RSI; break;
10652       case X86::DI: DestReg = X86::RDI; break;
10653       case X86::BP: DestReg = X86::RBP; break;
10654       case X86::SP: DestReg = X86::RSP; break;
10655       }
10656       if (DestReg) {
10657         Res.first = DestReg;
10658         Res.second = X86::GR64RegisterClass;
10659       }
10660     }
10661   } else if (Res.second == X86::FR32RegisterClass ||
10662              Res.second == X86::FR64RegisterClass ||
10663              Res.second == X86::VR128RegisterClass) {
10664     // Handle references to XMM physical registers that got mapped into the
10665     // wrong class.  This can happen with constraints like {xmm0} where the
10666     // target independent register mapper will just pick the first match it can
10667     // find, ignoring the required type.
10668     if (VT == MVT::f32)
10669       Res.second = X86::FR32RegisterClass;
10670     else if (VT == MVT::f64)
10671       Res.second = X86::FR64RegisterClass;
10672     else if (X86::VR128RegisterClass->hasType(VT))
10673       Res.second = X86::VR128RegisterClass;
10674   }
10675
10676   return Res;
10677 }