more tidying.
[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   switch (TM.getSubtarget<X86Subtarget>().TargetType) {
66   default: llvm_unreachable("unknown subtarget type");
67   case X86Subtarget::isDarwin:
68     if (TM.getSubtarget<X86Subtarget>().is64Bit())
69       return new X8664_MachoTargetObjectFile();
70     return new TargetLoweringObjectFileMachO();
71   case X86Subtarget::isELF:
72    if (TM.getSubtarget<X86Subtarget>().is64Bit())
73      return new X8664_ELFTargetObjectFile(TM);
74     return new X8632_ELFTargetObjectFile(TM);
75   case X86Subtarget::isMingw:
76   case X86Subtarget::isCygwin:
77   case X86Subtarget::isWindows:
78     return new TargetLoweringObjectFileCOFF();
79   }
80 }
81
82 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
83   : TargetLowering(TM, createTLOF(TM)) {
84   Subtarget = &TM.getSubtarget<X86Subtarget>();
85   X86ScalarSSEf64 = Subtarget->hasSSE2();
86   X86ScalarSSEf32 = Subtarget->hasSSE1();
87   X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
88
89   RegInfo = TM.getRegisterInfo();
90   TD = getTargetData();
91
92   // Set up the TargetLowering object.
93
94   // X86 is weird, it always uses i8 for shift amounts and setcc results.
95   setShiftAmountType(MVT::i8);
96   setBooleanContents(ZeroOrOneBooleanContent);
97   setSchedulingPreference(Sched::RegPressure);
98   setStackPointerRegisterToSaveRestore(X86StackPtr);
99
100   if (Subtarget->isTargetDarwin()) {
101     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
102     setUseUnderscoreSetJmp(false);
103     setUseUnderscoreLongJmp(false);
104   } else if (Subtarget->isTargetMingw()) {
105     // MS runtime is weird: it exports _setjmp, but longjmp!
106     setUseUnderscoreSetJmp(true);
107     setUseUnderscoreLongJmp(false);
108   } else {
109     setUseUnderscoreSetJmp(true);
110     setUseUnderscoreLongJmp(true);
111   }
112
113   // Set up the register classes.
114   addRegisterClass(MVT::i8, X86::GR8RegisterClass);
115   addRegisterClass(MVT::i16, X86::GR16RegisterClass);
116   addRegisterClass(MVT::i32, X86::GR32RegisterClass);
117   if (Subtarget->is64Bit())
118     addRegisterClass(MVT::i64, X86::GR64RegisterClass);
119
120   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
121
122   // We don't accept any truncstore of integer registers.
123   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
124   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
125   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
126   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
127   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
128   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
129
130   // SETOEQ and SETUNE require checking two conditions.
131   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
132   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
133   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
134   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
135   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
136   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
137
138   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
139   // operation.
140   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
141   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
142   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
143
144   if (Subtarget->is64Bit()) {
145     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
146     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Expand);
147   } else if (!UseSoftFloat) {
148     // We have an algorithm for SSE2->double, and we turn this into a
149     // 64-bit FILD followed by conditional FADD for other targets.
150     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
151     // We have an algorithm for SSE2, and we turn this into a 64-bit
152     // FILD for other targets.
153     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
154   }
155
156   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
157   // this operation.
158   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
159   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
160
161   if (!UseSoftFloat) {
162     // SSE has no i16 to fp conversion, only i32
163     if (X86ScalarSSEf32) {
164       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
165       // f32 and f64 cases are Legal, f80 case is not
166       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
167     } else {
168       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
169       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
170     }
171   } else {
172     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
173     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
174   }
175
176   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
177   // are Legal, f80 is custom lowered.
178   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
179   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
180
181   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
182   // this operation.
183   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
184   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
185
186   if (X86ScalarSSEf32) {
187     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
188     // f32 and f64 cases are Legal, f80 case is not
189     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
190   } else {
191     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
192     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
193   }
194
195   // Handle FP_TO_UINT by promoting the destination to a larger signed
196   // conversion.
197   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
198   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
199   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
200
201   if (Subtarget->is64Bit()) {
202     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
203     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
204   } else if (!UseSoftFloat) {
205     if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
206       // Expand FP_TO_UINT into a select.
207       // FIXME: We would like to use a Custom expander here eventually to do
208       // the optimal thing for SSE vs. the default expansion in the legalizer.
209       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
210     else
211       // With SSE3 we can use fisttpll to convert to a signed i64; without
212       // SSE, we're stuck with a fistpll.
213       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
214   }
215
216   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
217   if (!X86ScalarSSEf64) { 
218     setOperationAction(ISD::BIT_CONVERT      , MVT::f32  , Expand);
219     setOperationAction(ISD::BIT_CONVERT      , MVT::i32  , Expand);
220     if (Subtarget->is64Bit()) {
221       setOperationAction(ISD::BIT_CONVERT    , MVT::f64  , Expand);
222       // Without SSE, i64->f64 goes through memory; i64->MMX is Legal.
223       if (Subtarget->hasMMX() && !DisableMMX)
224         setOperationAction(ISD::BIT_CONVERT    , MVT::i64  , Custom);
225       else 
226         setOperationAction(ISD::BIT_CONVERT    , MVT::i64  , Expand);
227     }
228   }
229
230   // Scalar integer divide and remainder are lowered to use operations that
231   // produce two results, to match the available instructions. This exposes
232   // the two-result form to trivial CSE, which is able to combine x/y and x%y
233   // into a single instruction.
234   //
235   // Scalar integer multiply-high is also lowered to use two-result
236   // operations, to match the available instructions. However, plain multiply
237   // (low) operations are left as Legal, as there are single-result
238   // instructions for this in x86. Using the two-result multiply instructions
239   // when both high and low results are needed must be arranged by dagcombine.
240   setOperationAction(ISD::MULHS           , MVT::i8    , Expand);
241   setOperationAction(ISD::MULHU           , MVT::i8    , Expand);
242   setOperationAction(ISD::SDIV            , MVT::i8    , Expand);
243   setOperationAction(ISD::UDIV            , MVT::i8    , Expand);
244   setOperationAction(ISD::SREM            , MVT::i8    , Expand);
245   setOperationAction(ISD::UREM            , MVT::i8    , Expand);
246   setOperationAction(ISD::MULHS           , MVT::i16   , Expand);
247   setOperationAction(ISD::MULHU           , MVT::i16   , Expand);
248   setOperationAction(ISD::SDIV            , MVT::i16   , Expand);
249   setOperationAction(ISD::UDIV            , MVT::i16   , Expand);
250   setOperationAction(ISD::SREM            , MVT::i16   , Expand);
251   setOperationAction(ISD::UREM            , MVT::i16   , Expand);
252   setOperationAction(ISD::MULHS           , MVT::i32   , Expand);
253   setOperationAction(ISD::MULHU           , MVT::i32   , Expand);
254   setOperationAction(ISD::SDIV            , MVT::i32   , Expand);
255   setOperationAction(ISD::UDIV            , MVT::i32   , Expand);
256   setOperationAction(ISD::SREM            , MVT::i32   , Expand);
257   setOperationAction(ISD::UREM            , MVT::i32   , Expand);
258   setOperationAction(ISD::MULHS           , MVT::i64   , Expand);
259   setOperationAction(ISD::MULHU           , MVT::i64   , Expand);
260   setOperationAction(ISD::SDIV            , MVT::i64   , Expand);
261   setOperationAction(ISD::UDIV            , MVT::i64   , Expand);
262   setOperationAction(ISD::SREM            , MVT::i64   , Expand);
263   setOperationAction(ISD::UREM            , MVT::i64   , Expand);
264
265   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
266   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
267   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
268   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
269   if (Subtarget->is64Bit())
270     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
271   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
272   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
273   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
274   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
275   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
276   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
277   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
278   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
279
280   setOperationAction(ISD::CTPOP            , MVT::i8   , Expand);
281   setOperationAction(ISD::CTTZ             , MVT::i8   , Custom);
282   setOperationAction(ISD::CTLZ             , MVT::i8   , Custom);
283   setOperationAction(ISD::CTPOP            , MVT::i16  , Expand);
284   setOperationAction(ISD::CTTZ             , MVT::i16  , Custom);
285   setOperationAction(ISD::CTLZ             , MVT::i16  , Custom);
286   setOperationAction(ISD::CTPOP            , MVT::i32  , Expand);
287   setOperationAction(ISD::CTTZ             , MVT::i32  , Custom);
288   setOperationAction(ISD::CTLZ             , MVT::i32  , Custom);
289   if (Subtarget->is64Bit()) {
290     setOperationAction(ISD::CTPOP          , MVT::i64  , Expand);
291     setOperationAction(ISD::CTTZ           , MVT::i64  , Custom);
292     setOperationAction(ISD::CTLZ           , MVT::i64  , Custom);
293   }
294
295   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
296   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
297
298   // These should be promoted to a larger select which is supported.
299   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
300   // X86 wants to expand cmov itself.
301   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
302   setOperationAction(ISD::SELECT        , MVT::i16  , Custom);
303   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
304   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
305   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
306   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
307   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
308   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
309   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
310   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
311   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
312   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
313   if (Subtarget->is64Bit()) {
314     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
315     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
316   }
317   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
318
319   // Darwin ABI issue.
320   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
321   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
322   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
323   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
324   if (Subtarget->is64Bit())
325     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
326   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
327   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
328   if (Subtarget->is64Bit()) {
329     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
330     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
331     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
332     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
333     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
334   }
335   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
336   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
337   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
338   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
339   if (Subtarget->is64Bit()) {
340     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
341     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
342     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
343   }
344
345   if (Subtarget->hasSSE1())
346     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
347
348   if (!Subtarget->hasSSE2())
349     setOperationAction(ISD::MEMBARRIER    , MVT::Other, Expand);
350   // On X86 and X86-64, atomic operations are lowered to locked instructions.
351   // Locked instructions, in turn, have implicit fence semantics (all memory
352   // operations are flushed before issuing the locked instruction, and they
353   // are not buffered), so we can fold away the common pattern of
354   // fence-atomic-fence.
355   setShouldFoldAtomicFences(true);
356
357   // Expand certain atomics
358   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i8, Custom);
359   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i16, Custom);
360   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
361   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
362
363   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i8, Custom);
364   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i16, Custom);
365   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
366   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
367
368   if (!Subtarget->is64Bit()) {
369     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
370     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
371     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
372     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
373     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
374     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
375     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
376   }
377
378   // FIXME - use subtarget debug flags
379   if (!Subtarget->isTargetDarwin() &&
380       !Subtarget->isTargetELF() &&
381       !Subtarget->isTargetCygMing()) {
382     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
383   }
384
385   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
386   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
387   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
388   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
389   if (Subtarget->is64Bit()) {
390     setExceptionPointerRegister(X86::RAX);
391     setExceptionSelectorRegister(X86::RDX);
392   } else {
393     setExceptionPointerRegister(X86::EAX);
394     setExceptionSelectorRegister(X86::EDX);
395   }
396   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
397   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
398
399   setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
400
401   setOperationAction(ISD::TRAP, MVT::Other, Legal);
402
403   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
404   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
405   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
406   if (Subtarget->is64Bit()) {
407     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
408     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
409   } else {
410     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
411     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
412   }
413
414   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
415   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
416   if (Subtarget->is64Bit())
417     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
418   if (Subtarget->isTargetCygMing())
419     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
420   else
421     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
422
423   if (!UseSoftFloat && X86ScalarSSEf64) {
424     // f32 and f64 use SSE.
425     // Set up the FP register classes.
426     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
427     addRegisterClass(MVT::f64, X86::FR64RegisterClass);
428
429     // Use ANDPD to simulate FABS.
430     setOperationAction(ISD::FABS , MVT::f64, Custom);
431     setOperationAction(ISD::FABS , MVT::f32, Custom);
432
433     // Use XORP to simulate FNEG.
434     setOperationAction(ISD::FNEG , MVT::f64, Custom);
435     setOperationAction(ISD::FNEG , MVT::f32, Custom);
436
437     // Use ANDPD and ORPD to simulate FCOPYSIGN.
438     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
439     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
440
441     // We don't support sin/cos/fmod
442     setOperationAction(ISD::FSIN , MVT::f64, Expand);
443     setOperationAction(ISD::FCOS , MVT::f64, Expand);
444     setOperationAction(ISD::FSIN , MVT::f32, Expand);
445     setOperationAction(ISD::FCOS , MVT::f32, Expand);
446
447     // Expand FP immediates into loads from the stack, except for the special
448     // cases we handle.
449     addLegalFPImmediate(APFloat(+0.0)); // xorpd
450     addLegalFPImmediate(APFloat(+0.0f)); // xorps
451   } else if (!UseSoftFloat && X86ScalarSSEf32) {
452     // Use SSE for f32, x87 for f64.
453     // Set up the FP register classes.
454     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
455     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
456
457     // Use ANDPS to simulate FABS.
458     setOperationAction(ISD::FABS , MVT::f32, Custom);
459
460     // Use XORP to simulate FNEG.
461     setOperationAction(ISD::FNEG , MVT::f32, Custom);
462
463     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
464
465     // Use ANDPS and ORPS to simulate FCOPYSIGN.
466     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
467     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
468
469     // We don't support sin/cos/fmod
470     setOperationAction(ISD::FSIN , MVT::f32, Expand);
471     setOperationAction(ISD::FCOS , MVT::f32, Expand);
472
473     // Special cases we handle for FP constants.
474     addLegalFPImmediate(APFloat(+0.0f)); // xorps
475     addLegalFPImmediate(APFloat(+0.0)); // FLD0
476     addLegalFPImmediate(APFloat(+1.0)); // FLD1
477     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
478     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
479
480     if (!UnsafeFPMath) {
481       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
482       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
483     }
484   } else if (!UseSoftFloat) {
485     // f32 and f64 in x87.
486     // Set up the FP register classes.
487     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
488     addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
489
490     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
491     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
492     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
493     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
494
495     if (!UnsafeFPMath) {
496       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
497       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
498     }
499     addLegalFPImmediate(APFloat(+0.0)); // FLD0
500     addLegalFPImmediate(APFloat(+1.0)); // FLD1
501     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
502     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
503     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
504     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
505     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
506     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
507   }
508
509   // Long double always uses X87.
510   if (!UseSoftFloat) {
511     addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
512     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
513     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
514     {
515       bool ignored;
516       APFloat TmpFlt(+0.0);
517       TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
518                      &ignored);
519       addLegalFPImmediate(TmpFlt);  // FLD0
520       TmpFlt.changeSign();
521       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
522       APFloat TmpFlt2(+1.0);
523       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
524                       &ignored);
525       addLegalFPImmediate(TmpFlt2);  // FLD1
526       TmpFlt2.changeSign();
527       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
528     }
529
530     if (!UnsafeFPMath) {
531       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
532       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
533     }
534   }
535
536   // Always use a library call for pow.
537   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
538   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
539   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
540
541   setOperationAction(ISD::FLOG, MVT::f80, Expand);
542   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
543   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
544   setOperationAction(ISD::FEXP, MVT::f80, Expand);
545   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
546
547   // First set operation action for all vector types to either promote
548   // (for widening) or expand (for scalarization). Then we will selectively
549   // turn on ones that can be effectively codegen'd.
550   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
551        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
552     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
553     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
554     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
555     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
556     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
557     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
558     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
559     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
560     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
561     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
562     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
563     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
564     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
565     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
566     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
567     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
568     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
569     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
570     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
571     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
572     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
573     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
574     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
575     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
576     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
577     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
578     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
579     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
580     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
581     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
582     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
583     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
584     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
585     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
586     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
587     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
588     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
589     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
590     setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
591     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
592     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
593     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
594     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
595     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
596     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
597     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
598     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
599     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
600     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
601     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
602     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
603     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
604     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
605     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
606          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
607       setTruncStoreAction((MVT::SimpleValueType)VT,
608                           (MVT::SimpleValueType)InnerVT, Expand);
609     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
610     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
611     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
612   }
613
614   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
615   // with -msoft-float, disable use of MMX as well.
616   if (!UseSoftFloat && !DisableMMX && Subtarget->hasMMX()) {
617     addRegisterClass(MVT::v8i8,  X86::VR64RegisterClass, false);
618     addRegisterClass(MVT::v4i16, X86::VR64RegisterClass, false);
619     addRegisterClass(MVT::v2i32, X86::VR64RegisterClass, false);
620     
621     addRegisterClass(MVT::v1i64, X86::VR64RegisterClass, false);
622
623     setOperationAction(ISD::ADD,                MVT::v8i8,  Legal);
624     setOperationAction(ISD::ADD,                MVT::v4i16, Legal);
625     setOperationAction(ISD::ADD,                MVT::v2i32, Legal);
626     setOperationAction(ISD::ADD,                MVT::v1i64, Legal);
627
628     setOperationAction(ISD::SUB,                MVT::v8i8,  Legal);
629     setOperationAction(ISD::SUB,                MVT::v4i16, Legal);
630     setOperationAction(ISD::SUB,                MVT::v2i32, Legal);
631     setOperationAction(ISD::SUB,                MVT::v1i64, Legal);
632
633     setOperationAction(ISD::MULHS,              MVT::v4i16, Legal);
634     setOperationAction(ISD::MUL,                MVT::v4i16, Legal);
635
636     setOperationAction(ISD::AND,                MVT::v8i8,  Promote);
637     AddPromotedToType (ISD::AND,                MVT::v8i8,  MVT::v1i64);
638     setOperationAction(ISD::AND,                MVT::v4i16, Promote);
639     AddPromotedToType (ISD::AND,                MVT::v4i16, MVT::v1i64);
640     setOperationAction(ISD::AND,                MVT::v2i32, Promote);
641     AddPromotedToType (ISD::AND,                MVT::v2i32, MVT::v1i64);
642     setOperationAction(ISD::AND,                MVT::v1i64, Legal);
643
644     setOperationAction(ISD::OR,                 MVT::v8i8,  Promote);
645     AddPromotedToType (ISD::OR,                 MVT::v8i8,  MVT::v1i64);
646     setOperationAction(ISD::OR,                 MVT::v4i16, Promote);
647     AddPromotedToType (ISD::OR,                 MVT::v4i16, MVT::v1i64);
648     setOperationAction(ISD::OR,                 MVT::v2i32, Promote);
649     AddPromotedToType (ISD::OR,                 MVT::v2i32, MVT::v1i64);
650     setOperationAction(ISD::OR,                 MVT::v1i64, Legal);
651
652     setOperationAction(ISD::XOR,                MVT::v8i8,  Promote);
653     AddPromotedToType (ISD::XOR,                MVT::v8i8,  MVT::v1i64);
654     setOperationAction(ISD::XOR,                MVT::v4i16, Promote);
655     AddPromotedToType (ISD::XOR,                MVT::v4i16, MVT::v1i64);
656     setOperationAction(ISD::XOR,                MVT::v2i32, Promote);
657     AddPromotedToType (ISD::XOR,                MVT::v2i32, MVT::v1i64);
658     setOperationAction(ISD::XOR,                MVT::v1i64, Legal);
659
660     setOperationAction(ISD::LOAD,               MVT::v8i8,  Promote);
661     AddPromotedToType (ISD::LOAD,               MVT::v8i8,  MVT::v1i64);
662     setOperationAction(ISD::LOAD,               MVT::v4i16, Promote);
663     AddPromotedToType (ISD::LOAD,               MVT::v4i16, MVT::v1i64);
664     setOperationAction(ISD::LOAD,               MVT::v2i32, Promote);
665     AddPromotedToType (ISD::LOAD,               MVT::v2i32, MVT::v1i64);
666     setOperationAction(ISD::LOAD,               MVT::v1i64, Legal);
667
668     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i8,  Custom);
669     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i16, Custom);
670     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i32, Custom);
671     setOperationAction(ISD::BUILD_VECTOR,       MVT::v1i64, Custom);
672
673     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8i8,  Custom);
674     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i16, Custom);
675     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i32, Custom);
676     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v1i64, Custom);
677
678     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Custom);
679     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Custom);
680     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Custom);
681
682     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i16, Custom);
683
684     setOperationAction(ISD::SELECT,             MVT::v8i8, Promote);
685     setOperationAction(ISD::SELECT,             MVT::v4i16, Promote);
686     setOperationAction(ISD::SELECT,             MVT::v2i32, Promote);
687     setOperationAction(ISD::SELECT,             MVT::v1i64, Custom);
688     setOperationAction(ISD::VSETCC,             MVT::v8i8, Custom);
689     setOperationAction(ISD::VSETCC,             MVT::v4i16, Custom);
690     setOperationAction(ISD::VSETCC,             MVT::v2i32, Custom);
691
692     if (!X86ScalarSSEf64 && Subtarget->is64Bit()) {
693       setOperationAction(ISD::BIT_CONVERT,        MVT::v8i8,  Custom);
694       setOperationAction(ISD::BIT_CONVERT,        MVT::v4i16, Custom);
695       setOperationAction(ISD::BIT_CONVERT,        MVT::v2i32, Custom);
696       setOperationAction(ISD::BIT_CONVERT,        MVT::v1i64, Custom);
697     }
698   }
699
700   if (!UseSoftFloat && Subtarget->hasSSE1()) {
701     addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
702
703     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
704     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
705     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
706     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
707     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
708     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
709     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
710     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
711     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
712     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
713     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
714     setOperationAction(ISD::VSETCC,             MVT::v4f32, Custom);
715   }
716
717   if (!UseSoftFloat && Subtarget->hasSSE2()) {
718     addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
719
720     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
721     // registers cannot be used even for integer operations.
722     addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
723     addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
724     addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
725     addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
726
727     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
728     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
729     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
730     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
731     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
732     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
733     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
734     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
735     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
736     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
737     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
738     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
739     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
740     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
741     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
742     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
743
744     setOperationAction(ISD::VSETCC,             MVT::v2f64, Custom);
745     setOperationAction(ISD::VSETCC,             MVT::v16i8, Custom);
746     setOperationAction(ISD::VSETCC,             MVT::v8i16, Custom);
747     setOperationAction(ISD::VSETCC,             MVT::v4i32, Custom);
748
749     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
750     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
751     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
752     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
753     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
754
755     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2f64, Custom);
756     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2i64, Custom);
757     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i8, Custom);
758     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i16, Custom);
759     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i32, Custom);
760
761     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
762     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
763       EVT VT = (MVT::SimpleValueType)i;
764       // Do not attempt to custom lower non-power-of-2 vectors
765       if (!isPowerOf2_32(VT.getVectorNumElements()))
766         continue;
767       // Do not attempt to custom lower non-128-bit vectors
768       if (!VT.is128BitVector())
769         continue;
770       setOperationAction(ISD::BUILD_VECTOR,
771                          VT.getSimpleVT().SimpleTy, Custom);
772       setOperationAction(ISD::VECTOR_SHUFFLE,
773                          VT.getSimpleVT().SimpleTy, Custom);
774       setOperationAction(ISD::EXTRACT_VECTOR_ELT,
775                          VT.getSimpleVT().SimpleTy, Custom);
776     }
777
778     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
779     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
780     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
781     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
782     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
783     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
784
785     if (Subtarget->is64Bit()) {
786       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
787       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
788     }
789
790     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
791     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
792       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
793       EVT VT = SVT;
794
795       // Do not attempt to promote non-128-bit vectors
796       if (!VT.is128BitVector())
797         continue;
798       
799       setOperationAction(ISD::AND,    SVT, Promote);
800       AddPromotedToType (ISD::AND,    SVT, MVT::v2i64);
801       setOperationAction(ISD::OR,     SVT, Promote);
802       AddPromotedToType (ISD::OR,     SVT, MVT::v2i64);
803       setOperationAction(ISD::XOR,    SVT, Promote);
804       AddPromotedToType (ISD::XOR,    SVT, MVT::v2i64);
805       setOperationAction(ISD::LOAD,   SVT, Promote);
806       AddPromotedToType (ISD::LOAD,   SVT, MVT::v2i64);
807       setOperationAction(ISD::SELECT, SVT, Promote);
808       AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
809     }
810
811     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
812
813     // Custom lower v2i64 and v2f64 selects.
814     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
815     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
816     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
817     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
818
819     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
820     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
821     if (!DisableMMX && Subtarget->hasMMX()) {
822       setOperationAction(ISD::FP_TO_SINT,         MVT::v2i32, Custom);
823       setOperationAction(ISD::SINT_TO_FP,         MVT::v2i32, Custom);
824     }
825   }
826
827   if (Subtarget->hasSSE41()) {
828     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
829     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
830     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
831     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
832     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
833     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
834     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
835     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
836     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
837     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
838
839     // FIXME: Do we need to handle scalar-to-vector here?
840     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
841
842     // i8 and i16 vectors are custom , because the source register and source
843     // source memory operand types are not the same width.  f32 vectors are
844     // custom since the immediate controlling the insert encodes additional
845     // information.
846     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
847     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
848     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
849     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
850
851     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
852     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
853     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
854     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
855
856     if (Subtarget->is64Bit()) {
857       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Legal);
858       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
859     }
860   }
861
862   if (Subtarget->hasSSE42()) {
863     setOperationAction(ISD::VSETCC,             MVT::v2i64, Custom);
864   }
865
866   if (!UseSoftFloat && Subtarget->hasAVX()) {
867     addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
868     addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
869     addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
870     addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
871
872     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
873     setOperationAction(ISD::LOAD,               MVT::v8i32, Legal);
874     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
875     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
876     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
877     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
878     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
879     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
880     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
881     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
882     //setOperationAction(ISD::BUILD_VECTOR,       MVT::v8f32, Custom);
883     //setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8f32, Custom);
884     //setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8f32, Custom);
885     //setOperationAction(ISD::SELECT,             MVT::v8f32, Custom);
886     //setOperationAction(ISD::VSETCC,             MVT::v8f32, Custom);
887
888     // Operations to consider commented out -v16i16 v32i8
889     //setOperationAction(ISD::ADD,                MVT::v16i16, Legal);
890     setOperationAction(ISD::ADD,                MVT::v8i32, Custom);
891     setOperationAction(ISD::ADD,                MVT::v4i64, Custom);
892     //setOperationAction(ISD::SUB,                MVT::v32i8, Legal);
893     //setOperationAction(ISD::SUB,                MVT::v16i16, Legal);
894     setOperationAction(ISD::SUB,                MVT::v8i32, Custom);
895     setOperationAction(ISD::SUB,                MVT::v4i64, Custom);
896     //setOperationAction(ISD::MUL,                MVT::v16i16, Legal);
897     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
898     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
899     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
900     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
901     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
902     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
903
904     setOperationAction(ISD::VSETCC,             MVT::v4f64, Custom);
905     // setOperationAction(ISD::VSETCC,             MVT::v32i8, Custom);
906     // setOperationAction(ISD::VSETCC,             MVT::v16i16, Custom);
907     setOperationAction(ISD::VSETCC,             MVT::v8i32, Custom);
908
909     // setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v32i8, Custom);
910     // setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i16, Custom);
911     // setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i16, Custom);
912     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i32, Custom);
913     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8f32, Custom);
914
915     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f64, Custom);
916     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i64, Custom);
917     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f64, Custom);
918     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i64, Custom);
919     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f64, Custom);
920     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f64, Custom);
921
922 #if 0
923     // Not sure we want to do this since there are no 256-bit integer
924     // operations in AVX
925
926     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
927     // This includes 256-bit vectors
928     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; ++i) {
929       EVT VT = (MVT::SimpleValueType)i;
930
931       // Do not attempt to custom lower non-power-of-2 vectors
932       if (!isPowerOf2_32(VT.getVectorNumElements()))
933         continue;
934
935       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
936       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
937       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
938     }
939
940     if (Subtarget->is64Bit()) {
941       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i64, Custom);
942       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i64, Custom);
943     }
944 #endif
945
946 #if 0
947     // Not sure we want to do this since there are no 256-bit integer
948     // operations in AVX
949
950     // Promote v32i8, v16i16, v8i32 load, select, and, or, xor to v4i64.
951     // Including 256-bit vectors
952     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; i++) {
953       EVT VT = (MVT::SimpleValueType)i;
954
955       if (!VT.is256BitVector()) {
956         continue;
957       }
958       setOperationAction(ISD::AND,    VT, Promote);
959       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
960       setOperationAction(ISD::OR,     VT, Promote);
961       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
962       setOperationAction(ISD::XOR,    VT, Promote);
963       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
964       setOperationAction(ISD::LOAD,   VT, Promote);
965       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
966       setOperationAction(ISD::SELECT, VT, Promote);
967       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
968     }
969
970     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
971 #endif
972   }
973
974   // We want to custom lower some of our intrinsics.
975   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
976
977   // Add/Sub/Mul with overflow operations are custom lowered.
978   setOperationAction(ISD::SADDO, MVT::i32, Custom);
979   setOperationAction(ISD::UADDO, MVT::i32, Custom);
980   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
981   setOperationAction(ISD::USUBO, MVT::i32, Custom);
982   setOperationAction(ISD::SMULO, MVT::i32, Custom);
983
984   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
985   // handle type legalization for these operations here.
986   //
987   // FIXME: We really should do custom legalization for addition and
988   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
989   // than generic legalization for 64-bit multiplication-with-overflow, though.
990   if (Subtarget->is64Bit()) {
991     setOperationAction(ISD::SADDO, MVT::i64, Custom);
992     setOperationAction(ISD::UADDO, MVT::i64, Custom);
993     setOperationAction(ISD::SSUBO, MVT::i64, Custom);
994     setOperationAction(ISD::USUBO, MVT::i64, Custom);
995     setOperationAction(ISD::SMULO, MVT::i64, Custom);
996   }
997
998   if (!Subtarget->is64Bit()) {
999     // These libcalls are not available in 32-bit.
1000     setLibcallName(RTLIB::SHL_I128, 0);
1001     setLibcallName(RTLIB::SRL_I128, 0);
1002     setLibcallName(RTLIB::SRA_I128, 0);
1003   }
1004
1005   // We have target-specific dag combine patterns for the following nodes:
1006   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1007   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1008   setTargetDAGCombine(ISD::BUILD_VECTOR);
1009   setTargetDAGCombine(ISD::SELECT);
1010   setTargetDAGCombine(ISD::SHL);
1011   setTargetDAGCombine(ISD::SRA);
1012   setTargetDAGCombine(ISD::SRL);
1013   setTargetDAGCombine(ISD::OR);
1014   setTargetDAGCombine(ISD::STORE);
1015   setTargetDAGCombine(ISD::ZERO_EXTEND);
1016   if (Subtarget->is64Bit())
1017     setTargetDAGCombine(ISD::MUL);
1018
1019   computeRegisterProperties();
1020
1021   // FIXME: These should be based on subtarget info. Plus, the values should
1022   // be smaller when we are in optimizing for size mode.
1023   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1024   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1025   maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
1026   setPrefLoopAlignment(16);
1027   benefitFromCodePlacementOpt = true;
1028 }
1029
1030
1031 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
1032   return MVT::i8;
1033 }
1034
1035
1036 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1037 /// the desired ByVal argument alignment.
1038 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
1039   if (MaxAlign == 16)
1040     return;
1041   if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1042     if (VTy->getBitWidth() == 128)
1043       MaxAlign = 16;
1044   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1045     unsigned EltAlign = 0;
1046     getMaxByValAlign(ATy->getElementType(), EltAlign);
1047     if (EltAlign > MaxAlign)
1048       MaxAlign = EltAlign;
1049   } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1050     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1051       unsigned EltAlign = 0;
1052       getMaxByValAlign(STy->getElementType(i), EltAlign);
1053       if (EltAlign > MaxAlign)
1054         MaxAlign = EltAlign;
1055       if (MaxAlign == 16)
1056         break;
1057     }
1058   }
1059   return;
1060 }
1061
1062 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1063 /// function arguments in the caller parameter area. For X86, aggregates
1064 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1065 /// are at 4-byte boundaries.
1066 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1067   if (Subtarget->is64Bit()) {
1068     // Max of 8 and alignment of type.
1069     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1070     if (TyAlign > 8)
1071       return TyAlign;
1072     return 8;
1073   }
1074
1075   unsigned Align = 4;
1076   if (Subtarget->hasSSE1())
1077     getMaxByValAlign(Ty, Align);
1078   return Align;
1079 }
1080
1081 /// getOptimalMemOpType - Returns the target specific optimal type for load
1082 /// and store operations as a result of memset, memcpy, and memmove
1083 /// lowering. If DstAlign is zero that means it's safe to destination
1084 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1085 /// means there isn't a need to check it against alignment requirement,
1086 /// probably because the source does not need to be loaded. If
1087 /// 'NonScalarIntSafe' is true, that means it's safe to return a
1088 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1089 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1090 /// constant so it does not need to be loaded.
1091 /// It returns EVT::Other if the type should be determined using generic
1092 /// target-independent logic.
1093 EVT
1094 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1095                                        unsigned DstAlign, unsigned SrcAlign,
1096                                        bool NonScalarIntSafe,
1097                                        bool MemcpyStrSrc,
1098                                        MachineFunction &MF) const {
1099   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1100   // linux.  This is because the stack realignment code can't handle certain
1101   // cases like PR2962.  This should be removed when PR2962 is fixed.
1102   const Function *F = MF.getFunction();
1103   if (NonScalarIntSafe &&
1104       !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1105     if (Size >= 16 &&
1106         (Subtarget->isUnalignedMemAccessFast() ||
1107          ((DstAlign == 0 || DstAlign >= 16) &&
1108           (SrcAlign == 0 || SrcAlign >= 16))) &&
1109         Subtarget->getStackAlignment() >= 16) {
1110       if (Subtarget->hasSSE2())
1111         return MVT::v4i32;
1112       if (Subtarget->hasSSE1())
1113         return MVT::v4f32;
1114     } else if (!MemcpyStrSrc && Size >= 8 &&
1115                !Subtarget->is64Bit() &&
1116                Subtarget->getStackAlignment() >= 8 &&
1117                Subtarget->hasSSE2()) {
1118       // Do not use f64 to lower memcpy if source is string constant. It's
1119       // better to use i32 to avoid the loads.
1120       return MVT::f64;
1121     }
1122   }
1123   if (Subtarget->is64Bit() && Size >= 8)
1124     return MVT::i64;
1125   return MVT::i32;
1126 }
1127
1128 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1129 /// current function.  The returned value is a member of the
1130 /// MachineJumpTableInfo::JTEntryKind enum.
1131 unsigned X86TargetLowering::getJumpTableEncoding() const {
1132   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1133   // symbol.
1134   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1135       Subtarget->isPICStyleGOT())
1136     return MachineJumpTableInfo::EK_Custom32;
1137   
1138   // Otherwise, use the normal jump table encoding heuristics.
1139   return TargetLowering::getJumpTableEncoding();
1140 }
1141
1142 /// getPICBaseSymbol - Return the X86-32 PIC base.
1143 MCSymbol *
1144 X86TargetLowering::getPICBaseSymbol(const MachineFunction *MF,
1145                                     MCContext &Ctx) const {
1146   const MCAsmInfo &MAI = *getTargetMachine().getMCAsmInfo();
1147   return Ctx.GetOrCreateSymbol(Twine(MAI.getPrivateGlobalPrefix())+
1148                                Twine(MF->getFunctionNumber())+"$pb");
1149 }
1150
1151
1152 const MCExpr *
1153 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1154                                              const MachineBasicBlock *MBB,
1155                                              unsigned uid,MCContext &Ctx) const{
1156   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1157          Subtarget->isPICStyleGOT());
1158   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1159   // entries.
1160   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1161                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1162 }
1163
1164 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1165 /// jumptable.
1166 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1167                                                     SelectionDAG &DAG) const {
1168   if (!Subtarget->is64Bit())
1169     // This doesn't have DebugLoc associated with it, but is not really the
1170     // same as a Register.
1171     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1172   return Table;
1173 }
1174
1175 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1176 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1177 /// MCExpr.
1178 const MCExpr *X86TargetLowering::
1179 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1180                              MCContext &Ctx) const {
1181   // X86-64 uses RIP relative addressing based on the jump table label.
1182   if (Subtarget->isPICStyleRIPRel())
1183     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1184
1185   // Otherwise, the reference is relative to the PIC base.
1186   return MCSymbolRefExpr::Create(getPICBaseSymbol(MF, Ctx), Ctx);
1187 }
1188
1189 /// getFunctionAlignment - Return the Log2 alignment of this function.
1190 unsigned X86TargetLowering::getFunctionAlignment(const Function *F) const {
1191   return F->hasFnAttr(Attribute::OptimizeForSize) ? 0 : 4;
1192 }
1193
1194 //===----------------------------------------------------------------------===//
1195 //               Return Value Calling Convention Implementation
1196 //===----------------------------------------------------------------------===//
1197
1198 #include "X86GenCallingConv.inc"
1199
1200 bool 
1201 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv, bool isVarArg,
1202                         const SmallVectorImpl<EVT> &OutTys,
1203                         const SmallVectorImpl<ISD::ArgFlagsTy> &ArgsFlags,
1204                         SelectionDAG &DAG) const {
1205   SmallVector<CCValAssign, 16> RVLocs;
1206   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1207                  RVLocs, *DAG.getContext());
1208   return CCInfo.CheckReturn(OutTys, ArgsFlags, RetCC_X86);
1209 }
1210
1211 SDValue
1212 X86TargetLowering::LowerReturn(SDValue Chain,
1213                                CallingConv::ID CallConv, bool isVarArg,
1214                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1215                                DebugLoc dl, SelectionDAG &DAG) const {
1216   MachineFunction &MF = DAG.getMachineFunction();
1217   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1218
1219   SmallVector<CCValAssign, 16> RVLocs;
1220   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1221                  RVLocs, *DAG.getContext());
1222   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1223
1224   // Add the regs to the liveout set for the function.
1225   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1226   for (unsigned i = 0; i != RVLocs.size(); ++i)
1227     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1228       MRI.addLiveOut(RVLocs[i].getLocReg());
1229
1230   SDValue Flag;
1231
1232   SmallVector<SDValue, 6> RetOps;
1233   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1234   // Operand #1 = Bytes To Pop
1235   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1236                    MVT::i16));
1237
1238   // Copy the result values into the output registers.
1239   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1240     CCValAssign &VA = RVLocs[i];
1241     assert(VA.isRegLoc() && "Can only return in registers!");
1242     SDValue ValToCopy = Outs[i].Val;
1243
1244     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1245     // the RET instruction and handled by the FP Stackifier.
1246     if (VA.getLocReg() == X86::ST0 ||
1247         VA.getLocReg() == X86::ST1) {
1248       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1249       // change the value to the FP stack register class.
1250       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1251         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1252       RetOps.push_back(ValToCopy);
1253       // Don't emit a copytoreg.
1254       continue;
1255     }
1256
1257     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1258     // which is returned in RAX / RDX.
1259     if (Subtarget->is64Bit()) {
1260       EVT ValVT = ValToCopy.getValueType();
1261       if (ValVT.isVector() && ValVT.getSizeInBits() == 64) {
1262         ValToCopy = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, ValToCopy);
1263         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1)
1264           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, ValToCopy);
1265       }
1266     }
1267
1268     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1269     Flag = Chain.getValue(1);
1270   }
1271
1272   // The x86-64 ABI for returning structs by value requires that we copy
1273   // the sret argument into %rax for the return. We saved the argument into
1274   // a virtual register in the entry block, so now we copy the value out
1275   // and into %rax.
1276   if (Subtarget->is64Bit() &&
1277       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1278     MachineFunction &MF = DAG.getMachineFunction();
1279     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1280     unsigned Reg = FuncInfo->getSRetReturnReg();
1281     assert(Reg && 
1282            "SRetReturnReg should have been set in LowerFormalArguments().");
1283     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1284
1285     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1286     Flag = Chain.getValue(1);
1287
1288     // RAX now acts like a return value.
1289     MRI.addLiveOut(X86::RAX);
1290   }
1291
1292   RetOps[0] = Chain;  // Update chain.
1293
1294   // Add the flag if we have it.
1295   if (Flag.getNode())
1296     RetOps.push_back(Flag);
1297
1298   return DAG.getNode(X86ISD::RET_FLAG, dl,
1299                      MVT::Other, &RetOps[0], RetOps.size());
1300 }
1301
1302 /// LowerCallResult - Lower the result values of a call into the
1303 /// appropriate copies out of appropriate physical registers.
1304 ///
1305 SDValue
1306 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1307                                    CallingConv::ID CallConv, bool isVarArg,
1308                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1309                                    DebugLoc dl, SelectionDAG &DAG,
1310                                    SmallVectorImpl<SDValue> &InVals) const {
1311
1312   // Assign locations to each value returned by this call.
1313   SmallVector<CCValAssign, 16> RVLocs;
1314   bool Is64Bit = Subtarget->is64Bit();
1315   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1316                  RVLocs, *DAG.getContext());
1317   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1318
1319   // Copy all of the result registers out of their specified physreg.
1320   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1321     CCValAssign &VA = RVLocs[i];
1322     EVT CopyVT = VA.getValVT();
1323
1324     // If this is x86-64, and we disabled SSE, we can't return FP values
1325     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1326         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1327       report_fatal_error("SSE register return with SSE disabled");
1328     }
1329
1330     // If this is a call to a function that returns an fp value on the floating
1331     // point stack, but where we prefer to use the value in xmm registers, copy
1332     // it out as F80 and use a truncate to move it from fp stack reg to xmm reg.
1333     if ((VA.getLocReg() == X86::ST0 ||
1334          VA.getLocReg() == X86::ST1) &&
1335         isScalarFPTypeInSSEReg(VA.getValVT())) {
1336       CopyVT = MVT::f80;
1337     }
1338
1339     SDValue Val;
1340     if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1341       // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1342       if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1343         Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1344                                    MVT::v2i64, InFlag).getValue(1);
1345         Val = Chain.getValue(0);
1346         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1347                           Val, DAG.getConstant(0, MVT::i64));
1348       } else {
1349         Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1350                                    MVT::i64, InFlag).getValue(1);
1351         Val = Chain.getValue(0);
1352       }
1353       Val = DAG.getNode(ISD::BIT_CONVERT, dl, CopyVT, Val);
1354     } else {
1355       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1356                                  CopyVT, InFlag).getValue(1);
1357       Val = Chain.getValue(0);
1358     }
1359     InFlag = Chain.getValue(2);
1360
1361     if (CopyVT != VA.getValVT()) {
1362       // Round the F80 the right size, which also moves to the appropriate xmm
1363       // register.
1364       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1365                         // This truncation won't change the value.
1366                         DAG.getIntPtrConstant(1));
1367     }
1368
1369     InVals.push_back(Val);
1370   }
1371
1372   return Chain;
1373 }
1374
1375
1376 //===----------------------------------------------------------------------===//
1377 //                C & StdCall & Fast Calling Convention implementation
1378 //===----------------------------------------------------------------------===//
1379 //  StdCall calling convention seems to be standard for many Windows' API
1380 //  routines and around. It differs from C calling convention just a little:
1381 //  callee should clean up the stack, not caller. Symbols should be also
1382 //  decorated in some fancy way :) It doesn't support any vector arguments.
1383 //  For info on fast calling convention see Fast Calling Convention (tail call)
1384 //  implementation LowerX86_32FastCCCallTo.
1385
1386 /// CallIsStructReturn - Determines whether a call uses struct return
1387 /// semantics.
1388 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1389   if (Outs.empty())
1390     return false;
1391
1392   return Outs[0].Flags.isSRet();
1393 }
1394
1395 /// ArgsAreStructReturn - Determines whether a function uses struct
1396 /// return semantics.
1397 static bool
1398 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1399   if (Ins.empty())
1400     return false;
1401
1402   return Ins[0].Flags.isSRet();
1403 }
1404
1405 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1406 /// given CallingConvention value.
1407 CCAssignFn *X86TargetLowering::CCAssignFnForNode(CallingConv::ID CC) const {
1408   if (Subtarget->is64Bit()) {
1409     if (CC == CallingConv::GHC)
1410       return CC_X86_64_GHC;
1411     else if (Subtarget->isTargetWin64())
1412       return CC_X86_Win64_C;
1413     else
1414       return CC_X86_64_C;
1415   }
1416
1417   if (CC == CallingConv::X86_FastCall)
1418     return CC_X86_32_FastCall;
1419   else if (CC == CallingConv::X86_ThisCall)
1420     return CC_X86_32_ThisCall;
1421   else if (CC == CallingConv::Fast)
1422     return CC_X86_32_FastCC;
1423   else if (CC == CallingConv::GHC)
1424     return CC_X86_32_GHC;
1425   else
1426     return CC_X86_32_C;
1427 }
1428
1429 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1430 /// by "Src" to address "Dst" with size and alignment information specified by
1431 /// the specific parameter attribute. The copy will be passed as a byval
1432 /// function parameter.
1433 static SDValue
1434 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1435                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1436                           DebugLoc dl) {
1437   SDValue SizeNode     = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1438   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1439                        /*isVolatile*/false, /*AlwaysInline=*/true,
1440                        NULL, 0, NULL, 0);
1441 }
1442
1443 /// IsTailCallConvention - Return true if the calling convention is one that
1444 /// supports tail call optimization.
1445 static bool IsTailCallConvention(CallingConv::ID CC) {
1446   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1447 }
1448
1449 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1450 /// a tailcall target by changing its ABI.
1451 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1452   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1453 }
1454
1455 SDValue
1456 X86TargetLowering::LowerMemArgument(SDValue Chain,
1457                                     CallingConv::ID CallConv,
1458                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1459                                     DebugLoc dl, SelectionDAG &DAG,
1460                                     const CCValAssign &VA,
1461                                     MachineFrameInfo *MFI,
1462                                     unsigned i) const {
1463   // Create the nodes corresponding to a load from this parameter slot.
1464   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1465   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1466   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1467   EVT ValVT;
1468
1469   // If value is passed by pointer we have address passed instead of the value
1470   // itself.
1471   if (VA.getLocInfo() == CCValAssign::Indirect)
1472     ValVT = VA.getLocVT();
1473   else
1474     ValVT = VA.getValVT();
1475
1476   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1477   // changed with more analysis.
1478   // In case of tail call optimization mark all arguments mutable. Since they
1479   // could be overwritten by lowering of arguments in case of a tail call.
1480   if (Flags.isByVal()) {
1481     int FI = MFI->CreateFixedObject(Flags.getByValSize(),
1482                                     VA.getLocMemOffset(), isImmutable);
1483     return DAG.getFrameIndex(FI, getPointerTy());
1484   } else {
1485     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1486                                     VA.getLocMemOffset(), isImmutable);
1487     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1488     return DAG.getLoad(ValVT, dl, Chain, FIN,
1489                        PseudoSourceValue::getFixedStack(FI), 0,
1490                        false, false, 0);
1491   }
1492 }
1493
1494 SDValue
1495 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1496                                         CallingConv::ID CallConv,
1497                                         bool isVarArg,
1498                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1499                                         DebugLoc dl,
1500                                         SelectionDAG &DAG,
1501                                         SmallVectorImpl<SDValue> &InVals)
1502                                           const {
1503   MachineFunction &MF = DAG.getMachineFunction();
1504   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1505
1506   const Function* Fn = MF.getFunction();
1507   if (Fn->hasExternalLinkage() &&
1508       Subtarget->isTargetCygMing() &&
1509       Fn->getName() == "main")
1510     FuncInfo->setForceFramePointer(true);
1511
1512   MachineFrameInfo *MFI = MF.getFrameInfo();
1513   bool Is64Bit = Subtarget->is64Bit();
1514   bool IsWin64 = Subtarget->isTargetWin64();
1515
1516   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1517          "Var args not supported with calling convention fastcc or ghc");
1518
1519   // Assign locations to all of the incoming arguments.
1520   SmallVector<CCValAssign, 16> ArgLocs;
1521   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1522                  ArgLocs, *DAG.getContext());
1523   CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForNode(CallConv));
1524
1525   unsigned LastVal = ~0U;
1526   SDValue ArgValue;
1527   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1528     CCValAssign &VA = ArgLocs[i];
1529     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1530     // places.
1531     assert(VA.getValNo() != LastVal &&
1532            "Don't support value assigned to multiple locs yet");
1533     LastVal = VA.getValNo();
1534
1535     if (VA.isRegLoc()) {
1536       EVT RegVT = VA.getLocVT();
1537       TargetRegisterClass *RC = NULL;
1538       if (RegVT == MVT::i32)
1539         RC = X86::GR32RegisterClass;
1540       else if (Is64Bit && RegVT == MVT::i64)
1541         RC = X86::GR64RegisterClass;
1542       else if (RegVT == MVT::f32)
1543         RC = X86::FR32RegisterClass;
1544       else if (RegVT == MVT::f64)
1545         RC = X86::FR64RegisterClass;
1546       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1547         RC = X86::VR128RegisterClass;
1548       else if (RegVT.isVector() && RegVT.getSizeInBits() == 64)
1549         RC = X86::VR64RegisterClass;
1550       else
1551         llvm_unreachable("Unknown argument type!");
1552
1553       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1554       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1555
1556       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1557       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1558       // right size.
1559       if (VA.getLocInfo() == CCValAssign::SExt)
1560         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1561                                DAG.getValueType(VA.getValVT()));
1562       else if (VA.getLocInfo() == CCValAssign::ZExt)
1563         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1564                                DAG.getValueType(VA.getValVT()));
1565       else if (VA.getLocInfo() == CCValAssign::BCvt)
1566         ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1567
1568       if (VA.isExtInLoc()) {
1569         // Handle MMX values passed in XMM regs.
1570         if (RegVT.isVector()) {
1571           ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1572                                  ArgValue, DAG.getConstant(0, MVT::i64));
1573           ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1574         } else
1575           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1576       }
1577     } else {
1578       assert(VA.isMemLoc());
1579       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1580     }
1581
1582     // If value is passed via pointer - do a load.
1583     if (VA.getLocInfo() == CCValAssign::Indirect)
1584       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue, NULL, 0,
1585                              false, false, 0);
1586
1587     InVals.push_back(ArgValue);
1588   }
1589
1590   // The x86-64 ABI for returning structs by value requires that we copy
1591   // the sret argument into %rax for the return. Save the argument into
1592   // a virtual register so that we can access it from the return points.
1593   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1594     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1595     unsigned Reg = FuncInfo->getSRetReturnReg();
1596     if (!Reg) {
1597       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1598       FuncInfo->setSRetReturnReg(Reg);
1599     }
1600     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1601     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1602   }
1603
1604   unsigned StackSize = CCInfo.getNextStackOffset();
1605   // Align stack specially for tail calls.
1606   if (FuncIsMadeTailCallSafe(CallConv))
1607     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1608
1609   // If the function takes variable number of arguments, make a frame index for
1610   // the start of the first vararg value... for expansion of llvm.va_start.
1611   if (isVarArg) {
1612     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1613                     CallConv != CallingConv::X86_ThisCall)) {
1614       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1615     }
1616     if (Is64Bit) {
1617       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1618
1619       // FIXME: We should really autogenerate these arrays
1620       static const unsigned GPR64ArgRegsWin64[] = {
1621         X86::RCX, X86::RDX, X86::R8,  X86::R9
1622       };
1623       static const unsigned XMMArgRegsWin64[] = {
1624         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1625       };
1626       static const unsigned GPR64ArgRegs64Bit[] = {
1627         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1628       };
1629       static const unsigned XMMArgRegs64Bit[] = {
1630         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1631         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1632       };
1633       const unsigned *GPR64ArgRegs, *XMMArgRegs;
1634
1635       if (IsWin64) {
1636         TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1637         GPR64ArgRegs = GPR64ArgRegsWin64;
1638         XMMArgRegs = XMMArgRegsWin64;
1639       } else {
1640         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1641         GPR64ArgRegs = GPR64ArgRegs64Bit;
1642         XMMArgRegs = XMMArgRegs64Bit;
1643       }
1644       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1645                                                        TotalNumIntRegs);
1646       unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1647                                                        TotalNumXMMRegs);
1648
1649       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1650       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1651              "SSE register cannot be used when SSE is disabled!");
1652       assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1653              "SSE register cannot be used when SSE is disabled!");
1654       if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
1655         // Kernel mode asks for SSE to be disabled, so don't push them
1656         // on the stack.
1657         TotalNumXMMRegs = 0;
1658
1659       // For X86-64, if there are vararg parameters that are passed via
1660       // registers, then we must store them to their spots on the stack so they
1661       // may be loaded by deferencing the result of va_next.
1662       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1663       FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1664       FuncInfo->setRegSaveFrameIndex(
1665         MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1666                                false));
1667
1668       // Store the integer parameter registers.
1669       SmallVector<SDValue, 8> MemOps;
1670       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1671                                         getPointerTy());
1672       unsigned Offset = FuncInfo->getVarArgsGPOffset();
1673       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1674         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1675                                   DAG.getIntPtrConstant(Offset));
1676         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1677                                      X86::GR64RegisterClass);
1678         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1679         SDValue Store =
1680           DAG.getStore(Val.getValue(1), dl, Val, FIN,
1681                        PseudoSourceValue::getFixedStack(
1682                          FuncInfo->getRegSaveFrameIndex()),
1683                        Offset, false, false, 0);
1684         MemOps.push_back(Store);
1685         Offset += 8;
1686       }
1687
1688       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1689         // Now store the XMM (fp + vector) parameter registers.
1690         SmallVector<SDValue, 11> SaveXMMOps;
1691         SaveXMMOps.push_back(Chain);
1692
1693         unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1694         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1695         SaveXMMOps.push_back(ALVal);
1696
1697         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1698                                FuncInfo->getRegSaveFrameIndex()));
1699         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1700                                FuncInfo->getVarArgsFPOffset()));
1701
1702         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1703           unsigned VReg = MF.addLiveIn(XMMArgRegs[NumXMMRegs],
1704                                        X86::VR128RegisterClass);
1705           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1706           SaveXMMOps.push_back(Val);
1707         }
1708         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1709                                      MVT::Other,
1710                                      &SaveXMMOps[0], SaveXMMOps.size()));
1711       }
1712
1713       if (!MemOps.empty())
1714         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1715                             &MemOps[0], MemOps.size());
1716     }
1717   }
1718
1719   // Some CCs need callee pop.
1720   if (Subtarget->IsCalleePop(isVarArg, CallConv)) {
1721     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1722   } else {
1723     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1724     // If this is an sret function, the return should pop the hidden pointer.
1725     if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1726       FuncInfo->setBytesToPopOnReturn(4);
1727   }
1728
1729   if (!Is64Bit) {
1730     // RegSaveFrameIndex is X86-64 only.
1731     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1732     if (CallConv == CallingConv::X86_FastCall ||
1733         CallConv == CallingConv::X86_ThisCall)
1734       // fastcc functions can't have varargs.
1735       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1736   }
1737
1738   return Chain;
1739 }
1740
1741 SDValue
1742 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1743                                     SDValue StackPtr, SDValue Arg,
1744                                     DebugLoc dl, SelectionDAG &DAG,
1745                                     const CCValAssign &VA,
1746                                     ISD::ArgFlagsTy Flags) const {
1747   const unsigned FirstStackArgOffset = (Subtarget->isTargetWin64() ? 32 : 0);
1748   unsigned LocMemOffset = FirstStackArgOffset + VA.getLocMemOffset();
1749   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1750   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1751   if (Flags.isByVal()) {
1752     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1753   }
1754   return DAG.getStore(Chain, dl, Arg, PtrOff,
1755                       PseudoSourceValue::getStack(), LocMemOffset,
1756                       false, false, 0);
1757 }
1758
1759 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1760 /// optimization is performed and it is required.
1761 SDValue
1762 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1763                                            SDValue &OutRetAddr, SDValue Chain,
1764                                            bool IsTailCall, bool Is64Bit,
1765                                            int FPDiff, DebugLoc dl) const {
1766   // Adjust the Return address stack slot.
1767   EVT VT = getPointerTy();
1768   OutRetAddr = getReturnAddressFrameIndex(DAG);
1769
1770   // Load the "old" Return address.
1771   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, NULL, 0, false, false, 0);
1772   return SDValue(OutRetAddr.getNode(), 1);
1773 }
1774
1775 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1776 /// optimization is performed and it is required (FPDiff!=0).
1777 static SDValue
1778 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1779                          SDValue Chain, SDValue RetAddrFrIdx,
1780                          bool Is64Bit, int FPDiff, DebugLoc dl) {
1781   // Store the return address to the appropriate stack slot.
1782   if (!FPDiff) return Chain;
1783   // Calculate the new stack slot for the return address.
1784   int SlotSize = Is64Bit ? 8 : 4;
1785   int NewReturnAddrFI =
1786     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
1787   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1788   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1789   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1790                        PseudoSourceValue::getFixedStack(NewReturnAddrFI), 0,
1791                        false, false, 0);
1792   return Chain;
1793 }
1794
1795 SDValue
1796 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1797                              CallingConv::ID CallConv, bool isVarArg,
1798                              bool &isTailCall,
1799                              const SmallVectorImpl<ISD::OutputArg> &Outs,
1800                              const SmallVectorImpl<ISD::InputArg> &Ins,
1801                              DebugLoc dl, SelectionDAG &DAG,
1802                              SmallVectorImpl<SDValue> &InVals) const {
1803   MachineFunction &MF = DAG.getMachineFunction();
1804   bool Is64Bit        = Subtarget->is64Bit();
1805   bool IsStructRet    = CallIsStructReturn(Outs);
1806   bool IsSibcall      = false;
1807
1808   if (isTailCall) {
1809     // Check if it's really possible to do a tail call.
1810     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1811                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1812                                                    Outs, Ins, DAG);
1813
1814     // Sibcalls are automatically detected tailcalls which do not require
1815     // ABI changes.
1816     if (!GuaranteedTailCallOpt && isTailCall)
1817       IsSibcall = true;
1818
1819     if (isTailCall)
1820       ++NumTailCalls;
1821   }
1822
1823   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1824          "Var args not supported with calling convention fastcc or ghc");
1825
1826   // Analyze operands of the call, assigning locations to each operand.
1827   SmallVector<CCValAssign, 16> ArgLocs;
1828   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1829                  ArgLocs, *DAG.getContext());
1830   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CallConv));
1831
1832   // Get a count of how many bytes are to be pushed on the stack.
1833   unsigned NumBytes = CCInfo.getNextStackOffset();
1834   if (IsSibcall)
1835     // This is a sibcall. The memory operands are available in caller's
1836     // own caller's stack.
1837     NumBytes = 0;
1838   else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
1839     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1840
1841   int FPDiff = 0;
1842   if (isTailCall && !IsSibcall) {
1843     // Lower arguments at fp - stackoffset + fpdiff.
1844     unsigned NumBytesCallerPushed =
1845       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1846     FPDiff = NumBytesCallerPushed - NumBytes;
1847
1848     // Set the delta of movement of the returnaddr stackslot.
1849     // But only set if delta is greater than previous delta.
1850     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1851       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1852   }
1853
1854   if (!IsSibcall)
1855     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1856
1857   SDValue RetAddrFrIdx;
1858   // Load return adress for tail calls.
1859   if (isTailCall && FPDiff)
1860     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
1861                                     Is64Bit, FPDiff, dl);
1862
1863   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1864   SmallVector<SDValue, 8> MemOpChains;
1865   SDValue StackPtr;
1866
1867   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1868   // of tail call optimization arguments are handle later.
1869   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1870     CCValAssign &VA = ArgLocs[i];
1871     EVT RegVT = VA.getLocVT();
1872     SDValue Arg = Outs[i].Val;
1873     ISD::ArgFlagsTy Flags = Outs[i].Flags;
1874     bool isByVal = Flags.isByVal();
1875
1876     // Promote the value if needed.
1877     switch (VA.getLocInfo()) {
1878     default: llvm_unreachable("Unknown loc info!");
1879     case CCValAssign::Full: break;
1880     case CCValAssign::SExt:
1881       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
1882       break;
1883     case CCValAssign::ZExt:
1884       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
1885       break;
1886     case CCValAssign::AExt:
1887       if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
1888         // Special case: passing MMX values in XMM registers.
1889         Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1890         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
1891         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
1892       } else
1893         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
1894       break;
1895     case CCValAssign::BCvt:
1896       Arg = DAG.getNode(ISD::BIT_CONVERT, dl, RegVT, Arg);
1897       break;
1898     case CCValAssign::Indirect: {
1899       // Store the argument.
1900       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
1901       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1902       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
1903                            PseudoSourceValue::getFixedStack(FI), 0,
1904                            false, false, 0);
1905       Arg = SpillSlot;
1906       break;
1907     }
1908     }
1909
1910     if (VA.isRegLoc()) {
1911       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1912     } else if (!IsSibcall && (!isTailCall || isByVal)) {
1913       assert(VA.isMemLoc());
1914       if (StackPtr.getNode() == 0)
1915         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
1916       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1917                                              dl, DAG, VA, Flags));
1918     }
1919   }
1920
1921   if (!MemOpChains.empty())
1922     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1923                         &MemOpChains[0], MemOpChains.size());
1924
1925   // Build a sequence of copy-to-reg nodes chained together with token chain
1926   // and flag operands which copy the outgoing args into registers.
1927   SDValue InFlag;
1928   // Tail call byval lowering might overwrite argument registers so in case of
1929   // tail call optimization the copies to registers are lowered later.
1930   if (!isTailCall)
1931     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1932       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1933                                RegsToPass[i].second, InFlag);
1934       InFlag = Chain.getValue(1);
1935     }
1936
1937   if (Subtarget->isPICStyleGOT()) {
1938     // ELF / PIC requires GOT in the EBX register before function calls via PLT
1939     // GOT pointer.
1940     if (!isTailCall) {
1941       Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
1942                                DAG.getNode(X86ISD::GlobalBaseReg,
1943                                            DebugLoc(), getPointerTy()),
1944                                InFlag);
1945       InFlag = Chain.getValue(1);
1946     } else {
1947       // If we are tail calling and generating PIC/GOT style code load the
1948       // address of the callee into ECX. The value in ecx is used as target of
1949       // the tail jump. This is done to circumvent the ebx/callee-saved problem
1950       // for tail calls on PIC/GOT architectures. Normally we would just put the
1951       // address of GOT into ebx and then call target@PLT. But for tail calls
1952       // ebx would be restored (since ebx is callee saved) before jumping to the
1953       // target@PLT.
1954
1955       // Note: The actual moving to ECX is done further down.
1956       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1957       if (G && !G->getGlobal()->hasHiddenVisibility() &&
1958           !G->getGlobal()->hasProtectedVisibility())
1959         Callee = LowerGlobalAddress(Callee, DAG);
1960       else if (isa<ExternalSymbolSDNode>(Callee))
1961         Callee = LowerExternalSymbol(Callee, DAG);
1962     }
1963   }
1964
1965   if (Is64Bit && isVarArg) {
1966     // From AMD64 ABI document:
1967     // For calls that may call functions that use varargs or stdargs
1968     // (prototype-less calls or calls to functions containing ellipsis (...) in
1969     // the declaration) %al is used as hidden argument to specify the number
1970     // of SSE registers used. The contents of %al do not need to match exactly
1971     // the number of registers, but must be an ubound on the number of SSE
1972     // registers used and is in the range 0 - 8 inclusive.
1973
1974     // FIXME: Verify this on Win64
1975     // Count the number of XMM registers allocated.
1976     static const unsigned XMMArgRegs[] = {
1977       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1978       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1979     };
1980     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1981     assert((Subtarget->hasSSE1() || !NumXMMRegs)
1982            && "SSE registers cannot be used when SSE is disabled");
1983
1984     Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
1985                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1986     InFlag = Chain.getValue(1);
1987   }
1988
1989
1990   // For tail calls lower the arguments to the 'real' stack slot.
1991   if (isTailCall) {
1992     // Force all the incoming stack arguments to be loaded from the stack
1993     // before any new outgoing arguments are stored to the stack, because the
1994     // outgoing stack slots may alias the incoming argument stack slots, and
1995     // the alias isn't otherwise explicit. This is slightly more conservative
1996     // than necessary, because it means that each store effectively depends
1997     // on every argument instead of just those arguments it would clobber.
1998     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
1999
2000     SmallVector<SDValue, 8> MemOpChains2;
2001     SDValue FIN;
2002     int FI = 0;
2003     // Do not flag preceeding copytoreg stuff together with the following stuff.
2004     InFlag = SDValue();
2005     if (GuaranteedTailCallOpt) {
2006       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2007         CCValAssign &VA = ArgLocs[i];
2008         if (VA.isRegLoc())
2009           continue;
2010         assert(VA.isMemLoc());
2011         SDValue Arg = Outs[i].Val;
2012         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2013         // Create frame index.
2014         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2015         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2016         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2017         FIN = DAG.getFrameIndex(FI, getPointerTy());
2018
2019         if (Flags.isByVal()) {
2020           // Copy relative to framepointer.
2021           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2022           if (StackPtr.getNode() == 0)
2023             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2024                                           getPointerTy());
2025           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2026
2027           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2028                                                            ArgChain,
2029                                                            Flags, DAG, dl));
2030         } else {
2031           // Store relative to framepointer.
2032           MemOpChains2.push_back(
2033             DAG.getStore(ArgChain, dl, Arg, FIN,
2034                          PseudoSourceValue::getFixedStack(FI), 0,
2035                          false, false, 0));
2036         }
2037       }
2038     }
2039
2040     if (!MemOpChains2.empty())
2041       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2042                           &MemOpChains2[0], MemOpChains2.size());
2043
2044     // Copy arguments to their registers.
2045     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2046       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2047                                RegsToPass[i].second, InFlag);
2048       InFlag = Chain.getValue(1);
2049     }
2050     InFlag =SDValue();
2051
2052     // Store the return address to the appropriate stack slot.
2053     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2054                                      FPDiff, dl);
2055   }
2056
2057   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2058     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2059     // In the 64-bit large code model, we have to make all calls
2060     // through a register, since the call instruction's 32-bit
2061     // pc-relative offset may not be large enough to hold the whole
2062     // address.
2063   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2064     // If the callee is a GlobalAddress node (quite common, every direct call
2065     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2066     // it.
2067
2068     // We should use extra load for direct calls to dllimported functions in
2069     // non-JIT mode.
2070     const GlobalValue *GV = G->getGlobal();
2071     if (!GV->hasDLLImportLinkage()) {
2072       unsigned char OpFlags = 0;
2073
2074       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2075       // external symbols most go through the PLT in PIC mode.  If the symbol
2076       // has hidden or protected visibility, or if it is static or local, then
2077       // we don't need to use the PLT - we can directly call it.
2078       if (Subtarget->isTargetELF() &&
2079           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2080           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2081         OpFlags = X86II::MO_PLT;
2082       } else if (Subtarget->isPICStyleStubAny() &&
2083                (GV->isDeclaration() || GV->isWeakForLinker()) &&
2084                Subtarget->getDarwinVers() < 9) {
2085         // PC-relative references to external symbols should go through $stub,
2086         // unless we're building with the leopard linker or later, which
2087         // automatically synthesizes these stubs.
2088         OpFlags = X86II::MO_DARWIN_STUB;
2089       }
2090
2091       Callee = DAG.getTargetGlobalAddress(GV, getPointerTy(),
2092                                           G->getOffset(), OpFlags);
2093     }
2094   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2095     unsigned char OpFlags = 0;
2096
2097     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to external
2098     // symbols should go through the PLT.
2099     if (Subtarget->isTargetELF() &&
2100         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2101       OpFlags = X86II::MO_PLT;
2102     } else if (Subtarget->isPICStyleStubAny() &&
2103              Subtarget->getDarwinVers() < 9) {
2104       // PC-relative references to external symbols should go through $stub,
2105       // unless we're building with the leopard linker or later, which
2106       // automatically synthesizes these stubs.
2107       OpFlags = X86II::MO_DARWIN_STUB;
2108     }
2109
2110     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2111                                          OpFlags);
2112   }
2113
2114   // Returns a chain & a flag for retval copy to use.
2115   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
2116   SmallVector<SDValue, 8> Ops;
2117
2118   if (!IsSibcall && isTailCall) {
2119     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2120                            DAG.getIntPtrConstant(0, true), InFlag);
2121     InFlag = Chain.getValue(1);
2122   }
2123
2124   Ops.push_back(Chain);
2125   Ops.push_back(Callee);
2126
2127   if (isTailCall)
2128     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2129
2130   // Add argument registers to the end of the list so that they are known live
2131   // into the call.
2132   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2133     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2134                                   RegsToPass[i].second.getValueType()));
2135
2136   // Add an implicit use GOT pointer in EBX.
2137   if (!isTailCall && Subtarget->isPICStyleGOT())
2138     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2139
2140   // Add an implicit use of AL for x86 vararg functions.
2141   if (Is64Bit && isVarArg)
2142     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2143
2144   if (InFlag.getNode())
2145     Ops.push_back(InFlag);
2146
2147   if (isTailCall) {
2148     // We used to do:
2149     //// If this is the first return lowered for this function, add the regs
2150     //// to the liveout set for the function.
2151     // This isn't right, although it's probably harmless on x86; liveouts
2152     // should be computed from returns not tail calls.  Consider a void
2153     // function making a tail call to a function returning int.
2154     return DAG.getNode(X86ISD::TC_RETURN, dl,
2155                        NodeTys, &Ops[0], Ops.size());
2156   }
2157
2158   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2159   InFlag = Chain.getValue(1);
2160
2161   // Create the CALLSEQ_END node.
2162   unsigned NumBytesForCalleeToPush;
2163   if (Subtarget->IsCalleePop(isVarArg, CallConv))
2164     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2165   else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2166     // If this is a call to a struct-return function, the callee
2167     // pops the hidden struct pointer, so we have to push it back.
2168     // This is common for Darwin/X86, Linux & Mingw32 targets.
2169     NumBytesForCalleeToPush = 4;
2170   else
2171     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2172
2173   // Returns a flag for retval copy to use.
2174   if (!IsSibcall) {
2175     Chain = DAG.getCALLSEQ_END(Chain,
2176                                DAG.getIntPtrConstant(NumBytes, true),
2177                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2178                                                      true),
2179                                InFlag);
2180     InFlag = Chain.getValue(1);
2181   }
2182
2183   // Handle result values, copying them out of physregs into vregs that we
2184   // return.
2185   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2186                          Ins, dl, DAG, InVals);
2187 }
2188
2189
2190 //===----------------------------------------------------------------------===//
2191 //                Fast Calling Convention (tail call) implementation
2192 //===----------------------------------------------------------------------===//
2193
2194 //  Like std call, callee cleans arguments, convention except that ECX is
2195 //  reserved for storing the tail called function address. Only 2 registers are
2196 //  free for argument passing (inreg). Tail call optimization is performed
2197 //  provided:
2198 //                * tailcallopt is enabled
2199 //                * caller/callee are fastcc
2200 //  On X86_64 architecture with GOT-style position independent code only local
2201 //  (within module) calls are supported at the moment.
2202 //  To keep the stack aligned according to platform abi the function
2203 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2204 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2205 //  If a tail called function callee has more arguments than the caller the
2206 //  caller needs to make sure that there is room to move the RETADDR to. This is
2207 //  achieved by reserving an area the size of the argument delta right after the
2208 //  original REtADDR, but before the saved framepointer or the spilled registers
2209 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2210 //  stack layout:
2211 //    arg1
2212 //    arg2
2213 //    RETADDR
2214 //    [ new RETADDR
2215 //      move area ]
2216 //    (possible EBP)
2217 //    ESI
2218 //    EDI
2219 //    local1 ..
2220
2221 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2222 /// for a 16 byte align requirement.
2223 unsigned
2224 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2225                                                SelectionDAG& DAG) const {
2226   MachineFunction &MF = DAG.getMachineFunction();
2227   const TargetMachine &TM = MF.getTarget();
2228   const TargetFrameInfo &TFI = *TM.getFrameInfo();
2229   unsigned StackAlignment = TFI.getStackAlignment();
2230   uint64_t AlignMask = StackAlignment - 1;
2231   int64_t Offset = StackSize;
2232   uint64_t SlotSize = TD->getPointerSize();
2233   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2234     // Number smaller than 12 so just add the difference.
2235     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2236   } else {
2237     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2238     Offset = ((~AlignMask) & Offset) + StackAlignment +
2239       (StackAlignment-SlotSize);
2240   }
2241   return Offset;
2242 }
2243
2244 /// MatchingStackOffset - Return true if the given stack call argument is
2245 /// already available in the same position (relatively) of the caller's
2246 /// incoming argument stack.
2247 static
2248 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2249                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2250                          const X86InstrInfo *TII) {
2251   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2252   int FI = INT_MAX;
2253   if (Arg.getOpcode() == ISD::CopyFromReg) {
2254     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2255     if (!VR || TargetRegisterInfo::isPhysicalRegister(VR))
2256       return false;
2257     MachineInstr *Def = MRI->getVRegDef(VR);
2258     if (!Def)
2259       return false;
2260     if (!Flags.isByVal()) {
2261       if (!TII->isLoadFromStackSlot(Def, FI))
2262         return false;
2263     } else {
2264       unsigned Opcode = Def->getOpcode();
2265       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2266           Def->getOperand(1).isFI()) {
2267         FI = Def->getOperand(1).getIndex();
2268         Bytes = Flags.getByValSize();
2269       } else
2270         return false;
2271     }
2272   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2273     if (Flags.isByVal())
2274       // ByVal argument is passed in as a pointer but it's now being
2275       // dereferenced. e.g.
2276       // define @foo(%struct.X* %A) {
2277       //   tail call @bar(%struct.X* byval %A)
2278       // }
2279       return false;
2280     SDValue Ptr = Ld->getBasePtr();
2281     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2282     if (!FINode)
2283       return false;
2284     FI = FINode->getIndex();
2285   } else
2286     return false;
2287
2288   assert(FI != INT_MAX);
2289   if (!MFI->isFixedObjectIndex(FI))
2290     return false;
2291   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2292 }
2293
2294 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2295 /// for tail call optimization. Targets which want to do tail call
2296 /// optimization should implement this function.
2297 bool
2298 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2299                                                      CallingConv::ID CalleeCC,
2300                                                      bool isVarArg,
2301                                                      bool isCalleeStructRet,
2302                                                      bool isCallerStructRet,
2303                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2304                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2305                                                      SelectionDAG& DAG) const {
2306   if (!IsTailCallConvention(CalleeCC) &&
2307       CalleeCC != CallingConv::C)
2308     return false;
2309
2310   // If -tailcallopt is specified, make fastcc functions tail-callable.
2311   const MachineFunction &MF = DAG.getMachineFunction();
2312   const Function *CallerF = DAG.getMachineFunction().getFunction();
2313   CallingConv::ID CallerCC = CallerF->getCallingConv();
2314   bool CCMatch = CallerCC == CalleeCC;
2315
2316   if (GuaranteedTailCallOpt) {
2317     if (IsTailCallConvention(CalleeCC) && CCMatch)
2318       return true;
2319     return false;
2320   }
2321
2322   // Look for obvious safe cases to perform tail call optimization that do not
2323   // require ABI changes. This is what gcc calls sibcall.
2324
2325   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2326   // emit a special epilogue.
2327   if (RegInfo->needsStackRealignment(MF))
2328     return false;
2329
2330   // Do not sibcall optimize vararg calls unless the call site is not passing any
2331   // arguments.
2332   if (isVarArg && !Outs.empty())
2333     return false;
2334
2335   // Also avoid sibcall optimization if either caller or callee uses struct
2336   // return semantics.
2337   if (isCalleeStructRet || isCallerStructRet)
2338     return false;
2339
2340   // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2341   // Therefore if it's not used by the call it is not safe to optimize this into
2342   // a sibcall.
2343   bool Unused = false;
2344   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2345     if (!Ins[i].Used) {
2346       Unused = true;
2347       break;
2348     }
2349   }
2350   if (Unused) {
2351     SmallVector<CCValAssign, 16> RVLocs;
2352     CCState CCInfo(CalleeCC, false, getTargetMachine(),
2353                    RVLocs, *DAG.getContext());
2354     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2355     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2356       CCValAssign &VA = RVLocs[i];
2357       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2358         return false;
2359     }
2360   }
2361
2362   // If the calling conventions do not match, then we'd better make sure the
2363   // results are returned in the same way as what the caller expects.
2364   if (!CCMatch) {
2365     SmallVector<CCValAssign, 16> RVLocs1;
2366     CCState CCInfo1(CalleeCC, false, getTargetMachine(),
2367                     RVLocs1, *DAG.getContext());
2368     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2369
2370     SmallVector<CCValAssign, 16> RVLocs2;
2371     CCState CCInfo2(CallerCC, false, getTargetMachine(),
2372                     RVLocs2, *DAG.getContext());
2373     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2374
2375     if (RVLocs1.size() != RVLocs2.size())
2376       return false;
2377     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2378       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2379         return false;
2380       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2381         return false;
2382       if (RVLocs1[i].isRegLoc()) {
2383         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2384           return false;
2385       } else {
2386         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2387           return false;
2388       }
2389     }
2390   }
2391
2392   // If the callee takes no arguments then go on to check the results of the
2393   // call.
2394   if (!Outs.empty()) {
2395     // Check if stack adjustment is needed. For now, do not do this if any
2396     // argument is passed on the stack.
2397     SmallVector<CCValAssign, 16> ArgLocs;
2398     CCState CCInfo(CalleeCC, isVarArg, getTargetMachine(),
2399                    ArgLocs, *DAG.getContext());
2400     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CalleeCC));
2401     if (CCInfo.getNextStackOffset()) {
2402       MachineFunction &MF = DAG.getMachineFunction();
2403       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2404         return false;
2405       if (Subtarget->isTargetWin64())
2406         // Win64 ABI has additional complications.
2407         return false;
2408
2409       // Check if the arguments are already laid out in the right way as
2410       // the caller's fixed stack objects.
2411       MachineFrameInfo *MFI = MF.getFrameInfo();
2412       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2413       const X86InstrInfo *TII =
2414         ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2415       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2416         CCValAssign &VA = ArgLocs[i];
2417         SDValue Arg = Outs[i].Val;
2418         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2419         if (VA.getLocInfo() == CCValAssign::Indirect)
2420           return false;
2421         if (!VA.isRegLoc()) {
2422           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2423                                    MFI, MRI, TII))
2424             return false;
2425         }
2426       }
2427     }
2428
2429     // If the tailcall address may be in a register, then make sure it's
2430     // possible to register allocate for it. In 32-bit, the call address can
2431     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2432     // callee-saved registers are restored. In 64-bit, it's RAX, RCX, RDX, RSI,
2433     // RDI, R8, R9, R11.
2434     if (!isa<GlobalAddressSDNode>(Callee) &&
2435         !isa<ExternalSymbolSDNode>(Callee)) {
2436       unsigned Limit = Subtarget->is64Bit() ? 8 : 3;
2437       unsigned NumInRegs = 0;
2438       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2439         CCValAssign &VA = ArgLocs[i];
2440         if (VA.isRegLoc()) {
2441           if (++NumInRegs == Limit)
2442             return false;
2443         }
2444       }
2445     }
2446   }
2447
2448   return true;
2449 }
2450
2451 FastISel *
2452 X86TargetLowering::createFastISel(MachineFunction &mf,
2453                             DenseMap<const Value *, unsigned> &vm,
2454                             DenseMap<const BasicBlock*, MachineBasicBlock*> &bm,
2455                             DenseMap<const AllocaInst *, int> &am,
2456                             std::vector<std::pair<MachineInstr*, unsigned> > &pn
2457 #ifndef NDEBUG
2458                           , SmallSet<const Instruction *, 8> &cil
2459 #endif
2460                                   ) const {
2461   return X86::createFastISel(mf, vm, bm, am, pn
2462 #ifndef NDEBUG
2463                              , cil
2464 #endif
2465                              );
2466 }
2467
2468
2469 //===----------------------------------------------------------------------===//
2470 //                           Other Lowering Hooks
2471 //===----------------------------------------------------------------------===//
2472
2473
2474 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2475   MachineFunction &MF = DAG.getMachineFunction();
2476   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2477   int ReturnAddrIndex = FuncInfo->getRAIndex();
2478
2479   if (ReturnAddrIndex == 0) {
2480     // Set up a frame object for the return address.
2481     uint64_t SlotSize = TD->getPointerSize();
2482     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2483                                                            false);
2484     FuncInfo->setRAIndex(ReturnAddrIndex);
2485   }
2486
2487   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2488 }
2489
2490
2491 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2492                                        bool hasSymbolicDisplacement) {
2493   // Offset should fit into 32 bit immediate field.
2494   if (!isInt<32>(Offset))
2495     return false;
2496
2497   // If we don't have a symbolic displacement - we don't have any extra
2498   // restrictions.
2499   if (!hasSymbolicDisplacement)
2500     return true;
2501
2502   // FIXME: Some tweaks might be needed for medium code model.
2503   if (M != CodeModel::Small && M != CodeModel::Kernel)
2504     return false;
2505
2506   // For small code model we assume that latest object is 16MB before end of 31
2507   // bits boundary. We may also accept pretty large negative constants knowing
2508   // that all objects are in the positive half of address space.
2509   if (M == CodeModel::Small && Offset < 16*1024*1024)
2510     return true;
2511
2512   // For kernel code model we know that all object resist in the negative half
2513   // of 32bits address space. We may not accept negative offsets, since they may
2514   // be just off and we may accept pretty large positive ones.
2515   if (M == CodeModel::Kernel && Offset > 0)
2516     return true;
2517
2518   return false;
2519 }
2520
2521 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2522 /// specific condition code, returning the condition code and the LHS/RHS of the
2523 /// comparison to make.
2524 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2525                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2526   if (!isFP) {
2527     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2528       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2529         // X > -1   -> X == 0, jump !sign.
2530         RHS = DAG.getConstant(0, RHS.getValueType());
2531         return X86::COND_NS;
2532       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2533         // X < 0   -> X == 0, jump on sign.
2534         return X86::COND_S;
2535       } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2536         // X < 1   -> X <= 0
2537         RHS = DAG.getConstant(0, RHS.getValueType());
2538         return X86::COND_LE;
2539       }
2540     }
2541
2542     switch (SetCCOpcode) {
2543     default: llvm_unreachable("Invalid integer condition!");
2544     case ISD::SETEQ:  return X86::COND_E;
2545     case ISD::SETGT:  return X86::COND_G;
2546     case ISD::SETGE:  return X86::COND_GE;
2547     case ISD::SETLT:  return X86::COND_L;
2548     case ISD::SETLE:  return X86::COND_LE;
2549     case ISD::SETNE:  return X86::COND_NE;
2550     case ISD::SETULT: return X86::COND_B;
2551     case ISD::SETUGT: return X86::COND_A;
2552     case ISD::SETULE: return X86::COND_BE;
2553     case ISD::SETUGE: return X86::COND_AE;
2554     }
2555   }
2556
2557   // First determine if it is required or is profitable to flip the operands.
2558
2559   // If LHS is a foldable load, but RHS is not, flip the condition.
2560   if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2561       !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2562     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2563     std::swap(LHS, RHS);
2564   }
2565
2566   switch (SetCCOpcode) {
2567   default: break;
2568   case ISD::SETOLT:
2569   case ISD::SETOLE:
2570   case ISD::SETUGT:
2571   case ISD::SETUGE:
2572     std::swap(LHS, RHS);
2573     break;
2574   }
2575
2576   // On a floating point condition, the flags are set as follows:
2577   // ZF  PF  CF   op
2578   //  0 | 0 | 0 | X > Y
2579   //  0 | 0 | 1 | X < Y
2580   //  1 | 0 | 0 | X == Y
2581   //  1 | 1 | 1 | unordered
2582   switch (SetCCOpcode) {
2583   default: llvm_unreachable("Condcode should be pre-legalized away");
2584   case ISD::SETUEQ:
2585   case ISD::SETEQ:   return X86::COND_E;
2586   case ISD::SETOLT:              // flipped
2587   case ISD::SETOGT:
2588   case ISD::SETGT:   return X86::COND_A;
2589   case ISD::SETOLE:              // flipped
2590   case ISD::SETOGE:
2591   case ISD::SETGE:   return X86::COND_AE;
2592   case ISD::SETUGT:              // flipped
2593   case ISD::SETULT:
2594   case ISD::SETLT:   return X86::COND_B;
2595   case ISD::SETUGE:              // flipped
2596   case ISD::SETULE:
2597   case ISD::SETLE:   return X86::COND_BE;
2598   case ISD::SETONE:
2599   case ISD::SETNE:   return X86::COND_NE;
2600   case ISD::SETUO:   return X86::COND_P;
2601   case ISD::SETO:    return X86::COND_NP;
2602   case ISD::SETOEQ:
2603   case ISD::SETUNE:  return X86::COND_INVALID;
2604   }
2605 }
2606
2607 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2608 /// code. Current x86 isa includes the following FP cmov instructions:
2609 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2610 static bool hasFPCMov(unsigned X86CC) {
2611   switch (X86CC) {
2612   default:
2613     return false;
2614   case X86::COND_B:
2615   case X86::COND_BE:
2616   case X86::COND_E:
2617   case X86::COND_P:
2618   case X86::COND_A:
2619   case X86::COND_AE:
2620   case X86::COND_NE:
2621   case X86::COND_NP:
2622     return true;
2623   }
2624 }
2625
2626 /// isFPImmLegal - Returns true if the target can instruction select the
2627 /// specified FP immediate natively. If false, the legalizer will
2628 /// materialize the FP immediate as a load from a constant pool.
2629 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2630   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
2631     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
2632       return true;
2633   }
2634   return false;
2635 }
2636
2637 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2638 /// the specified range (L, H].
2639 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2640   return (Val < 0) || (Val >= Low && Val < Hi);
2641 }
2642
2643 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2644 /// specified value.
2645 static bool isUndefOrEqual(int Val, int CmpVal) {
2646   if (Val < 0 || Val == CmpVal)
2647     return true;
2648   return false;
2649 }
2650
2651 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2652 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
2653 /// the second operand.
2654 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2655   if (VT == MVT::v4f32 || VT == MVT::v4i32 || VT == MVT::v4i16)
2656     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2657   if (VT == MVT::v2f64 || VT == MVT::v2i64)
2658     return (Mask[0] < 2 && Mask[1] < 2);
2659   return false;
2660 }
2661
2662 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2663   SmallVector<int, 8> M;
2664   N->getMask(M);
2665   return ::isPSHUFDMask(M, N->getValueType(0));
2666 }
2667
2668 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2669 /// is suitable for input to PSHUFHW.
2670 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2671   if (VT != MVT::v8i16)
2672     return false;
2673
2674   // Lower quadword copied in order or undef.
2675   for (int i = 0; i != 4; ++i)
2676     if (Mask[i] >= 0 && Mask[i] != i)
2677       return false;
2678
2679   // Upper quadword shuffled.
2680   for (int i = 4; i != 8; ++i)
2681     if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2682       return false;
2683
2684   return true;
2685 }
2686
2687 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2688   SmallVector<int, 8> M;
2689   N->getMask(M);
2690   return ::isPSHUFHWMask(M, N->getValueType(0));
2691 }
2692
2693 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
2694 /// is suitable for input to PSHUFLW.
2695 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2696   if (VT != MVT::v8i16)
2697     return false;
2698
2699   // Upper quadword copied in order.
2700   for (int i = 4; i != 8; ++i)
2701     if (Mask[i] >= 0 && Mask[i] != i)
2702       return false;
2703
2704   // Lower quadword shuffled.
2705   for (int i = 0; i != 4; ++i)
2706     if (Mask[i] >= 4)
2707       return false;
2708
2709   return true;
2710 }
2711
2712 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
2713   SmallVector<int, 8> M;
2714   N->getMask(M);
2715   return ::isPSHUFLWMask(M, N->getValueType(0));
2716 }
2717
2718 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
2719 /// is suitable for input to PALIGNR.
2720 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
2721                           bool hasSSSE3) {
2722   int i, e = VT.getVectorNumElements();
2723   
2724   // Do not handle v2i64 / v2f64 shuffles with palignr.
2725   if (e < 4 || !hasSSSE3)
2726     return false;
2727   
2728   for (i = 0; i != e; ++i)
2729     if (Mask[i] >= 0)
2730       break;
2731   
2732   // All undef, not a palignr.
2733   if (i == e)
2734     return false;
2735
2736   // Determine if it's ok to perform a palignr with only the LHS, since we
2737   // don't have access to the actual shuffle elements to see if RHS is undef.
2738   bool Unary = Mask[i] < (int)e;
2739   bool NeedsUnary = false;
2740
2741   int s = Mask[i] - i;
2742   
2743   // Check the rest of the elements to see if they are consecutive.
2744   for (++i; i != e; ++i) {
2745     int m = Mask[i];
2746     if (m < 0) 
2747       continue;
2748     
2749     Unary = Unary && (m < (int)e);
2750     NeedsUnary = NeedsUnary || (m < s);
2751
2752     if (NeedsUnary && !Unary)
2753       return false;
2754     if (Unary && m != ((s+i) & (e-1)))
2755       return false;
2756     if (!Unary && m != (s+i))
2757       return false;
2758   }
2759   return true;
2760 }
2761
2762 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
2763   SmallVector<int, 8> M;
2764   N->getMask(M);
2765   return ::isPALIGNRMask(M, N->getValueType(0), true);
2766 }
2767
2768 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2769 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2770 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2771   int NumElems = VT.getVectorNumElements();
2772   if (NumElems != 2 && NumElems != 4)
2773     return false;
2774
2775   int Half = NumElems / 2;
2776   for (int i = 0; i < Half; ++i)
2777     if (!isUndefOrInRange(Mask[i], 0, NumElems))
2778       return false;
2779   for (int i = Half; i < NumElems; ++i)
2780     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2781       return false;
2782
2783   return true;
2784 }
2785
2786 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
2787   SmallVector<int, 8> M;
2788   N->getMask(M);
2789   return ::isSHUFPMask(M, N->getValueType(0));
2790 }
2791
2792 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2793 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2794 /// half elements to come from vector 1 (which would equal the dest.) and
2795 /// the upper half to come from vector 2.
2796 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2797   int NumElems = VT.getVectorNumElements();
2798
2799   if (NumElems != 2 && NumElems != 4)
2800     return false;
2801
2802   int Half = NumElems / 2;
2803   for (int i = 0; i < Half; ++i)
2804     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2805       return false;
2806   for (int i = Half; i < NumElems; ++i)
2807     if (!isUndefOrInRange(Mask[i], 0, NumElems))
2808       return false;
2809   return true;
2810 }
2811
2812 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
2813   SmallVector<int, 8> M;
2814   N->getMask(M);
2815   return isCommutedSHUFPMask(M, N->getValueType(0));
2816 }
2817
2818 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2819 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2820 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
2821   if (N->getValueType(0).getVectorNumElements() != 4)
2822     return false;
2823
2824   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2825   return isUndefOrEqual(N->getMaskElt(0), 6) &&
2826          isUndefOrEqual(N->getMaskElt(1), 7) &&
2827          isUndefOrEqual(N->getMaskElt(2), 2) &&
2828          isUndefOrEqual(N->getMaskElt(3), 3);
2829 }
2830
2831 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2832 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2833 /// <2, 3, 2, 3>
2834 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
2835   unsigned NumElems = N->getValueType(0).getVectorNumElements();
2836   
2837   if (NumElems != 4)
2838     return false;
2839   
2840   return isUndefOrEqual(N->getMaskElt(0), 2) &&
2841   isUndefOrEqual(N->getMaskElt(1), 3) &&
2842   isUndefOrEqual(N->getMaskElt(2), 2) &&
2843   isUndefOrEqual(N->getMaskElt(3), 3);
2844 }
2845
2846 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2847 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2848 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
2849   unsigned NumElems = N->getValueType(0).getVectorNumElements();
2850
2851   if (NumElems != 2 && NumElems != 4)
2852     return false;
2853
2854   for (unsigned i = 0; i < NumElems/2; ++i)
2855     if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
2856       return false;
2857
2858   for (unsigned i = NumElems/2; i < NumElems; ++i)
2859     if (!isUndefOrEqual(N->getMaskElt(i), i))
2860       return false;
2861
2862   return true;
2863 }
2864
2865 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
2866 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
2867 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
2868   unsigned NumElems = N->getValueType(0).getVectorNumElements();
2869
2870   if (NumElems != 2 && NumElems != 4)
2871     return false;
2872
2873   for (unsigned i = 0; i < NumElems/2; ++i)
2874     if (!isUndefOrEqual(N->getMaskElt(i), i))
2875       return false;
2876
2877   for (unsigned i = 0; i < NumElems/2; ++i)
2878     if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
2879       return false;
2880
2881   return true;
2882 }
2883
2884 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2885 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2886 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
2887                          bool V2IsSplat = false) {
2888   int NumElts = VT.getVectorNumElements();
2889   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2890     return false;
2891
2892   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2893     int BitI  = Mask[i];
2894     int BitI1 = Mask[i+1];
2895     if (!isUndefOrEqual(BitI, j))
2896       return false;
2897     if (V2IsSplat) {
2898       if (!isUndefOrEqual(BitI1, NumElts))
2899         return false;
2900     } else {
2901       if (!isUndefOrEqual(BitI1, j + NumElts))
2902         return false;
2903     }
2904   }
2905   return true;
2906 }
2907
2908 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2909   SmallVector<int, 8> M;
2910   N->getMask(M);
2911   return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
2912 }
2913
2914 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2915 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2916 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
2917                          bool V2IsSplat = false) {
2918   int NumElts = VT.getVectorNumElements();
2919   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2920     return false;
2921
2922   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2923     int BitI  = Mask[i];
2924     int BitI1 = Mask[i+1];
2925     if (!isUndefOrEqual(BitI, j + NumElts/2))
2926       return false;
2927     if (V2IsSplat) {
2928       if (isUndefOrEqual(BitI1, NumElts))
2929         return false;
2930     } else {
2931       if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2932         return false;
2933     }
2934   }
2935   return true;
2936 }
2937
2938 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2939   SmallVector<int, 8> M;
2940   N->getMask(M);
2941   return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
2942 }
2943
2944 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2945 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2946 /// <0, 0, 1, 1>
2947 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
2948   int NumElems = VT.getVectorNumElements();
2949   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2950     return false;
2951
2952   for (int i = 0, j = 0; i != NumElems; i += 2, ++j) {
2953     int BitI  = Mask[i];
2954     int BitI1 = Mask[i+1];
2955     if (!isUndefOrEqual(BitI, j))
2956       return false;
2957     if (!isUndefOrEqual(BitI1, j))
2958       return false;
2959   }
2960   return true;
2961 }
2962
2963 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
2964   SmallVector<int, 8> M;
2965   N->getMask(M);
2966   return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
2967 }
2968
2969 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2970 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2971 /// <2, 2, 3, 3>
2972 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
2973   int NumElems = VT.getVectorNumElements();
2974   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2975     return false;
2976
2977   for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2978     int BitI  = Mask[i];
2979     int BitI1 = Mask[i+1];
2980     if (!isUndefOrEqual(BitI, j))
2981       return false;
2982     if (!isUndefOrEqual(BitI1, j))
2983       return false;
2984   }
2985   return true;
2986 }
2987
2988 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
2989   SmallVector<int, 8> M;
2990   N->getMask(M);
2991   return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
2992 }
2993
2994 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2995 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2996 /// MOVSD, and MOVD, i.e. setting the lowest element.
2997 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2998   if (VT.getVectorElementType().getSizeInBits() < 32)
2999     return false;
3000
3001   int NumElts = VT.getVectorNumElements();
3002
3003   if (!isUndefOrEqual(Mask[0], NumElts))
3004     return false;
3005
3006   for (int i = 1; i < NumElts; ++i)
3007     if (!isUndefOrEqual(Mask[i], i))
3008       return false;
3009
3010   return true;
3011 }
3012
3013 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3014   SmallVector<int, 8> M;
3015   N->getMask(M);
3016   return ::isMOVLMask(M, N->getValueType(0));
3017 }
3018
3019 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3020 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3021 /// element of vector 2 and the other elements to come from vector 1 in order.
3022 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3023                                bool V2IsSplat = false, bool V2IsUndef = false) {
3024   int NumOps = VT.getVectorNumElements();
3025   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3026     return false;
3027
3028   if (!isUndefOrEqual(Mask[0], 0))
3029     return false;
3030
3031   for (int i = 1; i < NumOps; ++i)
3032     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3033           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3034           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3035       return false;
3036
3037   return true;
3038 }
3039
3040 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3041                            bool V2IsUndef = false) {
3042   SmallVector<int, 8> M;
3043   N->getMask(M);
3044   return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3045 }
3046
3047 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3048 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3049 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
3050   if (N->getValueType(0).getVectorNumElements() != 4)
3051     return false;
3052
3053   // Expect 1, 1, 3, 3
3054   for (unsigned i = 0; i < 2; ++i) {
3055     int Elt = N->getMaskElt(i);
3056     if (Elt >= 0 && Elt != 1)
3057       return false;
3058   }
3059
3060   bool HasHi = false;
3061   for (unsigned i = 2; i < 4; ++i) {
3062     int Elt = N->getMaskElt(i);
3063     if (Elt >= 0 && Elt != 3)
3064       return false;
3065     if (Elt == 3)
3066       HasHi = true;
3067   }
3068   // Don't use movshdup if it can be done with a shufps.
3069   // FIXME: verify that matching u, u, 3, 3 is what we want.
3070   return HasHi;
3071 }
3072
3073 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3074 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3075 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
3076   if (N->getValueType(0).getVectorNumElements() != 4)
3077     return false;
3078
3079   // Expect 0, 0, 2, 2
3080   for (unsigned i = 0; i < 2; ++i)
3081     if (N->getMaskElt(i) > 0)
3082       return false;
3083
3084   bool HasHi = false;
3085   for (unsigned i = 2; i < 4; ++i) {
3086     int Elt = N->getMaskElt(i);
3087     if (Elt >= 0 && Elt != 2)
3088       return false;
3089     if (Elt == 2)
3090       HasHi = true;
3091   }
3092   // Don't use movsldup if it can be done with a shufps.
3093   return HasHi;
3094 }
3095
3096 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3097 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3098 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3099   int e = N->getValueType(0).getVectorNumElements() / 2;
3100
3101   for (int i = 0; i < e; ++i)
3102     if (!isUndefOrEqual(N->getMaskElt(i), i))
3103       return false;
3104   for (int i = 0; i < e; ++i)
3105     if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3106       return false;
3107   return true;
3108 }
3109
3110 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3111 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3112 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3113   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3114   int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3115
3116   unsigned Shift = (NumOperands == 4) ? 2 : 1;
3117   unsigned Mask = 0;
3118   for (int i = 0; i < NumOperands; ++i) {
3119     int Val = SVOp->getMaskElt(NumOperands-i-1);
3120     if (Val < 0) Val = 0;
3121     if (Val >= NumOperands) Val -= NumOperands;
3122     Mask |= Val;
3123     if (i != NumOperands - 1)
3124       Mask <<= Shift;
3125   }
3126   return Mask;
3127 }
3128
3129 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3130 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3131 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3132   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3133   unsigned Mask = 0;
3134   // 8 nodes, but we only care about the last 4.
3135   for (unsigned i = 7; i >= 4; --i) {
3136     int Val = SVOp->getMaskElt(i);
3137     if (Val >= 0)
3138       Mask |= (Val - 4);
3139     if (i != 4)
3140       Mask <<= 2;
3141   }
3142   return Mask;
3143 }
3144
3145 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3146 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3147 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3148   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3149   unsigned Mask = 0;
3150   // 8 nodes, but we only care about the first 4.
3151   for (int i = 3; i >= 0; --i) {
3152     int Val = SVOp->getMaskElt(i);
3153     if (Val >= 0)
3154       Mask |= Val;
3155     if (i != 0)
3156       Mask <<= 2;
3157   }
3158   return Mask;
3159 }
3160
3161 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3162 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3163 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3164   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3165   EVT VVT = N->getValueType(0);
3166   unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3167   int Val = 0;
3168
3169   unsigned i, e;
3170   for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3171     Val = SVOp->getMaskElt(i);
3172     if (Val >= 0)
3173       break;
3174   }
3175   return (Val - i) * EltSize;
3176 }
3177
3178 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3179 /// constant +0.0.
3180 bool X86::isZeroNode(SDValue Elt) {
3181   return ((isa<ConstantSDNode>(Elt) &&
3182            cast<ConstantSDNode>(Elt)->isNullValue()) ||
3183           (isa<ConstantFPSDNode>(Elt) &&
3184            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3185 }
3186
3187 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3188 /// their permute mask.
3189 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3190                                     SelectionDAG &DAG) {
3191   EVT VT = SVOp->getValueType(0);
3192   unsigned NumElems = VT.getVectorNumElements();
3193   SmallVector<int, 8> MaskVec;
3194
3195   for (unsigned i = 0; i != NumElems; ++i) {
3196     int idx = SVOp->getMaskElt(i);
3197     if (idx < 0)
3198       MaskVec.push_back(idx);
3199     else if (idx < (int)NumElems)
3200       MaskVec.push_back(idx + NumElems);
3201     else
3202       MaskVec.push_back(idx - NumElems);
3203   }
3204   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3205                               SVOp->getOperand(0), &MaskVec[0]);
3206 }
3207
3208 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3209 /// the two vector operands have swapped position.
3210 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3211   unsigned NumElems = VT.getVectorNumElements();
3212   for (unsigned i = 0; i != NumElems; ++i) {
3213     int idx = Mask[i];
3214     if (idx < 0)
3215       continue;
3216     else if (idx < (int)NumElems)
3217       Mask[i] = idx + NumElems;
3218     else
3219       Mask[i] = idx - NumElems;
3220   }
3221 }
3222
3223 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3224 /// match movhlps. The lower half elements should come from upper half of
3225 /// V1 (and in order), and the upper half elements should come from the upper
3226 /// half of V2 (and in order).
3227 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3228   if (Op->getValueType(0).getVectorNumElements() != 4)
3229     return false;
3230   for (unsigned i = 0, e = 2; i != e; ++i)
3231     if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3232       return false;
3233   for (unsigned i = 2; i != 4; ++i)
3234     if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3235       return false;
3236   return true;
3237 }
3238
3239 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3240 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3241 /// required.
3242 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3243   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3244     return false;
3245   N = N->getOperand(0).getNode();
3246   if (!ISD::isNON_EXTLoad(N))
3247     return false;
3248   if (LD)
3249     *LD = cast<LoadSDNode>(N);
3250   return true;
3251 }
3252
3253 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3254 /// match movlp{s|d}. The lower half elements should come from lower half of
3255 /// V1 (and in order), and the upper half elements should come from the upper
3256 /// half of V2 (and in order). And since V1 will become the source of the
3257 /// MOVLP, it must be either a vector load or a scalar load to vector.
3258 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3259                                ShuffleVectorSDNode *Op) {
3260   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3261     return false;
3262   // Is V2 is a vector load, don't do this transformation. We will try to use
3263   // load folding shufps op.
3264   if (ISD::isNON_EXTLoad(V2))
3265     return false;
3266
3267   unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3268
3269   if (NumElems != 2 && NumElems != 4)
3270     return false;
3271   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3272     if (!isUndefOrEqual(Op->getMaskElt(i), i))
3273       return false;
3274   for (unsigned i = NumElems/2; i != NumElems; ++i)
3275     if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3276       return false;
3277   return true;
3278 }
3279
3280 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3281 /// all the same.
3282 static bool isSplatVector(SDNode *N) {
3283   if (N->getOpcode() != ISD::BUILD_VECTOR)
3284     return false;
3285
3286   SDValue SplatValue = N->getOperand(0);
3287   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3288     if (N->getOperand(i) != SplatValue)
3289       return false;
3290   return true;
3291 }
3292
3293 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3294 /// to an zero vector.
3295 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3296 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3297   SDValue V1 = N->getOperand(0);
3298   SDValue V2 = N->getOperand(1);
3299   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3300   for (unsigned i = 0; i != NumElems; ++i) {
3301     int Idx = N->getMaskElt(i);
3302     if (Idx >= (int)NumElems) {
3303       unsigned Opc = V2.getOpcode();
3304       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3305         continue;
3306       if (Opc != ISD::BUILD_VECTOR ||
3307           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3308         return false;
3309     } else if (Idx >= 0) {
3310       unsigned Opc = V1.getOpcode();
3311       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3312         continue;
3313       if (Opc != ISD::BUILD_VECTOR ||
3314           !X86::isZeroNode(V1.getOperand(Idx)))
3315         return false;
3316     }
3317   }
3318   return true;
3319 }
3320
3321 /// getZeroVector - Returns a vector of specified type with all zero elements.
3322 ///
3323 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3324                              DebugLoc dl) {
3325   assert(VT.isVector() && "Expected a vector type");
3326
3327   // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3328   // type.  This ensures they get CSE'd.
3329   SDValue Vec;
3330   if (VT.getSizeInBits() == 64) { // MMX
3331     SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3332     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3333   } else if (HasSSE2) {  // SSE2
3334     SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3335     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3336   } else { // SSE1
3337     SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3338     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3339   }
3340   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3341 }
3342
3343 /// getOnesVector - Returns a vector of specified type with all bits set.
3344 ///
3345 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3346   assert(VT.isVector() && "Expected a vector type");
3347
3348   // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3349   // type.  This ensures they get CSE'd.
3350   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3351   SDValue Vec;
3352   if (VT.getSizeInBits() == 64)  // MMX
3353     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3354   else                                              // SSE
3355     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3356   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3357 }
3358
3359
3360 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3361 /// that point to V2 points to its first element.
3362 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3363   EVT VT = SVOp->getValueType(0);
3364   unsigned NumElems = VT.getVectorNumElements();
3365
3366   bool Changed = false;
3367   SmallVector<int, 8> MaskVec;
3368   SVOp->getMask(MaskVec);
3369
3370   for (unsigned i = 0; i != NumElems; ++i) {
3371     if (MaskVec[i] > (int)NumElems) {
3372       MaskVec[i] = NumElems;
3373       Changed = true;
3374     }
3375   }
3376   if (Changed)
3377     return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3378                                 SVOp->getOperand(1), &MaskVec[0]);
3379   return SDValue(SVOp, 0);
3380 }
3381
3382 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3383 /// operation of specified width.
3384 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3385                        SDValue V2) {
3386   unsigned NumElems = VT.getVectorNumElements();
3387   SmallVector<int, 8> Mask;
3388   Mask.push_back(NumElems);
3389   for (unsigned i = 1; i != NumElems; ++i)
3390     Mask.push_back(i);
3391   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3392 }
3393
3394 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3395 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3396                           SDValue V2) {
3397   unsigned NumElems = VT.getVectorNumElements();
3398   SmallVector<int, 8> Mask;
3399   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3400     Mask.push_back(i);
3401     Mask.push_back(i + NumElems);
3402   }
3403   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3404 }
3405
3406 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3407 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3408                           SDValue V2) {
3409   unsigned NumElems = VT.getVectorNumElements();
3410   unsigned Half = NumElems/2;
3411   SmallVector<int, 8> Mask;
3412   for (unsigned i = 0; i != Half; ++i) {
3413     Mask.push_back(i + Half);
3414     Mask.push_back(i + NumElems + Half);
3415   }
3416   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3417 }
3418
3419 /// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
3420 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG,
3421                             bool HasSSE2) {
3422   if (SV->getValueType(0).getVectorNumElements() <= 4)
3423     return SDValue(SV, 0);
3424
3425   EVT PVT = MVT::v4f32;
3426   EVT VT = SV->getValueType(0);
3427   DebugLoc dl = SV->getDebugLoc();
3428   SDValue V1 = SV->getOperand(0);
3429   int NumElems = VT.getVectorNumElements();
3430   int EltNo = SV->getSplatIndex();
3431
3432   // unpack elements to the correct location
3433   while (NumElems > 4) {
3434     if (EltNo < NumElems/2) {
3435       V1 = getUnpackl(DAG, dl, VT, V1, V1);
3436     } else {
3437       V1 = getUnpackh(DAG, dl, VT, V1, V1);
3438       EltNo -= NumElems/2;
3439     }
3440     NumElems >>= 1;
3441   }
3442
3443   // Perform the splat.
3444   int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3445   V1 = DAG.getNode(ISD::BIT_CONVERT, dl, PVT, V1);
3446   V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3447   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, V1);
3448 }
3449
3450 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3451 /// vector of zero or undef vector.  This produces a shuffle where the low
3452 /// element of V2 is swizzled into the zero/undef vector, landing at element
3453 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
3454 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3455                                              bool isZero, bool HasSSE2,
3456                                              SelectionDAG &DAG) {
3457   EVT VT = V2.getValueType();
3458   SDValue V1 = isZero
3459     ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3460   unsigned NumElems = VT.getVectorNumElements();
3461   SmallVector<int, 16> MaskVec;
3462   for (unsigned i = 0; i != NumElems; ++i)
3463     // If this is the insertion idx, put the low elt of V2 here.
3464     MaskVec.push_back(i == Idx ? NumElems : i);
3465   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3466 }
3467
3468 /// getNumOfConsecutiveZeros - Return the number of elements in a result of
3469 /// a shuffle that is zero.
3470 static
3471 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, int NumElems,
3472                                   bool Low, SelectionDAG &DAG) {
3473   unsigned NumZeros = 0;
3474   for (int i = 0; i < NumElems; ++i) {
3475     unsigned Index = Low ? i : NumElems-i-1;
3476     int Idx = SVOp->getMaskElt(Index);
3477     if (Idx < 0) {
3478       ++NumZeros;
3479       continue;
3480     }
3481     SDValue Elt = DAG.getShuffleScalarElt(SVOp, Index);
3482     if (Elt.getNode() && X86::isZeroNode(Elt))
3483       ++NumZeros;
3484     else
3485       break;
3486   }
3487   return NumZeros;
3488 }
3489
3490 /// isVectorShift - Returns true if the shuffle can be implemented as a
3491 /// logical left or right shift of a vector.
3492 /// FIXME: split into pslldqi, psrldqi, palignr variants.
3493 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3494                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3495   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
3496
3497   isLeft = true;
3498   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, true, DAG);
3499   if (!NumZeros) {
3500     isLeft = false;
3501     NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, false, DAG);
3502     if (!NumZeros)
3503       return false;
3504   }
3505   bool SeenV1 = false;
3506   bool SeenV2 = false;
3507   for (unsigned i = NumZeros; i < NumElems; ++i) {
3508     unsigned Val = isLeft ? (i - NumZeros) : i;
3509     int Idx_ = SVOp->getMaskElt(isLeft ? i : (i - NumZeros));
3510     if (Idx_ < 0)
3511       continue;
3512     unsigned Idx = (unsigned) Idx_;
3513     if (Idx < NumElems)
3514       SeenV1 = true;
3515     else {
3516       Idx -= NumElems;
3517       SeenV2 = true;
3518     }
3519     if (Idx != Val)
3520       return false;
3521   }
3522   if (SeenV1 && SeenV2)
3523     return false;
3524
3525   ShVal = SeenV1 ? SVOp->getOperand(0) : SVOp->getOperand(1);
3526   ShAmt = NumZeros;
3527   return true;
3528 }
3529
3530
3531 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3532 ///
3533 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3534                                        unsigned NumNonZero, unsigned NumZero,
3535                                        SelectionDAG &DAG,
3536                                        const TargetLowering &TLI) {
3537   if (NumNonZero > 8)
3538     return SDValue();
3539
3540   DebugLoc dl = Op.getDebugLoc();
3541   SDValue V(0, 0);
3542   bool First = true;
3543   for (unsigned i = 0; i < 16; ++i) {
3544     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3545     if (ThisIsNonZero && First) {
3546       if (NumZero)
3547         V = getZeroVector(MVT::v8i16, true, DAG, dl);
3548       else
3549         V = DAG.getUNDEF(MVT::v8i16);
3550       First = false;
3551     }
3552
3553     if ((i & 1) != 0) {
3554       SDValue ThisElt(0, 0), LastElt(0, 0);
3555       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3556       if (LastIsNonZero) {
3557         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
3558                               MVT::i16, Op.getOperand(i-1));
3559       }
3560       if (ThisIsNonZero) {
3561         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
3562         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
3563                               ThisElt, DAG.getConstant(8, MVT::i8));
3564         if (LastIsNonZero)
3565           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
3566       } else
3567         ThisElt = LastElt;
3568
3569       if (ThisElt.getNode())
3570         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
3571                         DAG.getIntPtrConstant(i/2));
3572     }
3573   }
3574
3575   return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V);
3576 }
3577
3578 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3579 ///
3580 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3581                                      unsigned NumNonZero, unsigned NumZero,
3582                                      SelectionDAG &DAG,
3583                                      const TargetLowering &TLI) {
3584   if (NumNonZero > 4)
3585     return SDValue();
3586
3587   DebugLoc dl = Op.getDebugLoc();
3588   SDValue V(0, 0);
3589   bool First = true;
3590   for (unsigned i = 0; i < 8; ++i) {
3591     bool isNonZero = (NonZeros & (1 << i)) != 0;
3592     if (isNonZero) {
3593       if (First) {
3594         if (NumZero)
3595           V = getZeroVector(MVT::v8i16, true, DAG, dl);
3596         else
3597           V = DAG.getUNDEF(MVT::v8i16);
3598         First = false;
3599       }
3600       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
3601                       MVT::v8i16, V, Op.getOperand(i),
3602                       DAG.getIntPtrConstant(i));
3603     }
3604   }
3605
3606   return V;
3607 }
3608
3609 /// getVShift - Return a vector logical shift node.
3610 ///
3611 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
3612                          unsigned NumBits, SelectionDAG &DAG,
3613                          const TargetLowering &TLI, DebugLoc dl) {
3614   bool isMMX = VT.getSizeInBits() == 64;
3615   EVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
3616   unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3617   SrcOp = DAG.getNode(ISD::BIT_CONVERT, dl, ShVT, SrcOp);
3618   return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3619                      DAG.getNode(Opc, dl, ShVT, SrcOp,
3620                              DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3621 }
3622
3623 SDValue
3624 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
3625                                           SelectionDAG &DAG) const {
3626   
3627   // Check if the scalar load can be widened into a vector load. And if
3628   // the address is "base + cst" see if the cst can be "absorbed" into
3629   // the shuffle mask.
3630   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
3631     SDValue Ptr = LD->getBasePtr();
3632     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
3633       return SDValue();
3634     EVT PVT = LD->getValueType(0);
3635     if (PVT != MVT::i32 && PVT != MVT::f32)
3636       return SDValue();
3637
3638     int FI = -1;
3639     int64_t Offset = 0;
3640     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
3641       FI = FINode->getIndex();
3642       Offset = 0;
3643     } else if (Ptr.getOpcode() == ISD::ADD &&
3644                isa<ConstantSDNode>(Ptr.getOperand(1)) &&
3645                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
3646       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
3647       Offset = Ptr.getConstantOperandVal(1);
3648       Ptr = Ptr.getOperand(0);
3649     } else {
3650       return SDValue();
3651     }
3652
3653     SDValue Chain = LD->getChain();
3654     // Make sure the stack object alignment is at least 16.
3655     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3656     if (DAG.InferPtrAlignment(Ptr) < 16) {
3657       if (MFI->isFixedObjectIndex(FI)) {
3658         // Can't change the alignment. FIXME: It's possible to compute
3659         // the exact stack offset and reference FI + adjust offset instead.
3660         // If someone *really* cares about this. That's the way to implement it.
3661         return SDValue();
3662       } else {
3663         MFI->setObjectAlignment(FI, 16);
3664       }
3665     }
3666
3667     // (Offset % 16) must be multiple of 4. Then address is then
3668     // Ptr + (Offset & ~15).
3669     if (Offset < 0)
3670       return SDValue();
3671     if ((Offset % 16) & 3)
3672       return SDValue();
3673     int64_t StartOffset = Offset & ~15;
3674     if (StartOffset)
3675       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
3676                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
3677
3678     int EltNo = (Offset - StartOffset) >> 2;
3679     int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
3680     EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
3681     SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,LD->getSrcValue(),0,
3682                              false, false, 0);
3683     // Canonicalize it to a v4i32 shuffle.
3684     V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32, V1);
3685     return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3686                        DAG.getVectorShuffle(MVT::v4i32, dl, V1,
3687                                             DAG.getUNDEF(MVT::v4i32), &Mask[0]));
3688   }
3689
3690   return SDValue();
3691 }
3692
3693 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a 
3694 /// vector of type 'VT', see if the elements can be replaced by a single large 
3695 /// load which has the same value as a build_vector whose operands are 'elts'.
3696 ///
3697 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
3698 /// 
3699 /// FIXME: we'd also like to handle the case where the last elements are zero
3700 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
3701 /// There's even a handy isZeroNode for that purpose.
3702 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
3703                                         DebugLoc &dl, SelectionDAG &DAG) {
3704   EVT EltVT = VT.getVectorElementType();
3705   unsigned NumElems = Elts.size();
3706   
3707   LoadSDNode *LDBase = NULL;
3708   unsigned LastLoadedElt = -1U;
3709   
3710   // For each element in the initializer, see if we've found a load or an undef.
3711   // If we don't find an initial load element, or later load elements are 
3712   // non-consecutive, bail out.
3713   for (unsigned i = 0; i < NumElems; ++i) {
3714     SDValue Elt = Elts[i];
3715     
3716     if (!Elt.getNode() ||
3717         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
3718       return SDValue();
3719     if (!LDBase) {
3720       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
3721         return SDValue();
3722       LDBase = cast<LoadSDNode>(Elt.getNode());
3723       LastLoadedElt = i;
3724       continue;
3725     }
3726     if (Elt.getOpcode() == ISD::UNDEF)
3727       continue;
3728
3729     LoadSDNode *LD = cast<LoadSDNode>(Elt);
3730     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
3731       return SDValue();
3732     LastLoadedElt = i;
3733   }
3734
3735   // If we have found an entire vector of loads and undefs, then return a large
3736   // load of the entire vector width starting at the base pointer.  If we found
3737   // consecutive loads for the low half, generate a vzext_load node.
3738   if (LastLoadedElt == NumElems - 1) {
3739     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
3740       return DAG.getLoad(VT, dl, LDBase->getChain(), LDBase->getBasePtr(),
3741                          LDBase->getSrcValue(), LDBase->getSrcValueOffset(),
3742                          LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
3743     return DAG.getLoad(VT, dl, LDBase->getChain(), LDBase->getBasePtr(),
3744                        LDBase->getSrcValue(), LDBase->getSrcValueOffset(),
3745                        LDBase->isVolatile(), LDBase->isNonTemporal(),
3746                        LDBase->getAlignment());
3747   } else if (NumElems == 4 && LastLoadedElt == 1) {
3748     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
3749     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
3750     SDValue ResNode = DAG.getNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2);
3751     return DAG.getNode(ISD::BIT_CONVERT, dl, VT, ResNode);
3752   }
3753   return SDValue();
3754 }
3755
3756 SDValue
3757 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
3758   DebugLoc dl = Op.getDebugLoc();
3759   // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3760   if (ISD::isBuildVectorAllZeros(Op.getNode())
3761       || ISD::isBuildVectorAllOnes(Op.getNode())) {
3762     // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3763     // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3764     // eliminated on x86-32 hosts.
3765     if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3766       return Op;
3767
3768     if (ISD::isBuildVectorAllOnes(Op.getNode()))
3769       return getOnesVector(Op.getValueType(), DAG, dl);
3770     return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
3771   }
3772
3773   EVT VT = Op.getValueType();
3774   EVT ExtVT = VT.getVectorElementType();
3775   unsigned EVTBits = ExtVT.getSizeInBits();
3776
3777   unsigned NumElems = Op.getNumOperands();
3778   unsigned NumZero  = 0;
3779   unsigned NumNonZero = 0;
3780   unsigned NonZeros = 0;
3781   bool IsAllConstants = true;
3782   SmallSet<SDValue, 8> Values;
3783   for (unsigned i = 0; i < NumElems; ++i) {
3784     SDValue Elt = Op.getOperand(i);
3785     if (Elt.getOpcode() == ISD::UNDEF)
3786       continue;
3787     Values.insert(Elt);
3788     if (Elt.getOpcode() != ISD::Constant &&
3789         Elt.getOpcode() != ISD::ConstantFP)
3790       IsAllConstants = false;
3791     if (X86::isZeroNode(Elt))
3792       NumZero++;
3793     else {
3794       NonZeros |= (1 << i);
3795       NumNonZero++;
3796     }
3797   }
3798
3799   if (NumNonZero == 0) {
3800     // All undef vector. Return an UNDEF.  All zero vectors were handled above.
3801     return DAG.getUNDEF(VT);
3802   }
3803
3804   // Special case for single non-zero, non-undef, element.
3805   if (NumNonZero == 1) {
3806     unsigned Idx = CountTrailingZeros_32(NonZeros);
3807     SDValue Item = Op.getOperand(Idx);
3808
3809     // If this is an insertion of an i64 value on x86-32, and if the top bits of
3810     // the value are obviously zero, truncate the value to i32 and do the
3811     // insertion that way.  Only do this if the value is non-constant or if the
3812     // value is a constant being inserted into element 0.  It is cheaper to do
3813     // a constant pool load than it is to do a movd + shuffle.
3814     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
3815         (!IsAllConstants || Idx == 0)) {
3816       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3817         // Handle MMX and SSE both.
3818         EVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3819         unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
3820
3821         // Truncate the value (which may itself be a constant) to i32, and
3822         // convert it to a vector with movd (S2V+shuffle to zero extend).
3823         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
3824         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
3825         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3826                                            Subtarget->hasSSE2(), DAG);
3827
3828         // Now we have our 32-bit value zero extended in the low element of
3829         // a vector.  If Idx != 0, swizzle it into place.
3830         if (Idx != 0) {
3831           SmallVector<int, 4> Mask;
3832           Mask.push_back(Idx);
3833           for (unsigned i = 1; i != VecElts; ++i)
3834             Mask.push_back(i);
3835           Item = DAG.getVectorShuffle(VecVT, dl, Item,
3836                                       DAG.getUNDEF(Item.getValueType()),
3837                                       &Mask[0]);
3838         }
3839         return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Item);
3840       }
3841     }
3842
3843     // If we have a constant or non-constant insertion into the low element of
3844     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3845     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
3846     // depending on what the source datatype is.
3847     if (Idx == 0) {
3848       if (NumZero == 0) {
3849         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3850       } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
3851           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
3852         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3853         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3854         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
3855                                            DAG);
3856       } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
3857         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
3858         EVT MiddleVT = VT.getSizeInBits() == 64 ? MVT::v2i32 : MVT::v4i32;
3859         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
3860         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3861                                            Subtarget->hasSSE2(), DAG);
3862         return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Item);
3863       }
3864     }
3865
3866     // Is it a vector logical left shift?
3867     if (NumElems == 2 && Idx == 1 &&
3868         X86::isZeroNode(Op.getOperand(0)) &&
3869         !X86::isZeroNode(Op.getOperand(1))) {
3870       unsigned NumBits = VT.getSizeInBits();
3871       return getVShift(true, VT,
3872                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
3873                                    VT, Op.getOperand(1)),
3874                        NumBits/2, DAG, *this, dl);
3875     }
3876
3877     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3878       return SDValue();
3879
3880     // Otherwise, if this is a vector with i32 or f32 elements, and the element
3881     // is a non-constant being inserted into an element other than the low one,
3882     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
3883     // movd/movss) to move this into the low element, then shuffle it into
3884     // place.
3885     if (EVTBits == 32) {
3886       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3887
3888       // Turn it into a shuffle of zero and zero-extended scalar to vector.
3889       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3890                                          Subtarget->hasSSE2(), DAG);
3891       SmallVector<int, 8> MaskVec;
3892       for (unsigned i = 0; i < NumElems; i++)
3893         MaskVec.push_back(i == Idx ? 0 : 1);
3894       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
3895     }
3896   }
3897
3898   // Splat is obviously ok. Let legalizer expand it to a shuffle.
3899   if (Values.size() == 1) {
3900     if (EVTBits == 32) {
3901       // Instead of a shuffle like this:
3902       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
3903       // Check if it's possible to issue this instead.
3904       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
3905       unsigned Idx = CountTrailingZeros_32(NonZeros);
3906       SDValue Item = Op.getOperand(Idx);
3907       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
3908         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
3909     }
3910     return SDValue();
3911   }
3912
3913   // A vector full of immediates; various special cases are already
3914   // handled, so this is best done with a single constant-pool load.
3915   if (IsAllConstants)
3916     return SDValue();
3917
3918   // Let legalizer expand 2-wide build_vectors.
3919   if (EVTBits == 64) {
3920     if (NumNonZero == 1) {
3921       // One half is zero or undef.
3922       unsigned Idx = CountTrailingZeros_32(NonZeros);
3923       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
3924                                  Op.getOperand(Idx));
3925       return getShuffleVectorZeroOrUndef(V2, Idx, true,
3926                                          Subtarget->hasSSE2(), DAG);
3927     }
3928     return SDValue();
3929   }
3930
3931   // If element VT is < 32 bits, convert it to inserts into a zero vector.
3932   if (EVTBits == 8 && NumElems == 16) {
3933     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3934                                         *this);
3935     if (V.getNode()) return V;
3936   }
3937
3938   if (EVTBits == 16 && NumElems == 8) {
3939     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3940                                         *this);
3941     if (V.getNode()) return V;
3942   }
3943
3944   // If element VT is == 32 bits, turn it into a number of shuffles.
3945   SmallVector<SDValue, 8> V;
3946   V.resize(NumElems);
3947   if (NumElems == 4 && NumZero > 0) {
3948     for (unsigned i = 0; i < 4; ++i) {
3949       bool isZero = !(NonZeros & (1 << i));
3950       if (isZero)
3951         V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
3952       else
3953         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3954     }
3955
3956     for (unsigned i = 0; i < 2; ++i) {
3957       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3958         default: break;
3959         case 0:
3960           V[i] = V[i*2];  // Must be a zero vector.
3961           break;
3962         case 1:
3963           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
3964           break;
3965         case 2:
3966           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
3967           break;
3968         case 3:
3969           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
3970           break;
3971       }
3972     }
3973
3974     SmallVector<int, 8> MaskVec;
3975     bool Reverse = (NonZeros & 0x3) == 2;
3976     for (unsigned i = 0; i < 2; ++i)
3977       MaskVec.push_back(Reverse ? 1-i : i);
3978     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3979     for (unsigned i = 0; i < 2; ++i)
3980       MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
3981     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
3982   }
3983
3984   if (Values.size() > 1 && VT.getSizeInBits() == 128) {
3985     // Check for a build vector of consecutive loads.
3986     for (unsigned i = 0; i < NumElems; ++i)
3987       V[i] = Op.getOperand(i);
3988     
3989     // Check for elements which are consecutive loads.
3990     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
3991     if (LD.getNode())
3992       return LD;
3993     
3994     // For SSE 4.1, use inserts into undef.  
3995     if (getSubtarget()->hasSSE41()) {
3996       V[0] = DAG.getUNDEF(VT);
3997       for (unsigned i = 0; i < NumElems; ++i)
3998         if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
3999           V[0] = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, V[0],
4000                              Op.getOperand(i), DAG.getIntPtrConstant(i));
4001       return V[0];
4002     }
4003     
4004     // Otherwise, expand into a number of unpckl*
4005     // e.g. for v4f32
4006     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
4007     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
4008     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
4009     for (unsigned i = 0; i < NumElems; ++i)
4010       V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4011     NumElems >>= 1;
4012     while (NumElems != 0) {
4013       for (unsigned i = 0; i < NumElems; ++i)
4014         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + NumElems]);
4015       NumElems >>= 1;
4016     }
4017     return V[0];
4018   }
4019   return SDValue();
4020 }
4021
4022 SDValue
4023 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
4024   // We support concatenate two MMX registers and place them in a MMX
4025   // register.  This is better than doing a stack convert.
4026   DebugLoc dl = Op.getDebugLoc();
4027   EVT ResVT = Op.getValueType();
4028   assert(Op.getNumOperands() == 2);
4029   assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
4030          ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
4031   int Mask[2];
4032   SDValue InVec = DAG.getNode(ISD::BIT_CONVERT,dl, MVT::v1i64, Op.getOperand(0));
4033   SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4034   InVec = Op.getOperand(1);
4035   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4036     unsigned NumElts = ResVT.getVectorNumElements();
4037     VecOp = DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
4038     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
4039                        InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
4040   } else {
4041     InVec = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v1i64, InVec);
4042     SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4043     Mask[0] = 0; Mask[1] = 2;
4044     VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
4045   }
4046   return DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
4047 }
4048
4049 // v8i16 shuffles - Prefer shuffles in the following order:
4050 // 1. [all]   pshuflw, pshufhw, optional move
4051 // 2. [ssse3] 1 x pshufb
4052 // 3. [ssse3] 2 x pshufb + 1 x por
4053 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
4054 static
4055 SDValue LowerVECTOR_SHUFFLEv8i16(ShuffleVectorSDNode *SVOp,
4056                                  SelectionDAG &DAG,
4057                                  const X86TargetLowering &TLI) {
4058   SDValue V1 = SVOp->getOperand(0);
4059   SDValue V2 = SVOp->getOperand(1);
4060   DebugLoc dl = SVOp->getDebugLoc();
4061   SmallVector<int, 8> MaskVals;
4062
4063   // Determine if more than 1 of the words in each of the low and high quadwords
4064   // of the result come from the same quadword of one of the two inputs.  Undef
4065   // mask values count as coming from any quadword, for better codegen.
4066   SmallVector<unsigned, 4> LoQuad(4);
4067   SmallVector<unsigned, 4> HiQuad(4);
4068   BitVector InputQuads(4);
4069   for (unsigned i = 0; i < 8; ++i) {
4070     SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
4071     int EltIdx = SVOp->getMaskElt(i);
4072     MaskVals.push_back(EltIdx);
4073     if (EltIdx < 0) {
4074       ++Quad[0];
4075       ++Quad[1];
4076       ++Quad[2];
4077       ++Quad[3];
4078       continue;
4079     }
4080     ++Quad[EltIdx / 4];
4081     InputQuads.set(EltIdx / 4);
4082   }
4083
4084   int BestLoQuad = -1;
4085   unsigned MaxQuad = 1;
4086   for (unsigned i = 0; i < 4; ++i) {
4087     if (LoQuad[i] > MaxQuad) {
4088       BestLoQuad = i;
4089       MaxQuad = LoQuad[i];
4090     }
4091   }
4092
4093   int BestHiQuad = -1;
4094   MaxQuad = 1;
4095   for (unsigned i = 0; i < 4; ++i) {
4096     if (HiQuad[i] > MaxQuad) {
4097       BestHiQuad = i;
4098       MaxQuad = HiQuad[i];
4099     }
4100   }
4101
4102   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
4103   // of the two input vectors, shuffle them into one input vector so only a
4104   // single pshufb instruction is necessary. If There are more than 2 input
4105   // quads, disable the next transformation since it does not help SSSE3.
4106   bool V1Used = InputQuads[0] || InputQuads[1];
4107   bool V2Used = InputQuads[2] || InputQuads[3];
4108   if (TLI.getSubtarget()->hasSSSE3()) {
4109     if (InputQuads.count() == 2 && V1Used && V2Used) {
4110       BestLoQuad = InputQuads.find_first();
4111       BestHiQuad = InputQuads.find_next(BestLoQuad);
4112     }
4113     if (InputQuads.count() > 2) {
4114       BestLoQuad = -1;
4115       BestHiQuad = -1;
4116     }
4117   }
4118
4119   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
4120   // the shuffle mask.  If a quad is scored as -1, that means that it contains
4121   // words from all 4 input quadwords.
4122   SDValue NewV;
4123   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
4124     SmallVector<int, 8> MaskV;
4125     MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
4126     MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
4127     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
4128                   DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V1),
4129                   DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V2), &MaskV[0]);
4130     NewV = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, NewV);
4131
4132     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
4133     // source words for the shuffle, to aid later transformations.
4134     bool AllWordsInNewV = true;
4135     bool InOrder[2] = { true, true };
4136     for (unsigned i = 0; i != 8; ++i) {
4137       int idx = MaskVals[i];
4138       if (idx != (int)i)
4139         InOrder[i/4] = false;
4140       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
4141         continue;
4142       AllWordsInNewV = false;
4143       break;
4144     }
4145
4146     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
4147     if (AllWordsInNewV) {
4148       for (int i = 0; i != 8; ++i) {
4149         int idx = MaskVals[i];
4150         if (idx < 0)
4151           continue;
4152         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
4153         if ((idx != i) && idx < 4)
4154           pshufhw = false;
4155         if ((idx != i) && idx > 3)
4156           pshuflw = false;
4157       }
4158       V1 = NewV;
4159       V2Used = false;
4160       BestLoQuad = 0;
4161       BestHiQuad = 1;
4162     }
4163
4164     // If we've eliminated the use of V2, and the new mask is a pshuflw or
4165     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
4166     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
4167       return DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
4168                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
4169     }
4170   }
4171
4172   // If we have SSSE3, and all words of the result are from 1 input vector,
4173   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
4174   // is present, fall back to case 4.
4175   if (TLI.getSubtarget()->hasSSSE3()) {
4176     SmallVector<SDValue,16> pshufbMask;
4177
4178     // If we have elements from both input vectors, set the high bit of the
4179     // shuffle mask element to zero out elements that come from V2 in the V1
4180     // mask, and elements that come from V1 in the V2 mask, so that the two
4181     // results can be OR'd together.
4182     bool TwoInputs = V1Used && V2Used;
4183     for (unsigned i = 0; i != 8; ++i) {
4184       int EltIdx = MaskVals[i] * 2;
4185       if (TwoInputs && (EltIdx >= 16)) {
4186         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4187         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4188         continue;
4189       }
4190       pshufbMask.push_back(DAG.getConstant(EltIdx,   MVT::i8));
4191       pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
4192     }
4193     V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V1);
4194     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4195                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4196                                  MVT::v16i8, &pshufbMask[0], 16));
4197     if (!TwoInputs)
4198       return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4199
4200     // Calculate the shuffle mask for the second input, shuffle it, and
4201     // OR it with the first shuffled input.
4202     pshufbMask.clear();
4203     for (unsigned i = 0; i != 8; ++i) {
4204       int EltIdx = MaskVals[i] * 2;
4205       if (EltIdx < 16) {
4206         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4207         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4208         continue;
4209       }
4210       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4211       pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
4212     }
4213     V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V2);
4214     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4215                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4216                                  MVT::v16i8, &pshufbMask[0], 16));
4217     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4218     return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4219   }
4220
4221   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
4222   // and update MaskVals with new element order.
4223   BitVector InOrder(8);
4224   if (BestLoQuad >= 0) {
4225     SmallVector<int, 8> MaskV;
4226     for (int i = 0; i != 4; ++i) {
4227       int idx = MaskVals[i];
4228       if (idx < 0) {
4229         MaskV.push_back(-1);
4230         InOrder.set(i);
4231       } else if ((idx / 4) == BestLoQuad) {
4232         MaskV.push_back(idx & 3);
4233         InOrder.set(i);
4234       } else {
4235         MaskV.push_back(-1);
4236       }
4237     }
4238     for (unsigned i = 4; i != 8; ++i)
4239       MaskV.push_back(i);
4240     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4241                                 &MaskV[0]);
4242   }
4243
4244   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
4245   // and update MaskVals with the new element order.
4246   if (BestHiQuad >= 0) {
4247     SmallVector<int, 8> MaskV;
4248     for (unsigned i = 0; i != 4; ++i)
4249       MaskV.push_back(i);
4250     for (unsigned i = 4; i != 8; ++i) {
4251       int idx = MaskVals[i];
4252       if (idx < 0) {
4253         MaskV.push_back(-1);
4254         InOrder.set(i);
4255       } else if ((idx / 4) == BestHiQuad) {
4256         MaskV.push_back((idx & 3) + 4);
4257         InOrder.set(i);
4258       } else {
4259         MaskV.push_back(-1);
4260       }
4261     }
4262     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4263                                 &MaskV[0]);
4264   }
4265
4266   // In case BestHi & BestLo were both -1, which means each quadword has a word
4267   // from each of the four input quadwords, calculate the InOrder bitvector now
4268   // before falling through to the insert/extract cleanup.
4269   if (BestLoQuad == -1 && BestHiQuad == -1) {
4270     NewV = V1;
4271     for (int i = 0; i != 8; ++i)
4272       if (MaskVals[i] < 0 || MaskVals[i] == i)
4273         InOrder.set(i);
4274   }
4275
4276   // The other elements are put in the right place using pextrw and pinsrw.
4277   for (unsigned i = 0; i != 8; ++i) {
4278     if (InOrder[i])
4279       continue;
4280     int EltIdx = MaskVals[i];
4281     if (EltIdx < 0)
4282       continue;
4283     SDValue ExtOp = (EltIdx < 8)
4284     ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
4285                   DAG.getIntPtrConstant(EltIdx))
4286     : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
4287                   DAG.getIntPtrConstant(EltIdx - 8));
4288     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
4289                        DAG.getIntPtrConstant(i));
4290   }
4291   return NewV;
4292 }
4293
4294 // v16i8 shuffles - Prefer shuffles in the following order:
4295 // 1. [ssse3] 1 x pshufb
4296 // 2. [ssse3] 2 x pshufb + 1 x por
4297 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
4298 static
4299 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
4300                                  SelectionDAG &DAG,
4301                                  const X86TargetLowering &TLI) {
4302   SDValue V1 = SVOp->getOperand(0);
4303   SDValue V2 = SVOp->getOperand(1);
4304   DebugLoc dl = SVOp->getDebugLoc();
4305   SmallVector<int, 16> MaskVals;
4306   SVOp->getMask(MaskVals);
4307
4308   // If we have SSSE3, case 1 is generated when all result bytes come from
4309   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
4310   // present, fall back to case 3.
4311   // FIXME: kill V2Only once shuffles are canonizalized by getNode.
4312   bool V1Only = true;
4313   bool V2Only = true;
4314   for (unsigned i = 0; i < 16; ++i) {
4315     int EltIdx = MaskVals[i];
4316     if (EltIdx < 0)
4317       continue;
4318     if (EltIdx < 16)
4319       V2Only = false;
4320     else
4321       V1Only = false;
4322   }
4323
4324   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
4325   if (TLI.getSubtarget()->hasSSSE3()) {
4326     SmallVector<SDValue,16> pshufbMask;
4327
4328     // If all result elements are from one input vector, then only translate
4329     // undef mask values to 0x80 (zero out result) in the pshufb mask.
4330     //
4331     // Otherwise, we have elements from both input vectors, and must zero out
4332     // elements that come from V2 in the first mask, and V1 in the second mask
4333     // so that we can OR them together.
4334     bool TwoInputs = !(V1Only || V2Only);
4335     for (unsigned i = 0; i != 16; ++i) {
4336       int EltIdx = MaskVals[i];
4337       if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
4338         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4339         continue;
4340       }
4341       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4342     }
4343     // If all the elements are from V2, assign it to V1 and return after
4344     // building the first pshufb.
4345     if (V2Only)
4346       V1 = V2;
4347     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4348                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4349                                  MVT::v16i8, &pshufbMask[0], 16));
4350     if (!TwoInputs)
4351       return V1;
4352
4353     // Calculate the shuffle mask for the second input, shuffle it, and
4354     // OR it with the first shuffled input.
4355     pshufbMask.clear();
4356     for (unsigned i = 0; i != 16; ++i) {
4357       int EltIdx = MaskVals[i];
4358       if (EltIdx < 16) {
4359         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4360         continue;
4361       }
4362       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4363     }
4364     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4365                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4366                                  MVT::v16i8, &pshufbMask[0], 16));
4367     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4368   }
4369
4370   // No SSSE3 - Calculate in place words and then fix all out of place words
4371   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
4372   // the 16 different words that comprise the two doublequadword input vectors.
4373   V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4374   V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V2);
4375   SDValue NewV = V2Only ? V2 : V1;
4376   for (int i = 0; i != 8; ++i) {
4377     int Elt0 = MaskVals[i*2];
4378     int Elt1 = MaskVals[i*2+1];
4379
4380     // This word of the result is all undef, skip it.
4381     if (Elt0 < 0 && Elt1 < 0)
4382       continue;
4383
4384     // This word of the result is already in the correct place, skip it.
4385     if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
4386       continue;
4387     if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
4388       continue;
4389
4390     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
4391     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
4392     SDValue InsElt;
4393
4394     // If Elt0 and Elt1 are defined, are consecutive, and can be load
4395     // using a single extract together, load it and store it.
4396     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
4397       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4398                            DAG.getIntPtrConstant(Elt1 / 2));
4399       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4400                         DAG.getIntPtrConstant(i));
4401       continue;
4402     }
4403
4404     // If Elt1 is defined, extract it from the appropriate source.  If the
4405     // source byte is not also odd, shift the extracted word left 8 bits
4406     // otherwise clear the bottom 8 bits if we need to do an or.
4407     if (Elt1 >= 0) {
4408       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4409                            DAG.getIntPtrConstant(Elt1 / 2));
4410       if ((Elt1 & 1) == 0)
4411         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
4412                              DAG.getConstant(8, TLI.getShiftAmountTy()));
4413       else if (Elt0 >= 0)
4414         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
4415                              DAG.getConstant(0xFF00, MVT::i16));
4416     }
4417     // If Elt0 is defined, extract it from the appropriate source.  If the
4418     // source byte is not also even, shift the extracted word right 8 bits. If
4419     // Elt1 was also defined, OR the extracted values together before
4420     // inserting them in the result.
4421     if (Elt0 >= 0) {
4422       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
4423                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
4424       if ((Elt0 & 1) != 0)
4425         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
4426                               DAG.getConstant(8, TLI.getShiftAmountTy()));
4427       else if (Elt1 >= 0)
4428         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
4429                              DAG.getConstant(0x00FF, MVT::i16));
4430       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
4431                          : InsElt0;
4432     }
4433     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4434                        DAG.getIntPtrConstant(i));
4435   }
4436   return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, NewV);
4437 }
4438
4439 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
4440 /// ones, or rewriting v4i32 / v2i32 as 2 wide ones if possible. This can be
4441 /// done when every pair / quad of shuffle mask elements point to elements in
4442 /// the right sequence. e.g.
4443 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
4444 static
4445 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
4446                                  SelectionDAG &DAG,
4447                                  const TargetLowering &TLI, DebugLoc dl) {
4448   EVT VT = SVOp->getValueType(0);
4449   SDValue V1 = SVOp->getOperand(0);
4450   SDValue V2 = SVOp->getOperand(1);
4451   unsigned NumElems = VT.getVectorNumElements();
4452   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
4453   EVT MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
4454   EVT NewVT = MaskVT;
4455   switch (VT.getSimpleVT().SimpleTy) {
4456   default: assert(false && "Unexpected!");
4457   case MVT::v4f32: NewVT = MVT::v2f64; break;
4458   case MVT::v4i32: NewVT = MVT::v2i64; break;
4459   case MVT::v8i16: NewVT = MVT::v4i32; break;
4460   case MVT::v16i8: NewVT = MVT::v4i32; break;
4461   }
4462
4463   if (NewWidth == 2) {
4464     if (VT.isInteger())
4465       NewVT = MVT::v2i64;
4466     else
4467       NewVT = MVT::v2f64;
4468   }
4469   int Scale = NumElems / NewWidth;
4470   SmallVector<int, 8> MaskVec;
4471   for (unsigned i = 0; i < NumElems; i += Scale) {
4472     int StartIdx = -1;
4473     for (int j = 0; j < Scale; ++j) {
4474       int EltIdx = SVOp->getMaskElt(i+j);
4475       if (EltIdx < 0)
4476         continue;
4477       if (StartIdx == -1)
4478         StartIdx = EltIdx - (EltIdx % Scale);
4479       if (EltIdx != StartIdx + j)
4480         return SDValue();
4481     }
4482     if (StartIdx == -1)
4483       MaskVec.push_back(-1);
4484     else
4485       MaskVec.push_back(StartIdx / Scale);
4486   }
4487
4488   V1 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V1);
4489   V2 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V2);
4490   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
4491 }
4492
4493 /// getVZextMovL - Return a zero-extending vector move low node.
4494 ///
4495 static SDValue getVZextMovL(EVT VT, EVT OpVT,
4496                             SDValue SrcOp, SelectionDAG &DAG,
4497                             const X86Subtarget *Subtarget, DebugLoc dl) {
4498   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
4499     LoadSDNode *LD = NULL;
4500     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
4501       LD = dyn_cast<LoadSDNode>(SrcOp);
4502     if (!LD) {
4503       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
4504       // instead.
4505       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
4506       if ((ExtVT.SimpleTy != MVT::i64 || Subtarget->is64Bit()) &&
4507           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
4508           SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
4509           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
4510         // PR2108
4511         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
4512         return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4513                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4514                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4515                                                    OpVT,
4516                                                    SrcOp.getOperand(0)
4517                                                           .getOperand(0))));
4518       }
4519     }
4520   }
4521
4522   return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4523                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4524                                  DAG.getNode(ISD::BIT_CONVERT, dl,
4525                                              OpVT, SrcOp)));
4526 }
4527
4528 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
4529 /// shuffles.
4530 static SDValue
4531 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4532   SDValue V1 = SVOp->getOperand(0);
4533   SDValue V2 = SVOp->getOperand(1);
4534   DebugLoc dl = SVOp->getDebugLoc();
4535   EVT VT = SVOp->getValueType(0);
4536
4537   SmallVector<std::pair<int, int>, 8> Locs;
4538   Locs.resize(4);
4539   SmallVector<int, 8> Mask1(4U, -1);
4540   SmallVector<int, 8> PermMask;
4541   SVOp->getMask(PermMask);
4542
4543   unsigned NumHi = 0;
4544   unsigned NumLo = 0;
4545   for (unsigned i = 0; i != 4; ++i) {
4546     int Idx = PermMask[i];
4547     if (Idx < 0) {
4548       Locs[i] = std::make_pair(-1, -1);
4549     } else {
4550       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
4551       if (Idx < 4) {
4552         Locs[i] = std::make_pair(0, NumLo);
4553         Mask1[NumLo] = Idx;
4554         NumLo++;
4555       } else {
4556         Locs[i] = std::make_pair(1, NumHi);
4557         if (2+NumHi < 4)
4558           Mask1[2+NumHi] = Idx;
4559         NumHi++;
4560       }
4561     }
4562   }
4563
4564   if (NumLo <= 2 && NumHi <= 2) {
4565     // If no more than two elements come from either vector. This can be
4566     // implemented with two shuffles. First shuffle gather the elements.
4567     // The second shuffle, which takes the first shuffle as both of its
4568     // vector operands, put the elements into the right order.
4569     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4570
4571     SmallVector<int, 8> Mask2(4U, -1);
4572
4573     for (unsigned i = 0; i != 4; ++i) {
4574       if (Locs[i].first == -1)
4575         continue;
4576       else {
4577         unsigned Idx = (i < 2) ? 0 : 4;
4578         Idx += Locs[i].first * 2 + Locs[i].second;
4579         Mask2[i] = Idx;
4580       }
4581     }
4582
4583     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
4584   } else if (NumLo == 3 || NumHi == 3) {
4585     // Otherwise, we must have three elements from one vector, call it X, and
4586     // one element from the other, call it Y.  First, use a shufps to build an
4587     // intermediate vector with the one element from Y and the element from X
4588     // that will be in the same half in the final destination (the indexes don't
4589     // matter). Then, use a shufps to build the final vector, taking the half
4590     // containing the element from Y from the intermediate, and the other half
4591     // from X.
4592     if (NumHi == 3) {
4593       // Normalize it so the 3 elements come from V1.
4594       CommuteVectorShuffleMask(PermMask, VT);
4595       std::swap(V1, V2);
4596     }
4597
4598     // Find the element from V2.
4599     unsigned HiIndex;
4600     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
4601       int Val = PermMask[HiIndex];
4602       if (Val < 0)
4603         continue;
4604       if (Val >= 4)
4605         break;
4606     }
4607
4608     Mask1[0] = PermMask[HiIndex];
4609     Mask1[1] = -1;
4610     Mask1[2] = PermMask[HiIndex^1];
4611     Mask1[3] = -1;
4612     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4613
4614     if (HiIndex >= 2) {
4615       Mask1[0] = PermMask[0];
4616       Mask1[1] = PermMask[1];
4617       Mask1[2] = HiIndex & 1 ? 6 : 4;
4618       Mask1[3] = HiIndex & 1 ? 4 : 6;
4619       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4620     } else {
4621       Mask1[0] = HiIndex & 1 ? 2 : 0;
4622       Mask1[1] = HiIndex & 1 ? 0 : 2;
4623       Mask1[2] = PermMask[2];
4624       Mask1[3] = PermMask[3];
4625       if (Mask1[2] >= 0)
4626         Mask1[2] += 4;
4627       if (Mask1[3] >= 0)
4628         Mask1[3] += 4;
4629       return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
4630     }
4631   }
4632
4633   // Break it into (shuffle shuffle_hi, shuffle_lo).
4634   Locs.clear();
4635   SmallVector<int,8> LoMask(4U, -1);
4636   SmallVector<int,8> HiMask(4U, -1);
4637
4638   SmallVector<int,8> *MaskPtr = &LoMask;
4639   unsigned MaskIdx = 0;
4640   unsigned LoIdx = 0;
4641   unsigned HiIdx = 2;
4642   for (unsigned i = 0; i != 4; ++i) {
4643     if (i == 2) {
4644       MaskPtr = &HiMask;
4645       MaskIdx = 1;
4646       LoIdx = 0;
4647       HiIdx = 2;
4648     }
4649     int Idx = PermMask[i];
4650     if (Idx < 0) {
4651       Locs[i] = std::make_pair(-1, -1);
4652     } else if (Idx < 4) {
4653       Locs[i] = std::make_pair(MaskIdx, LoIdx);
4654       (*MaskPtr)[LoIdx] = Idx;
4655       LoIdx++;
4656     } else {
4657       Locs[i] = std::make_pair(MaskIdx, HiIdx);
4658       (*MaskPtr)[HiIdx] = Idx;
4659       HiIdx++;
4660     }
4661   }
4662
4663   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
4664   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
4665   SmallVector<int, 8> MaskOps;
4666   for (unsigned i = 0; i != 4; ++i) {
4667     if (Locs[i].first == -1) {
4668       MaskOps.push_back(-1);
4669     } else {
4670       unsigned Idx = Locs[i].first * 4 + Locs[i].second;
4671       MaskOps.push_back(Idx);
4672     }
4673   }
4674   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
4675 }
4676
4677 SDValue
4678 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
4679   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4680   SDValue V1 = Op.getOperand(0);
4681   SDValue V2 = Op.getOperand(1);
4682   EVT VT = Op.getValueType();
4683   DebugLoc dl = Op.getDebugLoc();
4684   unsigned NumElems = VT.getVectorNumElements();
4685   bool isMMX = VT.getSizeInBits() == 64;
4686   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
4687   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
4688   bool V1IsSplat = false;
4689   bool V2IsSplat = false;
4690
4691   if (isZeroShuffle(SVOp))
4692     return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4693
4694   // Promote splats to v4f32.
4695   if (SVOp->isSplat()) {
4696     if (isMMX || NumElems < 4)
4697       return Op;
4698     return PromoteSplat(SVOp, DAG, Subtarget->hasSSE2());
4699   }
4700
4701   // If the shuffle can be profitably rewritten as a narrower shuffle, then
4702   // do it!
4703   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
4704     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4705     if (NewOp.getNode())
4706       return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4707                          LowerVECTOR_SHUFFLE(NewOp, DAG));
4708   } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
4709     // FIXME: Figure out a cleaner way to do this.
4710     // Try to make use of movq to zero out the top part.
4711     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
4712       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4713       if (NewOp.getNode()) {
4714         if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
4715           return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
4716                               DAG, Subtarget, dl);
4717       }
4718     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
4719       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4720       if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
4721         return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
4722                             DAG, Subtarget, dl);
4723     }
4724   }
4725
4726   if (X86::isPSHUFDMask(SVOp))
4727     return Op;
4728
4729   // Check if this can be converted into a logical shift.
4730   bool isLeft = false;
4731   unsigned ShAmt = 0;
4732   SDValue ShVal;
4733   bool isShift = getSubtarget()->hasSSE2() &&
4734     isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
4735   if (isShift && ShVal.hasOneUse()) {
4736     // If the shifted value has multiple uses, it may be cheaper to use
4737     // v_set0 + movlhps or movhlps, etc.
4738     EVT EltVT = VT.getVectorElementType();
4739     ShAmt *= EltVT.getSizeInBits();
4740     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4741   }
4742
4743   if (X86::isMOVLMask(SVOp)) {
4744     if (V1IsUndef)
4745       return V2;
4746     if (ISD::isBuildVectorAllZeros(V1.getNode()))
4747       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
4748     if (!isMMX)
4749       return Op;
4750   }
4751
4752   // FIXME: fold these into legal mask.
4753   if (!isMMX && (X86::isMOVSHDUPMask(SVOp) ||
4754                  X86::isMOVSLDUPMask(SVOp) ||
4755                  X86::isMOVHLPSMask(SVOp) ||
4756                  X86::isMOVLHPSMask(SVOp) ||
4757                  X86::isMOVLPMask(SVOp)))
4758     return Op;
4759
4760   if (ShouldXformToMOVHLPS(SVOp) ||
4761       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
4762     return CommuteVectorShuffle(SVOp, DAG);
4763
4764   if (isShift) {
4765     // No better options. Use a vshl / vsrl.
4766     EVT EltVT = VT.getVectorElementType();
4767     ShAmt *= EltVT.getSizeInBits();
4768     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4769   }
4770
4771   bool Commuted = false;
4772   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
4773   // 1,1,1,1 -> v8i16 though.
4774   V1IsSplat = isSplatVector(V1.getNode());
4775   V2IsSplat = isSplatVector(V2.getNode());
4776
4777   // Canonicalize the splat or undef, if present, to be on the RHS.
4778   if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
4779     Op = CommuteVectorShuffle(SVOp, DAG);
4780     SVOp = cast<ShuffleVectorSDNode>(Op);
4781     V1 = SVOp->getOperand(0);
4782     V2 = SVOp->getOperand(1);
4783     std::swap(V1IsSplat, V2IsSplat);
4784     std::swap(V1IsUndef, V2IsUndef);
4785     Commuted = true;
4786   }
4787
4788   if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
4789     // Shuffling low element of v1 into undef, just return v1.
4790     if (V2IsUndef)
4791       return V1;
4792     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
4793     // the instruction selector will not match, so get a canonical MOVL with
4794     // swapped operands to undo the commute.
4795     return getMOVL(DAG, dl, VT, V2, V1);
4796   }
4797
4798   if (X86::isUNPCKL_v_undef_Mask(SVOp) ||
4799       X86::isUNPCKH_v_undef_Mask(SVOp) ||
4800       X86::isUNPCKLMask(SVOp) ||
4801       X86::isUNPCKHMask(SVOp))
4802     return Op;
4803
4804   if (V2IsSplat) {
4805     // Normalize mask so all entries that point to V2 points to its first
4806     // element then try to match unpck{h|l} again. If match, return a
4807     // new vector_shuffle with the corrected mask.
4808     SDValue NewMask = NormalizeMask(SVOp, DAG);
4809     ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
4810     if (NSVOp != SVOp) {
4811       if (X86::isUNPCKLMask(NSVOp, true)) {
4812         return NewMask;
4813       } else if (X86::isUNPCKHMask(NSVOp, true)) {
4814         return NewMask;
4815       }
4816     }
4817   }
4818
4819   if (Commuted) {
4820     // Commute is back and try unpck* again.
4821     // FIXME: this seems wrong.
4822     SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
4823     ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
4824     if (X86::isUNPCKL_v_undef_Mask(NewSVOp) ||
4825         X86::isUNPCKH_v_undef_Mask(NewSVOp) ||
4826         X86::isUNPCKLMask(NewSVOp) ||
4827         X86::isUNPCKHMask(NewSVOp))
4828       return NewOp;
4829   }
4830
4831   // FIXME: for mmx, bitcast v2i32 to v4i16 for shuffle.
4832
4833   // Normalize the node to match x86 shuffle ops if needed
4834   if (!isMMX && V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
4835     return CommuteVectorShuffle(SVOp, DAG);
4836
4837   // Check for legal shuffle and return?
4838   SmallVector<int, 16> PermMask;
4839   SVOp->getMask(PermMask);
4840   if (isShuffleMaskLegal(PermMask, VT))
4841     return Op;
4842
4843   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
4844   if (VT == MVT::v8i16) {
4845     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(SVOp, DAG, *this);
4846     if (NewOp.getNode())
4847       return NewOp;
4848   }
4849
4850   if (VT == MVT::v16i8) {
4851     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
4852     if (NewOp.getNode())
4853       return NewOp;
4854   }
4855
4856   // Handle all 4 wide cases with a number of shuffles except for MMX.
4857   if (NumElems == 4 && !isMMX)
4858     return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
4859
4860   return SDValue();
4861 }
4862
4863 SDValue
4864 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
4865                                                 SelectionDAG &DAG) const {
4866   EVT VT = Op.getValueType();
4867   DebugLoc dl = Op.getDebugLoc();
4868   if (VT.getSizeInBits() == 8) {
4869     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
4870                                     Op.getOperand(0), Op.getOperand(1));
4871     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4872                                     DAG.getValueType(VT));
4873     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4874   } else if (VT.getSizeInBits() == 16) {
4875     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4876     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
4877     if (Idx == 0)
4878       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4879                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4880                                      DAG.getNode(ISD::BIT_CONVERT, dl,
4881                                                  MVT::v4i32,
4882                                                  Op.getOperand(0)),
4883                                      Op.getOperand(1)));
4884     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
4885                                     Op.getOperand(0), Op.getOperand(1));
4886     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4887                                     DAG.getValueType(VT));
4888     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4889   } else if (VT == MVT::f32) {
4890     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
4891     // the result back to FR32 register. It's only worth matching if the
4892     // result has a single use which is a store or a bitcast to i32.  And in
4893     // the case of a store, it's not worth it if the index is a constant 0,
4894     // because a MOVSSmr can be used instead, which is smaller and faster.
4895     if (!Op.hasOneUse())
4896       return SDValue();
4897     SDNode *User = *Op.getNode()->use_begin();
4898     if ((User->getOpcode() != ISD::STORE ||
4899          (isa<ConstantSDNode>(Op.getOperand(1)) &&
4900           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
4901         (User->getOpcode() != ISD::BIT_CONVERT ||
4902          User->getValueType(0) != MVT::i32))
4903       return SDValue();
4904     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4905                                   DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32,
4906                                               Op.getOperand(0)),
4907                                               Op.getOperand(1));
4908     return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Extract);
4909   } else if (VT == MVT::i32) {
4910     // ExtractPS works with constant index.
4911     if (isa<ConstantSDNode>(Op.getOperand(1)))
4912       return Op;
4913   }
4914   return SDValue();
4915 }
4916
4917
4918 SDValue
4919 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
4920                                            SelectionDAG &DAG) const {
4921   if (!isa<ConstantSDNode>(Op.getOperand(1)))
4922     return SDValue();
4923
4924   if (Subtarget->hasSSE41()) {
4925     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
4926     if (Res.getNode())
4927       return Res;
4928   }
4929
4930   EVT VT = Op.getValueType();
4931   DebugLoc dl = Op.getDebugLoc();
4932   // TODO: handle v16i8.
4933   if (VT.getSizeInBits() == 16) {
4934     SDValue Vec = Op.getOperand(0);
4935     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4936     if (Idx == 0)
4937       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4938                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4939                                      DAG.getNode(ISD::BIT_CONVERT, dl,
4940                                                  MVT::v4i32, Vec),
4941                                      Op.getOperand(1)));
4942     // Transform it so it match pextrw which produces a 32-bit result.
4943     EVT EltVT = MVT::i32;
4944     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
4945                                     Op.getOperand(0), Op.getOperand(1));
4946     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
4947                                     DAG.getValueType(VT));
4948     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4949   } else if (VT.getSizeInBits() == 32) {
4950     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4951     if (Idx == 0)
4952       return Op;
4953
4954     // SHUFPS the element to the lowest double word, then movss.
4955     int Mask[4] = { Idx, -1, -1, -1 };
4956     EVT VVT = Op.getOperand(0).getValueType();
4957     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4958                                        DAG.getUNDEF(VVT), Mask);
4959     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4960                        DAG.getIntPtrConstant(0));
4961   } else if (VT.getSizeInBits() == 64) {
4962     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
4963     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
4964     //        to match extract_elt for f64.
4965     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4966     if (Idx == 0)
4967       return Op;
4968
4969     // UNPCKHPD the element to the lowest double word, then movsd.
4970     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
4971     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
4972     int Mask[2] = { 1, -1 };
4973     EVT VVT = Op.getOperand(0).getValueType();
4974     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4975                                        DAG.getUNDEF(VVT), Mask);
4976     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4977                        DAG.getIntPtrConstant(0));
4978   }
4979
4980   return SDValue();
4981 }
4982
4983 SDValue
4984 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
4985                                                SelectionDAG &DAG) const {
4986   EVT VT = Op.getValueType();
4987   EVT EltVT = VT.getVectorElementType();
4988   DebugLoc dl = Op.getDebugLoc();
4989
4990   SDValue N0 = Op.getOperand(0);
4991   SDValue N1 = Op.getOperand(1);
4992   SDValue N2 = Op.getOperand(2);
4993
4994   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
4995       isa<ConstantSDNode>(N2)) {
4996     unsigned Opc;
4997     if (VT == MVT::v8i16)
4998       Opc = X86ISD::PINSRW;
4999     else if (VT == MVT::v4i16)
5000       Opc = X86ISD::MMX_PINSRW;
5001     else if (VT == MVT::v16i8)
5002       Opc = X86ISD::PINSRB;
5003     else
5004       Opc = X86ISD::PINSRB;
5005
5006     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
5007     // argument.
5008     if (N1.getValueType() != MVT::i32)
5009       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
5010     if (N2.getValueType() != MVT::i32)
5011       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
5012     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
5013   } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
5014     // Bits [7:6] of the constant are the source select.  This will always be
5015     //  zero here.  The DAG Combiner may combine an extract_elt index into these
5016     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
5017     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
5018     // Bits [5:4] of the constant are the destination select.  This is the
5019     //  value of the incoming immediate.
5020     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
5021     //   combine either bitwise AND or insert of float 0.0 to set these bits.
5022     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
5023     // Create this as a scalar to vector..
5024     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
5025     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
5026   } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
5027     // PINSR* works with constant index.
5028     return Op;
5029   }
5030   return SDValue();
5031 }
5032
5033 SDValue
5034 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
5035   EVT VT = Op.getValueType();
5036   EVT EltVT = VT.getVectorElementType();
5037
5038   if (Subtarget->hasSSE41())
5039     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
5040
5041   if (EltVT == MVT::i8)
5042     return SDValue();
5043
5044   DebugLoc dl = Op.getDebugLoc();
5045   SDValue N0 = Op.getOperand(0);
5046   SDValue N1 = Op.getOperand(1);
5047   SDValue N2 = Op.getOperand(2);
5048
5049   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
5050     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
5051     // as its second argument.
5052     if (N1.getValueType() != MVT::i32)
5053       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
5054     if (N2.getValueType() != MVT::i32)
5055       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
5056     return DAG.getNode(VT == MVT::v8i16 ? X86ISD::PINSRW : X86ISD::MMX_PINSRW,
5057                        dl, VT, N0, N1, N2);
5058   }
5059   return SDValue();
5060 }
5061
5062 SDValue
5063 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5064   DebugLoc dl = Op.getDebugLoc();
5065   
5066   if (Op.getValueType() == MVT::v1i64 &&
5067       Op.getOperand(0).getValueType() == MVT::i64)
5068     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
5069
5070   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
5071   EVT VT = MVT::v2i32;
5072   switch (Op.getValueType().getSimpleVT().SimpleTy) {
5073   default: break;
5074   case MVT::v16i8:
5075   case MVT::v8i16:
5076     VT = MVT::v4i32;
5077     break;
5078   }
5079   return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(),
5080                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, AnyExt));
5081 }
5082
5083 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
5084 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
5085 // one of the above mentioned nodes. It has to be wrapped because otherwise
5086 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
5087 // be used to form addressing mode. These wrapped nodes will be selected
5088 // into MOV32ri.
5089 SDValue
5090 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
5091   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
5092
5093   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5094   // global base reg.
5095   unsigned char OpFlag = 0;
5096   unsigned WrapperKind = X86ISD::Wrapper;
5097   CodeModel::Model M = getTargetMachine().getCodeModel();
5098
5099   if (Subtarget->isPICStyleRIPRel() &&
5100       (M == CodeModel::Small || M == CodeModel::Kernel))
5101     WrapperKind = X86ISD::WrapperRIP;
5102   else if (Subtarget->isPICStyleGOT())
5103     OpFlag = X86II::MO_GOTOFF;
5104   else if (Subtarget->isPICStyleStubPIC())
5105     OpFlag = X86II::MO_PIC_BASE_OFFSET;
5106
5107   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
5108                                              CP->getAlignment(),
5109                                              CP->getOffset(), OpFlag);
5110   DebugLoc DL = CP->getDebugLoc();
5111   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5112   // With PIC, the address is actually $g + Offset.
5113   if (OpFlag) {
5114     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5115                          DAG.getNode(X86ISD::GlobalBaseReg,
5116                                      DebugLoc(), getPointerTy()),
5117                          Result);
5118   }
5119
5120   return Result;
5121 }
5122
5123 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
5124   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
5125
5126   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5127   // global base reg.
5128   unsigned char OpFlag = 0;
5129   unsigned WrapperKind = X86ISD::Wrapper;
5130   CodeModel::Model M = getTargetMachine().getCodeModel();
5131
5132   if (Subtarget->isPICStyleRIPRel() &&
5133       (M == CodeModel::Small || M == CodeModel::Kernel))
5134     WrapperKind = X86ISD::WrapperRIP;
5135   else if (Subtarget->isPICStyleGOT())
5136     OpFlag = X86II::MO_GOTOFF;
5137   else if (Subtarget->isPICStyleStubPIC())
5138     OpFlag = X86II::MO_PIC_BASE_OFFSET;
5139
5140   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
5141                                           OpFlag);
5142   DebugLoc DL = JT->getDebugLoc();
5143   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5144
5145   // With PIC, the address is actually $g + Offset.
5146   if (OpFlag) {
5147     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5148                          DAG.getNode(X86ISD::GlobalBaseReg,
5149                                      DebugLoc(), getPointerTy()),
5150                          Result);
5151   }
5152
5153   return Result;
5154 }
5155
5156 SDValue
5157 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
5158   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
5159
5160   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5161   // global base reg.
5162   unsigned char OpFlag = 0;
5163   unsigned WrapperKind = X86ISD::Wrapper;
5164   CodeModel::Model M = getTargetMachine().getCodeModel();
5165
5166   if (Subtarget->isPICStyleRIPRel() &&
5167       (M == CodeModel::Small || M == CodeModel::Kernel))
5168     WrapperKind = X86ISD::WrapperRIP;
5169   else if (Subtarget->isPICStyleGOT())
5170     OpFlag = X86II::MO_GOTOFF;
5171   else if (Subtarget->isPICStyleStubPIC())
5172     OpFlag = X86II::MO_PIC_BASE_OFFSET;
5173
5174   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
5175
5176   DebugLoc DL = Op.getDebugLoc();
5177   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5178
5179
5180   // With PIC, the address is actually $g + Offset.
5181   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
5182       !Subtarget->is64Bit()) {
5183     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5184                          DAG.getNode(X86ISD::GlobalBaseReg,
5185                                      DebugLoc(), getPointerTy()),
5186                          Result);
5187   }
5188
5189   return Result;
5190 }
5191
5192 SDValue
5193 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
5194   // Create the TargetBlockAddressAddress node.
5195   unsigned char OpFlags =
5196     Subtarget->ClassifyBlockAddressReference();
5197   CodeModel::Model M = getTargetMachine().getCodeModel();
5198   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
5199   DebugLoc dl = Op.getDebugLoc();
5200   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
5201                                        /*isTarget=*/true, OpFlags);
5202
5203   if (Subtarget->isPICStyleRIPRel() &&
5204       (M == CodeModel::Small || M == CodeModel::Kernel))
5205     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
5206   else
5207     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
5208
5209   // With PIC, the address is actually $g + Offset.
5210   if (isGlobalRelativeToPICBase(OpFlags)) {
5211     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5212                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
5213                          Result);
5214   }
5215
5216   return Result;
5217 }
5218
5219 SDValue
5220 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
5221                                       int64_t Offset,
5222                                       SelectionDAG &DAG) const {
5223   // Create the TargetGlobalAddress node, folding in the constant
5224   // offset if it is legal.
5225   unsigned char OpFlags =
5226     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
5227   CodeModel::Model M = getTargetMachine().getCodeModel();
5228   SDValue Result;
5229   if (OpFlags == X86II::MO_NO_FLAG &&
5230       X86::isOffsetSuitableForCodeModel(Offset, M)) {
5231     // A direct static reference to a global.
5232     Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), Offset);
5233     Offset = 0;
5234   } else {
5235     Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), 0, OpFlags);
5236   }
5237
5238   if (Subtarget->isPICStyleRIPRel() &&
5239       (M == CodeModel::Small || M == CodeModel::Kernel))
5240     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
5241   else
5242     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
5243
5244   // With PIC, the address is actually $g + Offset.
5245   if (isGlobalRelativeToPICBase(OpFlags)) {
5246     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5247                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
5248                          Result);
5249   }
5250
5251   // For globals that require a load from a stub to get the address, emit the
5252   // load.
5253   if (isGlobalStubReference(OpFlags))
5254     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
5255                          PseudoSourceValue::getGOT(), 0, false, false, 0);
5256
5257   // If there was a non-zero offset that we didn't fold, create an explicit
5258   // addition for it.
5259   if (Offset != 0)
5260     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
5261                          DAG.getConstant(Offset, getPointerTy()));
5262
5263   return Result;
5264 }
5265
5266 SDValue
5267 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
5268   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
5269   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
5270   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
5271 }
5272
5273 static SDValue
5274 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
5275            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
5276            unsigned char OperandFlags) {
5277   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5278   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
5279   DebugLoc dl = GA->getDebugLoc();
5280   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
5281                                            GA->getValueType(0),
5282                                            GA->getOffset(),
5283                                            OperandFlags);
5284   if (InFlag) {
5285     SDValue Ops[] = { Chain,  TGA, *InFlag };
5286     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
5287   } else {
5288     SDValue Ops[]  = { Chain, TGA };
5289     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
5290   }
5291
5292   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
5293   MFI->setAdjustsStack(true);
5294
5295   SDValue Flag = Chain.getValue(1);
5296   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
5297 }
5298
5299 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
5300 static SDValue
5301 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5302                                 const EVT PtrVT) {
5303   SDValue InFlag;
5304   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
5305   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
5306                                      DAG.getNode(X86ISD::GlobalBaseReg,
5307                                                  DebugLoc(), PtrVT), InFlag);
5308   InFlag = Chain.getValue(1);
5309
5310   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
5311 }
5312
5313 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
5314 static SDValue
5315 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5316                                 const EVT PtrVT) {
5317   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
5318                     X86::RAX, X86II::MO_TLSGD);
5319 }
5320
5321 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
5322 // "local exec" model.
5323 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5324                                    const EVT PtrVT, TLSModel::Model model,
5325                                    bool is64Bit) {
5326   DebugLoc dl = GA->getDebugLoc();
5327   // Get the Thread Pointer
5328   SDValue Base = DAG.getNode(X86ISD::SegmentBaseAddress,
5329                              DebugLoc(), PtrVT,
5330                              DAG.getRegister(is64Bit? X86::FS : X86::GS,
5331                                              MVT::i32));
5332
5333   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Base,
5334                                       NULL, 0, false, false, 0);
5335
5336   unsigned char OperandFlags = 0;
5337   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
5338   // initialexec.
5339   unsigned WrapperKind = X86ISD::Wrapper;
5340   if (model == TLSModel::LocalExec) {
5341     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
5342   } else if (is64Bit) {
5343     assert(model == TLSModel::InitialExec);
5344     OperandFlags = X86II::MO_GOTTPOFF;
5345     WrapperKind = X86ISD::WrapperRIP;
5346   } else {
5347     assert(model == TLSModel::InitialExec);
5348     OperandFlags = X86II::MO_INDNTPOFF;
5349   }
5350
5351   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
5352   // exec)
5353   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
5354                                            GA->getOffset(), OperandFlags);
5355   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
5356
5357   if (model == TLSModel::InitialExec)
5358     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
5359                          PseudoSourceValue::getGOT(), 0, false, false, 0);
5360
5361   // The address of the thread local variable is the add of the thread
5362   // pointer with the offset of the variable.
5363   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
5364 }
5365
5366 SDValue
5367 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
5368   
5369   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
5370   const GlobalValue *GV = GA->getGlobal();
5371
5372   if (Subtarget->isTargetELF()) {
5373     // TODO: implement the "local dynamic" model
5374     // TODO: implement the "initial exec"model for pic executables
5375     
5376     // If GV is an alias then use the aliasee for determining
5377     // thread-localness.
5378     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
5379       GV = GA->resolveAliasedGlobal(false);
5380     
5381     TLSModel::Model model 
5382       = getTLSModel(GV, getTargetMachine().getRelocationModel());
5383     
5384     switch (model) {
5385       case TLSModel::GeneralDynamic:
5386       case TLSModel::LocalDynamic: // not implemented
5387         if (Subtarget->is64Bit())
5388           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
5389         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
5390         
5391       case TLSModel::InitialExec:
5392       case TLSModel::LocalExec:
5393         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
5394                                    Subtarget->is64Bit());
5395     }
5396   } else if (Subtarget->isTargetDarwin()) {
5397     // Darwin only has one model of TLS.  Lower to that.
5398     unsigned char OpFlag = 0;
5399     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
5400                            X86ISD::WrapperRIP : X86ISD::Wrapper;
5401     
5402     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5403     // global base reg.
5404     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
5405                   !Subtarget->is64Bit();
5406     if (PIC32)
5407       OpFlag = X86II::MO_TLVP_PIC_BASE;
5408     else
5409       OpFlag = X86II::MO_TLVP;
5410     
5411     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), 
5412                                                 getPointerTy(),
5413                                                 GA->getOffset(), OpFlag);
5414     
5415     DebugLoc DL = Op.getDebugLoc();
5416     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5417   
5418     // With PIC32, the address is actually $g + Offset.
5419     if (PIC32)
5420       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5421                            DAG.getNode(X86ISD::GlobalBaseReg,
5422                                        DebugLoc(), getPointerTy()),
5423                            Offset);
5424     
5425     // Lowering the machine isd will make sure everything is in the right
5426     // location.
5427     SDValue Args[] = { Offset };
5428     SDValue Chain = DAG.getNode(X86ISD::TLSCALL, DL, MVT::Other, Args, 1);
5429     
5430     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
5431     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5432     MFI->setAdjustsStack(true);
5433
5434     // And our return value (tls address) is in the standard call return value
5435     // location.
5436     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
5437     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
5438   }
5439   
5440   assert(false &&
5441          "TLS not implemented for this target.");
5442
5443   llvm_unreachable("Unreachable");
5444   return SDValue();
5445 }
5446
5447
5448 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
5449 /// take a 2 x i32 value to shift plus a shift amount.
5450 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
5451   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5452   EVT VT = Op.getValueType();
5453   unsigned VTBits = VT.getSizeInBits();
5454   DebugLoc dl = Op.getDebugLoc();
5455   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
5456   SDValue ShOpLo = Op.getOperand(0);
5457   SDValue ShOpHi = Op.getOperand(1);
5458   SDValue ShAmt  = Op.getOperand(2);
5459   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
5460                                      DAG.getConstant(VTBits - 1, MVT::i8))
5461                        : DAG.getConstant(0, VT);
5462
5463   SDValue Tmp2, Tmp3;
5464   if (Op.getOpcode() == ISD::SHL_PARTS) {
5465     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
5466     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5467   } else {
5468     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
5469     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
5470   }
5471
5472   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
5473                                 DAG.getConstant(VTBits, MVT::i8));
5474   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
5475                              AndNode, DAG.getConstant(0, MVT::i8));
5476
5477   SDValue Hi, Lo;
5478   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5479   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
5480   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
5481
5482   if (Op.getOpcode() == ISD::SHL_PARTS) {
5483     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
5484     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
5485   } else {
5486     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
5487     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
5488   }
5489
5490   SDValue Ops[2] = { Lo, Hi };
5491   return DAG.getMergeValues(Ops, 2, dl);
5492 }
5493
5494 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
5495                                            SelectionDAG &DAG) const {
5496   EVT SrcVT = Op.getOperand(0).getValueType();
5497
5498   if (SrcVT.isVector()) {
5499     if (SrcVT == MVT::v2i32 && Op.getValueType() == MVT::v2f64) {
5500       return Op;
5501     }
5502     return SDValue();
5503   }
5504
5505   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
5506          "Unknown SINT_TO_FP to lower!");
5507
5508   // These are really Legal; return the operand so the caller accepts it as
5509   // Legal.
5510   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
5511     return Op;
5512   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
5513       Subtarget->is64Bit()) {
5514     return Op;
5515   }
5516
5517   DebugLoc dl = Op.getDebugLoc();
5518   unsigned Size = SrcVT.getSizeInBits()/8;
5519   MachineFunction &MF = DAG.getMachineFunction();
5520   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
5521   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5522   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5523                                StackSlot,
5524                                PseudoSourceValue::getFixedStack(SSFI), 0,
5525                                false, false, 0);
5526   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
5527 }
5528
5529 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
5530                                      SDValue StackSlot, 
5531                                      SelectionDAG &DAG) const {
5532   // Build the FILD
5533   DebugLoc dl = Op.getDebugLoc();
5534   SDVTList Tys;
5535   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
5536   if (useSSE)
5537     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
5538   else
5539     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
5540   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
5541   SDValue Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD, dl,
5542                                Tys, Ops, array_lengthof(Ops));
5543
5544   if (useSSE) {
5545     Chain = Result.getValue(1);
5546     SDValue InFlag = Result.getValue(2);
5547
5548     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
5549     // shouldn't be necessary except that RFP cannot be live across
5550     // multiple blocks. When stackifier is fixed, they can be uncoupled.
5551     MachineFunction &MF = DAG.getMachineFunction();
5552     int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
5553     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5554     Tys = DAG.getVTList(MVT::Other);
5555     SDValue Ops[] = {
5556       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
5557     };
5558     Chain = DAG.getNode(X86ISD::FST, dl, Tys, Ops, array_lengthof(Ops));
5559     Result = DAG.getLoad(Op.getValueType(), dl, Chain, StackSlot,
5560                          PseudoSourceValue::getFixedStack(SSFI), 0,
5561                          false, false, 0);
5562   }
5563
5564   return Result;
5565 }
5566
5567 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
5568 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
5569                                                SelectionDAG &DAG) const {
5570   // This algorithm is not obvious. Here it is in C code, more or less:
5571   /*
5572     double uint64_to_double( uint32_t hi, uint32_t lo ) {
5573       static const __m128i exp = { 0x4330000045300000ULL, 0 };
5574       static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
5575
5576       // Copy ints to xmm registers.
5577       __m128i xh = _mm_cvtsi32_si128( hi );
5578       __m128i xl = _mm_cvtsi32_si128( lo );
5579
5580       // Combine into low half of a single xmm register.
5581       __m128i x = _mm_unpacklo_epi32( xh, xl );
5582       __m128d d;
5583       double sd;
5584
5585       // Merge in appropriate exponents to give the integer bits the right
5586       // magnitude.
5587       x = _mm_unpacklo_epi32( x, exp );
5588
5589       // Subtract away the biases to deal with the IEEE-754 double precision
5590       // implicit 1.
5591       d = _mm_sub_pd( (__m128d) x, bias );
5592
5593       // All conversions up to here are exact. The correctly rounded result is
5594       // calculated using the current rounding mode using the following
5595       // horizontal add.
5596       d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
5597       _mm_store_sd( &sd, d );   // Because we are returning doubles in XMM, this
5598                                 // store doesn't really need to be here (except
5599                                 // maybe to zero the other double)
5600       return sd;
5601     }
5602   */
5603
5604   DebugLoc dl = Op.getDebugLoc();
5605   LLVMContext *Context = DAG.getContext();
5606
5607   // Build some magic constants.
5608   std::vector<Constant*> CV0;
5609   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
5610   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
5611   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
5612   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
5613   Constant *C0 = ConstantVector::get(CV0);
5614   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
5615
5616   std::vector<Constant*> CV1;
5617   CV1.push_back(
5618     ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
5619   CV1.push_back(
5620     ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
5621   Constant *C1 = ConstantVector::get(CV1);
5622   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
5623
5624   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5625                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5626                                         Op.getOperand(0),
5627                                         DAG.getIntPtrConstant(1)));
5628   SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5629                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5630                                         Op.getOperand(0),
5631                                         DAG.getIntPtrConstant(0)));
5632   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
5633   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
5634                               PseudoSourceValue::getConstantPool(), 0,
5635                               false, false, 16);
5636   SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
5637   SDValue XR2F = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Unpck2);
5638   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
5639                               PseudoSourceValue::getConstantPool(), 0,
5640                               false, false, 16);
5641   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
5642
5643   // Add the halves; easiest way is to swap them into another reg first.
5644   int ShufMask[2] = { 1, -1 };
5645   SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
5646                                       DAG.getUNDEF(MVT::v2f64), ShufMask);
5647   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
5648   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
5649                      DAG.getIntPtrConstant(0));
5650 }
5651
5652 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
5653 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
5654                                                SelectionDAG &DAG) const {
5655   DebugLoc dl = Op.getDebugLoc();
5656   // FP constant to bias correct the final result.
5657   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
5658                                    MVT::f64);
5659
5660   // Load the 32-bit value into an XMM register.
5661   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5662                              DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5663                                          Op.getOperand(0),
5664                                          DAG.getIntPtrConstant(0)));
5665
5666   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5667                      DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Load),
5668                      DAG.getIntPtrConstant(0));
5669
5670   // Or the load with the bias.
5671   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
5672                            DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5673                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5674                                                    MVT::v2f64, Load)),
5675                            DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5676                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5677                                                    MVT::v2f64, Bias)));
5678   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5679                    DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Or),
5680                    DAG.getIntPtrConstant(0));
5681
5682   // Subtract the bias.
5683   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
5684
5685   // Handle final rounding.
5686   EVT DestVT = Op.getValueType();
5687
5688   if (DestVT.bitsLT(MVT::f64)) {
5689     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
5690                        DAG.getIntPtrConstant(0));
5691   } else if (DestVT.bitsGT(MVT::f64)) {
5692     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
5693   }
5694
5695   // Handle final rounding.
5696   return Sub;
5697 }
5698
5699 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
5700                                            SelectionDAG &DAG) const {
5701   SDValue N0 = Op.getOperand(0);
5702   DebugLoc dl = Op.getDebugLoc();
5703
5704   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
5705   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
5706   // the optimization here.
5707   if (DAG.SignBitIsZero(N0))
5708     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
5709
5710   EVT SrcVT = N0.getValueType();
5711   EVT DstVT = Op.getValueType();
5712   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
5713     return LowerUINT_TO_FP_i64(Op, DAG);
5714   else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
5715     return LowerUINT_TO_FP_i32(Op, DAG);
5716
5717   // Make a 64-bit buffer, and use it to build an FILD.
5718   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
5719   if (SrcVT == MVT::i32) {
5720     SDValue WordOff = DAG.getConstant(4, getPointerTy());
5721     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
5722                                      getPointerTy(), StackSlot, WordOff);
5723     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5724                                   StackSlot, NULL, 0, false, false, 0);
5725     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
5726                                   OffsetSlot, NULL, 0, false, false, 0);
5727     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
5728     return Fild;
5729   }
5730
5731   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
5732   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5733                                 StackSlot, NULL, 0, false, false, 0);
5734   // For i64 source, we need to add the appropriate power of 2 if the input
5735   // was negative.  This is the same as the optimization in
5736   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
5737   // we must be careful to do the computation in x87 extended precision, not
5738   // in SSE. (The generic code can't know it's OK to do this, or how to.)
5739   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
5740   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
5741   SDValue Fild = DAG.getNode(X86ISD::FILD, dl, Tys, Ops, 3);
5742
5743   APInt FF(32, 0x5F800000ULL);
5744
5745   // Check whether the sign bit is set.
5746   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
5747                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
5748                                  ISD::SETLT);
5749
5750   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
5751   SDValue FudgePtr = DAG.getConstantPool(
5752                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
5753                                          getPointerTy());
5754
5755   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
5756   SDValue Zero = DAG.getIntPtrConstant(0);
5757   SDValue Four = DAG.getIntPtrConstant(4);
5758   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
5759                                Zero, Four);
5760   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
5761
5762   // Load the value out, extending it from f32 to f80.
5763   // FIXME: Avoid the extend by constructing the right constant pool?
5764   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
5765                                  FudgePtr, PseudoSourceValue::getConstantPool(),
5766                                  0, MVT::f32, false, false, 4);
5767   // Extend everything to 80 bits to force it to be done on x87.
5768   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
5769   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
5770 }
5771
5772 std::pair<SDValue,SDValue> X86TargetLowering::
5773 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
5774   DebugLoc dl = Op.getDebugLoc();
5775
5776   EVT DstTy = Op.getValueType();
5777
5778   if (!IsSigned) {
5779     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
5780     DstTy = MVT::i64;
5781   }
5782
5783   assert(DstTy.getSimpleVT() <= MVT::i64 &&
5784          DstTy.getSimpleVT() >= MVT::i16 &&
5785          "Unknown FP_TO_SINT to lower!");
5786
5787   // These are really Legal.
5788   if (DstTy == MVT::i32 &&
5789       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5790     return std::make_pair(SDValue(), SDValue());
5791   if (Subtarget->is64Bit() &&
5792       DstTy == MVT::i64 &&
5793       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5794     return std::make_pair(SDValue(), SDValue());
5795
5796   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
5797   // stack slot.
5798   MachineFunction &MF = DAG.getMachineFunction();
5799   unsigned MemSize = DstTy.getSizeInBits()/8;
5800   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
5801   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5802
5803   unsigned Opc;
5804   switch (DstTy.getSimpleVT().SimpleTy) {
5805   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
5806   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
5807   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
5808   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
5809   }
5810
5811   SDValue Chain = DAG.getEntryNode();
5812   SDValue Value = Op.getOperand(0);
5813   if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
5814     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
5815     Chain = DAG.getStore(Chain, dl, Value, StackSlot,
5816                          PseudoSourceValue::getFixedStack(SSFI), 0,
5817                          false, false, 0);
5818     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
5819     SDValue Ops[] = {
5820       Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
5821     };
5822     Value = DAG.getNode(X86ISD::FLD, dl, Tys, Ops, 3);
5823     Chain = Value.getValue(1);
5824     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
5825     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5826   }
5827
5828   // Build the FP_TO_INT*_IN_MEM
5829   SDValue Ops[] = { Chain, Value, StackSlot };
5830   SDValue FIST = DAG.getNode(Opc, dl, MVT::Other, Ops, 3);
5831
5832   return std::make_pair(FIST, StackSlot);
5833 }
5834
5835 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
5836                                            SelectionDAG &DAG) const {
5837   if (Op.getValueType().isVector()) {
5838     if (Op.getValueType() == MVT::v2i32 &&
5839         Op.getOperand(0).getValueType() == MVT::v2f64) {
5840       return Op;
5841     }
5842     return SDValue();
5843   }
5844
5845   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
5846   SDValue FIST = Vals.first, StackSlot = Vals.second;
5847   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
5848   if (FIST.getNode() == 0) return Op;
5849
5850   // Load the result.
5851   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5852                      FIST, StackSlot, NULL, 0, false, false, 0);
5853 }
5854
5855 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
5856                                            SelectionDAG &DAG) const {
5857   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
5858   SDValue FIST = Vals.first, StackSlot = Vals.second;
5859   assert(FIST.getNode() && "Unexpected failure");
5860
5861   // Load the result.
5862   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5863                      FIST, StackSlot, NULL, 0, false, false, 0);
5864 }
5865
5866 SDValue X86TargetLowering::LowerFABS(SDValue Op,
5867                                      SelectionDAG &DAG) const {
5868   LLVMContext *Context = DAG.getContext();
5869   DebugLoc dl = Op.getDebugLoc();
5870   EVT VT = Op.getValueType();
5871   EVT EltVT = VT;
5872   if (VT.isVector())
5873     EltVT = VT.getVectorElementType();
5874   std::vector<Constant*> CV;
5875   if (EltVT == MVT::f64) {
5876     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
5877     CV.push_back(C);
5878     CV.push_back(C);
5879   } else {
5880     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
5881     CV.push_back(C);
5882     CV.push_back(C);
5883     CV.push_back(C);
5884     CV.push_back(C);
5885   }
5886   Constant *C = ConstantVector::get(CV);
5887   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5888   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5889                              PseudoSourceValue::getConstantPool(), 0,
5890                              false, false, 16);
5891   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
5892 }
5893
5894 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
5895   LLVMContext *Context = DAG.getContext();
5896   DebugLoc dl = Op.getDebugLoc();
5897   EVT VT = Op.getValueType();
5898   EVT EltVT = VT;
5899   if (VT.isVector())
5900     EltVT = VT.getVectorElementType();
5901   std::vector<Constant*> CV;
5902   if (EltVT == MVT::f64) {
5903     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
5904     CV.push_back(C);
5905     CV.push_back(C);
5906   } else {
5907     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
5908     CV.push_back(C);
5909     CV.push_back(C);
5910     CV.push_back(C);
5911     CV.push_back(C);
5912   }
5913   Constant *C = ConstantVector::get(CV);
5914   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5915   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5916                              PseudoSourceValue::getConstantPool(), 0,
5917                              false, false, 16);
5918   if (VT.isVector()) {
5919     return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
5920                        DAG.getNode(ISD::XOR, dl, MVT::v2i64,
5921                     DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5922                                 Op.getOperand(0)),
5923                     DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, Mask)));
5924   } else {
5925     return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
5926   }
5927 }
5928
5929 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
5930   LLVMContext *Context = DAG.getContext();
5931   SDValue Op0 = Op.getOperand(0);
5932   SDValue Op1 = Op.getOperand(1);
5933   DebugLoc dl = Op.getDebugLoc();
5934   EVT VT = Op.getValueType();
5935   EVT SrcVT = Op1.getValueType();
5936
5937   // If second operand is smaller, extend it first.
5938   if (SrcVT.bitsLT(VT)) {
5939     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
5940     SrcVT = VT;
5941   }
5942   // And if it is bigger, shrink it first.
5943   if (SrcVT.bitsGT(VT)) {
5944     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
5945     SrcVT = VT;
5946   }
5947
5948   // At this point the operands and the result should have the same
5949   // type, and that won't be f80 since that is not custom lowered.
5950
5951   // First get the sign bit of second operand.
5952   std::vector<Constant*> CV;
5953   if (SrcVT == MVT::f64) {
5954     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
5955     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
5956   } else {
5957     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
5958     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5959     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5960     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5961   }
5962   Constant *C = ConstantVector::get(CV);
5963   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5964   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
5965                               PseudoSourceValue::getConstantPool(), 0,
5966                               false, false, 16);
5967   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
5968
5969   // Shift sign bit right or left if the two operands have different types.
5970   if (SrcVT.bitsGT(VT)) {
5971     // Op0 is MVT::f32, Op1 is MVT::f64.
5972     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
5973     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
5974                           DAG.getConstant(32, MVT::i32));
5975     SignBit = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, SignBit);
5976     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
5977                           DAG.getIntPtrConstant(0));
5978   }
5979
5980   // Clear first operand sign bit.
5981   CV.clear();
5982   if (VT == MVT::f64) {
5983     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
5984     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
5985   } else {
5986     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
5987     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5988     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5989     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5990   }
5991   C = ConstantVector::get(CV);
5992   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5993   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5994                               PseudoSourceValue::getConstantPool(), 0,
5995                               false, false, 16);
5996   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
5997
5998   // Or the value with the sign bit.
5999   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
6000 }
6001
6002 /// Emit nodes that will be selected as "test Op0,Op0", or something
6003 /// equivalent.
6004 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
6005                                     SelectionDAG &DAG) const {
6006   DebugLoc dl = Op.getDebugLoc();
6007
6008   // CF and OF aren't always set the way we want. Determine which
6009   // of these we need.
6010   bool NeedCF = false;
6011   bool NeedOF = false;
6012   switch (X86CC) {
6013   default: break;
6014   case X86::COND_A: case X86::COND_AE:
6015   case X86::COND_B: case X86::COND_BE:
6016     NeedCF = true;
6017     break;
6018   case X86::COND_G: case X86::COND_GE:
6019   case X86::COND_L: case X86::COND_LE:
6020   case X86::COND_O: case X86::COND_NO:
6021     NeedOF = true;
6022     break;
6023   }
6024
6025   // See if we can use the EFLAGS value from the operand instead of
6026   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
6027   // we prove that the arithmetic won't overflow, we can't use OF or CF.
6028   if (Op.getResNo() != 0 || NeedOF || NeedCF)
6029     // Emit a CMP with 0, which is the TEST pattern.
6030     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
6031                        DAG.getConstant(0, Op.getValueType()));
6032
6033   unsigned Opcode = 0;
6034   unsigned NumOperands = 0;
6035   switch (Op.getNode()->getOpcode()) {
6036   case ISD::ADD:
6037     // Due to an isel shortcoming, be conservative if this add is likely to be
6038     // selected as part of a load-modify-store instruction. When the root node
6039     // in a match is a store, isel doesn't know how to remap non-chain non-flag
6040     // uses of other nodes in the match, such as the ADD in this case. This
6041     // leads to the ADD being left around and reselected, with the result being
6042     // two adds in the output.  Alas, even if none our users are stores, that
6043     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
6044     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
6045     // climbing the DAG back to the root, and it doesn't seem to be worth the
6046     // effort.
6047     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6048            UE = Op.getNode()->use_end(); UI != UE; ++UI)
6049       if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
6050         goto default_case;
6051
6052     if (ConstantSDNode *C =
6053         dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
6054       // An add of one will be selected as an INC.
6055       if (C->getAPIntValue() == 1) {
6056         Opcode = X86ISD::INC;
6057         NumOperands = 1;
6058         break;
6059       }
6060
6061       // An add of negative one (subtract of one) will be selected as a DEC.
6062       if (C->getAPIntValue().isAllOnesValue()) {
6063         Opcode = X86ISD::DEC;
6064         NumOperands = 1;
6065         break;
6066       }
6067     }
6068
6069     // Otherwise use a regular EFLAGS-setting add.
6070     Opcode = X86ISD::ADD;
6071     NumOperands = 2;
6072     break;
6073   case ISD::AND: {
6074     // If the primary and result isn't used, don't bother using X86ISD::AND,
6075     // because a TEST instruction will be better.
6076     bool NonFlagUse = false;
6077     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6078            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
6079       SDNode *User = *UI;
6080       unsigned UOpNo = UI.getOperandNo();
6081       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
6082         // Look pass truncate.
6083         UOpNo = User->use_begin().getOperandNo();
6084         User = *User->use_begin();
6085       }
6086
6087       if (User->getOpcode() != ISD::BRCOND &&
6088           User->getOpcode() != ISD::SETCC &&
6089           (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
6090         NonFlagUse = true;
6091         break;
6092       }
6093     }
6094
6095     if (!NonFlagUse)
6096       break;
6097   }
6098     // FALL THROUGH
6099   case ISD::SUB:
6100   case ISD::OR:
6101   case ISD::XOR:
6102     // Due to the ISEL shortcoming noted above, be conservative if this op is
6103     // likely to be selected as part of a load-modify-store instruction.
6104     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6105            UE = Op.getNode()->use_end(); UI != UE; ++UI)
6106       if (UI->getOpcode() == ISD::STORE)
6107         goto default_case;
6108
6109     // Otherwise use a regular EFLAGS-setting instruction.
6110     switch (Op.getNode()->getOpcode()) {
6111     default: llvm_unreachable("unexpected operator!");
6112     case ISD::SUB: Opcode = X86ISD::SUB; break;
6113     case ISD::OR:  Opcode = X86ISD::OR;  break;
6114     case ISD::XOR: Opcode = X86ISD::XOR; break;
6115     case ISD::AND: Opcode = X86ISD::AND; break;
6116     }
6117
6118     NumOperands = 2;
6119     break;
6120   case X86ISD::ADD:
6121   case X86ISD::SUB:
6122   case X86ISD::INC:
6123   case X86ISD::DEC:
6124   case X86ISD::OR:
6125   case X86ISD::XOR:
6126   case X86ISD::AND:
6127     return SDValue(Op.getNode(), 1);
6128   default:
6129   default_case:
6130     break;
6131   }
6132
6133   if (Opcode == 0)
6134     // Emit a CMP with 0, which is the TEST pattern.
6135     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
6136                        DAG.getConstant(0, Op.getValueType()));
6137
6138   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
6139   SmallVector<SDValue, 4> Ops;
6140   for (unsigned i = 0; i != NumOperands; ++i)
6141     Ops.push_back(Op.getOperand(i));
6142
6143   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
6144   DAG.ReplaceAllUsesWith(Op, New);
6145   return SDValue(New.getNode(), 1);
6146 }
6147
6148 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
6149 /// equivalent.
6150 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
6151                                    SelectionDAG &DAG) const {
6152   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
6153     if (C->getAPIntValue() == 0)
6154       return EmitTest(Op0, X86CC, DAG);
6155
6156   DebugLoc dl = Op0.getDebugLoc();
6157   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
6158 }
6159
6160 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
6161 /// if it's possible.
6162 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
6163                                      DebugLoc dl, SelectionDAG &DAG) const {
6164   SDValue Op0 = And.getOperand(0);
6165   SDValue Op1 = And.getOperand(1);
6166   if (Op0.getOpcode() == ISD::TRUNCATE)
6167     Op0 = Op0.getOperand(0);
6168   if (Op1.getOpcode() == ISD::TRUNCATE)
6169     Op1 = Op1.getOperand(0);
6170
6171   SDValue LHS, RHS;
6172   if (Op1.getOpcode() == ISD::SHL)
6173     std::swap(Op0, Op1);
6174   if (Op0.getOpcode() == ISD::SHL) {
6175     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
6176       if (And00C->getZExtValue() == 1) {
6177         // If we looked past a truncate, check that it's only truncating away
6178         // known zeros.
6179         unsigned BitWidth = Op0.getValueSizeInBits();
6180         unsigned AndBitWidth = And.getValueSizeInBits();
6181         if (BitWidth > AndBitWidth) {
6182           APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
6183           DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
6184           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
6185             return SDValue();
6186         }
6187         LHS = Op1;
6188         RHS = Op0.getOperand(1);
6189       }
6190   } else if (Op1.getOpcode() == ISD::Constant) {
6191     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
6192     SDValue AndLHS = Op0;
6193     if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
6194       LHS = AndLHS.getOperand(0);
6195       RHS = AndLHS.getOperand(1);
6196     }
6197   }
6198
6199   if (LHS.getNode()) {
6200     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
6201     // instruction.  Since the shift amount is in-range-or-undefined, we know
6202     // that doing a bittest on the i32 value is ok.  We extend to i32 because
6203     // the encoding for the i16 version is larger than the i32 version.
6204     // Also promote i16 to i32 for performance / code size reason.
6205     if (LHS.getValueType() == MVT::i8 ||
6206         LHS.getValueType() == MVT::i16)
6207       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
6208
6209     // If the operand types disagree, extend the shift amount to match.  Since
6210     // BT ignores high bits (like shifts) we can use anyextend.
6211     if (LHS.getValueType() != RHS.getValueType())
6212       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
6213
6214     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
6215     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
6216     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6217                        DAG.getConstant(Cond, MVT::i8), BT);
6218   }
6219
6220   return SDValue();
6221 }
6222
6223 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
6224   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
6225   SDValue Op0 = Op.getOperand(0);
6226   SDValue Op1 = Op.getOperand(1);
6227   DebugLoc dl = Op.getDebugLoc();
6228   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6229
6230   // Optimize to BT if possible.
6231   // Lower (X & (1 << N)) == 0 to BT(X, N).
6232   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
6233   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
6234   if (Op0.getOpcode() == ISD::AND &&
6235       Op0.hasOneUse() &&
6236       Op1.getOpcode() == ISD::Constant &&
6237       cast<ConstantSDNode>(Op1)->isNullValue() &&
6238       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
6239     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
6240     if (NewSetCC.getNode())
6241       return NewSetCC;
6242   }
6243
6244   // Look for "(setcc) == / != 1" to avoid unncessary setcc.
6245   if (Op0.getOpcode() == X86ISD::SETCC &&
6246       Op1.getOpcode() == ISD::Constant &&
6247       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
6248        cast<ConstantSDNode>(Op1)->isNullValue()) &&
6249       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
6250     X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
6251     bool Invert = (CC == ISD::SETNE) ^
6252       cast<ConstantSDNode>(Op1)->isNullValue();
6253     if (Invert)
6254       CCode = X86::GetOppositeBranchCondition(CCode);
6255     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6256                        DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
6257   }
6258
6259   bool isFP = Op1.getValueType().isFloatingPoint();
6260   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
6261   if (X86CC == X86::COND_INVALID)
6262     return SDValue();
6263
6264   SDValue Cond = EmitCmp(Op0, Op1, X86CC, DAG);
6265
6266   // Use sbb x, x to materialize carry bit into a GPR.
6267   if (X86CC == X86::COND_B)
6268     return DAG.getNode(ISD::AND, dl, MVT::i8,
6269                        DAG.getNode(X86ISD::SETCC_CARRY, dl, MVT::i8,
6270                                    DAG.getConstant(X86CC, MVT::i8), Cond),
6271                        DAG.getConstant(1, MVT::i8));
6272
6273   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6274                      DAG.getConstant(X86CC, MVT::i8), Cond);
6275 }
6276
6277 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
6278   SDValue Cond;
6279   SDValue Op0 = Op.getOperand(0);
6280   SDValue Op1 = Op.getOperand(1);
6281   SDValue CC = Op.getOperand(2);
6282   EVT VT = Op.getValueType();
6283   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
6284   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
6285   DebugLoc dl = Op.getDebugLoc();
6286
6287   if (isFP) {
6288     unsigned SSECC = 8;
6289     EVT VT0 = Op0.getValueType();
6290     assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
6291     unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
6292     bool Swap = false;
6293
6294     switch (SetCCOpcode) {
6295     default: break;
6296     case ISD::SETOEQ:
6297     case ISD::SETEQ:  SSECC = 0; break;
6298     case ISD::SETOGT:
6299     case ISD::SETGT: Swap = true; // Fallthrough
6300     case ISD::SETLT:
6301     case ISD::SETOLT: SSECC = 1; break;
6302     case ISD::SETOGE:
6303     case ISD::SETGE: Swap = true; // Fallthrough
6304     case ISD::SETLE:
6305     case ISD::SETOLE: SSECC = 2; break;
6306     case ISD::SETUO:  SSECC = 3; break;
6307     case ISD::SETUNE:
6308     case ISD::SETNE:  SSECC = 4; break;
6309     case ISD::SETULE: Swap = true;
6310     case ISD::SETUGE: SSECC = 5; break;
6311     case ISD::SETULT: Swap = true;
6312     case ISD::SETUGT: SSECC = 6; break;
6313     case ISD::SETO:   SSECC = 7; break;
6314     }
6315     if (Swap)
6316       std::swap(Op0, Op1);
6317
6318     // In the two special cases we can't handle, emit two comparisons.
6319     if (SSECC == 8) {
6320       if (SetCCOpcode == ISD::SETUEQ) {
6321         SDValue UNORD, EQ;
6322         UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
6323         EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
6324         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
6325       }
6326       else if (SetCCOpcode == ISD::SETONE) {
6327         SDValue ORD, NEQ;
6328         ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
6329         NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
6330         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
6331       }
6332       llvm_unreachable("Illegal FP comparison");
6333     }
6334     // Handle all other FP comparisons here.
6335     return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
6336   }
6337
6338   // We are handling one of the integer comparisons here.  Since SSE only has
6339   // GT and EQ comparisons for integer, swapping operands and multiple
6340   // operations may be required for some comparisons.
6341   unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
6342   bool Swap = false, Invert = false, FlipSigns = false;
6343
6344   switch (VT.getSimpleVT().SimpleTy) {
6345   default: break;
6346   case MVT::v8i8:
6347   case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
6348   case MVT::v4i16:
6349   case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
6350   case MVT::v2i32:
6351   case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
6352   case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
6353   }
6354
6355   switch (SetCCOpcode) {
6356   default: break;
6357   case ISD::SETNE:  Invert = true;
6358   case ISD::SETEQ:  Opc = EQOpc; break;
6359   case ISD::SETLT:  Swap = true;
6360   case ISD::SETGT:  Opc = GTOpc; break;
6361   case ISD::SETGE:  Swap = true;
6362   case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
6363   case ISD::SETULT: Swap = true;
6364   case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
6365   case ISD::SETUGE: Swap = true;
6366   case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
6367   }
6368   if (Swap)
6369     std::swap(Op0, Op1);
6370
6371   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
6372   // bits of the inputs before performing those operations.
6373   if (FlipSigns) {
6374     EVT EltVT = VT.getVectorElementType();
6375     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
6376                                       EltVT);
6377     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
6378     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
6379                                     SignBits.size());
6380     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
6381     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
6382   }
6383
6384   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
6385
6386   // If the logical-not of the result is required, perform that now.
6387   if (Invert)
6388     Result = DAG.getNOT(dl, Result, VT);
6389
6390   return Result;
6391 }
6392
6393 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
6394 static bool isX86LogicalCmp(SDValue Op) {
6395   unsigned Opc = Op.getNode()->getOpcode();
6396   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
6397     return true;
6398   if (Op.getResNo() == 1 &&
6399       (Opc == X86ISD::ADD ||
6400        Opc == X86ISD::SUB ||
6401        Opc == X86ISD::SMUL ||
6402        Opc == X86ISD::UMUL ||
6403        Opc == X86ISD::INC ||
6404        Opc == X86ISD::DEC ||
6405        Opc == X86ISD::OR ||
6406        Opc == X86ISD::XOR ||
6407        Opc == X86ISD::AND))
6408     return true;
6409
6410   return false;
6411 }
6412
6413 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
6414   bool addTest = true;
6415   SDValue Cond  = Op.getOperand(0);
6416   DebugLoc dl = Op.getDebugLoc();
6417   SDValue CC;
6418
6419   if (Cond.getOpcode() == ISD::SETCC) {
6420     SDValue NewCond = LowerSETCC(Cond, DAG);
6421     if (NewCond.getNode())
6422       Cond = NewCond;
6423   }
6424
6425   // (select (x == 0), -1, 0) -> (sign_bit (x - 1))
6426   SDValue Op1 = Op.getOperand(1);
6427   SDValue Op2 = Op.getOperand(2);
6428   if (Cond.getOpcode() == X86ISD::SETCC &&
6429       cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue() == X86::COND_E) {
6430     SDValue Cmp = Cond.getOperand(1);
6431     if (Cmp.getOpcode() == X86ISD::CMP) {
6432       ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op1);
6433       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
6434       ConstantSDNode *RHSC =
6435         dyn_cast<ConstantSDNode>(Cmp.getOperand(1).getNode());
6436       if (N1C && N1C->isAllOnesValue() &&
6437           N2C && N2C->isNullValue() &&
6438           RHSC && RHSC->isNullValue()) {
6439         SDValue CmpOp0 = Cmp.getOperand(0);
6440         Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
6441                           CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
6442         return DAG.getNode(X86ISD::SETCC_CARRY, dl, Op.getValueType(),
6443                            DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
6444       }
6445     }
6446   }
6447
6448   // Look pass (and (setcc_carry (cmp ...)), 1).
6449   if (Cond.getOpcode() == ISD::AND &&
6450       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
6451     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
6452     if (C && C->getAPIntValue() == 1) 
6453       Cond = Cond.getOperand(0);
6454   }
6455
6456   // If condition flag is set by a X86ISD::CMP, then use it as the condition
6457   // setting operand in place of the X86ISD::SETCC.
6458   if (Cond.getOpcode() == X86ISD::SETCC ||
6459       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
6460     CC = Cond.getOperand(0);
6461
6462     SDValue Cmp = Cond.getOperand(1);
6463     unsigned Opc = Cmp.getOpcode();
6464     EVT VT = Op.getValueType();
6465
6466     bool IllegalFPCMov = false;
6467     if (VT.isFloatingPoint() && !VT.isVector() &&
6468         !isScalarFPTypeInSSEReg(VT))  // FPStack?
6469       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
6470
6471     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
6472         Opc == X86ISD::BT) { // FIXME
6473       Cond = Cmp;
6474       addTest = false;
6475     }
6476   }
6477
6478   if (addTest) {
6479     // Look pass the truncate.
6480     if (Cond.getOpcode() == ISD::TRUNCATE)
6481       Cond = Cond.getOperand(0);
6482
6483     // We know the result of AND is compared against zero. Try to match
6484     // it to BT.
6485     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) { 
6486       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
6487       if (NewSetCC.getNode()) {
6488         CC = NewSetCC.getOperand(0);
6489         Cond = NewSetCC.getOperand(1);
6490         addTest = false;
6491       }
6492     }
6493   }
6494
6495   if (addTest) {
6496     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6497     Cond = EmitTest(Cond, X86::COND_NE, DAG);
6498   }
6499
6500   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
6501   // condition is true.
6502   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Flag);
6503   SDValue Ops[] = { Op2, Op1, CC, Cond };
6504   return DAG.getNode(X86ISD::CMOV, dl, VTs, Ops, array_lengthof(Ops));
6505 }
6506
6507 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
6508 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
6509 // from the AND / OR.
6510 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
6511   Opc = Op.getOpcode();
6512   if (Opc != ISD::OR && Opc != ISD::AND)
6513     return false;
6514   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
6515           Op.getOperand(0).hasOneUse() &&
6516           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
6517           Op.getOperand(1).hasOneUse());
6518 }
6519
6520 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
6521 // 1 and that the SETCC node has a single use.
6522 static bool isXor1OfSetCC(SDValue Op) {
6523   if (Op.getOpcode() != ISD::XOR)
6524     return false;
6525   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6526   if (N1C && N1C->getAPIntValue() == 1) {
6527     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
6528       Op.getOperand(0).hasOneUse();
6529   }
6530   return false;
6531 }
6532
6533 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
6534   bool addTest = true;
6535   SDValue Chain = Op.getOperand(0);
6536   SDValue Cond  = Op.getOperand(1);
6537   SDValue Dest  = Op.getOperand(2);
6538   DebugLoc dl = Op.getDebugLoc();
6539   SDValue CC;
6540
6541   if (Cond.getOpcode() == ISD::SETCC) {
6542     SDValue NewCond = LowerSETCC(Cond, DAG);
6543     if (NewCond.getNode())
6544       Cond = NewCond;
6545   }
6546 #if 0
6547   // FIXME: LowerXALUO doesn't handle these!!
6548   else if (Cond.getOpcode() == X86ISD::ADD  ||
6549            Cond.getOpcode() == X86ISD::SUB  ||
6550            Cond.getOpcode() == X86ISD::SMUL ||
6551            Cond.getOpcode() == X86ISD::UMUL)
6552     Cond = LowerXALUO(Cond, DAG);
6553 #endif
6554
6555   // Look pass (and (setcc_carry (cmp ...)), 1).
6556   if (Cond.getOpcode() == ISD::AND &&
6557       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
6558     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
6559     if (C && C->getAPIntValue() == 1) 
6560       Cond = Cond.getOperand(0);
6561   }
6562
6563   // If condition flag is set by a X86ISD::CMP, then use it as the condition
6564   // setting operand in place of the X86ISD::SETCC.
6565   if (Cond.getOpcode() == X86ISD::SETCC ||
6566       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
6567     CC = Cond.getOperand(0);
6568
6569     SDValue Cmp = Cond.getOperand(1);
6570     unsigned Opc = Cmp.getOpcode();
6571     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
6572     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
6573       Cond = Cmp;
6574       addTest = false;
6575     } else {
6576       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
6577       default: break;
6578       case X86::COND_O:
6579       case X86::COND_B:
6580         // These can only come from an arithmetic instruction with overflow,
6581         // e.g. SADDO, UADDO.
6582         Cond = Cond.getNode()->getOperand(1);
6583         addTest = false;
6584         break;
6585       }
6586     }
6587   } else {
6588     unsigned CondOpc;
6589     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
6590       SDValue Cmp = Cond.getOperand(0).getOperand(1);
6591       if (CondOpc == ISD::OR) {
6592         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
6593         // two branches instead of an explicit OR instruction with a
6594         // separate test.
6595         if (Cmp == Cond.getOperand(1).getOperand(1) &&
6596             isX86LogicalCmp(Cmp)) {
6597           CC = Cond.getOperand(0).getOperand(0);
6598           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6599                               Chain, Dest, CC, Cmp);
6600           CC = Cond.getOperand(1).getOperand(0);
6601           Cond = Cmp;
6602           addTest = false;
6603         }
6604       } else { // ISD::AND
6605         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
6606         // two branches instead of an explicit AND instruction with a
6607         // separate test. However, we only do this if this block doesn't
6608         // have a fall-through edge, because this requires an explicit
6609         // jmp when the condition is false.
6610         if (Cmp == Cond.getOperand(1).getOperand(1) &&
6611             isX86LogicalCmp(Cmp) &&
6612             Op.getNode()->hasOneUse()) {
6613           X86::CondCode CCode =
6614             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
6615           CCode = X86::GetOppositeBranchCondition(CCode);
6616           CC = DAG.getConstant(CCode, MVT::i8);
6617           SDNode *User = *Op.getNode()->use_begin();
6618           // Look for an unconditional branch following this conditional branch.
6619           // We need this because we need to reverse the successors in order
6620           // to implement FCMP_OEQ.
6621           if (User->getOpcode() == ISD::BR) {
6622             SDValue FalseBB = User->getOperand(1);
6623             SDNode *NewBR =
6624               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
6625             assert(NewBR == User);
6626             (void)NewBR;
6627             Dest = FalseBB;
6628
6629             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6630                                 Chain, Dest, CC, Cmp);
6631             X86::CondCode CCode =
6632               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
6633             CCode = X86::GetOppositeBranchCondition(CCode);
6634             CC = DAG.getConstant(CCode, MVT::i8);
6635             Cond = Cmp;
6636             addTest = false;
6637           }
6638         }
6639       }
6640     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
6641       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
6642       // It should be transformed during dag combiner except when the condition
6643       // is set by a arithmetics with overflow node.
6644       X86::CondCode CCode =
6645         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
6646       CCode = X86::GetOppositeBranchCondition(CCode);
6647       CC = DAG.getConstant(CCode, MVT::i8);
6648       Cond = Cond.getOperand(0).getOperand(1);
6649       addTest = false;
6650     }
6651   }
6652
6653   if (addTest) {
6654     // Look pass the truncate.
6655     if (Cond.getOpcode() == ISD::TRUNCATE)
6656       Cond = Cond.getOperand(0);
6657
6658     // We know the result of AND is compared against zero. Try to match
6659     // it to BT.
6660     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) { 
6661       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
6662       if (NewSetCC.getNode()) {
6663         CC = NewSetCC.getOperand(0);
6664         Cond = NewSetCC.getOperand(1);
6665         addTest = false;
6666       }
6667     }
6668   }
6669
6670   if (addTest) {
6671     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6672     Cond = EmitTest(Cond, X86::COND_NE, DAG);
6673   }
6674   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6675                      Chain, Dest, CC, Cond);
6676 }
6677
6678
6679 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
6680 // Calls to _alloca is needed to probe the stack when allocating more than 4k
6681 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
6682 // that the guard pages used by the OS virtual memory manager are allocated in
6683 // correct sequence.
6684 SDValue
6685 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
6686                                            SelectionDAG &DAG) const {
6687   assert(Subtarget->isTargetCygMing() &&
6688          "This should be used only on Cygwin/Mingw targets");
6689   DebugLoc dl = Op.getDebugLoc();
6690
6691   // Get the inputs.
6692   SDValue Chain = Op.getOperand(0);
6693   SDValue Size  = Op.getOperand(1);
6694   // FIXME: Ensure alignment here
6695
6696   SDValue Flag;
6697
6698   EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
6699
6700   Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
6701   Flag = Chain.getValue(1);
6702
6703   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
6704
6705   Chain = DAG.getNode(X86ISD::MINGW_ALLOCA, dl, NodeTys, Chain, Flag);
6706   Flag = Chain.getValue(1);
6707
6708   Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
6709
6710   SDValue Ops1[2] = { Chain.getValue(0), Chain };
6711   return DAG.getMergeValues(Ops1, 2, dl);
6712 }
6713
6714 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
6715   MachineFunction &MF = DAG.getMachineFunction();
6716   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
6717
6718   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
6719   DebugLoc dl = Op.getDebugLoc();
6720
6721   if (!Subtarget->is64Bit()) {
6722     // vastart just stores the address of the VarArgsFrameIndex slot into the
6723     // memory location argument.
6724     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
6725                                    getPointerTy());
6726     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), SV, 0,
6727                         false, false, 0);
6728   }
6729
6730   // __va_list_tag:
6731   //   gp_offset         (0 - 6 * 8)
6732   //   fp_offset         (48 - 48 + 8 * 16)
6733   //   overflow_arg_area (point to parameters coming in memory).
6734   //   reg_save_area
6735   SmallVector<SDValue, 8> MemOps;
6736   SDValue FIN = Op.getOperand(1);
6737   // Store gp_offset
6738   SDValue Store = DAG.getStore(Op.getOperand(0), dl,
6739                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
6740                                                MVT::i32),
6741                                FIN, SV, 0, false, false, 0);
6742   MemOps.push_back(Store);
6743
6744   // Store fp_offset
6745   FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6746                     FIN, DAG.getIntPtrConstant(4));
6747   Store = DAG.getStore(Op.getOperand(0), dl,
6748                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
6749                                        MVT::i32),
6750                        FIN, SV, 0, false, false, 0);
6751   MemOps.push_back(Store);
6752
6753   // Store ptr to overflow_arg_area
6754   FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6755                     FIN, DAG.getIntPtrConstant(4));
6756   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
6757                                     getPointerTy());
6758   Store = DAG.getStore(Op.getOperand(0), dl, OVFIN, FIN, SV, 0,
6759                        false, false, 0);
6760   MemOps.push_back(Store);
6761
6762   // Store ptr to reg_save_area.
6763   FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6764                     FIN, DAG.getIntPtrConstant(8));
6765   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
6766                                     getPointerTy());
6767   Store = DAG.getStore(Op.getOperand(0), dl, RSFIN, FIN, SV, 0,
6768                        false, false, 0);
6769   MemOps.push_back(Store);
6770   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6771                      &MemOps[0], MemOps.size());
6772 }
6773
6774 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
6775   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6776   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
6777
6778   report_fatal_error("VAArgInst is not yet implemented for x86-64!");
6779   return SDValue();
6780 }
6781
6782 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
6783   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6784   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
6785   SDValue Chain = Op.getOperand(0);
6786   SDValue DstPtr = Op.getOperand(1);
6787   SDValue SrcPtr = Op.getOperand(2);
6788   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
6789   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6790   DebugLoc dl = Op.getDebugLoc();
6791
6792   return DAG.getMemcpy(Chain, dl, DstPtr, SrcPtr,
6793                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
6794                        false, DstSV, 0, SrcSV, 0);
6795 }
6796
6797 SDValue
6798 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
6799   DebugLoc dl = Op.getDebugLoc();
6800   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6801   switch (IntNo) {
6802   default: return SDValue();    // Don't custom lower most intrinsics.
6803   // Comparison intrinsics.
6804   case Intrinsic::x86_sse_comieq_ss:
6805   case Intrinsic::x86_sse_comilt_ss:
6806   case Intrinsic::x86_sse_comile_ss:
6807   case Intrinsic::x86_sse_comigt_ss:
6808   case Intrinsic::x86_sse_comige_ss:
6809   case Intrinsic::x86_sse_comineq_ss:
6810   case Intrinsic::x86_sse_ucomieq_ss:
6811   case Intrinsic::x86_sse_ucomilt_ss:
6812   case Intrinsic::x86_sse_ucomile_ss:
6813   case Intrinsic::x86_sse_ucomigt_ss:
6814   case Intrinsic::x86_sse_ucomige_ss:
6815   case Intrinsic::x86_sse_ucomineq_ss:
6816   case Intrinsic::x86_sse2_comieq_sd:
6817   case Intrinsic::x86_sse2_comilt_sd:
6818   case Intrinsic::x86_sse2_comile_sd:
6819   case Intrinsic::x86_sse2_comigt_sd:
6820   case Intrinsic::x86_sse2_comige_sd:
6821   case Intrinsic::x86_sse2_comineq_sd:
6822   case Intrinsic::x86_sse2_ucomieq_sd:
6823   case Intrinsic::x86_sse2_ucomilt_sd:
6824   case Intrinsic::x86_sse2_ucomile_sd:
6825   case Intrinsic::x86_sse2_ucomigt_sd:
6826   case Intrinsic::x86_sse2_ucomige_sd:
6827   case Intrinsic::x86_sse2_ucomineq_sd: {
6828     unsigned Opc = 0;
6829     ISD::CondCode CC = ISD::SETCC_INVALID;
6830     switch (IntNo) {
6831     default: break;
6832     case Intrinsic::x86_sse_comieq_ss:
6833     case Intrinsic::x86_sse2_comieq_sd:
6834       Opc = X86ISD::COMI;
6835       CC = ISD::SETEQ;
6836       break;
6837     case Intrinsic::x86_sse_comilt_ss:
6838     case Intrinsic::x86_sse2_comilt_sd:
6839       Opc = X86ISD::COMI;
6840       CC = ISD::SETLT;
6841       break;
6842     case Intrinsic::x86_sse_comile_ss:
6843     case Intrinsic::x86_sse2_comile_sd:
6844       Opc = X86ISD::COMI;
6845       CC = ISD::SETLE;
6846       break;
6847     case Intrinsic::x86_sse_comigt_ss:
6848     case Intrinsic::x86_sse2_comigt_sd:
6849       Opc = X86ISD::COMI;
6850       CC = ISD::SETGT;
6851       break;
6852     case Intrinsic::x86_sse_comige_ss:
6853     case Intrinsic::x86_sse2_comige_sd:
6854       Opc = X86ISD::COMI;
6855       CC = ISD::SETGE;
6856       break;
6857     case Intrinsic::x86_sse_comineq_ss:
6858     case Intrinsic::x86_sse2_comineq_sd:
6859       Opc = X86ISD::COMI;
6860       CC = ISD::SETNE;
6861       break;
6862     case Intrinsic::x86_sse_ucomieq_ss:
6863     case Intrinsic::x86_sse2_ucomieq_sd:
6864       Opc = X86ISD::UCOMI;
6865       CC = ISD::SETEQ;
6866       break;
6867     case Intrinsic::x86_sse_ucomilt_ss:
6868     case Intrinsic::x86_sse2_ucomilt_sd:
6869       Opc = X86ISD::UCOMI;
6870       CC = ISD::SETLT;
6871       break;
6872     case Intrinsic::x86_sse_ucomile_ss:
6873     case Intrinsic::x86_sse2_ucomile_sd:
6874       Opc = X86ISD::UCOMI;
6875       CC = ISD::SETLE;
6876       break;
6877     case Intrinsic::x86_sse_ucomigt_ss:
6878     case Intrinsic::x86_sse2_ucomigt_sd:
6879       Opc = X86ISD::UCOMI;
6880       CC = ISD::SETGT;
6881       break;
6882     case Intrinsic::x86_sse_ucomige_ss:
6883     case Intrinsic::x86_sse2_ucomige_sd:
6884       Opc = X86ISD::UCOMI;
6885       CC = ISD::SETGE;
6886       break;
6887     case Intrinsic::x86_sse_ucomineq_ss:
6888     case Intrinsic::x86_sse2_ucomineq_sd:
6889       Opc = X86ISD::UCOMI;
6890       CC = ISD::SETNE;
6891       break;
6892     }
6893
6894     SDValue LHS = Op.getOperand(1);
6895     SDValue RHS = Op.getOperand(2);
6896     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
6897     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
6898     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
6899     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6900                                 DAG.getConstant(X86CC, MVT::i8), Cond);
6901     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6902   }
6903   // ptest intrinsics. The intrinsic these come from are designed to return
6904   // an integer value, not just an instruction so lower it to the ptest
6905   // pattern and a setcc for the result.
6906   case Intrinsic::x86_sse41_ptestz:
6907   case Intrinsic::x86_sse41_ptestc:
6908   case Intrinsic::x86_sse41_ptestnzc:{
6909     unsigned X86CC = 0;
6910     switch (IntNo) {
6911     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
6912     case Intrinsic::x86_sse41_ptestz:
6913       // ZF = 1
6914       X86CC = X86::COND_E;
6915       break;
6916     case Intrinsic::x86_sse41_ptestc:
6917       // CF = 1
6918       X86CC = X86::COND_B;
6919       break;
6920     case Intrinsic::x86_sse41_ptestnzc:
6921       // ZF and CF = 0
6922       X86CC = X86::COND_A;
6923       break;
6924     }
6925
6926     SDValue LHS = Op.getOperand(1);
6927     SDValue RHS = Op.getOperand(2);
6928     SDValue Test = DAG.getNode(X86ISD::PTEST, dl, MVT::i32, LHS, RHS);
6929     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
6930     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
6931     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6932   }
6933
6934   // Fix vector shift instructions where the last operand is a non-immediate
6935   // i32 value.
6936   case Intrinsic::x86_sse2_pslli_w:
6937   case Intrinsic::x86_sse2_pslli_d:
6938   case Intrinsic::x86_sse2_pslli_q:
6939   case Intrinsic::x86_sse2_psrli_w:
6940   case Intrinsic::x86_sse2_psrli_d:
6941   case Intrinsic::x86_sse2_psrli_q:
6942   case Intrinsic::x86_sse2_psrai_w:
6943   case Intrinsic::x86_sse2_psrai_d:
6944   case Intrinsic::x86_mmx_pslli_w:
6945   case Intrinsic::x86_mmx_pslli_d:
6946   case Intrinsic::x86_mmx_pslli_q:
6947   case Intrinsic::x86_mmx_psrli_w:
6948   case Intrinsic::x86_mmx_psrli_d:
6949   case Intrinsic::x86_mmx_psrli_q:
6950   case Intrinsic::x86_mmx_psrai_w:
6951   case Intrinsic::x86_mmx_psrai_d: {
6952     SDValue ShAmt = Op.getOperand(2);
6953     if (isa<ConstantSDNode>(ShAmt))
6954       return SDValue();
6955
6956     unsigned NewIntNo = 0;
6957     EVT ShAmtVT = MVT::v4i32;
6958     switch (IntNo) {
6959     case Intrinsic::x86_sse2_pslli_w:
6960       NewIntNo = Intrinsic::x86_sse2_psll_w;
6961       break;
6962     case Intrinsic::x86_sse2_pslli_d:
6963       NewIntNo = Intrinsic::x86_sse2_psll_d;
6964       break;
6965     case Intrinsic::x86_sse2_pslli_q:
6966       NewIntNo = Intrinsic::x86_sse2_psll_q;
6967       break;
6968     case Intrinsic::x86_sse2_psrli_w:
6969       NewIntNo = Intrinsic::x86_sse2_psrl_w;
6970       break;
6971     case Intrinsic::x86_sse2_psrli_d:
6972       NewIntNo = Intrinsic::x86_sse2_psrl_d;
6973       break;
6974     case Intrinsic::x86_sse2_psrli_q:
6975       NewIntNo = Intrinsic::x86_sse2_psrl_q;
6976       break;
6977     case Intrinsic::x86_sse2_psrai_w:
6978       NewIntNo = Intrinsic::x86_sse2_psra_w;
6979       break;
6980     case Intrinsic::x86_sse2_psrai_d:
6981       NewIntNo = Intrinsic::x86_sse2_psra_d;
6982       break;
6983     default: {
6984       ShAmtVT = MVT::v2i32;
6985       switch (IntNo) {
6986       case Intrinsic::x86_mmx_pslli_w:
6987         NewIntNo = Intrinsic::x86_mmx_psll_w;
6988         break;
6989       case Intrinsic::x86_mmx_pslli_d:
6990         NewIntNo = Intrinsic::x86_mmx_psll_d;
6991         break;
6992       case Intrinsic::x86_mmx_pslli_q:
6993         NewIntNo = Intrinsic::x86_mmx_psll_q;
6994         break;
6995       case Intrinsic::x86_mmx_psrli_w:
6996         NewIntNo = Intrinsic::x86_mmx_psrl_w;
6997         break;
6998       case Intrinsic::x86_mmx_psrli_d:
6999         NewIntNo = Intrinsic::x86_mmx_psrl_d;
7000         break;
7001       case Intrinsic::x86_mmx_psrli_q:
7002         NewIntNo = Intrinsic::x86_mmx_psrl_q;
7003         break;
7004       case Intrinsic::x86_mmx_psrai_w:
7005         NewIntNo = Intrinsic::x86_mmx_psra_w;
7006         break;
7007       case Intrinsic::x86_mmx_psrai_d:
7008         NewIntNo = Intrinsic::x86_mmx_psra_d;
7009         break;
7010       default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7011       }
7012       break;
7013     }
7014     }
7015
7016     // The vector shift intrinsics with scalars uses 32b shift amounts but
7017     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
7018     // to be zero.
7019     SDValue ShOps[4];
7020     ShOps[0] = ShAmt;
7021     ShOps[1] = DAG.getConstant(0, MVT::i32);
7022     if (ShAmtVT == MVT::v4i32) {
7023       ShOps[2] = DAG.getUNDEF(MVT::i32);
7024       ShOps[3] = DAG.getUNDEF(MVT::i32);
7025       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
7026     } else {
7027       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
7028     }
7029
7030     EVT VT = Op.getValueType();
7031     ShAmt = DAG.getNode(ISD::BIT_CONVERT, dl, VT, ShAmt);
7032     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7033                        DAG.getConstant(NewIntNo, MVT::i32),
7034                        Op.getOperand(1), ShAmt);
7035   }
7036   }
7037 }
7038
7039 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
7040                                            SelectionDAG &DAG) const {
7041   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7042   MFI->setReturnAddressIsTaken(true);
7043
7044   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7045   DebugLoc dl = Op.getDebugLoc();
7046
7047   if (Depth > 0) {
7048     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
7049     SDValue Offset =
7050       DAG.getConstant(TD->getPointerSize(),
7051                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
7052     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7053                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
7054                                    FrameAddr, Offset),
7055                        NULL, 0, false, false, 0);
7056   }
7057
7058   // Just load the return address.
7059   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
7060   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7061                      RetAddrFI, NULL, 0, false, false, 0);
7062 }
7063
7064 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
7065   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7066   MFI->setFrameAddressIsTaken(true);
7067
7068   EVT VT = Op.getValueType();
7069   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
7070   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7071   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
7072   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
7073   while (Depth--)
7074     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, NULL, 0,
7075                             false, false, 0);
7076   return FrameAddr;
7077 }
7078
7079 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
7080                                                      SelectionDAG &DAG) const {
7081   return DAG.getIntPtrConstant(2*TD->getPointerSize());
7082 }
7083
7084 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
7085   MachineFunction &MF = DAG.getMachineFunction();
7086   SDValue Chain     = Op.getOperand(0);
7087   SDValue Offset    = Op.getOperand(1);
7088   SDValue Handler   = Op.getOperand(2);
7089   DebugLoc dl       = Op.getDebugLoc();
7090
7091   SDValue Frame = DAG.getRegister(Subtarget->is64Bit() ? X86::RBP : X86::EBP,
7092                                   getPointerTy());
7093   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
7094
7095   SDValue StoreAddr = DAG.getNode(ISD::SUB, dl, getPointerTy(), Frame,
7096                                   DAG.getIntPtrConstant(-TD->getPointerSize()));
7097   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
7098   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, NULL, 0, false, false, 0);
7099   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
7100   MF.getRegInfo().addLiveOut(StoreAddrReg);
7101
7102   return DAG.getNode(X86ISD::EH_RETURN, dl,
7103                      MVT::Other,
7104                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
7105 }
7106
7107 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
7108                                              SelectionDAG &DAG) const {
7109   SDValue Root = Op.getOperand(0);
7110   SDValue Trmp = Op.getOperand(1); // trampoline
7111   SDValue FPtr = Op.getOperand(2); // nested function
7112   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
7113   DebugLoc dl  = Op.getDebugLoc();
7114
7115   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
7116
7117   if (Subtarget->is64Bit()) {
7118     SDValue OutChains[6];
7119
7120     // Large code-model.
7121     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
7122     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
7123
7124     const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
7125     const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
7126
7127     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
7128
7129     // Load the pointer to the nested function into R11.
7130     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
7131     SDValue Addr = Trmp;
7132     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7133                                 Addr, TrmpAddr, 0, false, false, 0);
7134
7135     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7136                        DAG.getConstant(2, MVT::i64));
7137     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr, TrmpAddr, 2,
7138                                 false, false, 2);
7139
7140     // Load the 'nest' parameter value into R10.
7141     // R10 is specified in X86CallingConv.td
7142     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
7143     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7144                        DAG.getConstant(10, MVT::i64));
7145     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7146                                 Addr, TrmpAddr, 10, false, false, 0);
7147
7148     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7149                        DAG.getConstant(12, MVT::i64));
7150     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 12,
7151                                 false, false, 2);
7152
7153     // Jump to the nested function.
7154     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
7155     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7156                        DAG.getConstant(20, MVT::i64));
7157     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7158                                 Addr, TrmpAddr, 20, false, false, 0);
7159
7160     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
7161     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7162                        DAG.getConstant(22, MVT::i64));
7163     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
7164                                 TrmpAddr, 22, false, false, 0);
7165
7166     SDValue Ops[] =
7167       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
7168     return DAG.getMergeValues(Ops, 2, dl);
7169   } else {
7170     const Function *Func =
7171       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
7172     CallingConv::ID CC = Func->getCallingConv();
7173     unsigned NestReg;
7174
7175     switch (CC) {
7176     default:
7177       llvm_unreachable("Unsupported calling convention");
7178     case CallingConv::C:
7179     case CallingConv::X86_StdCall: {
7180       // Pass 'nest' parameter in ECX.
7181       // Must be kept in sync with X86CallingConv.td
7182       NestReg = X86::ECX;
7183
7184       // Check that ECX wasn't needed by an 'inreg' parameter.
7185       const FunctionType *FTy = Func->getFunctionType();
7186       const AttrListPtr &Attrs = Func->getAttributes();
7187
7188       if (!Attrs.isEmpty() && !Func->isVarArg()) {
7189         unsigned InRegCount = 0;
7190         unsigned Idx = 1;
7191
7192         for (FunctionType::param_iterator I = FTy->param_begin(),
7193              E = FTy->param_end(); I != E; ++I, ++Idx)
7194           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
7195             // FIXME: should only count parameters that are lowered to integers.
7196             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
7197
7198         if (InRegCount > 2) {
7199           report_fatal_error("Nest register in use - reduce number of inreg parameters!");
7200         }
7201       }
7202       break;
7203     }
7204     case CallingConv::X86_FastCall:
7205     case CallingConv::X86_ThisCall:
7206     case CallingConv::Fast:
7207       // Pass 'nest' parameter in EAX.
7208       // Must be kept in sync with X86CallingConv.td
7209       NestReg = X86::EAX;
7210       break;
7211     }
7212
7213     SDValue OutChains[4];
7214     SDValue Addr, Disp;
7215
7216     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7217                        DAG.getConstant(10, MVT::i32));
7218     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
7219
7220     // This is storing the opcode for MOV32ri.
7221     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
7222     const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
7223     OutChains[0] = DAG.getStore(Root, dl,
7224                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
7225                                 Trmp, TrmpAddr, 0, false, false, 0);
7226
7227     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7228                        DAG.getConstant(1, MVT::i32));
7229     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 1,
7230                                 false, false, 1);
7231
7232     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
7233     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7234                        DAG.getConstant(5, MVT::i32));
7235     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
7236                                 TrmpAddr, 5, false, false, 1);
7237
7238     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7239                        DAG.getConstant(6, MVT::i32));
7240     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr, TrmpAddr, 6,
7241                                 false, false, 1);
7242
7243     SDValue Ops[] =
7244       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
7245     return DAG.getMergeValues(Ops, 2, dl);
7246   }
7247 }
7248
7249 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
7250                                             SelectionDAG &DAG) const {
7251   /*
7252    The rounding mode is in bits 11:10 of FPSR, and has the following
7253    settings:
7254      00 Round to nearest
7255      01 Round to -inf
7256      10 Round to +inf
7257      11 Round to 0
7258
7259   FLT_ROUNDS, on the other hand, expects the following:
7260     -1 Undefined
7261      0 Round to 0
7262      1 Round to nearest
7263      2 Round to +inf
7264      3 Round to -inf
7265
7266   To perform the conversion, we do:
7267     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
7268   */
7269
7270   MachineFunction &MF = DAG.getMachineFunction();
7271   const TargetMachine &TM = MF.getTarget();
7272   const TargetFrameInfo &TFI = *TM.getFrameInfo();
7273   unsigned StackAlignment = TFI.getStackAlignment();
7274   EVT VT = Op.getValueType();
7275   DebugLoc dl = Op.getDebugLoc();
7276
7277   // Save FP Control Word to stack slot
7278   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
7279   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7280
7281   SDValue Chain = DAG.getNode(X86ISD::FNSTCW16m, dl, MVT::Other,
7282                               DAG.getEntryNode(), StackSlot);
7283
7284   // Load FP Control Word from stack slot
7285   SDValue CWD = DAG.getLoad(MVT::i16, dl, Chain, StackSlot, NULL, 0,
7286                             false, false, 0);
7287
7288   // Transform as necessary
7289   SDValue CWD1 =
7290     DAG.getNode(ISD::SRL, dl, MVT::i16,
7291                 DAG.getNode(ISD::AND, dl, MVT::i16,
7292                             CWD, DAG.getConstant(0x800, MVT::i16)),
7293                 DAG.getConstant(11, MVT::i8));
7294   SDValue CWD2 =
7295     DAG.getNode(ISD::SRL, dl, MVT::i16,
7296                 DAG.getNode(ISD::AND, dl, MVT::i16,
7297                             CWD, DAG.getConstant(0x400, MVT::i16)),
7298                 DAG.getConstant(9, MVT::i8));
7299
7300   SDValue RetVal =
7301     DAG.getNode(ISD::AND, dl, MVT::i16,
7302                 DAG.getNode(ISD::ADD, dl, MVT::i16,
7303                             DAG.getNode(ISD::OR, dl, MVT::i16, CWD1, CWD2),
7304                             DAG.getConstant(1, MVT::i16)),
7305                 DAG.getConstant(3, MVT::i16));
7306
7307
7308   return DAG.getNode((VT.getSizeInBits() < 16 ?
7309                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
7310 }
7311
7312 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
7313   EVT VT = Op.getValueType();
7314   EVT OpVT = VT;
7315   unsigned NumBits = VT.getSizeInBits();
7316   DebugLoc dl = Op.getDebugLoc();
7317
7318   Op = Op.getOperand(0);
7319   if (VT == MVT::i8) {
7320     // Zero extend to i32 since there is not an i8 bsr.
7321     OpVT = MVT::i32;
7322     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
7323   }
7324
7325   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
7326   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
7327   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
7328
7329   // If src is zero (i.e. bsr sets ZF), returns NumBits.
7330   SDValue Ops[] = {
7331     Op,
7332     DAG.getConstant(NumBits+NumBits-1, OpVT),
7333     DAG.getConstant(X86::COND_E, MVT::i8),
7334     Op.getValue(1)
7335   };
7336   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
7337
7338   // Finally xor with NumBits-1.
7339   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
7340
7341   if (VT == MVT::i8)
7342     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
7343   return Op;
7344 }
7345
7346 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
7347   EVT VT = Op.getValueType();
7348   EVT OpVT = VT;
7349   unsigned NumBits = VT.getSizeInBits();
7350   DebugLoc dl = Op.getDebugLoc();
7351
7352   Op = Op.getOperand(0);
7353   if (VT == MVT::i8) {
7354     OpVT = MVT::i32;
7355     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
7356   }
7357
7358   // Issue a bsf (scan bits forward) which also sets EFLAGS.
7359   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
7360   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
7361
7362   // If src is zero (i.e. bsf sets ZF), returns NumBits.
7363   SDValue Ops[] = {
7364     Op,
7365     DAG.getConstant(NumBits, OpVT),
7366     DAG.getConstant(X86::COND_E, MVT::i8),
7367     Op.getValue(1)
7368   };
7369   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
7370
7371   if (VT == MVT::i8)
7372     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
7373   return Op;
7374 }
7375
7376 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) const {
7377   EVT VT = Op.getValueType();
7378   assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
7379   DebugLoc dl = Op.getDebugLoc();
7380
7381   //  ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
7382   //  ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
7383   //  ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
7384   //  ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
7385   //  ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
7386   //
7387   //  AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
7388   //  AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
7389   //  return AloBlo + AloBhi + AhiBlo;
7390
7391   SDValue A = Op.getOperand(0);
7392   SDValue B = Op.getOperand(1);
7393
7394   SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7395                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
7396                        A, DAG.getConstant(32, MVT::i32));
7397   SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7398                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
7399                        B, DAG.getConstant(32, MVT::i32));
7400   SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7401                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7402                        A, B);
7403   SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7404                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7405                        A, Bhi);
7406   SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7407                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7408                        Ahi, B);
7409   AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7410                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
7411                        AloBhi, DAG.getConstant(32, MVT::i32));
7412   AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7413                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
7414                        AhiBlo, DAG.getConstant(32, MVT::i32));
7415   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
7416   Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
7417   return Res;
7418 }
7419
7420
7421 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
7422   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
7423   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
7424   // looks for this combo and may remove the "setcc" instruction if the "setcc"
7425   // has only one use.
7426   SDNode *N = Op.getNode();
7427   SDValue LHS = N->getOperand(0);
7428   SDValue RHS = N->getOperand(1);
7429   unsigned BaseOp = 0;
7430   unsigned Cond = 0;
7431   DebugLoc dl = Op.getDebugLoc();
7432
7433   switch (Op.getOpcode()) {
7434   default: llvm_unreachable("Unknown ovf instruction!");
7435   case ISD::SADDO:
7436     // A subtract of one will be selected as a INC. Note that INC doesn't
7437     // set CF, so we can't do this for UADDO.
7438     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
7439       if (C->getAPIntValue() == 1) {
7440         BaseOp = X86ISD::INC;
7441         Cond = X86::COND_O;
7442         break;
7443       }
7444     BaseOp = X86ISD::ADD;
7445     Cond = X86::COND_O;
7446     break;
7447   case ISD::UADDO:
7448     BaseOp = X86ISD::ADD;
7449     Cond = X86::COND_B;
7450     break;
7451   case ISD::SSUBO:
7452     // A subtract of one will be selected as a DEC. Note that DEC doesn't
7453     // set CF, so we can't do this for USUBO.
7454     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
7455       if (C->getAPIntValue() == 1) {
7456         BaseOp = X86ISD::DEC;
7457         Cond = X86::COND_O;
7458         break;
7459       }
7460     BaseOp = X86ISD::SUB;
7461     Cond = X86::COND_O;
7462     break;
7463   case ISD::USUBO:
7464     BaseOp = X86ISD::SUB;
7465     Cond = X86::COND_B;
7466     break;
7467   case ISD::SMULO:
7468     BaseOp = X86ISD::SMUL;
7469     Cond = X86::COND_O;
7470     break;
7471   case ISD::UMULO:
7472     BaseOp = X86ISD::UMUL;
7473     Cond = X86::COND_B;
7474     break;
7475   }
7476
7477   // Also sets EFLAGS.
7478   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
7479   SDValue Sum = DAG.getNode(BaseOp, dl, VTs, LHS, RHS);
7480
7481   SDValue SetCC =
7482     DAG.getNode(X86ISD::SETCC, dl, N->getValueType(1),
7483                 DAG.getConstant(Cond, MVT::i32), SDValue(Sum.getNode(), 1));
7484
7485   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
7486   return Sum;
7487 }
7488
7489 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
7490   EVT T = Op.getValueType();
7491   DebugLoc dl = Op.getDebugLoc();
7492   unsigned Reg = 0;
7493   unsigned size = 0;
7494   switch(T.getSimpleVT().SimpleTy) {
7495   default:
7496     assert(false && "Invalid value type!");
7497   case MVT::i8:  Reg = X86::AL;  size = 1; break;
7498   case MVT::i16: Reg = X86::AX;  size = 2; break;
7499   case MVT::i32: Reg = X86::EAX; size = 4; break;
7500   case MVT::i64:
7501     assert(Subtarget->is64Bit() && "Node not type legal!");
7502     Reg = X86::RAX; size = 8;
7503     break;
7504   }
7505   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), dl, Reg,
7506                                     Op.getOperand(2), SDValue());
7507   SDValue Ops[] = { cpIn.getValue(0),
7508                     Op.getOperand(1),
7509                     Op.getOperand(3),
7510                     DAG.getTargetConstant(size, MVT::i8),
7511                     cpIn.getValue(1) };
7512   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7513   SDValue Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, dl, Tys, Ops, 5);
7514   SDValue cpOut =
7515     DAG.getCopyFromReg(Result.getValue(0), dl, Reg, T, Result.getValue(1));
7516   return cpOut;
7517 }
7518
7519 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
7520                                                  SelectionDAG &DAG) const {
7521   assert(Subtarget->is64Bit() && "Result not type legalized?");
7522   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7523   SDValue TheChain = Op.getOperand(0);
7524   DebugLoc dl = Op.getDebugLoc();
7525   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
7526   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
7527   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
7528                                    rax.getValue(2));
7529   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
7530                             DAG.getConstant(32, MVT::i8));
7531   SDValue Ops[] = {
7532     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
7533     rdx.getValue(1)
7534   };
7535   return DAG.getMergeValues(Ops, 2, dl);
7536 }
7537
7538 SDValue X86TargetLowering::LowerBIT_CONVERT(SDValue Op,
7539                                             SelectionDAG &DAG) const {
7540   EVT SrcVT = Op.getOperand(0).getValueType();
7541   EVT DstVT = Op.getValueType();
7542   assert((Subtarget->is64Bit() && !Subtarget->hasSSE2() && 
7543           Subtarget->hasMMX() && !DisableMMX) &&
7544          "Unexpected custom BIT_CONVERT");
7545   assert((DstVT == MVT::i64 || 
7546           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
7547          "Unexpected custom BIT_CONVERT");
7548   // i64 <=> MMX conversions are Legal.
7549   if (SrcVT==MVT::i64 && DstVT.isVector())
7550     return Op;
7551   if (DstVT==MVT::i64 && SrcVT.isVector())
7552     return Op;
7553   // MMX <=> MMX conversions are Legal.
7554   if (SrcVT.isVector() && DstVT.isVector())
7555     return Op;
7556   // All other conversions need to be expanded.
7557   return SDValue();
7558 }
7559 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
7560   SDNode *Node = Op.getNode();
7561   DebugLoc dl = Node->getDebugLoc();
7562   EVT T = Node->getValueType(0);
7563   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
7564                               DAG.getConstant(0, T), Node->getOperand(2));
7565   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
7566                        cast<AtomicSDNode>(Node)->getMemoryVT(),
7567                        Node->getOperand(0),
7568                        Node->getOperand(1), negOp,
7569                        cast<AtomicSDNode>(Node)->getSrcValue(),
7570                        cast<AtomicSDNode>(Node)->getAlignment());
7571 }
7572
7573 /// LowerOperation - Provide custom lowering hooks for some operations.
7574 ///
7575 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
7576   switch (Op.getOpcode()) {
7577   default: llvm_unreachable("Should not custom lower this!");
7578   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
7579   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
7580   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
7581   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
7582   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
7583   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
7584   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
7585   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
7586   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
7587   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
7588   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
7589   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
7590   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
7591   case ISD::SHL_PARTS:
7592   case ISD::SRA_PARTS:
7593   case ISD::SRL_PARTS:          return LowerShift(Op, DAG);
7594   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
7595   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
7596   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
7597   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
7598   case ISD::FABS:               return LowerFABS(Op, DAG);
7599   case ISD::FNEG:               return LowerFNEG(Op, DAG);
7600   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
7601   case ISD::SETCC:              return LowerSETCC(Op, DAG);
7602   case ISD::VSETCC:             return LowerVSETCC(Op, DAG);
7603   case ISD::SELECT:             return LowerSELECT(Op, DAG);
7604   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
7605   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
7606   case ISD::VASTART:            return LowerVASTART(Op, DAG);
7607   case ISD::VAARG:              return LowerVAARG(Op, DAG);
7608   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
7609   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
7610   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
7611   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
7612   case ISD::FRAME_TO_ARGS_OFFSET:
7613                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
7614   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
7615   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
7616   case ISD::TRAMPOLINE:         return LowerTRAMPOLINE(Op, DAG);
7617   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
7618   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
7619   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
7620   case ISD::MUL:                return LowerMUL_V2I64(Op, DAG);
7621   case ISD::SADDO:
7622   case ISD::UADDO:
7623   case ISD::SSUBO:
7624   case ISD::USUBO:
7625   case ISD::SMULO:
7626   case ISD::UMULO:              return LowerXALUO(Op, DAG);
7627   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
7628   case ISD::BIT_CONVERT:        return LowerBIT_CONVERT(Op, DAG);
7629   }
7630 }
7631
7632 void X86TargetLowering::
7633 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
7634                         SelectionDAG &DAG, unsigned NewOp) const {
7635   EVT T = Node->getValueType(0);
7636   DebugLoc dl = Node->getDebugLoc();
7637   assert (T == MVT::i64 && "Only know how to expand i64 atomics");
7638
7639   SDValue Chain = Node->getOperand(0);
7640   SDValue In1 = Node->getOperand(1);
7641   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7642                              Node->getOperand(2), DAG.getIntPtrConstant(0));
7643   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7644                              Node->getOperand(2), DAG.getIntPtrConstant(1));
7645   SDValue Ops[] = { Chain, In1, In2L, In2H };
7646   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
7647   SDValue Result =
7648     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
7649                             cast<MemSDNode>(Node)->getMemOperand());
7650   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
7651   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
7652   Results.push_back(Result.getValue(2));
7653 }
7654
7655 /// ReplaceNodeResults - Replace a node with an illegal result type
7656 /// with a new node built out of custom code.
7657 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
7658                                            SmallVectorImpl<SDValue>&Results,
7659                                            SelectionDAG &DAG) const {
7660   DebugLoc dl = N->getDebugLoc();
7661   switch (N->getOpcode()) {
7662   default:
7663     assert(false && "Do not know how to custom type legalize this operation!");
7664     return;
7665   case ISD::FP_TO_SINT: {
7666     std::pair<SDValue,SDValue> Vals =
7667         FP_TO_INTHelper(SDValue(N, 0), DAG, true);
7668     SDValue FIST = Vals.first, StackSlot = Vals.second;
7669     if (FIST.getNode() != 0) {
7670       EVT VT = N->getValueType(0);
7671       // Return a load from the stack slot.
7672       Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot, NULL, 0,
7673                                     false, false, 0));
7674     }
7675     return;
7676   }
7677   case ISD::READCYCLECOUNTER: {
7678     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7679     SDValue TheChain = N->getOperand(0);
7680     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
7681     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
7682                                      rd.getValue(1));
7683     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
7684                                      eax.getValue(2));
7685     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
7686     SDValue Ops[] = { eax, edx };
7687     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
7688     Results.push_back(edx.getValue(1));
7689     return;
7690   }
7691   case ISD::ATOMIC_CMP_SWAP: {
7692     EVT T = N->getValueType(0);
7693     assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
7694     SDValue cpInL, cpInH;
7695     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7696                         DAG.getConstant(0, MVT::i32));
7697     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7698                         DAG.getConstant(1, MVT::i32));
7699     cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
7700     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
7701                              cpInL.getValue(1));
7702     SDValue swapInL, swapInH;
7703     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7704                           DAG.getConstant(0, MVT::i32));
7705     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7706                           DAG.getConstant(1, MVT::i32));
7707     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
7708                                cpInH.getValue(1));
7709     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
7710                                swapInL.getValue(1));
7711     SDValue Ops[] = { swapInH.getValue(0),
7712                       N->getOperand(1),
7713                       swapInH.getValue(1) };
7714     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7715     SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, dl, Tys, Ops, 3);
7716     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
7717                                         MVT::i32, Result.getValue(1));
7718     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
7719                                         MVT::i32, cpOutL.getValue(2));
7720     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
7721     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
7722     Results.push_back(cpOutH.getValue(1));
7723     return;
7724   }
7725   case ISD::ATOMIC_LOAD_ADD:
7726     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
7727     return;
7728   case ISD::ATOMIC_LOAD_AND:
7729     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
7730     return;
7731   case ISD::ATOMIC_LOAD_NAND:
7732     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
7733     return;
7734   case ISD::ATOMIC_LOAD_OR:
7735     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
7736     return;
7737   case ISD::ATOMIC_LOAD_SUB:
7738     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
7739     return;
7740   case ISD::ATOMIC_LOAD_XOR:
7741     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
7742     return;
7743   case ISD::ATOMIC_SWAP:
7744     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
7745     return;
7746   }
7747 }
7748
7749 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
7750   switch (Opcode) {
7751   default: return NULL;
7752   case X86ISD::BSF:                return "X86ISD::BSF";
7753   case X86ISD::BSR:                return "X86ISD::BSR";
7754   case X86ISD::SHLD:               return "X86ISD::SHLD";
7755   case X86ISD::SHRD:               return "X86ISD::SHRD";
7756   case X86ISD::FAND:               return "X86ISD::FAND";
7757   case X86ISD::FOR:                return "X86ISD::FOR";
7758   case X86ISD::FXOR:               return "X86ISD::FXOR";
7759   case X86ISD::FSRL:               return "X86ISD::FSRL";
7760   case X86ISD::FILD:               return "X86ISD::FILD";
7761   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
7762   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
7763   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
7764   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
7765   case X86ISD::FLD:                return "X86ISD::FLD";
7766   case X86ISD::FST:                return "X86ISD::FST";
7767   case X86ISD::CALL:               return "X86ISD::CALL";
7768   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
7769   case X86ISD::BT:                 return "X86ISD::BT";
7770   case X86ISD::CMP:                return "X86ISD::CMP";
7771   case X86ISD::COMI:               return "X86ISD::COMI";
7772   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
7773   case X86ISD::SETCC:              return "X86ISD::SETCC";
7774   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
7775   case X86ISD::CMOV:               return "X86ISD::CMOV";
7776   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
7777   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
7778   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
7779   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
7780   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
7781   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
7782   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
7783   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
7784   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
7785   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
7786   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
7787   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
7788   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
7789   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
7790   case X86ISD::FMAX:               return "X86ISD::FMAX";
7791   case X86ISD::FMIN:               return "X86ISD::FMIN";
7792   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
7793   case X86ISD::FRCP:               return "X86ISD::FRCP";
7794   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
7795   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
7796   case X86ISD::SegmentBaseAddress: return "X86ISD::SegmentBaseAddress";
7797   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
7798   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
7799   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
7800   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
7801   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
7802   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
7803   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
7804   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
7805   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
7806   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
7807   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
7808   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
7809   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
7810   case X86ISD::VSHL:               return "X86ISD::VSHL";
7811   case X86ISD::VSRL:               return "X86ISD::VSRL";
7812   case X86ISD::CMPPD:              return "X86ISD::CMPPD";
7813   case X86ISD::CMPPS:              return "X86ISD::CMPPS";
7814   case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
7815   case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
7816   case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
7817   case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
7818   case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
7819   case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
7820   case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
7821   case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
7822   case X86ISD::ADD:                return "X86ISD::ADD";
7823   case X86ISD::SUB:                return "X86ISD::SUB";
7824   case X86ISD::SMUL:               return "X86ISD::SMUL";
7825   case X86ISD::UMUL:               return "X86ISD::UMUL";
7826   case X86ISD::INC:                return "X86ISD::INC";
7827   case X86ISD::DEC:                return "X86ISD::DEC";
7828   case X86ISD::OR:                 return "X86ISD::OR";
7829   case X86ISD::XOR:                return "X86ISD::XOR";
7830   case X86ISD::AND:                return "X86ISD::AND";
7831   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
7832   case X86ISD::PTEST:              return "X86ISD::PTEST";
7833   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
7834   case X86ISD::MINGW_ALLOCA:       return "X86ISD::MINGW_ALLOCA";
7835   }
7836 }
7837
7838 // isLegalAddressingMode - Return true if the addressing mode represented
7839 // by AM is legal for this target, for a load/store of the specified type.
7840 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
7841                                               const Type *Ty) const {
7842   // X86 supports extremely general addressing modes.
7843   CodeModel::Model M = getTargetMachine().getCodeModel();
7844
7845   // X86 allows a sign-extended 32-bit immediate field as a displacement.
7846   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
7847     return false;
7848
7849   if (AM.BaseGV) {
7850     unsigned GVFlags =
7851       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
7852
7853     // If a reference to this global requires an extra load, we can't fold it.
7854     if (isGlobalStubReference(GVFlags))
7855       return false;
7856
7857     // If BaseGV requires a register for the PIC base, we cannot also have a
7858     // BaseReg specified.
7859     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
7860       return false;
7861
7862     // If lower 4G is not available, then we must use rip-relative addressing.
7863     if (Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
7864       return false;
7865   }
7866
7867   switch (AM.Scale) {
7868   case 0:
7869   case 1:
7870   case 2:
7871   case 4:
7872   case 8:
7873     // These scales always work.
7874     break;
7875   case 3:
7876   case 5:
7877   case 9:
7878     // These scales are formed with basereg+scalereg.  Only accept if there is
7879     // no basereg yet.
7880     if (AM.HasBaseReg)
7881       return false;
7882     break;
7883   default:  // Other stuff never works.
7884     return false;
7885   }
7886
7887   return true;
7888 }
7889
7890
7891 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
7892   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
7893     return false;
7894   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7895   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
7896   if (NumBits1 <= NumBits2)
7897     return false;
7898   return true;
7899 }
7900
7901 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
7902   if (!VT1.isInteger() || !VT2.isInteger())
7903     return false;
7904   unsigned NumBits1 = VT1.getSizeInBits();
7905   unsigned NumBits2 = VT2.getSizeInBits();
7906   if (NumBits1 <= NumBits2)
7907     return false;
7908   return true;
7909 }
7910
7911 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
7912   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
7913   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
7914 }
7915
7916 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
7917   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
7918   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
7919 }
7920
7921 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
7922   // i16 instructions are longer (0x66 prefix) and potentially slower.
7923   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
7924 }
7925
7926 /// isShuffleMaskLegal - Targets can use this to indicate that they only
7927 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
7928 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
7929 /// are assumed to be legal.
7930 bool
7931 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
7932                                       EVT VT) const {
7933   // Very little shuffling can be done for 64-bit vectors right now.
7934   if (VT.getSizeInBits() == 64)
7935     return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
7936
7937   // FIXME: pshufb, blends, shifts.
7938   return (VT.getVectorNumElements() == 2 ||
7939           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
7940           isMOVLMask(M, VT) ||
7941           isSHUFPMask(M, VT) ||
7942           isPSHUFDMask(M, VT) ||
7943           isPSHUFHWMask(M, VT) ||
7944           isPSHUFLWMask(M, VT) ||
7945           isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
7946           isUNPCKLMask(M, VT) ||
7947           isUNPCKHMask(M, VT) ||
7948           isUNPCKL_v_undef_Mask(M, VT) ||
7949           isUNPCKH_v_undef_Mask(M, VT));
7950 }
7951
7952 bool
7953 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
7954                                           EVT VT) const {
7955   unsigned NumElts = VT.getVectorNumElements();
7956   // FIXME: This collection of masks seems suspect.
7957   if (NumElts == 2)
7958     return true;
7959   if (NumElts == 4 && VT.getSizeInBits() == 128) {
7960     return (isMOVLMask(Mask, VT)  ||
7961             isCommutedMOVLMask(Mask, VT, true) ||
7962             isSHUFPMask(Mask, VT) ||
7963             isCommutedSHUFPMask(Mask, VT));
7964   }
7965   return false;
7966 }
7967
7968 //===----------------------------------------------------------------------===//
7969 //                           X86 Scheduler Hooks
7970 //===----------------------------------------------------------------------===//
7971
7972 // private utility function
7973 MachineBasicBlock *
7974 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
7975                                                        MachineBasicBlock *MBB,
7976                                                        unsigned regOpc,
7977                                                        unsigned immOpc,
7978                                                        unsigned LoadOpc,
7979                                                        unsigned CXchgOpc,
7980                                                        unsigned copyOpc,
7981                                                        unsigned notOpc,
7982                                                        unsigned EAXreg,
7983                                                        TargetRegisterClass *RC,
7984                                                        bool invSrc) const {
7985   // For the atomic bitwise operator, we generate
7986   //   thisMBB:
7987   //   newMBB:
7988   //     ld  t1 = [bitinstr.addr]
7989   //     op  t2 = t1, [bitinstr.val]
7990   //     mov EAX = t1
7991   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
7992   //     bz  newMBB
7993   //     fallthrough -->nextMBB
7994   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7995   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7996   MachineFunction::iterator MBBIter = MBB;
7997   ++MBBIter;
7998
7999   /// First build the CFG
8000   MachineFunction *F = MBB->getParent();
8001   MachineBasicBlock *thisMBB = MBB;
8002   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
8003   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
8004   F->insert(MBBIter, newMBB);
8005   F->insert(MBBIter, nextMBB);
8006
8007   // Move all successors to thisMBB to nextMBB
8008   nextMBB->transferSuccessors(thisMBB);
8009
8010   // Update thisMBB to fall through to newMBB
8011   thisMBB->addSuccessor(newMBB);
8012
8013   // newMBB jumps to itself and fall through to nextMBB
8014   newMBB->addSuccessor(nextMBB);
8015   newMBB->addSuccessor(newMBB);
8016
8017   // Insert instructions into newMBB based on incoming instruction
8018   assert(bInstr->getNumOperands() < X86AddrNumOperands + 4 &&
8019          "unexpected number of operands");
8020   DebugLoc dl = bInstr->getDebugLoc();
8021   MachineOperand& destOper = bInstr->getOperand(0);
8022   MachineOperand* argOpers[2 + X86AddrNumOperands];
8023   int numArgs = bInstr->getNumOperands() - 1;
8024   for (int i=0; i < numArgs; ++i)
8025     argOpers[i] = &bInstr->getOperand(i+1);
8026
8027   // x86 address has 4 operands: base, index, scale, and displacement
8028   int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
8029   int valArgIndx = lastAddrIndx + 1;
8030
8031   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
8032   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
8033   for (int i=0; i <= lastAddrIndx; ++i)
8034     (*MIB).addOperand(*argOpers[i]);
8035
8036   unsigned tt = F->getRegInfo().createVirtualRegister(RC);
8037   if (invSrc) {
8038     MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
8039   }
8040   else
8041     tt = t1;
8042
8043   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
8044   assert((argOpers[valArgIndx]->isReg() ||
8045           argOpers[valArgIndx]->isImm()) &&
8046          "invalid operand");
8047   if (argOpers[valArgIndx]->isReg())
8048     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
8049   else
8050     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
8051   MIB.addReg(tt);
8052   (*MIB).addOperand(*argOpers[valArgIndx]);
8053
8054   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), EAXreg);
8055   MIB.addReg(t1);
8056
8057   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
8058   for (int i=0; i <= lastAddrIndx; ++i)
8059     (*MIB).addOperand(*argOpers[i]);
8060   MIB.addReg(t2);
8061   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
8062   (*MIB).setMemRefs(bInstr->memoperands_begin(),
8063                     bInstr->memoperands_end());
8064
8065   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), destOper.getReg());
8066   MIB.addReg(EAXreg);
8067
8068   // insert branch
8069   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
8070
8071   F->DeleteMachineInstr(bInstr);   // The pseudo instruction is gone now.
8072   return nextMBB;
8073 }
8074
8075 // private utility function:  64 bit atomics on 32 bit host.
8076 MachineBasicBlock *
8077 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
8078                                                        MachineBasicBlock *MBB,
8079                                                        unsigned regOpcL,
8080                                                        unsigned regOpcH,
8081                                                        unsigned immOpcL,
8082                                                        unsigned immOpcH,
8083                                                        bool invSrc) const {
8084   // For the atomic bitwise operator, we generate
8085   //   thisMBB (instructions are in pairs, except cmpxchg8b)
8086   //     ld t1,t2 = [bitinstr.addr]
8087   //   newMBB:
8088   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
8089   //     op  t5, t6 <- out1, out2, [bitinstr.val]
8090   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
8091   //     mov ECX, EBX <- t5, t6
8092   //     mov EAX, EDX <- t1, t2
8093   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
8094   //     mov t3, t4 <- EAX, EDX
8095   //     bz  newMBB
8096   //     result in out1, out2
8097   //     fallthrough -->nextMBB
8098
8099   const TargetRegisterClass *RC = X86::GR32RegisterClass;
8100   const unsigned LoadOpc = X86::MOV32rm;
8101   const unsigned copyOpc = X86::MOV32rr;
8102   const unsigned NotOpc = X86::NOT32r;
8103   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8104   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8105   MachineFunction::iterator MBBIter = MBB;
8106   ++MBBIter;
8107
8108   /// First build the CFG
8109   MachineFunction *F = MBB->getParent();
8110   MachineBasicBlock *thisMBB = MBB;
8111   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
8112   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
8113   F->insert(MBBIter, newMBB);
8114   F->insert(MBBIter, nextMBB);
8115
8116   // Move all successors to thisMBB to nextMBB
8117   nextMBB->transferSuccessors(thisMBB);
8118
8119   // Update thisMBB to fall through to newMBB
8120   thisMBB->addSuccessor(newMBB);
8121
8122   // newMBB jumps to itself and fall through to nextMBB
8123   newMBB->addSuccessor(nextMBB);
8124   newMBB->addSuccessor(newMBB);
8125
8126   DebugLoc dl = bInstr->getDebugLoc();
8127   // Insert instructions into newMBB based on incoming instruction
8128   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
8129   assert(bInstr->getNumOperands() < X86AddrNumOperands + 14 &&
8130          "unexpected number of operands");
8131   MachineOperand& dest1Oper = bInstr->getOperand(0);
8132   MachineOperand& dest2Oper = bInstr->getOperand(1);
8133   MachineOperand* argOpers[2 + X86AddrNumOperands];
8134   for (int i=0; i < 2 + X86AddrNumOperands; ++i) {
8135     argOpers[i] = &bInstr->getOperand(i+2);
8136
8137     // We use some of the operands multiple times, so conservatively just
8138     // clear any kill flags that might be present.
8139     if (argOpers[i]->isReg() && argOpers[i]->isUse())
8140       argOpers[i]->setIsKill(false);
8141   }
8142
8143   // x86 address has 5 operands: base, index, scale, displacement, and segment.
8144   int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
8145
8146   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
8147   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
8148   for (int i=0; i <= lastAddrIndx; ++i)
8149     (*MIB).addOperand(*argOpers[i]);
8150   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
8151   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
8152   // add 4 to displacement.
8153   for (int i=0; i <= lastAddrIndx-2; ++i)
8154     (*MIB).addOperand(*argOpers[i]);
8155   MachineOperand newOp3 = *(argOpers[3]);
8156   if (newOp3.isImm())
8157     newOp3.setImm(newOp3.getImm()+4);
8158   else
8159     newOp3.setOffset(newOp3.getOffset()+4);
8160   (*MIB).addOperand(newOp3);
8161   (*MIB).addOperand(*argOpers[lastAddrIndx]);
8162
8163   // t3/4 are defined later, at the bottom of the loop
8164   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
8165   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
8166   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
8167     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
8168   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
8169     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
8170
8171   // The subsequent operations should be using the destination registers of
8172   //the PHI instructions.
8173   if (invSrc) {
8174     t1 = F->getRegInfo().createVirtualRegister(RC);
8175     t2 = F->getRegInfo().createVirtualRegister(RC);
8176     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
8177     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
8178   } else {
8179     t1 = dest1Oper.getReg();
8180     t2 = dest2Oper.getReg();
8181   }
8182
8183   int valArgIndx = lastAddrIndx + 1;
8184   assert((argOpers[valArgIndx]->isReg() ||
8185           argOpers[valArgIndx]->isImm()) &&
8186          "invalid operand");
8187   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
8188   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
8189   if (argOpers[valArgIndx]->isReg())
8190     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
8191   else
8192     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
8193   if (regOpcL != X86::MOV32rr)
8194     MIB.addReg(t1);
8195   (*MIB).addOperand(*argOpers[valArgIndx]);
8196   assert(argOpers[valArgIndx + 1]->isReg() ==
8197          argOpers[valArgIndx]->isReg());
8198   assert(argOpers[valArgIndx + 1]->isImm() ==
8199          argOpers[valArgIndx]->isImm());
8200   if (argOpers[valArgIndx + 1]->isReg())
8201     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
8202   else
8203     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
8204   if (regOpcH != X86::MOV32rr)
8205     MIB.addReg(t2);
8206   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
8207
8208   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EAX);
8209   MIB.addReg(t1);
8210   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EDX);
8211   MIB.addReg(t2);
8212
8213   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EBX);
8214   MIB.addReg(t5);
8215   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::ECX);
8216   MIB.addReg(t6);
8217
8218   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
8219   for (int i=0; i <= lastAddrIndx; ++i)
8220     (*MIB).addOperand(*argOpers[i]);
8221
8222   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
8223   (*MIB).setMemRefs(bInstr->memoperands_begin(),
8224                     bInstr->memoperands_end());
8225
8226   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t3);
8227   MIB.addReg(X86::EAX);
8228   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t4);
8229   MIB.addReg(X86::EDX);
8230
8231   // insert branch
8232   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
8233
8234   F->DeleteMachineInstr(bInstr);   // The pseudo instruction is gone now.
8235   return nextMBB;
8236 }
8237
8238 // private utility function
8239 MachineBasicBlock *
8240 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
8241                                                       MachineBasicBlock *MBB,
8242                                                       unsigned cmovOpc) const {
8243   // For the atomic min/max operator, we generate
8244   //   thisMBB:
8245   //   newMBB:
8246   //     ld t1 = [min/max.addr]
8247   //     mov t2 = [min/max.val]
8248   //     cmp  t1, t2
8249   //     cmov[cond] t2 = t1
8250   //     mov EAX = t1
8251   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
8252   //     bz   newMBB
8253   //     fallthrough -->nextMBB
8254   //
8255   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8256   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8257   MachineFunction::iterator MBBIter = MBB;
8258   ++MBBIter;
8259
8260   /// First build the CFG
8261   MachineFunction *F = MBB->getParent();
8262   MachineBasicBlock *thisMBB = MBB;
8263   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
8264   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
8265   F->insert(MBBIter, newMBB);
8266   F->insert(MBBIter, nextMBB);
8267
8268   // Move all successors of thisMBB to nextMBB
8269   nextMBB->transferSuccessors(thisMBB);
8270
8271   // Update thisMBB to fall through to newMBB
8272   thisMBB->addSuccessor(newMBB);
8273
8274   // newMBB jumps to newMBB and fall through to nextMBB
8275   newMBB->addSuccessor(nextMBB);
8276   newMBB->addSuccessor(newMBB);
8277
8278   DebugLoc dl = mInstr->getDebugLoc();
8279   // Insert instructions into newMBB based on incoming instruction
8280   assert(mInstr->getNumOperands() < X86AddrNumOperands + 4 &&
8281          "unexpected number of operands");
8282   MachineOperand& destOper = mInstr->getOperand(0);
8283   MachineOperand* argOpers[2 + X86AddrNumOperands];
8284   int numArgs = mInstr->getNumOperands() - 1;
8285   for (int i=0; i < numArgs; ++i)
8286     argOpers[i] = &mInstr->getOperand(i+1);
8287
8288   // x86 address has 4 operands: base, index, scale, and displacement
8289   int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
8290   int valArgIndx = lastAddrIndx + 1;
8291
8292   unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8293   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
8294   for (int i=0; i <= lastAddrIndx; ++i)
8295     (*MIB).addOperand(*argOpers[i]);
8296
8297   // We only support register and immediate values
8298   assert((argOpers[valArgIndx]->isReg() ||
8299           argOpers[valArgIndx]->isImm()) &&
8300          "invalid operand");
8301
8302   unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8303   if (argOpers[valArgIndx]->isReg())
8304     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
8305   else
8306     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
8307   (*MIB).addOperand(*argOpers[valArgIndx]);
8308
8309   MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), X86::EAX);
8310   MIB.addReg(t1);
8311
8312   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
8313   MIB.addReg(t1);
8314   MIB.addReg(t2);
8315
8316   // Generate movc
8317   unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8318   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
8319   MIB.addReg(t2);
8320   MIB.addReg(t1);
8321
8322   // Cmp and exchange if none has modified the memory location
8323   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
8324   for (int i=0; i <= lastAddrIndx; ++i)
8325     (*MIB).addOperand(*argOpers[i]);
8326   MIB.addReg(t3);
8327   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
8328   (*MIB).setMemRefs(mInstr->memoperands_begin(),
8329                     mInstr->memoperands_end());
8330
8331   MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), destOper.getReg());
8332   MIB.addReg(X86::EAX);
8333
8334   // insert branch
8335   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
8336
8337   F->DeleteMachineInstr(mInstr);   // The pseudo instruction is gone now.
8338   return nextMBB;
8339 }
8340
8341 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
8342 // all of this code can be replaced with that in the .td file.
8343 MachineBasicBlock *
8344 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
8345                             unsigned numArgs, bool memArg) const {
8346
8347   MachineFunction *F = BB->getParent();
8348   DebugLoc dl = MI->getDebugLoc();
8349   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8350
8351   unsigned Opc;
8352   if (memArg)
8353     Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
8354   else
8355     Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
8356
8357   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(Opc));
8358
8359   for (unsigned i = 0; i < numArgs; ++i) {
8360     MachineOperand &Op = MI->getOperand(i+1);
8361
8362     if (!(Op.isReg() && Op.isImplicit()))
8363       MIB.addOperand(Op);
8364   }
8365
8366   BuildMI(BB, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
8367     .addReg(X86::XMM0);
8368
8369   F->DeleteMachineInstr(MI);
8370
8371   return BB;
8372 }
8373
8374 MachineBasicBlock *
8375 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
8376                                                  MachineInstr *MI,
8377                                                  MachineBasicBlock *MBB) const {
8378   // Emit code to save XMM registers to the stack. The ABI says that the
8379   // number of registers to save is given in %al, so it's theoretically
8380   // possible to do an indirect jump trick to avoid saving all of them,
8381   // however this code takes a simpler approach and just executes all
8382   // of the stores if %al is non-zero. It's less code, and it's probably
8383   // easier on the hardware branch predictor, and stores aren't all that
8384   // expensive anyway.
8385
8386   // Create the new basic blocks. One block contains all the XMM stores,
8387   // and one block is the final destination regardless of whether any
8388   // stores were performed.
8389   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8390   MachineFunction *F = MBB->getParent();
8391   MachineFunction::iterator MBBIter = MBB;
8392   ++MBBIter;
8393   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
8394   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
8395   F->insert(MBBIter, XMMSaveMBB);
8396   F->insert(MBBIter, EndMBB);
8397
8398   // Set up the CFG.
8399   // Move any original successors of MBB to the end block.
8400   EndMBB->transferSuccessors(MBB);
8401   // The original block will now fall through to the XMM save block.
8402   MBB->addSuccessor(XMMSaveMBB);
8403   // The XMMSaveMBB will fall through to the end block.
8404   XMMSaveMBB->addSuccessor(EndMBB);
8405
8406   // Now add the instructions.
8407   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8408   DebugLoc DL = MI->getDebugLoc();
8409
8410   unsigned CountReg = MI->getOperand(0).getReg();
8411   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
8412   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
8413
8414   if (!Subtarget->isTargetWin64()) {
8415     // If %al is 0, branch around the XMM save block.
8416     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
8417     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
8418     MBB->addSuccessor(EndMBB);
8419   }
8420
8421   // In the XMM save block, save all the XMM argument registers.
8422   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
8423     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
8424     MachineMemOperand *MMO =
8425       F->getMachineMemOperand(
8426         PseudoSourceValue::getFixedStack(RegSaveFrameIndex),
8427         MachineMemOperand::MOStore, Offset,
8428         /*Size=*/16, /*Align=*/16);
8429     BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
8430       .addFrameIndex(RegSaveFrameIndex)
8431       .addImm(/*Scale=*/1)
8432       .addReg(/*IndexReg=*/0)
8433       .addImm(/*Disp=*/Offset)
8434       .addReg(/*Segment=*/0)
8435       .addReg(MI->getOperand(i).getReg())
8436       .addMemOperand(MMO);
8437   }
8438
8439   F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
8440
8441   return EndMBB;
8442 }
8443
8444 MachineBasicBlock *
8445 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
8446                                      MachineBasicBlock *BB) const {
8447   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8448   DebugLoc DL = MI->getDebugLoc();
8449
8450   // To "insert" a SELECT_CC instruction, we actually have to insert the
8451   // diamond control-flow pattern.  The incoming instruction knows the
8452   // destination vreg to set, the condition code register to branch on, the
8453   // true/false values to select between, and a branch opcode to use.
8454   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8455   MachineFunction::iterator It = BB;
8456   ++It;
8457
8458   //  thisMBB:
8459   //  ...
8460   //   TrueVal = ...
8461   //   cmpTY ccX, r1, r2
8462   //   bCC copy1MBB
8463   //   fallthrough --> copy0MBB
8464   MachineBasicBlock *thisMBB = BB;
8465   MachineFunction *F = BB->getParent();
8466   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
8467   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8468   unsigned Opc =
8469     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
8470
8471   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
8472   F->insert(It, copy0MBB);
8473   F->insert(It, sinkMBB);
8474
8475   // Update machine-CFG edges by first adding all successors of the current
8476   // block to the new block which will contain the Phi node for the select.
8477   for (MachineBasicBlock::succ_iterator I = BB->succ_begin(),
8478          E = BB->succ_end(); I != E; ++I)
8479     sinkMBB->addSuccessor(*I);
8480
8481   // Next, remove all successors of the current block, and add the true
8482   // and fallthrough blocks as its successors.
8483   while (!BB->succ_empty())
8484     BB->removeSuccessor(BB->succ_begin());
8485
8486   // Add the true and fallthrough blocks as its successors.
8487   BB->addSuccessor(copy0MBB);
8488   BB->addSuccessor(sinkMBB);
8489
8490   // If the EFLAGS register isn't dead in the terminator, then claim that it's
8491   // live into the sink and copy blocks.
8492   const MachineFunction *MF = BB->getParent();
8493   const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
8494   BitVector ReservedRegs = TRI->getReservedRegs(*MF);
8495   const MachineInstr *Term = BB->getFirstTerminator();
8496
8497   for (unsigned I = 0, E = Term->getNumOperands(); I != E; ++I) {
8498     const MachineOperand &MO = Term->getOperand(I);
8499     if (!MO.isReg() || MO.isKill() || MO.isDead()) continue;
8500     unsigned Reg = MO.getReg();
8501     if (Reg != X86::EFLAGS) continue;
8502     copy0MBB->addLiveIn(Reg);
8503     sinkMBB->addLiveIn(Reg);
8504   }
8505
8506   //  copy0MBB:
8507   //   %FalseValue = ...
8508   //   # fallthrough to sinkMBB
8509   copy0MBB->addSuccessor(sinkMBB);
8510
8511   //  sinkMBB:
8512   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
8513   //  ...
8514   BuildMI(sinkMBB, DL, TII->get(X86::PHI), MI->getOperand(0).getReg())
8515     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
8516     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
8517
8518   F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
8519   return sinkMBB;
8520 }
8521
8522 MachineBasicBlock *
8523 X86TargetLowering::EmitLoweredMingwAlloca(MachineInstr *MI,
8524                                           MachineBasicBlock *BB) const {
8525   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8526   DebugLoc DL = MI->getDebugLoc();
8527   MachineFunction *F = BB->getParent();
8528
8529   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
8530   // non-trivial part is impdef of ESP.
8531   // FIXME: The code should be tweaked as soon as we'll try to do codegen for
8532   // mingw-w64.
8533
8534   BuildMI(BB, DL, TII->get(X86::CALLpcrel32))
8535     .addExternalSymbol("_alloca")
8536     .addReg(X86::EAX, RegState::Implicit)
8537     .addReg(X86::ESP, RegState::Implicit)
8538     .addReg(X86::EAX, RegState::Define | RegState::Implicit)
8539     .addReg(X86::ESP, RegState::Define | RegState::Implicit);
8540
8541   F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
8542   return BB;
8543 }
8544
8545 MachineBasicBlock *
8546 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
8547                                       MachineBasicBlock *BB) const {
8548   // This is pretty easy.  We're taking the value that we received from
8549   // our load from the relocation, sticking it in either RDI (x86-64)
8550   // or EAX and doing an indirect call.  The return value will then
8551   // be in the normal return register.
8552   const X86InstrInfo *TII 
8553     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
8554   DebugLoc DL = MI->getDebugLoc();
8555   MachineFunction *F = BB->getParent();
8556   
8557   assert(MI->getOperand(3).isGlobal() && "This should be a global");
8558   
8559   if (Subtarget->is64Bit()) {
8560     MachineInstrBuilder MIB = BuildMI(BB, DL, TII->get(X86::MOV64rm), X86::RDI)
8561     .addReg(X86::RIP)
8562     .addImm(0).addReg(0)
8563     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0, 
8564                       MI->getOperand(3).getTargetFlags())
8565     .addReg(0);
8566     MIB = BuildMI(BB, DL, TII->get(X86::CALL64m));
8567     addDirectMem(MIB, X86::RDI).addReg(0);
8568   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
8569     MachineInstrBuilder MIB = BuildMI(BB, DL, TII->get(X86::MOV32rm), X86::EAX)
8570     .addReg(0)
8571     .addImm(0).addReg(0)
8572     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0, 
8573                       MI->getOperand(3).getTargetFlags())
8574     .addReg(0);
8575     MIB = BuildMI(BB, DL, TII->get(X86::CALL32m));
8576     addDirectMem(MIB, X86::EAX).addReg(0);
8577   } else {
8578     MachineInstrBuilder MIB = BuildMI(BB, DL, TII->get(X86::MOV32rm), X86::EAX)
8579     .addReg(TII->getGlobalBaseReg(F))
8580     .addImm(0).addReg(0)
8581     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0, 
8582                       MI->getOperand(3).getTargetFlags())
8583     .addReg(0);
8584     MIB = BuildMI(BB, DL, TII->get(X86::CALL32m));
8585     addDirectMem(MIB, X86::EAX).addReg(0);
8586   }
8587   
8588   F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
8589   return BB;
8590 }
8591
8592 MachineBasicBlock *
8593 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
8594                                                MachineBasicBlock *BB) const {
8595   switch (MI->getOpcode()) {
8596   default: assert(false && "Unexpected instr type to insert");
8597   case X86::MINGW_ALLOCA:
8598     return EmitLoweredMingwAlloca(MI, BB);
8599   case X86::TLSCall_32:
8600   case X86::TLSCall_64:
8601     return EmitLoweredTLSCall(MI, BB);
8602   case X86::CMOV_GR8:
8603   case X86::CMOV_V1I64:
8604   case X86::CMOV_FR32:
8605   case X86::CMOV_FR64:
8606   case X86::CMOV_V4F32:
8607   case X86::CMOV_V2F64:
8608   case X86::CMOV_V2I64:
8609   case X86::CMOV_GR16:
8610   case X86::CMOV_GR32:
8611   case X86::CMOV_RFP32:
8612   case X86::CMOV_RFP64:
8613   case X86::CMOV_RFP80:
8614     return EmitLoweredSelect(MI, BB);
8615
8616   case X86::FP32_TO_INT16_IN_MEM:
8617   case X86::FP32_TO_INT32_IN_MEM:
8618   case X86::FP32_TO_INT64_IN_MEM:
8619   case X86::FP64_TO_INT16_IN_MEM:
8620   case X86::FP64_TO_INT32_IN_MEM:
8621   case X86::FP64_TO_INT64_IN_MEM:
8622   case X86::FP80_TO_INT16_IN_MEM:
8623   case X86::FP80_TO_INT32_IN_MEM:
8624   case X86::FP80_TO_INT64_IN_MEM: {
8625     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8626     DebugLoc DL = MI->getDebugLoc();
8627
8628     // Change the floating point control register to use "round towards zero"
8629     // mode when truncating to an integer value.
8630     MachineFunction *F = BB->getParent();
8631     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
8632     addFrameReference(BuildMI(BB, DL, TII->get(X86::FNSTCW16m)), CWFrameIdx);
8633
8634     // Load the old value of the high byte of the control word...
8635     unsigned OldCW =
8636       F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
8637     addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16rm), OldCW),
8638                       CWFrameIdx);
8639
8640     // Set the high part to be round to zero...
8641     addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
8642       .addImm(0xC7F);
8643
8644     // Reload the modified control word now...
8645     addFrameReference(BuildMI(BB, DL, TII->get(X86::FLDCW16m)), CWFrameIdx);
8646
8647     // Restore the memory image of control word to original value
8648     addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
8649       .addReg(OldCW);
8650
8651     // Get the X86 opcode to use.
8652     unsigned Opc;
8653     switch (MI->getOpcode()) {
8654     default: llvm_unreachable("illegal opcode!");
8655     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
8656     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
8657     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
8658     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
8659     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
8660     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
8661     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
8662     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
8663     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
8664     }
8665
8666     X86AddressMode AM;
8667     MachineOperand &Op = MI->getOperand(0);
8668     if (Op.isReg()) {
8669       AM.BaseType = X86AddressMode::RegBase;
8670       AM.Base.Reg = Op.getReg();
8671     } else {
8672       AM.BaseType = X86AddressMode::FrameIndexBase;
8673       AM.Base.FrameIndex = Op.getIndex();
8674     }
8675     Op = MI->getOperand(1);
8676     if (Op.isImm())
8677       AM.Scale = Op.getImm();
8678     Op = MI->getOperand(2);
8679     if (Op.isImm())
8680       AM.IndexReg = Op.getImm();
8681     Op = MI->getOperand(3);
8682     if (Op.isGlobal()) {
8683       AM.GV = Op.getGlobal();
8684     } else {
8685       AM.Disp = Op.getImm();
8686     }
8687     addFullAddress(BuildMI(BB, DL, TII->get(Opc)), AM)
8688                       .addReg(MI->getOperand(X86AddrNumOperands).getReg());
8689
8690     // Reload the original control word now.
8691     addFrameReference(BuildMI(BB, DL, TII->get(X86::FLDCW16m)), CWFrameIdx);
8692
8693     F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
8694     return BB;
8695   }
8696     // String/text processing lowering.
8697   case X86::PCMPISTRM128REG:
8698     return EmitPCMP(MI, BB, 3, false /* in-mem */);
8699   case X86::PCMPISTRM128MEM:
8700     return EmitPCMP(MI, BB, 3, true /* in-mem */);
8701   case X86::PCMPESTRM128REG:
8702     return EmitPCMP(MI, BB, 5, false /* in mem */);
8703   case X86::PCMPESTRM128MEM:
8704     return EmitPCMP(MI, BB, 5, true /* in mem */);
8705
8706     // Atomic Lowering.
8707   case X86::ATOMAND32:
8708     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
8709                                                X86::AND32ri, X86::MOV32rm,
8710                                                X86::LCMPXCHG32, X86::MOV32rr,
8711                                                X86::NOT32r, X86::EAX,
8712                                                X86::GR32RegisterClass);
8713   case X86::ATOMOR32:
8714     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
8715                                                X86::OR32ri, X86::MOV32rm,
8716                                                X86::LCMPXCHG32, X86::MOV32rr,
8717                                                X86::NOT32r, X86::EAX,
8718                                                X86::GR32RegisterClass);
8719   case X86::ATOMXOR32:
8720     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
8721                                                X86::XOR32ri, X86::MOV32rm,
8722                                                X86::LCMPXCHG32, X86::MOV32rr,
8723                                                X86::NOT32r, X86::EAX,
8724                                                X86::GR32RegisterClass);
8725   case X86::ATOMNAND32:
8726     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
8727                                                X86::AND32ri, X86::MOV32rm,
8728                                                X86::LCMPXCHG32, X86::MOV32rr,
8729                                                X86::NOT32r, X86::EAX,
8730                                                X86::GR32RegisterClass, true);
8731   case X86::ATOMMIN32:
8732     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
8733   case X86::ATOMMAX32:
8734     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
8735   case X86::ATOMUMIN32:
8736     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
8737   case X86::ATOMUMAX32:
8738     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
8739
8740   case X86::ATOMAND16:
8741     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
8742                                                X86::AND16ri, X86::MOV16rm,
8743                                                X86::LCMPXCHG16, X86::MOV16rr,
8744                                                X86::NOT16r, X86::AX,
8745                                                X86::GR16RegisterClass);
8746   case X86::ATOMOR16:
8747     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
8748                                                X86::OR16ri, X86::MOV16rm,
8749                                                X86::LCMPXCHG16, X86::MOV16rr,
8750                                                X86::NOT16r, X86::AX,
8751                                                X86::GR16RegisterClass);
8752   case X86::ATOMXOR16:
8753     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
8754                                                X86::XOR16ri, X86::MOV16rm,
8755                                                X86::LCMPXCHG16, X86::MOV16rr,
8756                                                X86::NOT16r, X86::AX,
8757                                                X86::GR16RegisterClass);
8758   case X86::ATOMNAND16:
8759     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
8760                                                X86::AND16ri, X86::MOV16rm,
8761                                                X86::LCMPXCHG16, X86::MOV16rr,
8762                                                X86::NOT16r, X86::AX,
8763                                                X86::GR16RegisterClass, true);
8764   case X86::ATOMMIN16:
8765     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
8766   case X86::ATOMMAX16:
8767     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
8768   case X86::ATOMUMIN16:
8769     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
8770   case X86::ATOMUMAX16:
8771     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
8772
8773   case X86::ATOMAND8:
8774     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
8775                                                X86::AND8ri, X86::MOV8rm,
8776                                                X86::LCMPXCHG8, X86::MOV8rr,
8777                                                X86::NOT8r, X86::AL,
8778                                                X86::GR8RegisterClass);
8779   case X86::ATOMOR8:
8780     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
8781                                                X86::OR8ri, X86::MOV8rm,
8782                                                X86::LCMPXCHG8, X86::MOV8rr,
8783                                                X86::NOT8r, X86::AL,
8784                                                X86::GR8RegisterClass);
8785   case X86::ATOMXOR8:
8786     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
8787                                                X86::XOR8ri, X86::MOV8rm,
8788                                                X86::LCMPXCHG8, X86::MOV8rr,
8789                                                X86::NOT8r, X86::AL,
8790                                                X86::GR8RegisterClass);
8791   case X86::ATOMNAND8:
8792     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
8793                                                X86::AND8ri, X86::MOV8rm,
8794                                                X86::LCMPXCHG8, X86::MOV8rr,
8795                                                X86::NOT8r, X86::AL,
8796                                                X86::GR8RegisterClass, true);
8797   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
8798   // This group is for 64-bit host.
8799   case X86::ATOMAND64:
8800     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
8801                                                X86::AND64ri32, X86::MOV64rm,
8802                                                X86::LCMPXCHG64, X86::MOV64rr,
8803                                                X86::NOT64r, X86::RAX,
8804                                                X86::GR64RegisterClass);
8805   case X86::ATOMOR64:
8806     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
8807                                                X86::OR64ri32, X86::MOV64rm,
8808                                                X86::LCMPXCHG64, X86::MOV64rr,
8809                                                X86::NOT64r, X86::RAX,
8810                                                X86::GR64RegisterClass);
8811   case X86::ATOMXOR64:
8812     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
8813                                                X86::XOR64ri32, X86::MOV64rm,
8814                                                X86::LCMPXCHG64, X86::MOV64rr,
8815                                                X86::NOT64r, X86::RAX,
8816                                                X86::GR64RegisterClass);
8817   case X86::ATOMNAND64:
8818     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
8819                                                X86::AND64ri32, X86::MOV64rm,
8820                                                X86::LCMPXCHG64, X86::MOV64rr,
8821                                                X86::NOT64r, X86::RAX,
8822                                                X86::GR64RegisterClass, true);
8823   case X86::ATOMMIN64:
8824     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
8825   case X86::ATOMMAX64:
8826     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
8827   case X86::ATOMUMIN64:
8828     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
8829   case X86::ATOMUMAX64:
8830     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
8831
8832   // This group does 64-bit operations on a 32-bit host.
8833   case X86::ATOMAND6432:
8834     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8835                                                X86::AND32rr, X86::AND32rr,
8836                                                X86::AND32ri, X86::AND32ri,
8837                                                false);
8838   case X86::ATOMOR6432:
8839     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8840                                                X86::OR32rr, X86::OR32rr,
8841                                                X86::OR32ri, X86::OR32ri,
8842                                                false);
8843   case X86::ATOMXOR6432:
8844     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8845                                                X86::XOR32rr, X86::XOR32rr,
8846                                                X86::XOR32ri, X86::XOR32ri,
8847                                                false);
8848   case X86::ATOMNAND6432:
8849     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8850                                                X86::AND32rr, X86::AND32rr,
8851                                                X86::AND32ri, X86::AND32ri,
8852                                                true);
8853   case X86::ATOMADD6432:
8854     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8855                                                X86::ADD32rr, X86::ADC32rr,
8856                                                X86::ADD32ri, X86::ADC32ri,
8857                                                false);
8858   case X86::ATOMSUB6432:
8859     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8860                                                X86::SUB32rr, X86::SBB32rr,
8861                                                X86::SUB32ri, X86::SBB32ri,
8862                                                false);
8863   case X86::ATOMSWAP6432:
8864     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8865                                                X86::MOV32rr, X86::MOV32rr,
8866                                                X86::MOV32ri, X86::MOV32ri,
8867                                                false);
8868   case X86::VASTART_SAVE_XMM_REGS:
8869     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
8870   }
8871 }
8872
8873 //===----------------------------------------------------------------------===//
8874 //                           X86 Optimization Hooks
8875 //===----------------------------------------------------------------------===//
8876
8877 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
8878                                                        const APInt &Mask,
8879                                                        APInt &KnownZero,
8880                                                        APInt &KnownOne,
8881                                                        const SelectionDAG &DAG,
8882                                                        unsigned Depth) const {
8883   unsigned Opc = Op.getOpcode();
8884   assert((Opc >= ISD::BUILTIN_OP_END ||
8885           Opc == ISD::INTRINSIC_WO_CHAIN ||
8886           Opc == ISD::INTRINSIC_W_CHAIN ||
8887           Opc == ISD::INTRINSIC_VOID) &&
8888          "Should use MaskedValueIsZero if you don't know whether Op"
8889          " is a target node!");
8890
8891   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
8892   switch (Opc) {
8893   default: break;
8894   case X86ISD::ADD:
8895   case X86ISD::SUB:
8896   case X86ISD::SMUL:
8897   case X86ISD::UMUL:
8898   case X86ISD::INC:
8899   case X86ISD::DEC:
8900   case X86ISD::OR:
8901   case X86ISD::XOR:
8902   case X86ISD::AND:
8903     // These nodes' second result is a boolean.
8904     if (Op.getResNo() == 0)
8905       break;
8906     // Fallthrough
8907   case X86ISD::SETCC:
8908     KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
8909                                        Mask.getBitWidth() - 1);
8910     break;
8911   }
8912 }
8913
8914 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
8915 /// node is a GlobalAddress + offset.
8916 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
8917                                        const GlobalValue* &GA,
8918                                        int64_t &Offset) const {
8919   if (N->getOpcode() == X86ISD::Wrapper) {
8920     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
8921       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
8922       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
8923       return true;
8924     }
8925   }
8926   return TargetLowering::isGAPlusOffset(N, GA, Offset);
8927 }
8928
8929 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
8930 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
8931 /// if the load addresses are consecutive, non-overlapping, and in the right
8932 /// order.
8933 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
8934                                      const TargetLowering &TLI) {
8935   DebugLoc dl = N->getDebugLoc();
8936   EVT VT = N->getValueType(0);
8937   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8938
8939   if (VT.getSizeInBits() != 128)
8940     return SDValue();
8941
8942   SmallVector<SDValue, 16> Elts;
8943   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
8944     Elts.push_back(DAG.getShuffleScalarElt(SVN, i));
8945   
8946   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
8947 }
8948
8949 /// PerformShuffleCombine - Detect vector gather/scatter index generation
8950 /// and convert it from being a bunch of shuffles and extracts to a simple
8951 /// store and scalar loads to extract the elements.
8952 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
8953                                                 const TargetLowering &TLI) {
8954   SDValue InputVector = N->getOperand(0);
8955
8956   // Only operate on vectors of 4 elements, where the alternative shuffling
8957   // gets to be more expensive.
8958   if (InputVector.getValueType() != MVT::v4i32)
8959     return SDValue();
8960
8961   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
8962   // single use which is a sign-extend or zero-extend, and all elements are
8963   // used.
8964   SmallVector<SDNode *, 4> Uses;
8965   unsigned ExtractedElements = 0;
8966   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
8967        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
8968     if (UI.getUse().getResNo() != InputVector.getResNo())
8969       return SDValue();
8970
8971     SDNode *Extract = *UI;
8972     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8973       return SDValue();
8974
8975     if (Extract->getValueType(0) != MVT::i32)
8976       return SDValue();
8977     if (!Extract->hasOneUse())
8978       return SDValue();
8979     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
8980         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
8981       return SDValue();
8982     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
8983       return SDValue();
8984
8985     // Record which element was extracted.
8986     ExtractedElements |=
8987       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
8988
8989     Uses.push_back(Extract);
8990   }
8991
8992   // If not all the elements were used, this may not be worthwhile.
8993   if (ExtractedElements != 15)
8994     return SDValue();
8995
8996   // Ok, we've now decided to do the transformation.
8997   DebugLoc dl = InputVector.getDebugLoc();
8998
8999   // Store the value to a temporary stack slot.
9000   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
9001   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr, NULL, 0,
9002                             false, false, 0);
9003
9004   // Replace each use (extract) with a load of the appropriate element.
9005   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
9006        UE = Uses.end(); UI != UE; ++UI) {
9007     SDNode *Extract = *UI;
9008
9009     // Compute the element's address.
9010     SDValue Idx = Extract->getOperand(1);
9011     unsigned EltSize =
9012         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
9013     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
9014     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
9015
9016     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(), OffsetVal, StackPtr);
9017
9018     // Load the scalar.
9019     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch, ScalarAddr,
9020                           NULL, 0, false, false, 0);
9021
9022     // Replace the exact with the load.
9023     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
9024   }
9025
9026   // The replacement was made in place; don't return anything.
9027   return SDValue();
9028 }
9029
9030 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
9031 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
9032                                     const X86Subtarget *Subtarget) {
9033   DebugLoc DL = N->getDebugLoc();
9034   SDValue Cond = N->getOperand(0);
9035   // Get the LHS/RHS of the select.
9036   SDValue LHS = N->getOperand(1);
9037   SDValue RHS = N->getOperand(2);
9038
9039   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
9040   // instructions match the semantics of the common C idiom x<y?x:y but not
9041   // x<=y?x:y, because of how they handle negative zero (which can be
9042   // ignored in unsafe-math mode).
9043   if (Subtarget->hasSSE2() &&
9044       (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
9045       Cond.getOpcode() == ISD::SETCC) {
9046     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
9047
9048     unsigned Opcode = 0;
9049     // Check for x CC y ? x : y.
9050     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
9051         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
9052       switch (CC) {
9053       default: break;
9054       case ISD::SETULT:
9055         // Converting this to a min would handle NaNs incorrectly, and swapping
9056         // the operands would cause it to handle comparisons between positive
9057         // and negative zero incorrectly.
9058         if (!FiniteOnlyFPMath() &&
9059             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))) {
9060           if (!UnsafeFPMath &&
9061               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9062             break;
9063           std::swap(LHS, RHS);
9064         }
9065         Opcode = X86ISD::FMIN;
9066         break;
9067       case ISD::SETOLE:
9068         // Converting this to a min would handle comparisons between positive
9069         // and negative zero incorrectly.
9070         if (!UnsafeFPMath &&
9071             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
9072           break;
9073         Opcode = X86ISD::FMIN;
9074         break;
9075       case ISD::SETULE:
9076         // Converting this to a min would handle both negative zeros and NaNs
9077         // incorrectly, but we can swap the operands to fix both.
9078         std::swap(LHS, RHS);
9079       case ISD::SETOLT:
9080       case ISD::SETLT:
9081       case ISD::SETLE:
9082         Opcode = X86ISD::FMIN;
9083         break;
9084
9085       case ISD::SETOGE:
9086         // Converting this to a max would handle comparisons between positive
9087         // and negative zero incorrectly.
9088         if (!UnsafeFPMath &&
9089             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS))
9090           break;
9091         Opcode = X86ISD::FMAX;
9092         break;
9093       case ISD::SETUGT:
9094         // Converting this to a max would handle NaNs incorrectly, and swapping
9095         // the operands would cause it to handle comparisons between positive
9096         // and negative zero incorrectly.
9097         if (!FiniteOnlyFPMath() &&
9098             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))) {
9099           if (!UnsafeFPMath &&
9100               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9101             break;
9102           std::swap(LHS, RHS);
9103         }
9104         Opcode = X86ISD::FMAX;
9105         break;
9106       case ISD::SETUGE:
9107         // Converting this to a max would handle both negative zeros and NaNs
9108         // incorrectly, but we can swap the operands to fix both.
9109         std::swap(LHS, RHS);
9110       case ISD::SETOGT:
9111       case ISD::SETGT:
9112       case ISD::SETGE:
9113         Opcode = X86ISD::FMAX;
9114         break;
9115       }
9116     // Check for x CC y ? y : x -- a min/max with reversed arms.
9117     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
9118                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
9119       switch (CC) {
9120       default: break;
9121       case ISD::SETOGE:
9122         // Converting this to a min would handle comparisons between positive
9123         // and negative zero incorrectly, and swapping the operands would
9124         // cause it to handle NaNs incorrectly.
9125         if (!UnsafeFPMath &&
9126             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
9127           if (!FiniteOnlyFPMath() &&
9128               (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
9129             break;
9130           std::swap(LHS, RHS);
9131         }
9132         Opcode = X86ISD::FMIN;
9133         break;
9134       case ISD::SETUGT:
9135         // Converting this to a min would handle NaNs incorrectly.
9136         if (!UnsafeFPMath &&
9137             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
9138           break;
9139         Opcode = X86ISD::FMIN;
9140         break;
9141       case ISD::SETUGE:
9142         // Converting this to a min would handle both negative zeros and NaNs
9143         // incorrectly, but we can swap the operands to fix both.
9144         std::swap(LHS, RHS);
9145       case ISD::SETOGT:
9146       case ISD::SETGT:
9147       case ISD::SETGE:
9148         Opcode = X86ISD::FMIN;
9149         break;
9150
9151       case ISD::SETULT:
9152         // Converting this to a max would handle NaNs incorrectly.
9153         if (!FiniteOnlyFPMath() &&
9154             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
9155           break;
9156         Opcode = X86ISD::FMAX;
9157         break;
9158       case ISD::SETOLE:
9159         // Converting this to a max would handle comparisons between positive
9160         // and negative zero incorrectly, and swapping the operands would
9161         // cause it to handle NaNs incorrectly.
9162         if (!UnsafeFPMath &&
9163             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
9164           if (!FiniteOnlyFPMath() &&
9165               (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
9166             break;
9167           std::swap(LHS, RHS);
9168         }
9169         Opcode = X86ISD::FMAX;
9170         break;
9171       case ISD::SETULE:
9172         // Converting this to a max would handle both negative zeros and NaNs
9173         // incorrectly, but we can swap the operands to fix both.
9174         std::swap(LHS, RHS);
9175       case ISD::SETOLT:
9176       case ISD::SETLT:
9177       case ISD::SETLE:
9178         Opcode = X86ISD::FMAX;
9179         break;
9180       }
9181     }
9182
9183     if (Opcode)
9184       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
9185   }
9186
9187   // If this is a select between two integer constants, try to do some
9188   // optimizations.
9189   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
9190     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
9191       // Don't do this for crazy integer types.
9192       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
9193         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
9194         // so that TrueC (the true value) is larger than FalseC.
9195         bool NeedsCondInvert = false;
9196
9197         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
9198             // Efficiently invertible.
9199             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
9200              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
9201               isa<ConstantSDNode>(Cond.getOperand(1))))) {
9202           NeedsCondInvert = true;
9203           std::swap(TrueC, FalseC);
9204         }
9205
9206         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
9207         if (FalseC->getAPIntValue() == 0 &&
9208             TrueC->getAPIntValue().isPowerOf2()) {
9209           if (NeedsCondInvert) // Invert the condition if needed.
9210             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
9211                                DAG.getConstant(1, Cond.getValueType()));
9212
9213           // Zero extend the condition if needed.
9214           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
9215
9216           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
9217           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
9218                              DAG.getConstant(ShAmt, MVT::i8));
9219         }
9220
9221         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
9222         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
9223           if (NeedsCondInvert) // Invert the condition if needed.
9224             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
9225                                DAG.getConstant(1, Cond.getValueType()));
9226
9227           // Zero extend the condition if needed.
9228           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
9229                              FalseC->getValueType(0), Cond);
9230           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9231                              SDValue(FalseC, 0));
9232         }
9233
9234         // Optimize cases that will turn into an LEA instruction.  This requires
9235         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
9236         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
9237           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
9238           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
9239
9240           bool isFastMultiplier = false;
9241           if (Diff < 10) {
9242             switch ((unsigned char)Diff) {
9243               default: break;
9244               case 1:  // result = add base, cond
9245               case 2:  // result = lea base(    , cond*2)
9246               case 3:  // result = lea base(cond, cond*2)
9247               case 4:  // result = lea base(    , cond*4)
9248               case 5:  // result = lea base(cond, cond*4)
9249               case 8:  // result = lea base(    , cond*8)
9250               case 9:  // result = lea base(cond, cond*8)
9251                 isFastMultiplier = true;
9252                 break;
9253             }
9254           }
9255
9256           if (isFastMultiplier) {
9257             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
9258             if (NeedsCondInvert) // Invert the condition if needed.
9259               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
9260                                  DAG.getConstant(1, Cond.getValueType()));
9261
9262             // Zero extend the condition if needed.
9263             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
9264                                Cond);
9265             // Scale the condition by the difference.
9266             if (Diff != 1)
9267               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
9268                                  DAG.getConstant(Diff, Cond.getValueType()));
9269
9270             // Add the base if non-zero.
9271             if (FalseC->getAPIntValue() != 0)
9272               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9273                                  SDValue(FalseC, 0));
9274             return Cond;
9275           }
9276         }
9277       }
9278   }
9279
9280   return SDValue();
9281 }
9282
9283 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
9284 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
9285                                   TargetLowering::DAGCombinerInfo &DCI) {
9286   DebugLoc DL = N->getDebugLoc();
9287
9288   // If the flag operand isn't dead, don't touch this CMOV.
9289   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
9290     return SDValue();
9291
9292   // If this is a select between two integer constants, try to do some
9293   // optimizations.  Note that the operands are ordered the opposite of SELECT
9294   // operands.
9295   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
9296     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9297       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
9298       // larger than FalseC (the false value).
9299       X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
9300
9301       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
9302         CC = X86::GetOppositeBranchCondition(CC);
9303         std::swap(TrueC, FalseC);
9304       }
9305
9306       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
9307       // This is efficient for any integer data type (including i8/i16) and
9308       // shift amount.
9309       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
9310         SDValue Cond = N->getOperand(3);
9311         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9312                            DAG.getConstant(CC, MVT::i8), Cond);
9313
9314         // Zero extend the condition if needed.
9315         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
9316
9317         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
9318         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
9319                            DAG.getConstant(ShAmt, MVT::i8));
9320         if (N->getNumValues() == 2)  // Dead flag value?
9321           return DCI.CombineTo(N, Cond, SDValue());
9322         return Cond;
9323       }
9324
9325       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
9326       // for any integer data type, including i8/i16.
9327       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
9328         SDValue Cond = N->getOperand(3);
9329         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9330                            DAG.getConstant(CC, MVT::i8), Cond);
9331
9332         // Zero extend the condition if needed.
9333         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
9334                            FalseC->getValueType(0), Cond);
9335         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9336                            SDValue(FalseC, 0));
9337
9338         if (N->getNumValues() == 2)  // Dead flag value?
9339           return DCI.CombineTo(N, Cond, SDValue());
9340         return Cond;
9341       }
9342
9343       // Optimize cases that will turn into an LEA instruction.  This requires
9344       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
9345       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
9346         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
9347         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
9348
9349         bool isFastMultiplier = false;
9350         if (Diff < 10) {
9351           switch ((unsigned char)Diff) {
9352           default: break;
9353           case 1:  // result = add base, cond
9354           case 2:  // result = lea base(    , cond*2)
9355           case 3:  // result = lea base(cond, cond*2)
9356           case 4:  // result = lea base(    , cond*4)
9357           case 5:  // result = lea base(cond, cond*4)
9358           case 8:  // result = lea base(    , cond*8)
9359           case 9:  // result = lea base(cond, cond*8)
9360             isFastMultiplier = true;
9361             break;
9362           }
9363         }
9364
9365         if (isFastMultiplier) {
9366           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
9367           SDValue Cond = N->getOperand(3);
9368           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9369                              DAG.getConstant(CC, MVT::i8), Cond);
9370           // Zero extend the condition if needed.
9371           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
9372                              Cond);
9373           // Scale the condition by the difference.
9374           if (Diff != 1)
9375             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
9376                                DAG.getConstant(Diff, Cond.getValueType()));
9377
9378           // Add the base if non-zero.
9379           if (FalseC->getAPIntValue() != 0)
9380             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9381                                SDValue(FalseC, 0));
9382           if (N->getNumValues() == 2)  // Dead flag value?
9383             return DCI.CombineTo(N, Cond, SDValue());
9384           return Cond;
9385         }
9386       }
9387     }
9388   }
9389   return SDValue();
9390 }
9391
9392
9393 /// PerformMulCombine - Optimize a single multiply with constant into two
9394 /// in order to implement it with two cheaper instructions, e.g.
9395 /// LEA + SHL, LEA + LEA.
9396 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
9397                                  TargetLowering::DAGCombinerInfo &DCI) {
9398   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9399     return SDValue();
9400
9401   EVT VT = N->getValueType(0);
9402   if (VT != MVT::i64)
9403     return SDValue();
9404
9405   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
9406   if (!C)
9407     return SDValue();
9408   uint64_t MulAmt = C->getZExtValue();
9409   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
9410     return SDValue();
9411
9412   uint64_t MulAmt1 = 0;
9413   uint64_t MulAmt2 = 0;
9414   if ((MulAmt % 9) == 0) {
9415     MulAmt1 = 9;
9416     MulAmt2 = MulAmt / 9;
9417   } else if ((MulAmt % 5) == 0) {
9418     MulAmt1 = 5;
9419     MulAmt2 = MulAmt / 5;
9420   } else if ((MulAmt % 3) == 0) {
9421     MulAmt1 = 3;
9422     MulAmt2 = MulAmt / 3;
9423   }
9424   if (MulAmt2 &&
9425       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
9426     DebugLoc DL = N->getDebugLoc();
9427
9428     if (isPowerOf2_64(MulAmt2) &&
9429         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
9430       // If second multiplifer is pow2, issue it first. We want the multiply by
9431       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
9432       // is an add.
9433       std::swap(MulAmt1, MulAmt2);
9434
9435     SDValue NewMul;
9436     if (isPowerOf2_64(MulAmt1))
9437       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
9438                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
9439     else
9440       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
9441                            DAG.getConstant(MulAmt1, VT));
9442
9443     if (isPowerOf2_64(MulAmt2))
9444       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
9445                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
9446     else
9447       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
9448                            DAG.getConstant(MulAmt2, VT));
9449
9450     // Do not add new nodes to DAG combiner worklist.
9451     DCI.CombineTo(N, NewMul, false);
9452   }
9453   return SDValue();
9454 }
9455
9456 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
9457   SDValue N0 = N->getOperand(0);
9458   SDValue N1 = N->getOperand(1);
9459   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
9460   EVT VT = N0.getValueType();
9461
9462   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
9463   // since the result of setcc_c is all zero's or all ones.
9464   if (N1C && N0.getOpcode() == ISD::AND &&
9465       N0.getOperand(1).getOpcode() == ISD::Constant) {
9466     SDValue N00 = N0.getOperand(0);
9467     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
9468         ((N00.getOpcode() == ISD::ANY_EXTEND ||
9469           N00.getOpcode() == ISD::ZERO_EXTEND) &&
9470          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
9471       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
9472       APInt ShAmt = N1C->getAPIntValue();
9473       Mask = Mask.shl(ShAmt);
9474       if (Mask != 0)
9475         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
9476                            N00, DAG.getConstant(Mask, VT));
9477     }
9478   }
9479
9480   return SDValue();
9481 }
9482
9483 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
9484 ///                       when possible.
9485 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
9486                                    const X86Subtarget *Subtarget) {
9487   EVT VT = N->getValueType(0);
9488   if (!VT.isVector() && VT.isInteger() &&
9489       N->getOpcode() == ISD::SHL)
9490     return PerformSHLCombine(N, DAG);
9491
9492   // On X86 with SSE2 support, we can transform this to a vector shift if
9493   // all elements are shifted by the same amount.  We can't do this in legalize
9494   // because the a constant vector is typically transformed to a constant pool
9495   // so we have no knowledge of the shift amount.
9496   if (!Subtarget->hasSSE2())
9497     return SDValue();
9498
9499   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
9500     return SDValue();
9501
9502   SDValue ShAmtOp = N->getOperand(1);
9503   EVT EltVT = VT.getVectorElementType();
9504   DebugLoc DL = N->getDebugLoc();
9505   SDValue BaseShAmt = SDValue();
9506   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
9507     unsigned NumElts = VT.getVectorNumElements();
9508     unsigned i = 0;
9509     for (; i != NumElts; ++i) {
9510       SDValue Arg = ShAmtOp.getOperand(i);
9511       if (Arg.getOpcode() == ISD::UNDEF) continue;
9512       BaseShAmt = Arg;
9513       break;
9514     }
9515     for (; i != NumElts; ++i) {
9516       SDValue Arg = ShAmtOp.getOperand(i);
9517       if (Arg.getOpcode() == ISD::UNDEF) continue;
9518       if (Arg != BaseShAmt) {
9519         return SDValue();
9520       }
9521     }
9522   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
9523              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
9524     SDValue InVec = ShAmtOp.getOperand(0);
9525     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
9526       unsigned NumElts = InVec.getValueType().getVectorNumElements();
9527       unsigned i = 0;
9528       for (; i != NumElts; ++i) {
9529         SDValue Arg = InVec.getOperand(i);
9530         if (Arg.getOpcode() == ISD::UNDEF) continue;
9531         BaseShAmt = Arg;
9532         break;
9533       }
9534     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
9535        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
9536          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
9537          if (C->getZExtValue() == SplatIdx)
9538            BaseShAmt = InVec.getOperand(1);
9539        }
9540     }
9541     if (BaseShAmt.getNode() == 0)
9542       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
9543                               DAG.getIntPtrConstant(0));
9544   } else
9545     return SDValue();
9546
9547   // The shift amount is an i32.
9548   if (EltVT.bitsGT(MVT::i32))
9549     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
9550   else if (EltVT.bitsLT(MVT::i32))
9551     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
9552
9553   // The shift amount is identical so we can do a vector shift.
9554   SDValue  ValOp = N->getOperand(0);
9555   switch (N->getOpcode()) {
9556   default:
9557     llvm_unreachable("Unknown shift opcode!");
9558     break;
9559   case ISD::SHL:
9560     if (VT == MVT::v2i64)
9561       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9562                          DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9563                          ValOp, BaseShAmt);
9564     if (VT == MVT::v4i32)
9565       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9566                          DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
9567                          ValOp, BaseShAmt);
9568     if (VT == MVT::v8i16)
9569       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9570                          DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
9571                          ValOp, BaseShAmt);
9572     break;
9573   case ISD::SRA:
9574     if (VT == MVT::v4i32)
9575       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9576                          DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
9577                          ValOp, BaseShAmt);
9578     if (VT == MVT::v8i16)
9579       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9580                          DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
9581                          ValOp, BaseShAmt);
9582     break;
9583   case ISD::SRL:
9584     if (VT == MVT::v2i64)
9585       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9586                          DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9587                          ValOp, BaseShAmt);
9588     if (VT == MVT::v4i32)
9589       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9590                          DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
9591                          ValOp, BaseShAmt);
9592     if (VT ==  MVT::v8i16)
9593       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9594                          DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
9595                          ValOp, BaseShAmt);
9596     break;
9597   }
9598   return SDValue();
9599 }
9600
9601 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
9602                                 TargetLowering::DAGCombinerInfo &DCI,
9603                                 const X86Subtarget *Subtarget) {
9604   if (DCI.isBeforeLegalizeOps())
9605     return SDValue();
9606
9607   EVT VT = N->getValueType(0);
9608   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
9609     return SDValue();
9610
9611   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
9612   SDValue N0 = N->getOperand(0);
9613   SDValue N1 = N->getOperand(1);
9614   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
9615     std::swap(N0, N1);
9616   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
9617     return SDValue();
9618   if (!N0.hasOneUse() || !N1.hasOneUse())
9619     return SDValue();
9620
9621   SDValue ShAmt0 = N0.getOperand(1);
9622   if (ShAmt0.getValueType() != MVT::i8)
9623     return SDValue();
9624   SDValue ShAmt1 = N1.getOperand(1);
9625   if (ShAmt1.getValueType() != MVT::i8)
9626     return SDValue();
9627   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
9628     ShAmt0 = ShAmt0.getOperand(0);
9629   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
9630     ShAmt1 = ShAmt1.getOperand(0);
9631
9632   DebugLoc DL = N->getDebugLoc();
9633   unsigned Opc = X86ISD::SHLD;
9634   SDValue Op0 = N0.getOperand(0);
9635   SDValue Op1 = N1.getOperand(0);
9636   if (ShAmt0.getOpcode() == ISD::SUB) {
9637     Opc = X86ISD::SHRD;
9638     std::swap(Op0, Op1);
9639     std::swap(ShAmt0, ShAmt1);
9640   }
9641
9642   unsigned Bits = VT.getSizeInBits();
9643   if (ShAmt1.getOpcode() == ISD::SUB) {
9644     SDValue Sum = ShAmt1.getOperand(0);
9645     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
9646       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
9647       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
9648         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
9649       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
9650         return DAG.getNode(Opc, DL, VT,
9651                            Op0, Op1,
9652                            DAG.getNode(ISD::TRUNCATE, DL,
9653                                        MVT::i8, ShAmt0));
9654     }
9655   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
9656     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
9657     if (ShAmt0C &&
9658         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
9659       return DAG.getNode(Opc, DL, VT,
9660                          N0.getOperand(0), N1.getOperand(0),
9661                          DAG.getNode(ISD::TRUNCATE, DL,
9662                                        MVT::i8, ShAmt0));
9663   }
9664
9665   return SDValue();
9666 }
9667
9668 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
9669 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
9670                                    const X86Subtarget *Subtarget) {
9671   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
9672   // the FP state in cases where an emms may be missing.
9673   // A preferable solution to the general problem is to figure out the right
9674   // places to insert EMMS.  This qualifies as a quick hack.
9675
9676   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
9677   StoreSDNode *St = cast<StoreSDNode>(N);
9678   EVT VT = St->getValue().getValueType();
9679   if (VT.getSizeInBits() != 64)
9680     return SDValue();
9681
9682   const Function *F = DAG.getMachineFunction().getFunction();
9683   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
9684   bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
9685     && Subtarget->hasSSE2();
9686   if ((VT.isVector() ||
9687        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
9688       isa<LoadSDNode>(St->getValue()) &&
9689       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
9690       St->getChain().hasOneUse() && !St->isVolatile()) {
9691     SDNode* LdVal = St->getValue().getNode();
9692     LoadSDNode *Ld = 0;
9693     int TokenFactorIndex = -1;
9694     SmallVector<SDValue, 8> Ops;
9695     SDNode* ChainVal = St->getChain().getNode();
9696     // Must be a store of a load.  We currently handle two cases:  the load
9697     // is a direct child, and it's under an intervening TokenFactor.  It is
9698     // possible to dig deeper under nested TokenFactors.
9699     if (ChainVal == LdVal)
9700       Ld = cast<LoadSDNode>(St->getChain());
9701     else if (St->getValue().hasOneUse() &&
9702              ChainVal->getOpcode() == ISD::TokenFactor) {
9703       for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
9704         if (ChainVal->getOperand(i).getNode() == LdVal) {
9705           TokenFactorIndex = i;
9706           Ld = cast<LoadSDNode>(St->getValue());
9707         } else
9708           Ops.push_back(ChainVal->getOperand(i));
9709       }
9710     }
9711
9712     if (!Ld || !ISD::isNormalLoad(Ld))
9713       return SDValue();
9714
9715     // If this is not the MMX case, i.e. we are just turning i64 load/store
9716     // into f64 load/store, avoid the transformation if there are multiple
9717     // uses of the loaded value.
9718     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
9719       return SDValue();
9720
9721     DebugLoc LdDL = Ld->getDebugLoc();
9722     DebugLoc StDL = N->getDebugLoc();
9723     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
9724     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
9725     // pair instead.
9726     if (Subtarget->is64Bit() || F64IsLegal) {
9727       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
9728       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(),
9729                                   Ld->getBasePtr(), Ld->getSrcValue(),
9730                                   Ld->getSrcValueOffset(), Ld->isVolatile(),
9731                                   Ld->isNonTemporal(), Ld->getAlignment());
9732       SDValue NewChain = NewLd.getValue(1);
9733       if (TokenFactorIndex != -1) {
9734         Ops.push_back(NewChain);
9735         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
9736                                Ops.size());
9737       }
9738       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
9739                           St->getSrcValue(), St->getSrcValueOffset(),
9740                           St->isVolatile(), St->isNonTemporal(),
9741                           St->getAlignment());
9742     }
9743
9744     // Otherwise, lower to two pairs of 32-bit loads / stores.
9745     SDValue LoAddr = Ld->getBasePtr();
9746     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
9747                                  DAG.getConstant(4, MVT::i32));
9748
9749     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
9750                                Ld->getSrcValue(), Ld->getSrcValueOffset(),
9751                                Ld->isVolatile(), Ld->isNonTemporal(),
9752                                Ld->getAlignment());
9753     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
9754                                Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
9755                                Ld->isVolatile(), Ld->isNonTemporal(),
9756                                MinAlign(Ld->getAlignment(), 4));
9757
9758     SDValue NewChain = LoLd.getValue(1);
9759     if (TokenFactorIndex != -1) {
9760       Ops.push_back(LoLd);
9761       Ops.push_back(HiLd);
9762       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
9763                              Ops.size());
9764     }
9765
9766     LoAddr = St->getBasePtr();
9767     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
9768                          DAG.getConstant(4, MVT::i32));
9769
9770     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
9771                                 St->getSrcValue(), St->getSrcValueOffset(),
9772                                 St->isVolatile(), St->isNonTemporal(),
9773                                 St->getAlignment());
9774     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
9775                                 St->getSrcValue(),
9776                                 St->getSrcValueOffset() + 4,
9777                                 St->isVolatile(),
9778                                 St->isNonTemporal(),
9779                                 MinAlign(St->getAlignment(), 4));
9780     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
9781   }
9782   return SDValue();
9783 }
9784
9785 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
9786 /// X86ISD::FXOR nodes.
9787 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
9788   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
9789   // F[X]OR(0.0, x) -> x
9790   // F[X]OR(x, 0.0) -> x
9791   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
9792     if (C->getValueAPF().isPosZero())
9793       return N->getOperand(1);
9794   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
9795     if (C->getValueAPF().isPosZero())
9796       return N->getOperand(0);
9797   return SDValue();
9798 }
9799
9800 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
9801 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
9802   // FAND(0.0, x) -> 0.0
9803   // FAND(x, 0.0) -> 0.0
9804   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
9805     if (C->getValueAPF().isPosZero())
9806       return N->getOperand(0);
9807   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
9808     if (C->getValueAPF().isPosZero())
9809       return N->getOperand(1);
9810   return SDValue();
9811 }
9812
9813 static SDValue PerformBTCombine(SDNode *N,
9814                                 SelectionDAG &DAG,
9815                                 TargetLowering::DAGCombinerInfo &DCI) {
9816   // BT ignores high bits in the bit index operand.
9817   SDValue Op1 = N->getOperand(1);
9818   if (Op1.hasOneUse()) {
9819     unsigned BitWidth = Op1.getValueSizeInBits();
9820     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
9821     APInt KnownZero, KnownOne;
9822     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
9823                                           !DCI.isBeforeLegalizeOps());
9824     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9825     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
9826         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
9827       DCI.CommitTargetLoweringOpt(TLO);
9828   }
9829   return SDValue();
9830 }
9831
9832 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
9833   SDValue Op = N->getOperand(0);
9834   if (Op.getOpcode() == ISD::BIT_CONVERT)
9835     Op = Op.getOperand(0);
9836   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
9837   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
9838       VT.getVectorElementType().getSizeInBits() ==
9839       OpVT.getVectorElementType().getSizeInBits()) {
9840     return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT, Op);
9841   }
9842   return SDValue();
9843 }
9844
9845 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
9846   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
9847   //           (and (i32 x86isd::setcc_carry), 1)
9848   // This eliminates the zext. This transformation is necessary because
9849   // ISD::SETCC is always legalized to i8.
9850   DebugLoc dl = N->getDebugLoc();
9851   SDValue N0 = N->getOperand(0);
9852   EVT VT = N->getValueType(0);
9853   if (N0.getOpcode() == ISD::AND &&
9854       N0.hasOneUse() &&
9855       N0.getOperand(0).hasOneUse()) {
9856     SDValue N00 = N0.getOperand(0);
9857     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
9858       return SDValue();
9859     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
9860     if (!C || C->getZExtValue() != 1)
9861       return SDValue();
9862     return DAG.getNode(ISD::AND, dl, VT,
9863                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
9864                                    N00.getOperand(0), N00.getOperand(1)),
9865                        DAG.getConstant(1, VT));
9866   }
9867
9868   return SDValue();
9869 }
9870
9871 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
9872                                              DAGCombinerInfo &DCI) const {
9873   SelectionDAG &DAG = DCI.DAG;
9874   switch (N->getOpcode()) {
9875   default: break;
9876   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
9877   case ISD::EXTRACT_VECTOR_ELT:
9878                         return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
9879   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
9880   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
9881   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
9882   case ISD::SHL:
9883   case ISD::SRA:
9884   case ISD::SRL:            return PerformShiftCombine(N, DAG, Subtarget);
9885   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
9886   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
9887   case X86ISD::FXOR:
9888   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
9889   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
9890   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
9891   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
9892   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG);
9893   }
9894
9895   return SDValue();
9896 }
9897
9898 /// isTypeDesirableForOp - Return true if the target has native support for
9899 /// the specified value type and it is 'desirable' to use the type for the
9900 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
9901 /// instruction encodings are longer and some i16 instructions are slow.
9902 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
9903   if (!isTypeLegal(VT))
9904     return false;
9905   if (VT != MVT::i16)
9906     return true;
9907
9908   switch (Opc) {
9909   default:
9910     return true;
9911   case ISD::LOAD:
9912   case ISD::SIGN_EXTEND:
9913   case ISD::ZERO_EXTEND:
9914   case ISD::ANY_EXTEND:
9915   case ISD::SHL:
9916   case ISD::SRL:
9917   case ISD::SUB:
9918   case ISD::ADD:
9919   case ISD::MUL:
9920   case ISD::AND:
9921   case ISD::OR:
9922   case ISD::XOR:
9923     return false;
9924   }
9925 }
9926
9927 static bool MayFoldLoad(SDValue Op) {
9928   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
9929 }
9930
9931 static bool MayFoldIntoStore(SDValue Op) {
9932   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
9933 }
9934
9935 /// IsDesirableToPromoteOp - This method query the target whether it is
9936 /// beneficial for dag combiner to promote the specified node. If true, it
9937 /// should return the desired promotion type by reference.
9938 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
9939   EVT VT = Op.getValueType();
9940   if (VT != MVT::i16)
9941     return false;
9942
9943   bool Promote = false;
9944   bool Commute = false;
9945   switch (Op.getOpcode()) {
9946   default: break;
9947   case ISD::LOAD: {
9948     LoadSDNode *LD = cast<LoadSDNode>(Op);
9949     // If the non-extending load has a single use and it's not live out, then it
9950     // might be folded.
9951     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
9952                                                      Op.hasOneUse()*/) {
9953       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9954              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
9955         // The only case where we'd want to promote LOAD (rather then it being
9956         // promoted as an operand is when it's only use is liveout.
9957         if (UI->getOpcode() != ISD::CopyToReg)
9958           return false;
9959       }
9960     }
9961     Promote = true;
9962     break;
9963   }
9964   case ISD::SIGN_EXTEND:
9965   case ISD::ZERO_EXTEND:
9966   case ISD::ANY_EXTEND:
9967     Promote = true;
9968     break;
9969   case ISD::SHL:
9970   case ISD::SRL: {
9971     SDValue N0 = Op.getOperand(0);
9972     // Look out for (store (shl (load), x)).
9973     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
9974       return false;
9975     Promote = true;
9976     break;
9977   }
9978   case ISD::ADD:
9979   case ISD::MUL:
9980   case ISD::AND:
9981   case ISD::OR:
9982   case ISD::XOR:
9983     Commute = true;
9984     // fallthrough
9985   case ISD::SUB: {
9986     SDValue N0 = Op.getOperand(0);
9987     SDValue N1 = Op.getOperand(1);
9988     if (!Commute && MayFoldLoad(N1))
9989       return false;
9990     // Avoid disabling potential load folding opportunities.
9991     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
9992       return false;
9993     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
9994       return false;
9995     Promote = true;
9996   }
9997   }
9998
9999   PVT = MVT::i32;
10000   return Promote;
10001 }
10002
10003 //===----------------------------------------------------------------------===//
10004 //                           X86 Inline Assembly Support
10005 //===----------------------------------------------------------------------===//
10006
10007 static bool LowerToBSwap(CallInst *CI) {
10008   // FIXME: this should verify that we are targetting a 486 or better.  If not,
10009   // we will turn this bswap into something that will be lowered to logical ops
10010   // instead of emitting the bswap asm.  For now, we don't support 486 or lower
10011   // so don't worry about this.
10012
10013   // Verify this is a simple bswap.
10014   if (CI->getNumArgOperands() != 1 ||
10015       CI->getType() != CI->getArgOperand(0)->getType() ||
10016       !CI->getType()->isIntegerTy())
10017     return false;
10018
10019   const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10020   if (!Ty || Ty->getBitWidth() % 16 != 0)
10021     return false;
10022
10023   // Okay, we can do this xform, do so now.
10024   const Type *Tys[] = { Ty };
10025   Module *M = CI->getParent()->getParent()->getParent();
10026   Constant *Int = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
10027
10028   Value *Op = CI->getArgOperand(0);
10029   Op = CallInst::Create(Int, Op, CI->getName(), CI);
10030
10031   CI->replaceAllUsesWith(Op);
10032   CI->eraseFromParent();
10033   return true;
10034 }
10035
10036 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
10037   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10038   std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
10039
10040   std::string AsmStr = IA->getAsmString();
10041
10042   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
10043   SmallVector<StringRef, 4> AsmPieces;
10044   SplitString(AsmStr, AsmPieces, "\n");  // ; as separator?
10045
10046   switch (AsmPieces.size()) {
10047   default: return false;
10048   case 1:
10049     AsmStr = AsmPieces[0];
10050     AsmPieces.clear();
10051     SplitString(AsmStr, AsmPieces, " \t");  // Split with whitespace.
10052
10053     // bswap $0
10054     if (AsmPieces.size() == 2 &&
10055         (AsmPieces[0] == "bswap" ||
10056          AsmPieces[0] == "bswapq" ||
10057          AsmPieces[0] == "bswapl") &&
10058         (AsmPieces[1] == "$0" ||
10059          AsmPieces[1] == "${0:q}")) {
10060       // No need to check constraints, nothing other than the equivalent of
10061       // "=r,0" would be valid here.
10062       return LowerToBSwap(CI);
10063     }
10064     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
10065     if (CI->getType()->isIntegerTy(16) &&
10066         AsmPieces.size() == 3 &&
10067         (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
10068         AsmPieces[1] == "$$8," &&
10069         AsmPieces[2] == "${0:w}" &&
10070         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
10071       AsmPieces.clear();
10072       const std::string &Constraints = IA->getConstraintString();
10073       SplitString(StringRef(Constraints).substr(5), AsmPieces, ",");
10074       std::sort(AsmPieces.begin(), AsmPieces.end());
10075       if (AsmPieces.size() == 4 &&
10076           AsmPieces[0] == "~{cc}" &&
10077           AsmPieces[1] == "~{dirflag}" &&
10078           AsmPieces[2] == "~{flags}" &&
10079           AsmPieces[3] == "~{fpsr}") {
10080         return LowerToBSwap(CI);
10081       }
10082     }
10083     break;
10084   case 3:
10085     if (CI->getType()->isIntegerTy(64) &&
10086         Constraints.size() >= 2 &&
10087         Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
10088         Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
10089       // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
10090       SmallVector<StringRef, 4> Words;
10091       SplitString(AsmPieces[0], Words, " \t");
10092       if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
10093         Words.clear();
10094         SplitString(AsmPieces[1], Words, " \t");
10095         if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
10096           Words.clear();
10097           SplitString(AsmPieces[2], Words, " \t,");
10098           if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
10099               Words[2] == "%edx") {
10100             return LowerToBSwap(CI);
10101           }
10102         }
10103       }
10104     }
10105     break;
10106   }
10107   return false;
10108 }
10109
10110
10111
10112 /// getConstraintType - Given a constraint letter, return the type of
10113 /// constraint it is for this target.
10114 X86TargetLowering::ConstraintType
10115 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
10116   if (Constraint.size() == 1) {
10117     switch (Constraint[0]) {
10118     case 'A':
10119       return C_Register;
10120     case 'f':
10121     case 'r':
10122     case 'R':
10123     case 'l':
10124     case 'q':
10125     case 'Q':
10126     case 'x':
10127     case 'y':
10128     case 'Y':
10129       return C_RegisterClass;
10130     case 'e':
10131     case 'Z':
10132       return C_Other;
10133     default:
10134       break;
10135     }
10136   }
10137   return TargetLowering::getConstraintType(Constraint);
10138 }
10139
10140 /// LowerXConstraint - try to replace an X constraint, which matches anything,
10141 /// with another that has more specific requirements based on the type of the
10142 /// corresponding operand.
10143 const char *X86TargetLowering::
10144 LowerXConstraint(EVT ConstraintVT) const {
10145   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
10146   // 'f' like normal targets.
10147   if (ConstraintVT.isFloatingPoint()) {
10148     if (Subtarget->hasSSE2())
10149       return "Y";
10150     if (Subtarget->hasSSE1())
10151       return "x";
10152   }
10153
10154   return TargetLowering::LowerXConstraint(ConstraintVT);
10155 }
10156
10157 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10158 /// vector.  If it is invalid, don't add anything to Ops.
10159 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10160                                                      char Constraint,
10161                                                      std::vector<SDValue>&Ops,
10162                                                      SelectionDAG &DAG) const {
10163   SDValue Result(0, 0);
10164
10165   switch (Constraint) {
10166   default: break;
10167   case 'I':
10168     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10169       if (C->getZExtValue() <= 31) {
10170         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10171         break;
10172       }
10173     }
10174     return;
10175   case 'J':
10176     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10177       if (C->getZExtValue() <= 63) {
10178         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10179         break;
10180       }
10181     }
10182     return;
10183   case 'K':
10184     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10185       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
10186         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10187         break;
10188       }
10189     }
10190     return;
10191   case 'N':
10192     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10193       if (C->getZExtValue() <= 255) {
10194         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10195         break;
10196       }
10197     }
10198     return;
10199   case 'e': {
10200     // 32-bit signed value
10201     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10202       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
10203                                            C->getSExtValue())) {
10204         // Widen to 64 bits here to get it sign extended.
10205         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
10206         break;
10207       }
10208     // FIXME gcc accepts some relocatable values here too, but only in certain
10209     // memory models; it's complicated.
10210     }
10211     return;
10212   }
10213   case 'Z': {
10214     // 32-bit unsigned value
10215     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10216       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
10217                                            C->getZExtValue())) {
10218         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10219         break;
10220       }
10221     }
10222     // FIXME gcc accepts some relocatable values here too, but only in certain
10223     // memory models; it's complicated.
10224     return;
10225   }
10226   case 'i': {
10227     // Literal immediates are always ok.
10228     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
10229       // Widen to 64 bits here to get it sign extended.
10230       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
10231       break;
10232     }
10233
10234     // In any sort of PIC mode addresses need to be computed at runtime by
10235     // adding in a register or some sort of table lookup.  These can't
10236     // be used as immediates.
10237     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC() ||
10238         Subtarget->isPICStyleRIPRel())
10239       return;
10240
10241     // If we are in non-pic codegen mode, we allow the address of a global (with
10242     // an optional displacement) to be used with 'i'.
10243     GlobalAddressSDNode *GA = 0;
10244     int64_t Offset = 0;
10245
10246     // Match either (GA), (GA+C), (GA+C1+C2), etc.
10247     while (1) {
10248       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
10249         Offset += GA->getOffset();
10250         break;
10251       } else if (Op.getOpcode() == ISD::ADD) {
10252         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
10253           Offset += C->getZExtValue();
10254           Op = Op.getOperand(0);
10255           continue;
10256         }
10257       } else if (Op.getOpcode() == ISD::SUB) {
10258         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
10259           Offset += -C->getZExtValue();
10260           Op = Op.getOperand(0);
10261           continue;
10262         }
10263       }
10264
10265       // Otherwise, this isn't something we can handle, reject it.
10266       return;
10267     }
10268
10269     const GlobalValue *GV = GA->getGlobal();
10270     // If we require an extra load to get this address, as in PIC mode, we
10271     // can't accept it.
10272     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
10273                                                         getTargetMachine())))
10274       return;
10275
10276     Result = DAG.getTargetGlobalAddress(GV, GA->getValueType(0), Offset);
10277     break;
10278   }
10279   }
10280
10281   if (Result.getNode()) {
10282     Ops.push_back(Result);
10283     return;
10284   }
10285   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10286 }
10287
10288 std::vector<unsigned> X86TargetLowering::
10289 getRegClassForInlineAsmConstraint(const std::string &Constraint,
10290                                   EVT VT) const {
10291   if (Constraint.size() == 1) {
10292     // FIXME: not handling fp-stack yet!
10293     switch (Constraint[0]) {      // GCC X86 Constraint Letters
10294     default: break;  // Unknown constraint letter
10295     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
10296       if (Subtarget->is64Bit()) {
10297         if (VT == MVT::i32)
10298           return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
10299                                        X86::ESI, X86::EDI, X86::R8D, X86::R9D,
10300                                        X86::R10D,X86::R11D,X86::R12D,
10301                                        X86::R13D,X86::R14D,X86::R15D,
10302                                        X86::EBP, X86::ESP, 0);
10303         else if (VT == MVT::i16)
10304           return make_vector<unsigned>(X86::AX,  X86::DX,  X86::CX, X86::BX,
10305                                        X86::SI,  X86::DI,  X86::R8W,X86::R9W,
10306                                        X86::R10W,X86::R11W,X86::R12W,
10307                                        X86::R13W,X86::R14W,X86::R15W,
10308                                        X86::BP,  X86::SP, 0);
10309         else if (VT == MVT::i8)
10310           return make_vector<unsigned>(X86::AL,  X86::DL,  X86::CL, X86::BL,
10311                                        X86::SIL, X86::DIL, X86::R8B,X86::R9B,
10312                                        X86::R10B,X86::R11B,X86::R12B,
10313                                        X86::R13B,X86::R14B,X86::R15B,
10314                                        X86::BPL, X86::SPL, 0);
10315
10316         else if (VT == MVT::i64)
10317           return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
10318                                        X86::RSI, X86::RDI, X86::R8,  X86::R9,
10319                                        X86::R10, X86::R11, X86::R12,
10320                                        X86::R13, X86::R14, X86::R15,
10321                                        X86::RBP, X86::RSP, 0);
10322
10323         break;
10324       }
10325       // 32-bit fallthrough
10326     case 'Q':   // Q_REGS
10327       if (VT == MVT::i32)
10328         return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
10329       else if (VT == MVT::i16)
10330         return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
10331       else if (VT == MVT::i8)
10332         return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
10333       else if (VT == MVT::i64)
10334         return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
10335       break;
10336     }
10337   }
10338
10339   return std::vector<unsigned>();
10340 }
10341
10342 std::pair<unsigned, const TargetRegisterClass*>
10343 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10344                                                 EVT VT) const {
10345   // First, see if this is a constraint that directly corresponds to an LLVM
10346   // register class.
10347   if (Constraint.size() == 1) {
10348     // GCC Constraint Letters
10349     switch (Constraint[0]) {
10350     default: break;
10351     case 'r':   // GENERAL_REGS
10352     case 'l':   // INDEX_REGS
10353       if (VT == MVT::i8)
10354         return std::make_pair(0U, X86::GR8RegisterClass);
10355       if (VT == MVT::i16)
10356         return std::make_pair(0U, X86::GR16RegisterClass);
10357       if (VT == MVT::i32 || !Subtarget->is64Bit())
10358         return std::make_pair(0U, X86::GR32RegisterClass);
10359       return std::make_pair(0U, X86::GR64RegisterClass);
10360     case 'R':   // LEGACY_REGS
10361       if (VT == MVT::i8)
10362         return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
10363       if (VT == MVT::i16)
10364         return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
10365       if (VT == MVT::i32 || !Subtarget->is64Bit())
10366         return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
10367       return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
10368     case 'f':  // FP Stack registers.
10369       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
10370       // value to the correct fpstack register class.
10371       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
10372         return std::make_pair(0U, X86::RFP32RegisterClass);
10373       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
10374         return std::make_pair(0U, X86::RFP64RegisterClass);
10375       return std::make_pair(0U, X86::RFP80RegisterClass);
10376     case 'y':   // MMX_REGS if MMX allowed.
10377       if (!Subtarget->hasMMX()) break;
10378       return std::make_pair(0U, X86::VR64RegisterClass);
10379     case 'Y':   // SSE_REGS if SSE2 allowed
10380       if (!Subtarget->hasSSE2()) break;
10381       // FALL THROUGH.
10382     case 'x':   // SSE_REGS if SSE1 allowed
10383       if (!Subtarget->hasSSE1()) break;
10384
10385       switch (VT.getSimpleVT().SimpleTy) {
10386       default: break;
10387       // Scalar SSE types.
10388       case MVT::f32:
10389       case MVT::i32:
10390         return std::make_pair(0U, X86::FR32RegisterClass);
10391       case MVT::f64:
10392       case MVT::i64:
10393         return std::make_pair(0U, X86::FR64RegisterClass);
10394       // Vector types.
10395       case MVT::v16i8:
10396       case MVT::v8i16:
10397       case MVT::v4i32:
10398       case MVT::v2i64:
10399       case MVT::v4f32:
10400       case MVT::v2f64:
10401         return std::make_pair(0U, X86::VR128RegisterClass);
10402       }
10403       break;
10404     }
10405   }
10406
10407   // Use the default implementation in TargetLowering to convert the register
10408   // constraint into a member of a register class.
10409   std::pair<unsigned, const TargetRegisterClass*> Res;
10410   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10411
10412   // Not found as a standard register?
10413   if (Res.second == 0) {
10414     // Map st(0) -> st(7) -> ST0
10415     if (Constraint.size() == 7 && Constraint[0] == '{' &&
10416         tolower(Constraint[1]) == 's' &&
10417         tolower(Constraint[2]) == 't' &&
10418         Constraint[3] == '(' &&
10419         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
10420         Constraint[5] == ')' &&
10421         Constraint[6] == '}') {
10422
10423       Res.first = X86::ST0+Constraint[4]-'0';
10424       Res.second = X86::RFP80RegisterClass;
10425       return Res;
10426     }
10427
10428     // GCC allows "st(0)" to be called just plain "st".
10429     if (StringRef("{st}").equals_lower(Constraint)) {
10430       Res.first = X86::ST0;
10431       Res.second = X86::RFP80RegisterClass;
10432       return Res;
10433     }
10434
10435     // flags -> EFLAGS
10436     if (StringRef("{flags}").equals_lower(Constraint)) {
10437       Res.first = X86::EFLAGS;
10438       Res.second = X86::CCRRegisterClass;
10439       return Res;
10440     }
10441
10442     // 'A' means EAX + EDX.
10443     if (Constraint == "A") {
10444       Res.first = X86::EAX;
10445       Res.second = X86::GR32_ADRegisterClass;
10446       return Res;
10447     }
10448     return Res;
10449   }
10450
10451   // Otherwise, check to see if this is a register class of the wrong value
10452   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
10453   // turn into {ax},{dx}.
10454   if (Res.second->hasType(VT))
10455     return Res;   // Correct type already, nothing to do.
10456
10457   // All of the single-register GCC register classes map their values onto
10458   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
10459   // really want an 8-bit or 32-bit register, map to the appropriate register
10460   // class and return the appropriate register.
10461   if (Res.second == X86::GR16RegisterClass) {
10462     if (VT == MVT::i8) {
10463       unsigned DestReg = 0;
10464       switch (Res.first) {
10465       default: break;
10466       case X86::AX: DestReg = X86::AL; break;
10467       case X86::DX: DestReg = X86::DL; break;
10468       case X86::CX: DestReg = X86::CL; break;
10469       case X86::BX: DestReg = X86::BL; break;
10470       }
10471       if (DestReg) {
10472         Res.first = DestReg;
10473         Res.second = X86::GR8RegisterClass;
10474       }
10475     } else if (VT == MVT::i32) {
10476       unsigned DestReg = 0;
10477       switch (Res.first) {
10478       default: break;
10479       case X86::AX: DestReg = X86::EAX; break;
10480       case X86::DX: DestReg = X86::EDX; break;
10481       case X86::CX: DestReg = X86::ECX; break;
10482       case X86::BX: DestReg = X86::EBX; break;
10483       case X86::SI: DestReg = X86::ESI; break;
10484       case X86::DI: DestReg = X86::EDI; break;
10485       case X86::BP: DestReg = X86::EBP; break;
10486       case X86::SP: DestReg = X86::ESP; break;
10487       }
10488       if (DestReg) {
10489         Res.first = DestReg;
10490         Res.second = X86::GR32RegisterClass;
10491       }
10492     } else if (VT == MVT::i64) {
10493       unsigned DestReg = 0;
10494       switch (Res.first) {
10495       default: break;
10496       case X86::AX: DestReg = X86::RAX; break;
10497       case X86::DX: DestReg = X86::RDX; break;
10498       case X86::CX: DestReg = X86::RCX; break;
10499       case X86::BX: DestReg = X86::RBX; break;
10500       case X86::SI: DestReg = X86::RSI; break;
10501       case X86::DI: DestReg = X86::RDI; break;
10502       case X86::BP: DestReg = X86::RBP; break;
10503       case X86::SP: DestReg = X86::RSP; break;
10504       }
10505       if (DestReg) {
10506         Res.first = DestReg;
10507         Res.second = X86::GR64RegisterClass;
10508       }
10509     }
10510   } else if (Res.second == X86::FR32RegisterClass ||
10511              Res.second == X86::FR64RegisterClass ||
10512              Res.second == X86::VR128RegisterClass) {
10513     // Handle references to XMM physical registers that got mapped into the
10514     // wrong class.  This can happen with constraints like {xmm0} where the
10515     // target independent register mapper will just pick the first match it can
10516     // find, ignoring the required type.
10517     if (VT == MVT::f32)
10518       Res.second = X86::FR32RegisterClass;
10519     else if (VT == MVT::f64)
10520       Res.second = X86::FR64RegisterClass;
10521     else if (X86::VR128RegisterClass->hasType(VT))
10522       Res.second = X86::VR128RegisterClass;
10523   }
10524
10525   return Res;
10526 }