b67c625287b1a27ff73bd7449252dc3ed5d6d4f0
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "X86.h"
16 #include "X86InstrBuilder.h"
17 #include "X86ISelLowering.h"
18 #include "X86MachineFunctionInfo.h"
19 #include "X86TargetMachine.h"
20 #include "llvm/CallingConv.h"
21 #include "llvm/Constants.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/GlobalVariable.h"
24 #include "llvm/Function.h"
25 #include "llvm/Intrinsics.h"
26 #include "llvm/ADT/BitVector.h"
27 #include "llvm/ADT/VectorExtras.h"
28 #include "llvm/CodeGen/CallingConvLower.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/CodeGen/PseudoSourceValue.h"
35 #include "llvm/CodeGen/SelectionDAG.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Target/TargetOptions.h"
39 #include "llvm/ADT/SmallSet.h"
40 #include "llvm/ADT/StringExtras.h"
41 using namespace llvm;
42
43 // Forward declarations.
44 static SDValue getMOVLMask(unsigned NumElems, SelectionDAG &DAG);
45
46 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
47   : TargetLowering(TM) {
48   Subtarget = &TM.getSubtarget<X86Subtarget>();
49   X86ScalarSSEf64 = Subtarget->hasSSE2();
50   X86ScalarSSEf32 = Subtarget->hasSSE1();
51   X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
52   
53   bool Fast = false;
54
55   RegInfo = TM.getRegisterInfo();
56
57   // Set up the TargetLowering object.
58
59   // X86 is weird, it always uses i8 for shift amounts and setcc results.
60   setShiftAmountType(MVT::i8);
61   setSetCCResultContents(ZeroOrOneSetCCResult);
62   setSchedulingPreference(SchedulingForRegPressure);
63   setShiftAmountFlavor(Mask);   // shl X, 32 == shl X, 0
64   setStackPointerRegisterToSaveRestore(X86StackPtr);
65
66   if (Subtarget->isTargetDarwin()) {
67     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
68     setUseUnderscoreSetJmp(false);
69     setUseUnderscoreLongJmp(false);
70   } else if (Subtarget->isTargetMingw()) {
71     // MS runtime is weird: it exports _setjmp, but longjmp!
72     setUseUnderscoreSetJmp(true);
73     setUseUnderscoreLongJmp(false);
74   } else {
75     setUseUnderscoreSetJmp(true);
76     setUseUnderscoreLongJmp(true);
77   }
78   
79   // Set up the register classes.
80   addRegisterClass(MVT::i8, X86::GR8RegisterClass);
81   addRegisterClass(MVT::i16, X86::GR16RegisterClass);
82   addRegisterClass(MVT::i32, X86::GR32RegisterClass);
83   if (Subtarget->is64Bit())
84     addRegisterClass(MVT::i64, X86::GR64RegisterClass);
85
86   setLoadXAction(ISD::SEXTLOAD, MVT::i1, Promote);
87
88   // We don't accept any truncstore of integer registers.  
89   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
90   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
91   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
92   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
93   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
94   setTruncStoreAction(MVT::i16, MVT::i8, Expand);
95
96   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
97   // operation.
98   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
99   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
100   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
101
102   if (Subtarget->is64Bit()) {
103     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Expand);
104     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
105   } else {
106     if (X86ScalarSSEf64)
107       // If SSE i64 SINT_TO_FP is not available, expand i32 UINT_TO_FP.
108       setOperationAction(ISD::UINT_TO_FP   , MVT::i32  , Expand);
109     else
110       setOperationAction(ISD::UINT_TO_FP   , MVT::i32  , Promote);
111   }
112
113   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
114   // this operation.
115   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
116   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
117   // SSE has no i16 to fp conversion, only i32
118   if (X86ScalarSSEf32) {
119     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
120     // f32 and f64 cases are Legal, f80 case is not
121     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
122   } else {
123     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
124     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
125   }
126
127   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
128   // are Legal, f80 is custom lowered.
129   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
130   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
131
132   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
133   // this operation.
134   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
135   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
136
137   if (X86ScalarSSEf32) {
138     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
139     // f32 and f64 cases are Legal, f80 case is not
140     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
141   } else {
142     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
143     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
144   }
145
146   // Handle FP_TO_UINT by promoting the destination to a larger signed
147   // conversion.
148   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
149   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
150   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
151
152   if (Subtarget->is64Bit()) {
153     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
154     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
155   } else {
156     if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
157       // Expand FP_TO_UINT into a select.
158       // FIXME: We would like to use a Custom expander here eventually to do
159       // the optimal thing for SSE vs. the default expansion in the legalizer.
160       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
161     else
162       // With SSE3 we can use fisttpll to convert to a signed i64.
163       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Promote);
164   }
165
166   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
167   if (!X86ScalarSSEf64) {
168     setOperationAction(ISD::BIT_CONVERT      , MVT::f32  , Expand);
169     setOperationAction(ISD::BIT_CONVERT      , MVT::i32  , Expand);
170   }
171
172   // Scalar integer divide and remainder are lowered to use operations that
173   // produce two results, to match the available instructions. This exposes
174   // the two-result form to trivial CSE, which is able to combine x/y and x%y
175   // into a single instruction.
176   //
177   // Scalar integer multiply-high is also lowered to use two-result
178   // operations, to match the available instructions. However, plain multiply
179   // (low) operations are left as Legal, as there are single-result
180   // instructions for this in x86. Using the two-result multiply instructions
181   // when both high and low results are needed must be arranged by dagcombine.
182   setOperationAction(ISD::MULHS           , MVT::i8    , Expand);
183   setOperationAction(ISD::MULHU           , MVT::i8    , Expand);
184   setOperationAction(ISD::SDIV            , MVT::i8    , Expand);
185   setOperationAction(ISD::UDIV            , MVT::i8    , Expand);
186   setOperationAction(ISD::SREM            , MVT::i8    , Expand);
187   setOperationAction(ISD::UREM            , MVT::i8    , Expand);
188   setOperationAction(ISD::MULHS           , MVT::i16   , Expand);
189   setOperationAction(ISD::MULHU           , MVT::i16   , Expand);
190   setOperationAction(ISD::SDIV            , MVT::i16   , Expand);
191   setOperationAction(ISD::UDIV            , MVT::i16   , Expand);
192   setOperationAction(ISD::SREM            , MVT::i16   , Expand);
193   setOperationAction(ISD::UREM            , MVT::i16   , Expand);
194   setOperationAction(ISD::MULHS           , MVT::i32   , Expand);
195   setOperationAction(ISD::MULHU           , MVT::i32   , Expand);
196   setOperationAction(ISD::SDIV            , MVT::i32   , Expand);
197   setOperationAction(ISD::UDIV            , MVT::i32   , Expand);
198   setOperationAction(ISD::SREM            , MVT::i32   , Expand);
199   setOperationAction(ISD::UREM            , MVT::i32   , Expand);
200   setOperationAction(ISD::MULHS           , MVT::i64   , Expand);
201   setOperationAction(ISD::MULHU           , MVT::i64   , Expand);
202   setOperationAction(ISD::SDIV            , MVT::i64   , Expand);
203   setOperationAction(ISD::UDIV            , MVT::i64   , Expand);
204   setOperationAction(ISD::SREM            , MVT::i64   , Expand);
205   setOperationAction(ISD::UREM            , MVT::i64   , Expand);
206
207   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
208   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
209   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
210   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
211   if (Subtarget->is64Bit())
212     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
213   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
214   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
215   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
216   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
217   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
218   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
219   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
220   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
221   
222   setOperationAction(ISD::CTPOP            , MVT::i8   , Expand);
223   setOperationAction(ISD::CTTZ             , MVT::i8   , Custom);
224   setOperationAction(ISD::CTLZ             , MVT::i8   , Custom);
225   setOperationAction(ISD::CTPOP            , MVT::i16  , Expand);
226   setOperationAction(ISD::CTTZ             , MVT::i16  , Custom);
227   setOperationAction(ISD::CTLZ             , MVT::i16  , Custom);
228   setOperationAction(ISD::CTPOP            , MVT::i32  , Expand);
229   setOperationAction(ISD::CTTZ             , MVT::i32  , Custom);
230   setOperationAction(ISD::CTLZ             , MVT::i32  , Custom);
231   if (Subtarget->is64Bit()) {
232     setOperationAction(ISD::CTPOP          , MVT::i64  , Expand);
233     setOperationAction(ISD::CTTZ           , MVT::i64  , Custom);
234     setOperationAction(ISD::CTLZ           , MVT::i64  , Custom);
235   }
236
237   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
238   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
239
240   // These should be promoted to a larger select which is supported.
241   setOperationAction(ISD::SELECT           , MVT::i1   , Promote);
242   setOperationAction(ISD::SELECT           , MVT::i8   , Promote);
243   // X86 wants to expand cmov itself.
244   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
245   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
246   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
247   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
248   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
249   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
250   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
251   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
252   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
253   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
254   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
255   if (Subtarget->is64Bit()) {
256     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
257     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
258   }
259   // X86 ret instruction may pop stack.
260   setOperationAction(ISD::RET             , MVT::Other, Custom);
261   if (!Subtarget->is64Bit())
262     setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
263
264   // Darwin ABI issue.
265   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
266   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
267   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
268   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
269   if (Subtarget->is64Bit())
270     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
271   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
272   if (Subtarget->is64Bit()) {
273     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
274     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
275     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
276     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
277   }
278   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
279   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
280   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
281   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
282   if (Subtarget->is64Bit()) {
283     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
284     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
285     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
286   }
287
288   if (Subtarget->hasSSE1())
289     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
290
291   if (!Subtarget->hasSSE2())
292     setOperationAction(ISD::MEMBARRIER    , MVT::Other, Expand);
293
294   // Expand certain atomics
295   setOperationAction(ISD::ATOMIC_CMP_SWAP , MVT::i8, Custom);
296   setOperationAction(ISD::ATOMIC_CMP_SWAP , MVT::i16, Custom);
297   setOperationAction(ISD::ATOMIC_CMP_SWAP , MVT::i32, Custom);
298   setOperationAction(ISD::ATOMIC_CMP_SWAP , MVT::i64, Custom);
299   setOperationAction(ISD::ATOMIC_LOAD_SUB , MVT::i8, Expand);
300   setOperationAction(ISD::ATOMIC_LOAD_SUB , MVT::i16, Expand);
301   setOperationAction(ISD::ATOMIC_LOAD_SUB , MVT::i32, Expand);
302
303   // Use the default ISD::DBG_STOPPOINT, ISD::DECLARE expansion.
304   setOperationAction(ISD::DBG_STOPPOINT, MVT::Other, Expand);
305   // FIXME - use subtarget debug flags
306   if (!Subtarget->isTargetDarwin() &&
307       !Subtarget->isTargetELF() &&
308       !Subtarget->isTargetCygMing()) {
309     setOperationAction(ISD::DBG_LABEL, MVT::Other, Expand);
310     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
311   }
312
313   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
314   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
315   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
316   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
317   if (Subtarget->is64Bit()) {
318     // FIXME: Verify
319     setExceptionPointerRegister(X86::RAX);
320     setExceptionSelectorRegister(X86::RDX);
321   } else {
322     setExceptionPointerRegister(X86::EAX);
323     setExceptionSelectorRegister(X86::EDX);
324   }
325   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
326   
327   setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
328
329   setOperationAction(ISD::TRAP, MVT::Other, Legal);
330
331   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
332   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
333   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
334   if (Subtarget->is64Bit()) {
335     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
336     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
337   } else {
338     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
339     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
340   }
341
342   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
343   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
344   if (Subtarget->is64Bit())
345     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
346   if (Subtarget->isTargetCygMing())
347     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
348   else
349     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
350
351   if (X86ScalarSSEf64) {
352     // f32 and f64 use SSE.
353     // Set up the FP register classes.
354     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
355     addRegisterClass(MVT::f64, X86::FR64RegisterClass);
356
357     // Use ANDPD to simulate FABS.
358     setOperationAction(ISD::FABS , MVT::f64, Custom);
359     setOperationAction(ISD::FABS , MVT::f32, Custom);
360
361     // Use XORP to simulate FNEG.
362     setOperationAction(ISD::FNEG , MVT::f64, Custom);
363     setOperationAction(ISD::FNEG , MVT::f32, Custom);
364
365     // Use ANDPD and ORPD to simulate FCOPYSIGN.
366     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
367     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
368
369     // We don't support sin/cos/fmod
370     setOperationAction(ISD::FSIN , MVT::f64, Expand);
371     setOperationAction(ISD::FCOS , MVT::f64, Expand);
372     setOperationAction(ISD::FSIN , MVT::f32, Expand);
373     setOperationAction(ISD::FCOS , MVT::f32, Expand);
374
375     // Expand FP immediates into loads from the stack, except for the special
376     // cases we handle.
377     addLegalFPImmediate(APFloat(+0.0)); // xorpd
378     addLegalFPImmediate(APFloat(+0.0f)); // xorps
379
380     // Floating truncations from f80 and extensions to f80 go through memory.
381     // If optimizing, we lie about this though and handle it in
382     // InstructionSelectPreprocess so that dagcombine2 can hack on these.
383     if (Fast) {
384       setConvertAction(MVT::f32, MVT::f80, Expand);
385       setConvertAction(MVT::f64, MVT::f80, Expand);
386       setConvertAction(MVT::f80, MVT::f32, Expand);
387       setConvertAction(MVT::f80, MVT::f64, Expand);
388     }
389   } else if (X86ScalarSSEf32) {
390     // Use SSE for f32, x87 for f64.
391     // Set up the FP register classes.
392     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
393     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
394
395     // Use ANDPS to simulate FABS.
396     setOperationAction(ISD::FABS , MVT::f32, Custom);
397
398     // Use XORP to simulate FNEG.
399     setOperationAction(ISD::FNEG , MVT::f32, Custom);
400
401     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
402
403     // Use ANDPS and ORPS to simulate FCOPYSIGN.
404     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
405     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
406
407     // We don't support sin/cos/fmod
408     setOperationAction(ISD::FSIN , MVT::f32, Expand);
409     setOperationAction(ISD::FCOS , MVT::f32, Expand);
410
411     // Special cases we handle for FP constants.
412     addLegalFPImmediate(APFloat(+0.0f)); // xorps
413     addLegalFPImmediate(APFloat(+0.0)); // FLD0
414     addLegalFPImmediate(APFloat(+1.0)); // FLD1
415     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
416     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
417
418     // SSE <-> X87 conversions go through memory.  If optimizing, we lie about
419     // this though and handle it in InstructionSelectPreprocess so that
420     // dagcombine2 can hack on these.
421     if (Fast) {
422       setConvertAction(MVT::f32, MVT::f64, Expand);
423       setConvertAction(MVT::f32, MVT::f80, Expand);
424       setConvertAction(MVT::f80, MVT::f32, Expand);    
425       setConvertAction(MVT::f64, MVT::f32, Expand);
426       // And x87->x87 truncations also.
427       setConvertAction(MVT::f80, MVT::f64, Expand);
428     }
429
430     if (!UnsafeFPMath) {
431       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
432       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
433     }
434   } else {
435     // f32 and f64 in x87.
436     // Set up the FP register classes.
437     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
438     addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
439
440     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
441     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
442     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
443     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
444
445     // Floating truncations go through memory.  If optimizing, we lie about
446     // this though and handle it in InstructionSelectPreprocess so that
447     // dagcombine2 can hack on these.
448     if (Fast) {
449       setConvertAction(MVT::f80, MVT::f32, Expand);    
450       setConvertAction(MVT::f64, MVT::f32, Expand);
451       setConvertAction(MVT::f80, MVT::f64, Expand);
452     }
453
454     if (!UnsafeFPMath) {
455       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
456       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
457     }
458     addLegalFPImmediate(APFloat(+0.0)); // FLD0
459     addLegalFPImmediate(APFloat(+1.0)); // FLD1
460     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
461     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
462     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
463     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
464     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
465     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
466   }
467
468   // Long double always uses X87.
469   addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
470   setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
471   setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
472   {
473     APFloat TmpFlt(+0.0);
474     TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven);
475     addLegalFPImmediate(TmpFlt);  // FLD0
476     TmpFlt.changeSign();
477     addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
478     APFloat TmpFlt2(+1.0);
479     TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven);
480     addLegalFPImmediate(TmpFlt2);  // FLD1
481     TmpFlt2.changeSign();
482     addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
483   }
484     
485   if (!UnsafeFPMath) {
486     setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
487     setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
488   }
489
490   // Always use a library call for pow.
491   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
492   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
493   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
494
495   // First set operation action for all vector types to expand. Then we
496   // will selectively turn on ones that can be effectively codegen'd.
497   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
498        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
499     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
500     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
501     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
502     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
503     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
504     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
505     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
506     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
507     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
508     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
509     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
510     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
511     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
512     setOperationAction(ISD::VECTOR_SHUFFLE,     (MVT::SimpleValueType)VT, Expand);
513     setOperationAction(ISD::EXTRACT_VECTOR_ELT, (MVT::SimpleValueType)VT, Expand);
514     setOperationAction(ISD::INSERT_VECTOR_ELT,  (MVT::SimpleValueType)VT, Expand);
515     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
516     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
517     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
518     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
519     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
520     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
521     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
522     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
523     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
524     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
525     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
526     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
527     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
528     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
529     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
530     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
531     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
532     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
533     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
534     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
535     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
536     setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
537   }
538
539   if (Subtarget->hasMMX()) {
540     addRegisterClass(MVT::v8i8,  X86::VR64RegisterClass);
541     addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
542     addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
543     addRegisterClass(MVT::v2f32, X86::VR64RegisterClass);
544     addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
545
546     // FIXME: add MMX packed arithmetics
547
548     setOperationAction(ISD::ADD,                MVT::v8i8,  Legal);
549     setOperationAction(ISD::ADD,                MVT::v4i16, Legal);
550     setOperationAction(ISD::ADD,                MVT::v2i32, Legal);
551     setOperationAction(ISD::ADD,                MVT::v1i64, Legal);
552
553     setOperationAction(ISD::SUB,                MVT::v8i8,  Legal);
554     setOperationAction(ISD::SUB,                MVT::v4i16, Legal);
555     setOperationAction(ISD::SUB,                MVT::v2i32, Legal);
556     setOperationAction(ISD::SUB,                MVT::v1i64, Legal);
557
558     setOperationAction(ISD::MULHS,              MVT::v4i16, Legal);
559     setOperationAction(ISD::MUL,                MVT::v4i16, Legal);
560
561     setOperationAction(ISD::AND,                MVT::v8i8,  Promote);
562     AddPromotedToType (ISD::AND,                MVT::v8i8,  MVT::v1i64);
563     setOperationAction(ISD::AND,                MVT::v4i16, Promote);
564     AddPromotedToType (ISD::AND,                MVT::v4i16, MVT::v1i64);
565     setOperationAction(ISD::AND,                MVT::v2i32, Promote);
566     AddPromotedToType (ISD::AND,                MVT::v2i32, MVT::v1i64);
567     setOperationAction(ISD::AND,                MVT::v1i64, Legal);
568
569     setOperationAction(ISD::OR,                 MVT::v8i8,  Promote);
570     AddPromotedToType (ISD::OR,                 MVT::v8i8,  MVT::v1i64);
571     setOperationAction(ISD::OR,                 MVT::v4i16, Promote);
572     AddPromotedToType (ISD::OR,                 MVT::v4i16, MVT::v1i64);
573     setOperationAction(ISD::OR,                 MVT::v2i32, Promote);
574     AddPromotedToType (ISD::OR,                 MVT::v2i32, MVT::v1i64);
575     setOperationAction(ISD::OR,                 MVT::v1i64, Legal);
576
577     setOperationAction(ISD::XOR,                MVT::v8i8,  Promote);
578     AddPromotedToType (ISD::XOR,                MVT::v8i8,  MVT::v1i64);
579     setOperationAction(ISD::XOR,                MVT::v4i16, Promote);
580     AddPromotedToType (ISD::XOR,                MVT::v4i16, MVT::v1i64);
581     setOperationAction(ISD::XOR,                MVT::v2i32, Promote);
582     AddPromotedToType (ISD::XOR,                MVT::v2i32, MVT::v1i64);
583     setOperationAction(ISD::XOR,                MVT::v1i64, Legal);
584
585     setOperationAction(ISD::LOAD,               MVT::v8i8,  Promote);
586     AddPromotedToType (ISD::LOAD,               MVT::v8i8,  MVT::v1i64);
587     setOperationAction(ISD::LOAD,               MVT::v4i16, Promote);
588     AddPromotedToType (ISD::LOAD,               MVT::v4i16, MVT::v1i64);
589     setOperationAction(ISD::LOAD,               MVT::v2i32, Promote);
590     AddPromotedToType (ISD::LOAD,               MVT::v2i32, MVT::v1i64);
591     setOperationAction(ISD::LOAD,               MVT::v2f32, Promote);
592     AddPromotedToType (ISD::LOAD,               MVT::v2f32, MVT::v1i64);
593     setOperationAction(ISD::LOAD,               MVT::v1i64, Legal);
594
595     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i8,  Custom);
596     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i16, Custom);
597     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i32, Custom);
598     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f32, Custom);
599     setOperationAction(ISD::BUILD_VECTOR,       MVT::v1i64, Custom);
600
601     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8i8,  Custom);
602     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i16, Custom);
603     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i32, Custom);
604     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v1i64, Custom);
605
606     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2f32, Custom);
607     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Custom);
608     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Custom);
609     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Custom);
610
611     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i16, Custom);
612   }
613
614   if (Subtarget->hasSSE1()) {
615     addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
616
617     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
618     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
619     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
620     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
621     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
622     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
623     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
624     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
625     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
626     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
627     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
628     setOperationAction(ISD::VSETCC,             MVT::v4f32, Custom);
629   }
630
631   if (Subtarget->hasSSE2()) {
632     addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
633     addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
634     addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
635     addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
636     addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
637
638     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
639     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
640     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
641     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
642     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
643     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
644     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
645     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
646     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
647     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
648     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
649     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
650     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
651     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
652     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
653
654     setOperationAction(ISD::VSETCC,             MVT::v2f64, Custom);
655     setOperationAction(ISD::VSETCC,             MVT::v16i8, Custom);
656     setOperationAction(ISD::VSETCC,             MVT::v8i16, Custom);
657     setOperationAction(ISD::VSETCC,             MVT::v4i32, Custom);
658
659     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
660     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
661     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
662     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
663     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
664
665     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
666     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
667       MVT VT = (MVT::SimpleValueType)i;
668       // Do not attempt to custom lower non-power-of-2 vectors
669       if (!isPowerOf2_32(VT.getVectorNumElements()))
670         continue;
671       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
672       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
673       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
674     }
675     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
676     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
677     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
678     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
679     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
680     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
681     if (Subtarget->is64Bit()) {
682       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
683       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
684     }
685
686     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
687     for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
688       setOperationAction(ISD::AND,    (MVT::SimpleValueType)VT, Promote);
689       AddPromotedToType (ISD::AND,    (MVT::SimpleValueType)VT, MVT::v2i64);
690       setOperationAction(ISD::OR,     (MVT::SimpleValueType)VT, Promote);
691       AddPromotedToType (ISD::OR,     (MVT::SimpleValueType)VT, MVT::v2i64);
692       setOperationAction(ISD::XOR,    (MVT::SimpleValueType)VT, Promote);
693       AddPromotedToType (ISD::XOR,    (MVT::SimpleValueType)VT, MVT::v2i64);
694       setOperationAction(ISD::LOAD,   (MVT::SimpleValueType)VT, Promote);
695       AddPromotedToType (ISD::LOAD,   (MVT::SimpleValueType)VT, MVT::v2i64);
696       setOperationAction(ISD::SELECT, (MVT::SimpleValueType)VT, Promote);
697       AddPromotedToType (ISD::SELECT, (MVT::SimpleValueType)VT, MVT::v2i64);
698     }
699
700     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
701
702     // Custom lower v2i64 and v2f64 selects.
703     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
704     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
705     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
706     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
707     
708   }
709   
710   if (Subtarget->hasSSE41()) {
711     // FIXME: Do we need to handle scalar-to-vector here?
712     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
713     setOperationAction(ISD::MUL,                MVT::v2i64, Legal);
714
715     // i8 and i16 vectors are custom , because the source register and source
716     // source memory operand types are not the same width.  f32 vectors are
717     // custom since the immediate controlling the insert encodes additional
718     // information.
719     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
720     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
721     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Legal);
722     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
723
724     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
725     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
726     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
727     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
728
729     if (Subtarget->is64Bit()) {
730       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Legal);
731       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
732     }
733   }
734
735   if (Subtarget->hasSSE42()) {
736     setOperationAction(ISD::VSETCC,             MVT::v2i64, Custom);
737   }
738   
739   // We want to custom lower some of our intrinsics.
740   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
741
742   // We have target-specific dag combine patterns for the following nodes:
743   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
744   setTargetDAGCombine(ISD::BUILD_VECTOR);
745   setTargetDAGCombine(ISD::SELECT);
746   setTargetDAGCombine(ISD::STORE);
747
748   computeRegisterProperties();
749
750   // FIXME: These should be based on subtarget info. Plus, the values should
751   // be smaller when we are in optimizing for size mode.
752   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
753   maxStoresPerMemcpy = 16; // For @llvm.memcpy -> sequence of stores
754   maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
755   allowUnalignedMemoryAccesses = true; // x86 supports it!
756   setPrefLoopAlignment(16);
757 }
758
759
760 MVT X86TargetLowering::getSetCCResultType(const SDValue &) const {
761   return MVT::i8;
762 }
763
764
765 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
766 /// the desired ByVal argument alignment.
767 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
768   if (MaxAlign == 16)
769     return;
770   if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
771     if (VTy->getBitWidth() == 128)
772       MaxAlign = 16;
773   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
774     unsigned EltAlign = 0;
775     getMaxByValAlign(ATy->getElementType(), EltAlign);
776     if (EltAlign > MaxAlign)
777       MaxAlign = EltAlign;
778   } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
779     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
780       unsigned EltAlign = 0;
781       getMaxByValAlign(STy->getElementType(i), EltAlign);
782       if (EltAlign > MaxAlign)
783         MaxAlign = EltAlign;
784       if (MaxAlign == 16)
785         break;
786     }
787   }
788   return;
789 }
790
791 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
792 /// function arguments in the caller parameter area. For X86, aggregates
793 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
794 /// are at 4-byte boundaries.
795 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
796   if (Subtarget->is64Bit())
797     return getTargetData()->getABITypeAlignment(Ty);
798   unsigned Align = 4;
799   if (Subtarget->hasSSE1())
800     getMaxByValAlign(Ty, Align);
801   return Align;
802 }
803
804 /// getOptimalMemOpType - Returns the target specific optimal type for load
805 /// and store operations as a result of memset, memcpy, and memmove
806 /// lowering. It returns MVT::iAny if SelectionDAG should be responsible for
807 /// determining it.
808 MVT
809 X86TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned Align,
810                                        bool isSrcConst, bool isSrcStr) const {
811   if ((isSrcConst || isSrcStr) && Subtarget->hasSSE2() && Size >= 16)
812     return MVT::v4i32;
813   if ((isSrcConst || isSrcStr) && Subtarget->hasSSE1() && Size >= 16)
814     return MVT::v4f32;
815   if (Subtarget->is64Bit() && Size >= 8)
816     return MVT::i64;
817   return MVT::i32;
818 }
819
820
821 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
822 /// jumptable.
823 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
824                                                       SelectionDAG &DAG) const {
825   if (usesGlobalOffsetTable())
826     return DAG.getNode(ISD::GLOBAL_OFFSET_TABLE, getPointerTy());
827   if (!Subtarget->isPICStyleRIPRel())
828     return DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy());
829   return Table;
830 }
831
832 //===----------------------------------------------------------------------===//
833 //               Return Value Calling Convention Implementation
834 //===----------------------------------------------------------------------===//
835
836 #include "X86GenCallingConv.inc"
837
838 /// LowerRET - Lower an ISD::RET node.
839 SDValue X86TargetLowering::LowerRET(SDValue Op, SelectionDAG &DAG) {
840   assert((Op.getNumOperands() & 1) == 1 && "ISD::RET should have odd # args");
841   
842   SmallVector<CCValAssign, 16> RVLocs;
843   unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
844   bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
845   CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs);
846   CCInfo.AnalyzeReturn(Op.Val, RetCC_X86);
847     
848   // If this is the first return lowered for this function, add the regs to the
849   // liveout set for the function.
850   if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
851     for (unsigned i = 0; i != RVLocs.size(); ++i)
852       if (RVLocs[i].isRegLoc())
853         DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
854   }
855   SDValue Chain = Op.getOperand(0);
856   
857   // Handle tail call return.
858   Chain = GetPossiblePreceedingTailCall(Chain, X86ISD::TAILCALL);
859   if (Chain.getOpcode() == X86ISD::TAILCALL) {
860     SDValue TailCall = Chain;
861     SDValue TargetAddress = TailCall.getOperand(1);
862     SDValue StackAdjustment = TailCall.getOperand(2);
863     assert(((TargetAddress.getOpcode() == ISD::Register &&
864                (cast<RegisterSDNode>(TargetAddress)->getReg() == X86::ECX ||
865                 cast<RegisterSDNode>(TargetAddress)->getReg() == X86::R9)) ||
866               TargetAddress.getOpcode() == ISD::TargetExternalSymbol ||
867               TargetAddress.getOpcode() == ISD::TargetGlobalAddress) && 
868              "Expecting an global address, external symbol, or register");
869     assert(StackAdjustment.getOpcode() == ISD::Constant &&
870            "Expecting a const value");
871
872     SmallVector<SDValue,8> Operands;
873     Operands.push_back(Chain.getOperand(0));
874     Operands.push_back(TargetAddress);
875     Operands.push_back(StackAdjustment);
876     // Copy registers used by the call. Last operand is a flag so it is not
877     // copied.
878     for (unsigned i=3; i < TailCall.getNumOperands()-1; i++) {
879       Operands.push_back(Chain.getOperand(i));
880     }
881     return DAG.getNode(X86ISD::TC_RETURN, MVT::Other, &Operands[0], 
882                        Operands.size());
883   }
884   
885   // Regular return.
886   SDValue Flag;
887
888   SmallVector<SDValue, 6> RetOps;
889   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
890   // Operand #1 = Bytes To Pop
891   RetOps.push_back(DAG.getConstant(getBytesToPopOnReturn(), MVT::i16));
892   
893   // Copy the result values into the output registers.
894   for (unsigned i = 0; i != RVLocs.size(); ++i) {
895     CCValAssign &VA = RVLocs[i];
896     assert(VA.isRegLoc() && "Can only return in registers!");
897     SDValue ValToCopy = Op.getOperand(i*2+1);
898     
899     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
900     // the RET instruction and handled by the FP Stackifier.
901     if (RVLocs[i].getLocReg() == X86::ST0 ||
902         RVLocs[i].getLocReg() == X86::ST1) {
903       // If this is a copy from an xmm register to ST(0), use an FPExtend to
904       // change the value to the FP stack register class.
905       if (isScalarFPTypeInSSEReg(RVLocs[i].getValVT()))
906         ValToCopy = DAG.getNode(ISD::FP_EXTEND, MVT::f80, ValToCopy);
907       RetOps.push_back(ValToCopy);
908       // Don't emit a copytoreg.
909       continue;
910     }
911
912     Chain = DAG.getCopyToReg(Chain, VA.getLocReg(), ValToCopy, Flag);
913     Flag = Chain.getValue(1);
914   }
915
916   // The x86-64 ABI for returning structs by value requires that we copy
917   // the sret argument into %rax for the return. We saved the argument into
918   // a virtual register in the entry block, so now we copy the value out
919   // and into %rax.
920   if (Subtarget->is64Bit() &&
921       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
922     MachineFunction &MF = DAG.getMachineFunction();
923     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
924     unsigned Reg = FuncInfo->getSRetReturnReg();
925     if (!Reg) {
926       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
927       FuncInfo->setSRetReturnReg(Reg);
928     }
929     SDValue Val = DAG.getCopyFromReg(Chain, Reg, getPointerTy());
930
931     Chain = DAG.getCopyToReg(Chain, X86::RAX, Val, Flag);
932     Flag = Chain.getValue(1);
933   }
934   
935   RetOps[0] = Chain;  // Update chain.
936
937   // Add the flag if we have it.
938   if (Flag.Val)
939     RetOps.push_back(Flag);
940   
941   return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, &RetOps[0], RetOps.size());
942 }
943
944
945 /// LowerCallResult - Lower the result values of an ISD::CALL into the
946 /// appropriate copies out of appropriate physical registers.  This assumes that
947 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
948 /// being lowered.  The returns a SDNode with the same number of values as the
949 /// ISD::CALL.
950 SDNode *X86TargetLowering::
951 LowerCallResult(SDValue Chain, SDValue InFlag, SDNode *TheCall, 
952                 unsigned CallingConv, SelectionDAG &DAG) {
953   
954   // Assign locations to each value returned by this call.
955   SmallVector<CCValAssign, 16> RVLocs;
956   bool isVarArg = cast<ConstantSDNode>(TheCall->getOperand(2))->getValue() != 0;
957   CCState CCInfo(CallingConv, isVarArg, getTargetMachine(), RVLocs);
958   CCInfo.AnalyzeCallResult(TheCall, RetCC_X86);
959
960   SmallVector<SDValue, 8> ResultVals;
961   
962   // Copy all of the result registers out of their specified physreg.
963   for (unsigned i = 0; i != RVLocs.size(); ++i) {
964     MVT CopyVT = RVLocs[i].getValVT();
965     
966     // If this is a call to a function that returns an fp value on the floating
967     // point stack, but where we prefer to use the value in xmm registers, copy
968     // it out as F80 and use a truncate to move it from fp stack reg to xmm reg.
969     if (RVLocs[i].getLocReg() == X86::ST0 &&
970         isScalarFPTypeInSSEReg(RVLocs[i].getValVT())) {
971       CopyVT = MVT::f80;
972     }
973     
974     Chain = DAG.getCopyFromReg(Chain, RVLocs[i].getLocReg(),
975                                CopyVT, InFlag).getValue(1);
976     SDValue Val = Chain.getValue(0);
977     InFlag = Chain.getValue(2);
978
979     if (CopyVT != RVLocs[i].getValVT()) {
980       // Round the F80 the right size, which also moves to the appropriate xmm
981       // register.
982       Val = DAG.getNode(ISD::FP_ROUND, RVLocs[i].getValVT(), Val,
983                         // This truncation won't change the value.
984                         DAG.getIntPtrConstant(1));
985     }
986     
987     ResultVals.push_back(Val);
988   }
989
990   // Merge everything together with a MERGE_VALUES node.
991   ResultVals.push_back(Chain);
992   return DAG.getMergeValues(TheCall->getVTList(), &ResultVals[0],
993                             ResultVals.size()).Val;
994 }
995
996
997 //===----------------------------------------------------------------------===//
998 //                C & StdCall & Fast Calling Convention implementation
999 //===----------------------------------------------------------------------===//
1000 //  StdCall calling convention seems to be standard for many Windows' API
1001 //  routines and around. It differs from C calling convention just a little:
1002 //  callee should clean up the stack, not caller. Symbols should be also
1003 //  decorated in some fancy way :) It doesn't support any vector arguments.
1004 //  For info on fast calling convention see Fast Calling Convention (tail call)
1005 //  implementation LowerX86_32FastCCCallTo.
1006
1007 /// AddLiveIn - This helper function adds the specified physical register to the
1008 /// MachineFunction as a live in value.  It also creates a corresponding virtual
1009 /// register for it.
1010 static unsigned AddLiveIn(MachineFunction &MF, unsigned PReg,
1011                           const TargetRegisterClass *RC) {
1012   assert(RC->contains(PReg) && "Not the correct regclass!");
1013   unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
1014   MF.getRegInfo().addLiveIn(PReg, VReg);
1015   return VReg;
1016 }
1017
1018 /// CallIsStructReturn - Determines whether a CALL node uses struct return
1019 /// semantics.
1020 static bool CallIsStructReturn(SDValue Op) {
1021   unsigned NumOps = (Op.getNumOperands() - 5) / 2;
1022   if (!NumOps)
1023     return false;
1024
1025   return cast<ARG_FLAGSSDNode>(Op.getOperand(6))->getArgFlags().isSRet();
1026 }
1027
1028 /// ArgsAreStructReturn - Determines whether a FORMAL_ARGUMENTS node uses struct
1029 /// return semantics.
1030 static bool ArgsAreStructReturn(SDValue Op) {
1031   unsigned NumArgs = Op.Val->getNumValues() - 1;
1032   if (!NumArgs)
1033     return false;
1034
1035   return cast<ARG_FLAGSSDNode>(Op.getOperand(3))->getArgFlags().isSRet();
1036 }
1037
1038 /// IsCalleePop - Determines whether a CALL or FORMAL_ARGUMENTS node requires
1039 /// the callee to pop its own arguments. Callee pop is necessary to support tail
1040 /// calls.
1041 bool X86TargetLowering::IsCalleePop(SDValue Op) {
1042   bool IsVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1043   if (IsVarArg)
1044     return false;
1045
1046   switch (cast<ConstantSDNode>(Op.getOperand(1))->getValue()) {
1047   default:
1048     return false;
1049   case CallingConv::X86_StdCall:
1050     return !Subtarget->is64Bit();
1051   case CallingConv::X86_FastCall:
1052     return !Subtarget->is64Bit();
1053   case CallingConv::Fast:
1054     return PerformTailCallOpt;
1055   }
1056 }
1057
1058 /// CCAssignFnForNode - Selects the correct CCAssignFn for a CALL or
1059 /// FORMAL_ARGUMENTS node.
1060 CCAssignFn *X86TargetLowering::CCAssignFnForNode(SDValue Op) const {
1061   unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
1062   
1063   if (Subtarget->is64Bit()) {
1064     if (Subtarget->isTargetWin64())
1065       return CC_X86_Win64_C;
1066     else {
1067       if (CC == CallingConv::Fast && PerformTailCallOpt)
1068         return CC_X86_64_TailCall;
1069       else
1070         return CC_X86_64_C;
1071     }
1072   }
1073
1074   if (CC == CallingConv::X86_FastCall)
1075     return CC_X86_32_FastCall;
1076   else if (CC == CallingConv::Fast && PerformTailCallOpt)
1077     return CC_X86_32_TailCall;
1078   else
1079     return CC_X86_32_C;
1080 }
1081
1082 /// NameDecorationForFORMAL_ARGUMENTS - Selects the appropriate decoration to
1083 /// apply to a MachineFunction containing a given FORMAL_ARGUMENTS node.
1084 NameDecorationStyle
1085 X86TargetLowering::NameDecorationForFORMAL_ARGUMENTS(SDValue Op) {
1086   unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
1087   if (CC == CallingConv::X86_FastCall)
1088     return FastCall;
1089   else if (CC == CallingConv::X86_StdCall)
1090     return StdCall;
1091   return None;
1092 }
1093
1094
1095 /// CallRequiresGOTInRegister - Check whether the call requires the GOT pointer
1096 /// in a register before calling.
1097 bool X86TargetLowering::CallRequiresGOTPtrInReg(bool Is64Bit, bool IsTailCall) {
1098   return !IsTailCall && !Is64Bit &&
1099     getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1100     Subtarget->isPICStyleGOT();
1101 }
1102
1103 /// CallRequiresFnAddressInReg - Check whether the call requires the function
1104 /// address to be loaded in a register.
1105 bool 
1106 X86TargetLowering::CallRequiresFnAddressInReg(bool Is64Bit, bool IsTailCall) {
1107   return !Is64Bit && IsTailCall &&  
1108     getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1109     Subtarget->isPICStyleGOT();
1110 }
1111
1112 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1113 /// by "Src" to address "Dst" with size and alignment information specified by
1114 /// the specific parameter attribute. The copy will be passed as a byval
1115 /// function parameter.
1116 static SDValue 
1117 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1118                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG) {
1119   SDValue SizeNode     = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1120   return DAG.getMemcpy(Chain, Dst, Src, SizeNode, Flags.getByValAlign(),
1121                        /*AlwaysInline=*/true, NULL, 0, NULL, 0);
1122 }
1123
1124 SDValue X86TargetLowering::LowerMemArgument(SDValue Op, SelectionDAG &DAG,
1125                                               const CCValAssign &VA,
1126                                               MachineFrameInfo *MFI,
1127                                               unsigned CC,
1128                                               SDValue Root, unsigned i) {
1129   // Create the nodes corresponding to a load from this parameter slot.
1130   ISD::ArgFlagsTy Flags =
1131     cast<ARG_FLAGSSDNode>(Op.getOperand(3 + i))->getArgFlags();
1132   bool AlwaysUseMutable = (CC==CallingConv::Fast) && PerformTailCallOpt;
1133   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1134
1135   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1136   // changed with more analysis.  
1137   // In case of tail call optimization mark all arguments mutable. Since they
1138   // could be overwritten by lowering of arguments in case of a tail call.
1139   int FI = MFI->CreateFixedObject(VA.getValVT().getSizeInBits()/8,
1140                                   VA.getLocMemOffset(), isImmutable);
1141   SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1142   if (Flags.isByVal())
1143     return FIN;
1144   return DAG.getLoad(VA.getValVT(), Root, FIN,
1145                      PseudoSourceValue::getFixedStack(FI), 0);
1146 }
1147
1148 SDValue
1149 X86TargetLowering::LowerFORMAL_ARGUMENTS(SDValue Op, SelectionDAG &DAG) {
1150   MachineFunction &MF = DAG.getMachineFunction();
1151   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1152   
1153   const Function* Fn = MF.getFunction();
1154   if (Fn->hasExternalLinkage() &&
1155       Subtarget->isTargetCygMing() &&
1156       Fn->getName() == "main")
1157     FuncInfo->setForceFramePointer(true);
1158
1159   // Decorate the function name.
1160   FuncInfo->setDecorationStyle(NameDecorationForFORMAL_ARGUMENTS(Op));
1161   
1162   MachineFrameInfo *MFI = MF.getFrameInfo();
1163   SDValue Root = Op.getOperand(0);
1164   bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1165   unsigned CC = MF.getFunction()->getCallingConv();
1166   bool Is64Bit = Subtarget->is64Bit();
1167   bool IsWin64 = Subtarget->isTargetWin64();
1168
1169   assert(!(isVarArg && CC == CallingConv::Fast) &&
1170          "Var args not supported with calling convention fastcc");
1171
1172   // Assign locations to all of the incoming arguments.
1173   SmallVector<CCValAssign, 16> ArgLocs;
1174   CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1175   CCInfo.AnalyzeFormalArguments(Op.Val, CCAssignFnForNode(Op));
1176   
1177   SmallVector<SDValue, 8> ArgValues;
1178   unsigned LastVal = ~0U;
1179   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1180     CCValAssign &VA = ArgLocs[i];
1181     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1182     // places.
1183     assert(VA.getValNo() != LastVal &&
1184            "Don't support value assigned to multiple locs yet");
1185     LastVal = VA.getValNo();
1186     
1187     if (VA.isRegLoc()) {
1188       MVT RegVT = VA.getLocVT();
1189       TargetRegisterClass *RC;
1190       if (RegVT == MVT::i32)
1191         RC = X86::GR32RegisterClass;
1192       else if (Is64Bit && RegVT == MVT::i64)
1193         RC = X86::GR64RegisterClass;
1194       else if (RegVT == MVT::f32)
1195         RC = X86::FR32RegisterClass;
1196       else if (RegVT == MVT::f64)
1197         RC = X86::FR64RegisterClass;
1198       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1199         RC = X86::VR128RegisterClass;
1200       else if (RegVT.isVector()) {
1201         assert(RegVT.getSizeInBits() == 64);
1202         if (!Is64Bit)
1203           RC = X86::VR64RegisterClass;     // MMX values are passed in MMXs.
1204         else {
1205           // Darwin calling convention passes MMX values in either GPRs or
1206           // XMMs in x86-64. Other targets pass them in memory.
1207           if (RegVT != MVT::v1i64 && Subtarget->hasSSE2()) {
1208             RC = X86::VR128RegisterClass;  // MMX values are passed in XMMs.
1209             RegVT = MVT::v2i64;
1210           } else {
1211             RC = X86::GR64RegisterClass;   // v1i64 values are passed in GPRs.
1212             RegVT = MVT::i64;
1213           }
1214         }
1215       } else {
1216         assert(0 && "Unknown argument type!");
1217       }
1218
1219       unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
1220       SDValue ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
1221       
1222       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1223       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1224       // right size.
1225       if (VA.getLocInfo() == CCValAssign::SExt)
1226         ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
1227                                DAG.getValueType(VA.getValVT()));
1228       else if (VA.getLocInfo() == CCValAssign::ZExt)
1229         ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
1230                                DAG.getValueType(VA.getValVT()));
1231       
1232       if (VA.getLocInfo() != CCValAssign::Full)
1233         ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
1234       
1235       // Handle MMX values passed in GPRs.
1236       if (Is64Bit && RegVT != VA.getLocVT()) {
1237         if (RegVT.getSizeInBits() == 64 && RC == X86::GR64RegisterClass)
1238           ArgValue = DAG.getNode(ISD::BIT_CONVERT, VA.getLocVT(), ArgValue);
1239         else if (RC == X86::VR128RegisterClass) {
1240           ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i64, ArgValue,
1241                                  DAG.getConstant(0, MVT::i64));
1242           ArgValue = DAG.getNode(ISD::BIT_CONVERT, VA.getLocVT(), ArgValue);
1243         }
1244       }
1245       
1246       ArgValues.push_back(ArgValue);
1247     } else {
1248       assert(VA.isMemLoc());
1249       ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, CC, Root, i));
1250     }
1251   }
1252
1253   // The x86-64 ABI for returning structs by value requires that we copy
1254   // the sret argument into %rax for the return. Save the argument into
1255   // a virtual register so that we can access it from the return points.
1256   if (Is64Bit && DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1257     MachineFunction &MF = DAG.getMachineFunction();
1258     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1259     unsigned Reg = FuncInfo->getSRetReturnReg();
1260     if (!Reg) {
1261       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1262       FuncInfo->setSRetReturnReg(Reg);
1263     }
1264     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), Reg, ArgValues[0]);
1265     Root = DAG.getNode(ISD::TokenFactor, MVT::Other, Copy, Root);
1266   }
1267
1268   unsigned StackSize = CCInfo.getNextStackOffset();
1269   // align stack specially for tail calls
1270   if (CC == CallingConv::Fast)
1271     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1272
1273   // If the function takes variable number of arguments, make a frame index for
1274   // the start of the first vararg value... for expansion of llvm.va_start.
1275   if (isVarArg) {
1276     if (Is64Bit || CC != CallingConv::X86_FastCall) {
1277       VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
1278     }
1279     if (Is64Bit) {
1280       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1281
1282       // FIXME: We should really autogenerate these arrays
1283       static const unsigned GPR64ArgRegsWin64[] = {
1284         X86::RCX, X86::RDX, X86::R8,  X86::R9
1285       };
1286       static const unsigned XMMArgRegsWin64[] = {
1287         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1288       };
1289       static const unsigned GPR64ArgRegs64Bit[] = {
1290         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1291       };
1292       static const unsigned XMMArgRegs64Bit[] = {
1293         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1294         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1295       };
1296       const unsigned *GPR64ArgRegs, *XMMArgRegs;
1297
1298       if (IsWin64) {
1299         TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1300         GPR64ArgRegs = GPR64ArgRegsWin64;
1301         XMMArgRegs = XMMArgRegsWin64;
1302       } else {
1303         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1304         GPR64ArgRegs = GPR64ArgRegs64Bit;
1305         XMMArgRegs = XMMArgRegs64Bit;
1306       }
1307       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1308                                                        TotalNumIntRegs);
1309       unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1310                                                        TotalNumXMMRegs);
1311
1312       // For X86-64, if there are vararg parameters that are passed via
1313       // registers, then we must store them to their spots on the stack so they
1314       // may be loaded by deferencing the result of va_next.
1315       VarArgsGPOffset = NumIntRegs * 8;
1316       VarArgsFPOffset = TotalNumIntRegs * 8 + NumXMMRegs * 16;
1317       RegSaveFrameIndex = MFI->CreateStackObject(TotalNumIntRegs * 8 +
1318                                                  TotalNumXMMRegs * 16, 16);
1319
1320       // Store the integer parameter registers.
1321       SmallVector<SDValue, 8> MemOps;
1322       SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1323       SDValue FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1324                                   DAG.getIntPtrConstant(VarArgsGPOffset));
1325       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1326         unsigned VReg = AddLiveIn(MF, GPR64ArgRegs[NumIntRegs],
1327                                   X86::GR64RegisterClass);
1328         SDValue Val = DAG.getCopyFromReg(Root, VReg, MVT::i64);
1329         SDValue Store =
1330           DAG.getStore(Val.getValue(1), Val, FIN,
1331                        PseudoSourceValue::getFixedStack(RegSaveFrameIndex), 0);
1332         MemOps.push_back(Store);
1333         FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1334                           DAG.getIntPtrConstant(8));
1335       }
1336
1337       // Now store the XMM (fp + vector) parameter registers.
1338       FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1339                         DAG.getIntPtrConstant(VarArgsFPOffset));
1340       for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1341         unsigned VReg = AddLiveIn(MF, XMMArgRegs[NumXMMRegs],
1342                                   X86::VR128RegisterClass);
1343         SDValue Val = DAG.getCopyFromReg(Root, VReg, MVT::v4f32);
1344         SDValue Store =
1345           DAG.getStore(Val.getValue(1), Val, FIN,
1346                        PseudoSourceValue::getFixedStack(RegSaveFrameIndex), 0);
1347         MemOps.push_back(Store);
1348         FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1349                           DAG.getIntPtrConstant(16));
1350       }
1351       if (!MemOps.empty())
1352           Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
1353                              &MemOps[0], MemOps.size());
1354     }
1355   }
1356   
1357   // Make sure the instruction takes 8n+4 bytes to make sure the start of the
1358   // arguments and the arguments after the retaddr has been pushed are
1359   // aligned.
1360   if (!Is64Bit && CC == CallingConv::X86_FastCall &&
1361       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWindows() &&
1362       (StackSize & 7) == 0)
1363     StackSize += 4;
1364
1365   ArgValues.push_back(Root);
1366
1367   // Some CCs need callee pop.
1368   if (IsCalleePop(Op)) {
1369     BytesToPopOnReturn  = StackSize; // Callee pops everything.
1370     BytesCallerReserves = 0;
1371   } else {
1372     BytesToPopOnReturn  = 0; // Callee pops nothing.
1373     // If this is an sret function, the return should pop the hidden pointer.
1374     if (!Is64Bit && ArgsAreStructReturn(Op))
1375       BytesToPopOnReturn = 4;  
1376     BytesCallerReserves = StackSize;
1377   }
1378
1379   if (!Is64Bit) {
1380     RegSaveFrameIndex = 0xAAAAAAA;   // RegSaveFrameIndex is X86-64 only.
1381     if (CC == CallingConv::X86_FastCall)
1382       VarArgsFrameIndex = 0xAAAAAAA;   // fastcc functions can't have varargs.
1383   }
1384
1385   FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1386
1387   // Return the new list of results.
1388   return DAG.getMergeValues(Op.Val->getVTList(), &ArgValues[0],
1389                             ArgValues.size()).getValue(Op.ResNo);
1390 }
1391
1392 SDValue
1393 X86TargetLowering::LowerMemOpCallTo(SDValue Op, SelectionDAG &DAG,
1394                                     const SDValue &StackPtr,
1395                                     const CCValAssign &VA,
1396                                     SDValue Chain,
1397                                     SDValue Arg) {
1398   unsigned LocMemOffset = VA.getLocMemOffset();
1399   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1400   PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
1401   ISD::ArgFlagsTy Flags =
1402     cast<ARG_FLAGSSDNode>(Op.getOperand(6+2*VA.getValNo()))->getArgFlags();
1403   if (Flags.isByVal()) {
1404     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG);
1405   }
1406   return DAG.getStore(Chain, Arg, PtrOff,
1407                       PseudoSourceValue::getStack(), LocMemOffset);
1408 }
1409
1410 /// EmitTailCallLoadRetAddr - Emit a load of return adress if tail call
1411 /// optimization is performed and it is required.
1412 SDValue 
1413 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG, 
1414                                            SDValue &OutRetAddr,
1415                                            SDValue Chain, 
1416                                            bool IsTailCall, 
1417                                            bool Is64Bit, 
1418                                            int FPDiff) {
1419   if (!IsTailCall || FPDiff==0) return Chain;
1420
1421   // Adjust the Return address stack slot.
1422   MVT VT = getPointerTy();
1423   OutRetAddr = getReturnAddressFrameIndex(DAG);
1424   // Load the "old" Return address.
1425   OutRetAddr = DAG.getLoad(VT, Chain,OutRetAddr, NULL, 0);
1426   return SDValue(OutRetAddr.Val, 1);
1427 }
1428
1429 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1430 /// optimization is performed and it is required (FPDiff!=0).
1431 static SDValue 
1432 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF, 
1433                          SDValue Chain, SDValue RetAddrFrIdx,
1434                          bool Is64Bit, int FPDiff) {
1435   // Store the return address to the appropriate stack slot.
1436   if (!FPDiff) return Chain;
1437   // Calculate the new stack slot for the return address.
1438   int SlotSize = Is64Bit ? 8 : 4;
1439   int NewReturnAddrFI = 
1440     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize);
1441   MVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1442   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1443   Chain = DAG.getStore(Chain, RetAddrFrIdx, NewRetAddrFrIdx, 
1444                        PseudoSourceValue::getFixedStack(NewReturnAddrFI), 0);
1445   return Chain;
1446 }
1447
1448 SDValue X86TargetLowering::LowerCALL(SDValue Op, SelectionDAG &DAG) {
1449   MachineFunction &MF = DAG.getMachineFunction();
1450   SDValue Chain     = Op.getOperand(0);
1451   unsigned CC         = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
1452   bool isVarArg       = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1453   bool IsTailCall     = cast<ConstantSDNode>(Op.getOperand(3))->getValue() != 0
1454                         && CC == CallingConv::Fast && PerformTailCallOpt;
1455   SDValue Callee    = Op.getOperand(4);
1456   bool Is64Bit        = Subtarget->is64Bit();
1457   bool IsStructRet    = CallIsStructReturn(Op);
1458
1459   assert(!(isVarArg && CC == CallingConv::Fast) &&
1460          "Var args not supported with calling convention fastcc");
1461
1462   // Analyze operands of the call, assigning locations to each operand.
1463   SmallVector<CCValAssign, 16> ArgLocs;
1464   CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1465   CCInfo.AnalyzeCallOperands(Op.Val, CCAssignFnForNode(Op));
1466   
1467   // Get a count of how many bytes are to be pushed on the stack.
1468   unsigned NumBytes = CCInfo.getNextStackOffset();
1469   if (CC == CallingConv::Fast)
1470     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1471
1472   // Make sure the instruction takes 8n+4 bytes to make sure the start of the
1473   // arguments and the arguments after the retaddr has been pushed are aligned.
1474   if (!Is64Bit && CC == CallingConv::X86_FastCall &&
1475       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWindows() &&
1476       (NumBytes & 7) == 0)
1477     NumBytes += 4;
1478
1479   int FPDiff = 0;
1480   if (IsTailCall) {
1481     // Lower arguments at fp - stackoffset + fpdiff.
1482     unsigned NumBytesCallerPushed = 
1483       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1484     FPDiff = NumBytesCallerPushed - NumBytes;
1485
1486     // Set the delta of movement of the returnaddr stackslot.
1487     // But only set if delta is greater than previous delta.
1488     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1489       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1490   }
1491
1492   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes));
1493
1494   SDValue RetAddrFrIdx;
1495   // Load return adress for tail calls.
1496   Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, IsTailCall, Is64Bit,
1497                                   FPDiff);
1498
1499   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1500   SmallVector<SDValue, 8> MemOpChains;
1501   SDValue StackPtr;
1502
1503   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1504   // of tail call optimization arguments are handle later.
1505   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1506     CCValAssign &VA = ArgLocs[i];
1507     SDValue Arg = Op.getOperand(5+2*VA.getValNo());
1508     bool isByVal = cast<ARG_FLAGSSDNode>(Op.getOperand(6+2*VA.getValNo()))->
1509       getArgFlags().isByVal();
1510   
1511     // Promote the value if needed.
1512     switch (VA.getLocInfo()) {
1513     default: assert(0 && "Unknown loc info!");
1514     case CCValAssign::Full: break;
1515     case CCValAssign::SExt:
1516       Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1517       break;
1518     case CCValAssign::ZExt:
1519       Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1520       break;
1521     case CCValAssign::AExt:
1522       Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1523       break;
1524     }
1525     
1526     if (VA.isRegLoc()) {
1527       if (Is64Bit) {
1528         MVT RegVT = VA.getLocVT();
1529         if (RegVT.isVector() && RegVT.getSizeInBits() == 64)
1530           switch (VA.getLocReg()) {
1531           default:
1532             break;
1533           case X86::RDI: case X86::RSI: case X86::RDX: case X86::RCX:
1534           case X86::R8: {
1535             // Special case: passing MMX values in GPR registers.
1536             Arg = DAG.getNode(ISD::BIT_CONVERT, MVT::i64, Arg);
1537             break;
1538           }
1539           case X86::XMM0: case X86::XMM1: case X86::XMM2: case X86::XMM3:
1540           case X86::XMM4: case X86::XMM5: case X86::XMM6: case X86::XMM7: {
1541             // Special case: passing MMX values in XMM registers.
1542             Arg = DAG.getNode(ISD::BIT_CONVERT, MVT::i64, Arg);
1543             Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Arg);
1544             Arg = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v2i64,
1545                               DAG.getNode(ISD::UNDEF, MVT::v2i64), Arg,
1546                               getMOVLMask(2, DAG));
1547             break;
1548           }
1549           }
1550       }
1551       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1552     } else {
1553       if (!IsTailCall || (IsTailCall && isByVal)) {
1554         assert(VA.isMemLoc());
1555         if (StackPtr.Val == 0)
1556           StackPtr = DAG.getCopyFromReg(Chain, X86StackPtr, getPointerTy());
1557         
1558         MemOpChains.push_back(LowerMemOpCallTo(Op, DAG, StackPtr, VA, Chain,
1559                                                Arg));
1560       }
1561     }
1562   }
1563   
1564   if (!MemOpChains.empty())
1565     Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1566                         &MemOpChains[0], MemOpChains.size());
1567
1568   // Build a sequence of copy-to-reg nodes chained together with token chain
1569   // and flag operands which copy the outgoing args into registers.
1570   SDValue InFlag;
1571   // Tail call byval lowering might overwrite argument registers so in case of
1572   // tail call optimization the copies to registers are lowered later.
1573   if (!IsTailCall)
1574     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1575       Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1576                                InFlag);
1577       InFlag = Chain.getValue(1);
1578     }
1579
1580   // ELF / PIC requires GOT in the EBX register before function calls via PLT
1581   // GOT pointer.  
1582   if (CallRequiresGOTPtrInReg(Is64Bit, IsTailCall)) {
1583     Chain = DAG.getCopyToReg(Chain, X86::EBX,
1584                              DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
1585                              InFlag);
1586     InFlag = Chain.getValue(1);
1587   }
1588   // If we are tail calling and generating PIC/GOT style code load the address
1589   // of the callee into ecx. The value in ecx is used as target of the tail
1590   // jump. This is done to circumvent the ebx/callee-saved problem for tail
1591   // calls on PIC/GOT architectures. Normally we would just put the address of
1592   // GOT into ebx and then call target@PLT. But for tail callss ebx would be
1593   // restored (since ebx is callee saved) before jumping to the target@PLT.
1594   if (CallRequiresFnAddressInReg(Is64Bit, IsTailCall)) {
1595     // Note: The actual moving to ecx is done further down.
1596     GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1597     if (G &&  !G->getGlobal()->hasHiddenVisibility() &&
1598         !G->getGlobal()->hasProtectedVisibility())
1599       Callee =  LowerGlobalAddress(Callee, DAG);
1600     else if (isa<ExternalSymbolSDNode>(Callee))
1601       Callee = LowerExternalSymbol(Callee,DAG);
1602   }
1603
1604   if (Is64Bit && isVarArg) {
1605     // From AMD64 ABI document:
1606     // For calls that may call functions that use varargs or stdargs
1607     // (prototype-less calls or calls to functions containing ellipsis (...) in
1608     // the declaration) %al is used as hidden argument to specify the number
1609     // of SSE registers used. The contents of %al do not need to match exactly
1610     // the number of registers, but must be an ubound on the number of SSE
1611     // registers used and is in the range 0 - 8 inclusive.
1612
1613     // FIXME: Verify this on Win64
1614     // Count the number of XMM registers allocated.
1615     static const unsigned XMMArgRegs[] = {
1616       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1617       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1618     };
1619     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1620     
1621     Chain = DAG.getCopyToReg(Chain, X86::AL,
1622                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1623     InFlag = Chain.getValue(1);
1624   }
1625
1626
1627   // For tail calls lower the arguments to the 'real' stack slot.
1628   if (IsTailCall) {
1629     SmallVector<SDValue, 8> MemOpChains2;
1630     SDValue FIN;
1631     int FI = 0;
1632     // Do not flag preceeding copytoreg stuff together with the following stuff.
1633     InFlag = SDValue();
1634     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1635       CCValAssign &VA = ArgLocs[i];
1636       if (!VA.isRegLoc()) {
1637         assert(VA.isMemLoc());
1638         SDValue Arg = Op.getOperand(5+2*VA.getValNo());
1639         SDValue FlagsOp = Op.getOperand(6+2*VA.getValNo());
1640         ISD::ArgFlagsTy Flags =
1641           cast<ARG_FLAGSSDNode>(FlagsOp)->getArgFlags();
1642         // Create frame index.
1643         int32_t Offset = VA.getLocMemOffset()+FPDiff;
1644         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
1645         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset);
1646         FIN = DAG.getFrameIndex(FI, getPointerTy());
1647
1648         if (Flags.isByVal()) {
1649           // Copy relative to framepointer.
1650           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
1651           if (StackPtr.Val == 0)
1652             StackPtr = DAG.getCopyFromReg(Chain, X86StackPtr, getPointerTy());
1653           Source = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, Source);
1654
1655           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN, Chain,
1656                                                            Flags, DAG));
1657         } else {
1658           // Store relative to framepointer.
1659           MemOpChains2.push_back(
1660             DAG.getStore(Chain, Arg, FIN,
1661                          PseudoSourceValue::getFixedStack(FI), 0));
1662         }            
1663       }
1664     }
1665
1666     if (!MemOpChains2.empty())
1667       Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1668                           &MemOpChains2[0], MemOpChains2.size());
1669
1670     // Copy arguments to their registers.
1671     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1672       Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1673                                InFlag);
1674       InFlag = Chain.getValue(1);
1675     }
1676     InFlag =SDValue();
1677
1678     // Store the return address to the appropriate stack slot.
1679     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
1680                                      FPDiff);
1681   }
1682
1683   // If the callee is a GlobalAddress node (quite common, every direct call is)
1684   // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1685   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1686     // We should use extra load for direct calls to dllimported functions in
1687     // non-JIT mode.
1688     if (!Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1689                                         getTargetMachine(), true))
1690       Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1691   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1692     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1693   } else if (IsTailCall) {
1694     unsigned Opc = Is64Bit ? X86::R9 : X86::ECX;
1695
1696     Chain = DAG.getCopyToReg(Chain, 
1697                              DAG.getRegister(Opc, getPointerTy()), 
1698                              Callee,InFlag);
1699     Callee = DAG.getRegister(Opc, getPointerTy());
1700     // Add register as live out.
1701     DAG.getMachineFunction().getRegInfo().addLiveOut(Opc);
1702   }
1703  
1704   // Returns a chain & a flag for retval copy to use.
1705   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1706   SmallVector<SDValue, 8> Ops;
1707
1708   if (IsTailCall) {
1709     Ops.push_back(Chain);
1710     Ops.push_back(DAG.getIntPtrConstant(NumBytes));
1711     Ops.push_back(DAG.getIntPtrConstant(0));
1712     if (InFlag.Val)
1713       Ops.push_back(InFlag);
1714     Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
1715     InFlag = Chain.getValue(1);
1716  
1717     // Returns a chain & a flag for retval copy to use.
1718     NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1719     Ops.clear();
1720   }
1721   
1722   Ops.push_back(Chain);
1723   Ops.push_back(Callee);
1724
1725   if (IsTailCall)
1726     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
1727
1728   // Add argument registers to the end of the list so that they are known live
1729   // into the call.
1730   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1731     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1732                                   RegsToPass[i].second.getValueType()));
1733   
1734   // Add an implicit use GOT pointer in EBX.
1735   if (!IsTailCall && !Is64Bit &&
1736       getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1737       Subtarget->isPICStyleGOT())
1738     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1739
1740   // Add an implicit use of AL for x86 vararg functions.
1741   if (Is64Bit && isVarArg)
1742     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
1743
1744   if (InFlag.Val)
1745     Ops.push_back(InFlag);
1746
1747   if (IsTailCall) {
1748     assert(InFlag.Val && 
1749            "Flag must be set. Depend on flag being set in LowerRET");
1750     Chain = DAG.getNode(X86ISD::TAILCALL,
1751                         Op.Val->getVTList(), &Ops[0], Ops.size());
1752       
1753     return SDValue(Chain.Val, Op.ResNo);
1754   }
1755
1756   Chain = DAG.getNode(X86ISD::CALL, NodeTys, &Ops[0], Ops.size());
1757   InFlag = Chain.getValue(1);
1758
1759   // Create the CALLSEQ_END node.
1760   unsigned NumBytesForCalleeToPush;
1761   if (IsCalleePop(Op))
1762     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
1763   else if (!Is64Bit && IsStructRet)
1764     // If this is is a call to a struct-return function, the callee
1765     // pops the hidden struct pointer, so we have to push it back.
1766     // This is common for Darwin/X86, Linux & Mingw32 targets.
1767     NumBytesForCalleeToPush = 4;
1768   else
1769     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
1770   
1771   // Returns a flag for retval copy to use.
1772   Chain = DAG.getCALLSEQ_END(Chain,
1773                              DAG.getIntPtrConstant(NumBytes),
1774                              DAG.getIntPtrConstant(NumBytesForCalleeToPush),
1775                              InFlag);
1776   InFlag = Chain.getValue(1);
1777
1778   // Handle result values, copying them out of physregs into vregs that we
1779   // return.
1780   return SDValue(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
1781 }
1782
1783
1784 //===----------------------------------------------------------------------===//
1785 //                Fast Calling Convention (tail call) implementation
1786 //===----------------------------------------------------------------------===//
1787
1788 //  Like std call, callee cleans arguments, convention except that ECX is
1789 //  reserved for storing the tail called function address. Only 2 registers are
1790 //  free for argument passing (inreg). Tail call optimization is performed
1791 //  provided:
1792 //                * tailcallopt is enabled
1793 //                * caller/callee are fastcc
1794 //  On X86_64 architecture with GOT-style position independent code only local
1795 //  (within module) calls are supported at the moment.
1796 //  To keep the stack aligned according to platform abi the function
1797 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
1798 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
1799 //  If a tail called function callee has more arguments than the caller the
1800 //  caller needs to make sure that there is room to move the RETADDR to. This is
1801 //  achieved by reserving an area the size of the argument delta right after the
1802 //  original REtADDR, but before the saved framepointer or the spilled registers
1803 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
1804 //  stack layout:
1805 //    arg1
1806 //    arg2
1807 //    RETADDR
1808 //    [ new RETADDR 
1809 //      move area ]
1810 //    (possible EBP)
1811 //    ESI
1812 //    EDI
1813 //    local1 ..
1814
1815 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
1816 /// for a 16 byte align requirement.
1817 unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize, 
1818                                                         SelectionDAG& DAG) {
1819   if (PerformTailCallOpt) {
1820     MachineFunction &MF = DAG.getMachineFunction();
1821     const TargetMachine &TM = MF.getTarget();
1822     const TargetFrameInfo &TFI = *TM.getFrameInfo();
1823     unsigned StackAlignment = TFI.getStackAlignment();
1824     uint64_t AlignMask = StackAlignment - 1; 
1825     int64_t Offset = StackSize;
1826     unsigned SlotSize = Subtarget->is64Bit() ? 8 : 4;
1827     if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
1828       // Number smaller than 12 so just add the difference.
1829       Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
1830     } else {
1831       // Mask out lower bits, add stackalignment once plus the 12 bytes.
1832       Offset = ((~AlignMask) & Offset) + StackAlignment + 
1833         (StackAlignment-SlotSize);
1834     }
1835     StackSize = Offset;
1836   }
1837   return StackSize;
1838 }
1839
1840 /// IsEligibleForTailCallElimination - Check to see whether the next instruction
1841 /// following the call is a return. A function is eligible if caller/callee
1842 /// calling conventions match, currently only fastcc supports tail calls, and
1843 /// the function CALL is immediatly followed by a RET.
1844 bool X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Call,
1845                                                       SDValue Ret,
1846                                                       SelectionDAG& DAG) const {
1847   if (!PerformTailCallOpt)
1848     return false;
1849
1850   if (CheckTailCallReturnConstraints(Call, Ret)) {
1851     MachineFunction &MF = DAG.getMachineFunction();
1852     unsigned CallerCC = MF.getFunction()->getCallingConv();
1853     unsigned CalleeCC = cast<ConstantSDNode>(Call.getOperand(1))->getValue();
1854     if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
1855       SDValue Callee = Call.getOperand(4);
1856       // On x86/32Bit PIC/GOT  tail calls are supported.
1857       if (getTargetMachine().getRelocationModel() != Reloc::PIC_ ||
1858           !Subtarget->isPICStyleGOT()|| !Subtarget->is64Bit())
1859         return true;
1860
1861       // Can only do local tail calls (in same module, hidden or protected) on
1862       // x86_64 PIC/GOT at the moment.
1863       if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1864         return G->getGlobal()->hasHiddenVisibility()
1865             || G->getGlobal()->hasProtectedVisibility();
1866     }
1867   }
1868
1869   return false;
1870 }
1871
1872 //===----------------------------------------------------------------------===//
1873 //                           Other Lowering Hooks
1874 //===----------------------------------------------------------------------===//
1875
1876
1877 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
1878   MachineFunction &MF = DAG.getMachineFunction();
1879   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1880   int ReturnAddrIndex = FuncInfo->getRAIndex();
1881
1882   if (ReturnAddrIndex == 0) {
1883     // Set up a frame object for the return address.
1884     if (Subtarget->is64Bit())
1885       ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(8, -8);
1886     else
1887       ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(4, -4);
1888
1889     FuncInfo->setRAIndex(ReturnAddrIndex);
1890   }
1891
1892   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
1893 }
1894
1895
1896
1897 /// translateX86CC - do a one to one translation of a ISD::CondCode to the X86
1898 /// specific condition code. It returns a false if it cannot do a direct
1899 /// translation. X86CC is the translated CondCode.  LHS/RHS are modified as
1900 /// needed.
1901 static bool translateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
1902                            unsigned &X86CC, SDValue &LHS, SDValue &RHS,
1903                            SelectionDAG &DAG) {
1904   X86CC = X86::COND_INVALID;
1905   if (!isFP) {
1906     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
1907       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
1908         // X > -1   -> X == 0, jump !sign.
1909         RHS = DAG.getConstant(0, RHS.getValueType());
1910         X86CC = X86::COND_NS;
1911         return true;
1912       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
1913         // X < 0   -> X == 0, jump on sign.
1914         X86CC = X86::COND_S;
1915         return true;
1916       } else if (SetCCOpcode == ISD::SETLT && RHSC->getValue() == 1) {
1917         // X < 1   -> X <= 0
1918         RHS = DAG.getConstant(0, RHS.getValueType());
1919         X86CC = X86::COND_LE;
1920         return true;
1921       }
1922     }
1923
1924     switch (SetCCOpcode) {
1925     default: break;
1926     case ISD::SETEQ:  X86CC = X86::COND_E;  break;
1927     case ISD::SETGT:  X86CC = X86::COND_G;  break;
1928     case ISD::SETGE:  X86CC = X86::COND_GE; break;
1929     case ISD::SETLT:  X86CC = X86::COND_L;  break;
1930     case ISD::SETLE:  X86CC = X86::COND_LE; break;
1931     case ISD::SETNE:  X86CC = X86::COND_NE; break;
1932     case ISD::SETULT: X86CC = X86::COND_B;  break;
1933     case ISD::SETUGT: X86CC = X86::COND_A;  break;
1934     case ISD::SETULE: X86CC = X86::COND_BE; break;
1935     case ISD::SETUGE: X86CC = X86::COND_AE; break;
1936     }
1937   } else {
1938     // On a floating point condition, the flags are set as follows:
1939     // ZF  PF  CF   op
1940     //  0 | 0 | 0 | X > Y
1941     //  0 | 0 | 1 | X < Y
1942     //  1 | 0 | 0 | X == Y
1943     //  1 | 1 | 1 | unordered
1944     bool Flip = false;
1945     switch (SetCCOpcode) {
1946     default: break;
1947     case ISD::SETUEQ:
1948     case ISD::SETEQ: X86CC = X86::COND_E;  break;
1949     case ISD::SETOLT: Flip = true; // Fallthrough
1950     case ISD::SETOGT:
1951     case ISD::SETGT: X86CC = X86::COND_A;  break;
1952     case ISD::SETOLE: Flip = true; // Fallthrough
1953     case ISD::SETOGE:
1954     case ISD::SETGE: X86CC = X86::COND_AE; break;
1955     case ISD::SETUGT: Flip = true; // Fallthrough
1956     case ISD::SETULT:
1957     case ISD::SETLT: X86CC = X86::COND_B;  break;
1958     case ISD::SETUGE: Flip = true; // Fallthrough
1959     case ISD::SETULE:
1960     case ISD::SETLE: X86CC = X86::COND_BE; break;
1961     case ISD::SETONE:
1962     case ISD::SETNE: X86CC = X86::COND_NE; break;
1963     case ISD::SETUO: X86CC = X86::COND_P;  break;
1964     case ISD::SETO:  X86CC = X86::COND_NP; break;
1965     }
1966     if (Flip)
1967       std::swap(LHS, RHS);
1968   }
1969
1970   return X86CC != X86::COND_INVALID;
1971 }
1972
1973 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
1974 /// code. Current x86 isa includes the following FP cmov instructions:
1975 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
1976 static bool hasFPCMov(unsigned X86CC) {
1977   switch (X86CC) {
1978   default:
1979     return false;
1980   case X86::COND_B:
1981   case X86::COND_BE:
1982   case X86::COND_E:
1983   case X86::COND_P:
1984   case X86::COND_A:
1985   case X86::COND_AE:
1986   case X86::COND_NE:
1987   case X86::COND_NP:
1988     return true;
1989   }
1990 }
1991
1992 /// isUndefOrInRange - Op is either an undef node or a ConstantSDNode.  Return
1993 /// true if Op is undef or if its value falls within the specified range (L, H].
1994 static bool isUndefOrInRange(SDValue Op, unsigned Low, unsigned Hi) {
1995   if (Op.getOpcode() == ISD::UNDEF)
1996     return true;
1997
1998   unsigned Val = cast<ConstantSDNode>(Op)->getValue();
1999   return (Val >= Low && Val < Hi);
2000 }
2001
2002 /// isUndefOrEqual - Op is either an undef node or a ConstantSDNode.  Return
2003 /// true if Op is undef or if its value equal to the specified value.
2004 static bool isUndefOrEqual(SDValue Op, unsigned Val) {
2005   if (Op.getOpcode() == ISD::UNDEF)
2006     return true;
2007   return cast<ConstantSDNode>(Op)->getValue() == Val;
2008 }
2009
2010 /// isPSHUFDMask - Return true if the specified VECTOR_SHUFFLE operand
2011 /// specifies a shuffle of elements that is suitable for input to PSHUFD.
2012 bool X86::isPSHUFDMask(SDNode *N) {
2013   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2014
2015   if (N->getNumOperands() != 2 && N->getNumOperands() != 4)
2016     return false;
2017
2018   // Check if the value doesn't reference the second vector.
2019   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2020     SDValue Arg = N->getOperand(i);
2021     if (Arg.getOpcode() == ISD::UNDEF) continue;
2022     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2023     if (cast<ConstantSDNode>(Arg)->getValue() >= e)
2024       return false;
2025   }
2026
2027   return true;
2028 }
2029
2030 /// isPSHUFHWMask - Return true if the specified VECTOR_SHUFFLE operand
2031 /// specifies a shuffle of elements that is suitable for input to PSHUFHW.
2032 bool X86::isPSHUFHWMask(SDNode *N) {
2033   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2034
2035   if (N->getNumOperands() != 8)
2036     return false;
2037
2038   // Lower quadword copied in order.
2039   for (unsigned i = 0; i != 4; ++i) {
2040     SDValue Arg = N->getOperand(i);
2041     if (Arg.getOpcode() == ISD::UNDEF) continue;
2042     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2043     if (cast<ConstantSDNode>(Arg)->getValue() != i)
2044       return false;
2045   }
2046
2047   // Upper quadword shuffled.
2048   for (unsigned i = 4; i != 8; ++i) {
2049     SDValue Arg = N->getOperand(i);
2050     if (Arg.getOpcode() == ISD::UNDEF) continue;
2051     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2052     unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2053     if (Val < 4 || Val > 7)
2054       return false;
2055   }
2056
2057   return true;
2058 }
2059
2060 /// isPSHUFLWMask - Return true if the specified VECTOR_SHUFFLE operand
2061 /// specifies a shuffle of elements that is suitable for input to PSHUFLW.
2062 bool X86::isPSHUFLWMask(SDNode *N) {
2063   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2064
2065   if (N->getNumOperands() != 8)
2066     return false;
2067
2068   // Upper quadword copied in order.
2069   for (unsigned i = 4; i != 8; ++i)
2070     if (!isUndefOrEqual(N->getOperand(i), i))
2071       return false;
2072
2073   // Lower quadword shuffled.
2074   for (unsigned i = 0; i != 4; ++i)
2075     if (!isUndefOrInRange(N->getOperand(i), 0, 4))
2076       return false;
2077
2078   return true;
2079 }
2080
2081 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2082 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2083 static bool isSHUFPMask(SDOperandPtr Elems, unsigned NumElems) {
2084   if (NumElems != 2 && NumElems != 4) return false;
2085
2086   unsigned Half = NumElems / 2;
2087   for (unsigned i = 0; i < Half; ++i)
2088     if (!isUndefOrInRange(Elems[i], 0, NumElems))
2089       return false;
2090   for (unsigned i = Half; i < NumElems; ++i)
2091     if (!isUndefOrInRange(Elems[i], NumElems, NumElems*2))
2092       return false;
2093
2094   return true;
2095 }
2096
2097 bool X86::isSHUFPMask(SDNode *N) {
2098   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2099   return ::isSHUFPMask(N->op_begin(), N->getNumOperands());
2100 }
2101
2102 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2103 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2104 /// half elements to come from vector 1 (which would equal the dest.) and
2105 /// the upper half to come from vector 2.
2106 static bool isCommutedSHUFP(SDOperandPtr Ops, unsigned NumOps) {
2107   if (NumOps != 2 && NumOps != 4) return false;
2108
2109   unsigned Half = NumOps / 2;
2110   for (unsigned i = 0; i < Half; ++i)
2111     if (!isUndefOrInRange(Ops[i], NumOps, NumOps*2))
2112       return false;
2113   for (unsigned i = Half; i < NumOps; ++i)
2114     if (!isUndefOrInRange(Ops[i], 0, NumOps))
2115       return false;
2116   return true;
2117 }
2118
2119 static bool isCommutedSHUFP(SDNode *N) {
2120   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2121   return isCommutedSHUFP(N->op_begin(), N->getNumOperands());
2122 }
2123
2124 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2125 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2126 bool X86::isMOVHLPSMask(SDNode *N) {
2127   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2128
2129   if (N->getNumOperands() != 4)
2130     return false;
2131
2132   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2133   return isUndefOrEqual(N->getOperand(0), 6) &&
2134          isUndefOrEqual(N->getOperand(1), 7) &&
2135          isUndefOrEqual(N->getOperand(2), 2) &&
2136          isUndefOrEqual(N->getOperand(3), 3);
2137 }
2138
2139 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2140 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2141 /// <2, 3, 2, 3>
2142 bool X86::isMOVHLPS_v_undef_Mask(SDNode *N) {
2143   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2144
2145   if (N->getNumOperands() != 4)
2146     return false;
2147
2148   // Expect bit0 == 2, bit1 == 3, bit2 == 2, bit3 == 3
2149   return isUndefOrEqual(N->getOperand(0), 2) &&
2150          isUndefOrEqual(N->getOperand(1), 3) &&
2151          isUndefOrEqual(N->getOperand(2), 2) &&
2152          isUndefOrEqual(N->getOperand(3), 3);
2153 }
2154
2155 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2156 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2157 bool X86::isMOVLPMask(SDNode *N) {
2158   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2159
2160   unsigned NumElems = N->getNumOperands();
2161   if (NumElems != 2 && NumElems != 4)
2162     return false;
2163
2164   for (unsigned i = 0; i < NumElems/2; ++i)
2165     if (!isUndefOrEqual(N->getOperand(i), i + NumElems))
2166       return false;
2167
2168   for (unsigned i = NumElems/2; i < NumElems; ++i)
2169     if (!isUndefOrEqual(N->getOperand(i), i))
2170       return false;
2171
2172   return true;
2173 }
2174
2175 /// isMOVHPMask - Return true if the specified VECTOR_SHUFFLE operand
2176 /// specifies a shuffle of elements that is suitable for input to MOVHP{S|D}
2177 /// and MOVLHPS.
2178 bool X86::isMOVHPMask(SDNode *N) {
2179   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2180
2181   unsigned NumElems = N->getNumOperands();
2182   if (NumElems != 2 && NumElems != 4)
2183     return false;
2184
2185   for (unsigned i = 0; i < NumElems/2; ++i)
2186     if (!isUndefOrEqual(N->getOperand(i), i))
2187       return false;
2188
2189   for (unsigned i = 0; i < NumElems/2; ++i) {
2190     SDValue Arg = N->getOperand(i + NumElems/2);
2191     if (!isUndefOrEqual(Arg, i + NumElems))
2192       return false;
2193   }
2194
2195   return true;
2196 }
2197
2198 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2199 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2200 bool static isUNPCKLMask(SDOperandPtr Elts, unsigned NumElts,
2201                          bool V2IsSplat = false) {
2202   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2203     return false;
2204
2205   for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2206     SDValue BitI  = Elts[i];
2207     SDValue BitI1 = Elts[i+1];
2208     if (!isUndefOrEqual(BitI, j))
2209       return false;
2210     if (V2IsSplat) {
2211       if (isUndefOrEqual(BitI1, NumElts))
2212         return false;
2213     } else {
2214       if (!isUndefOrEqual(BitI1, j + NumElts))
2215         return false;
2216     }
2217   }
2218
2219   return true;
2220 }
2221
2222 bool X86::isUNPCKLMask(SDNode *N, bool V2IsSplat) {
2223   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2224   return ::isUNPCKLMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2225 }
2226
2227 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2228 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2229 bool static isUNPCKHMask(SDOperandPtr Elts, unsigned NumElts,
2230                          bool V2IsSplat = false) {
2231   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2232     return false;
2233
2234   for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2235     SDValue BitI  = Elts[i];
2236     SDValue BitI1 = Elts[i+1];
2237     if (!isUndefOrEqual(BitI, j + NumElts/2))
2238       return false;
2239     if (V2IsSplat) {
2240       if (isUndefOrEqual(BitI1, NumElts))
2241         return false;
2242     } else {
2243       if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2244         return false;
2245     }
2246   }
2247
2248   return true;
2249 }
2250
2251 bool X86::isUNPCKHMask(SDNode *N, bool V2IsSplat) {
2252   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2253   return ::isUNPCKHMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2254 }
2255
2256 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2257 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2258 /// <0, 0, 1, 1>
2259 bool X86::isUNPCKL_v_undef_Mask(SDNode *N) {
2260   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2261
2262   unsigned NumElems = N->getNumOperands();
2263   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2264     return false;
2265
2266   for (unsigned i = 0, j = 0; i != NumElems; i += 2, ++j) {
2267     SDValue BitI  = N->getOperand(i);
2268     SDValue BitI1 = N->getOperand(i+1);
2269
2270     if (!isUndefOrEqual(BitI, j))
2271       return false;
2272     if (!isUndefOrEqual(BitI1, j))
2273       return false;
2274   }
2275
2276   return true;
2277 }
2278
2279 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2280 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2281 /// <2, 2, 3, 3>
2282 bool X86::isUNPCKH_v_undef_Mask(SDNode *N) {
2283   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2284
2285   unsigned NumElems = N->getNumOperands();
2286   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2287     return false;
2288
2289   for (unsigned i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2290     SDValue BitI  = N->getOperand(i);
2291     SDValue BitI1 = N->getOperand(i + 1);
2292
2293     if (!isUndefOrEqual(BitI, j))
2294       return false;
2295     if (!isUndefOrEqual(BitI1, j))
2296       return false;
2297   }
2298
2299   return true;
2300 }
2301
2302 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2303 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2304 /// MOVSD, and MOVD, i.e. setting the lowest element.
2305 static bool isMOVLMask(SDOperandPtr Elts, unsigned NumElts) {
2306   if (NumElts != 2 && NumElts != 4)
2307     return false;
2308
2309   if (!isUndefOrEqual(Elts[0], NumElts))
2310     return false;
2311
2312   for (unsigned i = 1; i < NumElts; ++i) {
2313     if (!isUndefOrEqual(Elts[i], i))
2314       return false;
2315   }
2316
2317   return true;
2318 }
2319
2320 bool X86::isMOVLMask(SDNode *N) {
2321   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2322   return ::isMOVLMask(N->op_begin(), N->getNumOperands());
2323 }
2324
2325 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2326 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
2327 /// element of vector 2 and the other elements to come from vector 1 in order.
2328 static bool isCommutedMOVL(SDOperandPtr Ops, unsigned NumOps,
2329                            bool V2IsSplat = false,
2330                            bool V2IsUndef = false) {
2331   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2332     return false;
2333
2334   if (!isUndefOrEqual(Ops[0], 0))
2335     return false;
2336
2337   for (unsigned i = 1; i < NumOps; ++i) {
2338     SDValue Arg = Ops[i];
2339     if (!(isUndefOrEqual(Arg, i+NumOps) ||
2340           (V2IsUndef && isUndefOrInRange(Arg, NumOps, NumOps*2)) ||
2341           (V2IsSplat && isUndefOrEqual(Arg, NumOps))))
2342       return false;
2343   }
2344
2345   return true;
2346 }
2347
2348 static bool isCommutedMOVL(SDNode *N, bool V2IsSplat = false,
2349                            bool V2IsUndef = false) {
2350   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2351   return isCommutedMOVL(N->op_begin(), N->getNumOperands(),
2352                         V2IsSplat, V2IsUndef);
2353 }
2354
2355 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2356 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2357 bool X86::isMOVSHDUPMask(SDNode *N) {
2358   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2359
2360   if (N->getNumOperands() != 4)
2361     return false;
2362
2363   // Expect 1, 1, 3, 3
2364   for (unsigned i = 0; i < 2; ++i) {
2365     SDValue Arg = N->getOperand(i);
2366     if (Arg.getOpcode() == ISD::UNDEF) continue;
2367     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2368     unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2369     if (Val != 1) return false;
2370   }
2371
2372   bool HasHi = false;
2373   for (unsigned i = 2; i < 4; ++i) {
2374     SDValue Arg = N->getOperand(i);
2375     if (Arg.getOpcode() == ISD::UNDEF) continue;
2376     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2377     unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2378     if (Val != 3) return false;
2379     HasHi = true;
2380   }
2381
2382   // Don't use movshdup if it can be done with a shufps.
2383   return HasHi;
2384 }
2385
2386 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2387 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2388 bool X86::isMOVSLDUPMask(SDNode *N) {
2389   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2390
2391   if (N->getNumOperands() != 4)
2392     return false;
2393
2394   // Expect 0, 0, 2, 2
2395   for (unsigned i = 0; i < 2; ++i) {
2396     SDValue Arg = N->getOperand(i);
2397     if (Arg.getOpcode() == ISD::UNDEF) continue;
2398     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2399     unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2400     if (Val != 0) return false;
2401   }
2402
2403   bool HasHi = false;
2404   for (unsigned i = 2; i < 4; ++i) {
2405     SDValue Arg = N->getOperand(i);
2406     if (Arg.getOpcode() == ISD::UNDEF) continue;
2407     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2408     unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2409     if (Val != 2) return false;
2410     HasHi = true;
2411   }
2412
2413   // Don't use movshdup if it can be done with a shufps.
2414   return HasHi;
2415 }
2416
2417 /// isIdentityMask - Return true if the specified VECTOR_SHUFFLE operand
2418 /// specifies a identity operation on the LHS or RHS.
2419 static bool isIdentityMask(SDNode *N, bool RHS = false) {
2420   unsigned NumElems = N->getNumOperands();
2421   for (unsigned i = 0; i < NumElems; ++i)
2422     if (!isUndefOrEqual(N->getOperand(i), i + (RHS ? NumElems : 0)))
2423       return false;
2424   return true;
2425 }
2426
2427 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2428 /// a splat of a single element.
2429 static bool isSplatMask(SDNode *N) {
2430   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2431
2432   // This is a splat operation if each element of the permute is the same, and
2433   // if the value doesn't reference the second vector.
2434   unsigned NumElems = N->getNumOperands();
2435   SDValue ElementBase;
2436   unsigned i = 0;
2437   for (; i != NumElems; ++i) {
2438     SDValue Elt = N->getOperand(i);
2439     if (isa<ConstantSDNode>(Elt)) {
2440       ElementBase = Elt;
2441       break;
2442     }
2443   }
2444
2445   if (!ElementBase.Val)
2446     return false;
2447
2448   for (; i != NumElems; ++i) {
2449     SDValue Arg = N->getOperand(i);
2450     if (Arg.getOpcode() == ISD::UNDEF) continue;
2451     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2452     if (Arg != ElementBase) return false;
2453   }
2454
2455   // Make sure it is a splat of the first vector operand.
2456   return cast<ConstantSDNode>(ElementBase)->getValue() < NumElems;
2457 }
2458
2459 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2460 /// a splat of a single element and it's a 2 or 4 element mask.
2461 bool X86::isSplatMask(SDNode *N) {
2462   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2463
2464   // We can only splat 64-bit, and 32-bit quantities with a single instruction.
2465   if (N->getNumOperands() != 4 && N->getNumOperands() != 2)
2466     return false;
2467   return ::isSplatMask(N);
2468 }
2469
2470 /// isSplatLoMask - Return true if the specified VECTOR_SHUFFLE operand
2471 /// specifies a splat of zero element.
2472 bool X86::isSplatLoMask(SDNode *N) {
2473   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2474
2475   for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i)
2476     if (!isUndefOrEqual(N->getOperand(i), 0))
2477       return false;
2478   return true;
2479 }
2480
2481 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2482 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUF* and SHUFP*
2483 /// instructions.
2484 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2485   unsigned NumOperands = N->getNumOperands();
2486   unsigned Shift = (NumOperands == 4) ? 2 : 1;
2487   unsigned Mask = 0;
2488   for (unsigned i = 0; i < NumOperands; ++i) {
2489     unsigned Val = 0;
2490     SDValue Arg = N->getOperand(NumOperands-i-1);
2491     if (Arg.getOpcode() != ISD::UNDEF)
2492       Val = cast<ConstantSDNode>(Arg)->getValue();
2493     if (Val >= NumOperands) Val -= NumOperands;
2494     Mask |= Val;
2495     if (i != NumOperands - 1)
2496       Mask <<= Shift;
2497   }
2498
2499   return Mask;
2500 }
2501
2502 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2503 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFHW
2504 /// instructions.
2505 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2506   unsigned Mask = 0;
2507   // 8 nodes, but we only care about the last 4.
2508   for (unsigned i = 7; i >= 4; --i) {
2509     unsigned Val = 0;
2510     SDValue Arg = N->getOperand(i);
2511     if (Arg.getOpcode() != ISD::UNDEF)
2512       Val = cast<ConstantSDNode>(Arg)->getValue();
2513     Mask |= (Val - 4);
2514     if (i != 4)
2515       Mask <<= 2;
2516   }
2517
2518   return Mask;
2519 }
2520
2521 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2522 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFLW
2523 /// instructions.
2524 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2525   unsigned Mask = 0;
2526   // 8 nodes, but we only care about the first 4.
2527   for (int i = 3; i >= 0; --i) {
2528     unsigned Val = 0;
2529     SDValue Arg = N->getOperand(i);
2530     if (Arg.getOpcode() != ISD::UNDEF)
2531       Val = cast<ConstantSDNode>(Arg)->getValue();
2532     Mask |= Val;
2533     if (i != 0)
2534       Mask <<= 2;
2535   }
2536
2537   return Mask;
2538 }
2539
2540 /// isPSHUFHW_PSHUFLWMask - true if the specified VECTOR_SHUFFLE operand
2541 /// specifies a 8 element shuffle that can be broken into a pair of
2542 /// PSHUFHW and PSHUFLW.
2543 static bool isPSHUFHW_PSHUFLWMask(SDNode *N) {
2544   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2545
2546   if (N->getNumOperands() != 8)
2547     return false;
2548
2549   // Lower quadword shuffled.
2550   for (unsigned i = 0; i != 4; ++i) {
2551     SDValue Arg = N->getOperand(i);
2552     if (Arg.getOpcode() == ISD::UNDEF) continue;
2553     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2554     unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2555     if (Val >= 4)
2556       return false;
2557   }
2558
2559   // Upper quadword shuffled.
2560   for (unsigned i = 4; i != 8; ++i) {
2561     SDValue Arg = N->getOperand(i);
2562     if (Arg.getOpcode() == ISD::UNDEF) continue;
2563     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2564     unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2565     if (Val < 4 || Val > 7)
2566       return false;
2567   }
2568
2569   return true;
2570 }
2571
2572 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as
2573 /// values in ther permute mask.
2574 static SDValue CommuteVectorShuffle(SDValue Op, SDValue &V1,
2575                                       SDValue &V2, SDValue &Mask,
2576                                       SelectionDAG &DAG) {
2577   MVT VT = Op.getValueType();
2578   MVT MaskVT = Mask.getValueType();
2579   MVT EltVT = MaskVT.getVectorElementType();
2580   unsigned NumElems = Mask.getNumOperands();
2581   SmallVector<SDValue, 8> MaskVec;
2582
2583   for (unsigned i = 0; i != NumElems; ++i) {
2584     SDValue Arg = Mask.getOperand(i);
2585     if (Arg.getOpcode() == ISD::UNDEF) {
2586       MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2587       continue;
2588     }
2589     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2590     unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2591     if (Val < NumElems)
2592       MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2593     else
2594       MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2595   }
2596
2597   std::swap(V1, V2);
2598   Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
2599   return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2600 }
2601
2602 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
2603 /// the two vector operands have swapped position.
2604 static
2605 SDValue CommuteVectorShuffleMask(SDValue Mask, SelectionDAG &DAG) {
2606   MVT MaskVT = Mask.getValueType();
2607   MVT EltVT = MaskVT.getVectorElementType();
2608   unsigned NumElems = Mask.getNumOperands();
2609   SmallVector<SDValue, 8> MaskVec;
2610   for (unsigned i = 0; i != NumElems; ++i) {
2611     SDValue Arg = Mask.getOperand(i);
2612     if (Arg.getOpcode() == ISD::UNDEF) {
2613       MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2614       continue;
2615     }
2616     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2617     unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2618     if (Val < NumElems)
2619       MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2620     else
2621       MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2622   }
2623   return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
2624 }
2625
2626
2627 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2628 /// match movhlps. The lower half elements should come from upper half of
2629 /// V1 (and in order), and the upper half elements should come from the upper
2630 /// half of V2 (and in order).
2631 static bool ShouldXformToMOVHLPS(SDNode *Mask) {
2632   unsigned NumElems = Mask->getNumOperands();
2633   if (NumElems != 4)
2634     return false;
2635   for (unsigned i = 0, e = 2; i != e; ++i)
2636     if (!isUndefOrEqual(Mask->getOperand(i), i+2))
2637       return false;
2638   for (unsigned i = 2; i != 4; ++i)
2639     if (!isUndefOrEqual(Mask->getOperand(i), i+4))
2640       return false;
2641   return true;
2642 }
2643
2644 /// isScalarLoadToVector - Returns true if the node is a scalar load that
2645 /// is promoted to a vector. It also returns the LoadSDNode by reference if
2646 /// required.
2647 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
2648   if (N->getOpcode() == ISD::SCALAR_TO_VECTOR) {
2649     N = N->getOperand(0).Val;
2650     if (ISD::isNON_EXTLoad(N)) {
2651       if (LD)
2652         *LD = cast<LoadSDNode>(N);
2653       return true;
2654     }
2655   }
2656   return false;
2657 }
2658
2659 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
2660 /// match movlp{s|d}. The lower half elements should come from lower half of
2661 /// V1 (and in order), and the upper half elements should come from the upper
2662 /// half of V2 (and in order). And since V1 will become the source of the
2663 /// MOVLP, it must be either a vector load or a scalar load to vector.
2664 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2, SDNode *Mask) {
2665   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
2666     return false;
2667   // Is V2 is a vector load, don't do this transformation. We will try to use
2668   // load folding shufps op.
2669   if (ISD::isNON_EXTLoad(V2))
2670     return false;
2671
2672   unsigned NumElems = Mask->getNumOperands();
2673   if (NumElems != 2 && NumElems != 4)
2674     return false;
2675   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
2676     if (!isUndefOrEqual(Mask->getOperand(i), i))
2677       return false;
2678   for (unsigned i = NumElems/2; i != NumElems; ++i)
2679     if (!isUndefOrEqual(Mask->getOperand(i), i+NumElems))
2680       return false;
2681   return true;
2682 }
2683
2684 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
2685 /// all the same.
2686 static bool isSplatVector(SDNode *N) {
2687   if (N->getOpcode() != ISD::BUILD_VECTOR)
2688     return false;
2689
2690   SDValue SplatValue = N->getOperand(0);
2691   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
2692     if (N->getOperand(i) != SplatValue)
2693       return false;
2694   return true;
2695 }
2696
2697 /// isUndefShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2698 /// to an undef.
2699 static bool isUndefShuffle(SDNode *N) {
2700   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2701     return false;
2702
2703   SDValue V1 = N->getOperand(0);
2704   SDValue V2 = N->getOperand(1);
2705   SDValue Mask = N->getOperand(2);
2706   unsigned NumElems = Mask.getNumOperands();
2707   for (unsigned i = 0; i != NumElems; ++i) {
2708     SDValue Arg = Mask.getOperand(i);
2709     if (Arg.getOpcode() != ISD::UNDEF) {
2710       unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2711       if (Val < NumElems && V1.getOpcode() != ISD::UNDEF)
2712         return false;
2713       else if (Val >= NumElems && V2.getOpcode() != ISD::UNDEF)
2714         return false;
2715     }
2716   }
2717   return true;
2718 }
2719
2720 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
2721 /// constant +0.0.
2722 static inline bool isZeroNode(SDValue Elt) {
2723   return ((isa<ConstantSDNode>(Elt) &&
2724            cast<ConstantSDNode>(Elt)->getValue() == 0) ||
2725           (isa<ConstantFPSDNode>(Elt) &&
2726            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
2727 }
2728
2729 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2730 /// to an zero vector.
2731 static bool isZeroShuffle(SDNode *N) {
2732   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2733     return false;
2734
2735   SDValue V1 = N->getOperand(0);
2736   SDValue V2 = N->getOperand(1);
2737   SDValue Mask = N->getOperand(2);
2738   unsigned NumElems = Mask.getNumOperands();
2739   for (unsigned i = 0; i != NumElems; ++i) {
2740     SDValue Arg = Mask.getOperand(i);
2741     if (Arg.getOpcode() == ISD::UNDEF)
2742       continue;
2743     
2744     unsigned Idx = cast<ConstantSDNode>(Arg)->getValue();
2745     if (Idx < NumElems) {
2746       unsigned Opc = V1.Val->getOpcode();
2747       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.Val))
2748         continue;
2749       if (Opc != ISD::BUILD_VECTOR ||
2750           !isZeroNode(V1.Val->getOperand(Idx)))
2751         return false;
2752     } else if (Idx >= NumElems) {
2753       unsigned Opc = V2.Val->getOpcode();
2754       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.Val))
2755         continue;
2756       if (Opc != ISD::BUILD_VECTOR ||
2757           !isZeroNode(V2.Val->getOperand(Idx - NumElems)))
2758         return false;
2759     }
2760   }
2761   return true;
2762 }
2763
2764 /// getZeroVector - Returns a vector of specified type with all zero elements.
2765 ///
2766 static SDValue getZeroVector(MVT VT, bool HasSSE2, SelectionDAG &DAG) {
2767   assert(VT.isVector() && "Expected a vector type");
2768   
2769   // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2770   // type.  This ensures they get CSE'd.
2771   SDValue Vec;
2772   if (VT.getSizeInBits() == 64) { // MMX
2773     SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
2774     Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
2775   } else if (HasSSE2) {  // SSE2
2776     SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
2777     Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
2778   } else { // SSE1
2779     SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
2780     Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4f32, Cst, Cst, Cst, Cst);
2781   }
2782   return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
2783 }
2784
2785 /// getOnesVector - Returns a vector of specified type with all bits set.
2786 ///
2787 static SDValue getOnesVector(MVT VT, SelectionDAG &DAG) {
2788   assert(VT.isVector() && "Expected a vector type");
2789   
2790   // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2791   // type.  This ensures they get CSE'd.
2792   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
2793   SDValue Vec;
2794   if (VT.getSizeInBits() == 64)  // MMX
2795     Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
2796   else                                              // SSE
2797     Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
2798   return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
2799 }
2800
2801
2802 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
2803 /// that point to V2 points to its first element.
2804 static SDValue NormalizeMask(SDValue Mask, SelectionDAG &DAG) {
2805   assert(Mask.getOpcode() == ISD::BUILD_VECTOR);
2806
2807   bool Changed = false;
2808   SmallVector<SDValue, 8> MaskVec;
2809   unsigned NumElems = Mask.getNumOperands();
2810   for (unsigned i = 0; i != NumElems; ++i) {
2811     SDValue Arg = Mask.getOperand(i);
2812     if (Arg.getOpcode() != ISD::UNDEF) {
2813       unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2814       if (Val > NumElems) {
2815         Arg = DAG.getConstant(NumElems, Arg.getValueType());
2816         Changed = true;
2817       }
2818     }
2819     MaskVec.push_back(Arg);
2820   }
2821
2822   if (Changed)
2823     Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getValueType(),
2824                        &MaskVec[0], MaskVec.size());
2825   return Mask;
2826 }
2827
2828 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
2829 /// operation of specified width.
2830 static SDValue getMOVLMask(unsigned NumElems, SelectionDAG &DAG) {
2831   MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2832   MVT BaseVT = MaskVT.getVectorElementType();
2833
2834   SmallVector<SDValue, 8> MaskVec;
2835   MaskVec.push_back(DAG.getConstant(NumElems, BaseVT));
2836   for (unsigned i = 1; i != NumElems; ++i)
2837     MaskVec.push_back(DAG.getConstant(i, BaseVT));
2838   return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2839 }
2840
2841 /// getUnpacklMask - Returns a vector_shuffle mask for an unpackl operation
2842 /// of specified width.
2843 static SDValue getUnpacklMask(unsigned NumElems, SelectionDAG &DAG) {
2844   MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2845   MVT BaseVT = MaskVT.getVectorElementType();
2846   SmallVector<SDValue, 8> MaskVec;
2847   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
2848     MaskVec.push_back(DAG.getConstant(i,            BaseVT));
2849     MaskVec.push_back(DAG.getConstant(i + NumElems, BaseVT));
2850   }
2851   return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2852 }
2853
2854 /// getUnpackhMask - Returns a vector_shuffle mask for an unpackh operation
2855 /// of specified width.
2856 static SDValue getUnpackhMask(unsigned NumElems, SelectionDAG &DAG) {
2857   MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2858   MVT BaseVT = MaskVT.getVectorElementType();
2859   unsigned Half = NumElems/2;
2860   SmallVector<SDValue, 8> MaskVec;
2861   for (unsigned i = 0; i != Half; ++i) {
2862     MaskVec.push_back(DAG.getConstant(i + Half,            BaseVT));
2863     MaskVec.push_back(DAG.getConstant(i + NumElems + Half, BaseVT));
2864   }
2865   return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2866 }
2867
2868 /// getSwapEltZeroMask - Returns a vector_shuffle mask for a shuffle that swaps
2869 /// element #0 of a vector with the specified index, leaving the rest of the
2870 /// elements in place.
2871 static SDValue getSwapEltZeroMask(unsigned NumElems, unsigned DestElt,
2872                                    SelectionDAG &DAG) {
2873   MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2874   MVT BaseVT = MaskVT.getVectorElementType();
2875   SmallVector<SDValue, 8> MaskVec;
2876   // Element #0 of the result gets the elt we are replacing.
2877   MaskVec.push_back(DAG.getConstant(DestElt, BaseVT));
2878   for (unsigned i = 1; i != NumElems; ++i)
2879     MaskVec.push_back(DAG.getConstant(i == DestElt ? 0 : i, BaseVT));
2880   return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2881 }
2882
2883 /// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
2884 static SDValue PromoteSplat(SDValue Op, SelectionDAG &DAG, bool HasSSE2) {
2885   MVT PVT = HasSSE2 ? MVT::v4i32 : MVT::v4f32;
2886   MVT VT = Op.getValueType();
2887   if (PVT == VT)
2888     return Op;
2889   SDValue V1 = Op.getOperand(0);
2890   SDValue Mask = Op.getOperand(2);
2891   unsigned NumElems = Mask.getNumOperands();
2892   // Special handling of v4f32 -> v4i32.
2893   if (VT != MVT::v4f32) {
2894     Mask = getUnpacklMask(NumElems, DAG);
2895     while (NumElems > 4) {
2896       V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1, Mask);
2897       NumElems >>= 1;
2898     }
2899     Mask = getZeroVector(MVT::v4i32, true, DAG);
2900   }
2901
2902   V1 = DAG.getNode(ISD::BIT_CONVERT, PVT, V1);
2903   SDValue Shuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, PVT, V1,
2904                                   DAG.getNode(ISD::UNDEF, PVT), Mask);
2905   return DAG.getNode(ISD::BIT_CONVERT, VT, Shuffle);
2906 }
2907
2908 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
2909 /// vector of zero or undef vector.  This produces a shuffle where the low
2910 /// element of V2 is swizzled into the zero/undef vector, landing at element
2911 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
2912 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
2913                                              bool isZero, bool HasSSE2,
2914                                              SelectionDAG &DAG) {
2915   MVT VT = V2.getValueType();
2916   SDValue V1 = isZero
2917     ? getZeroVector(VT, HasSSE2, DAG) : DAG.getNode(ISD::UNDEF, VT);
2918   unsigned NumElems = V2.getValueType().getVectorNumElements();
2919   MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2920   MVT EVT = MaskVT.getVectorElementType();
2921   SmallVector<SDValue, 16> MaskVec;
2922   for (unsigned i = 0; i != NumElems; ++i)
2923     if (i == Idx)  // If this is the insertion idx, put the low elt of V2 here.
2924       MaskVec.push_back(DAG.getConstant(NumElems, EVT));
2925     else
2926       MaskVec.push_back(DAG.getConstant(i, EVT));
2927   SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2928                                &MaskVec[0], MaskVec.size());
2929   return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2930 }
2931
2932 /// getNumOfConsecutiveZeros - Return the number of elements in a result of
2933 /// a shuffle that is zero.
2934 static
2935 unsigned getNumOfConsecutiveZeros(SDValue Op, SDValue Mask,
2936                                   unsigned NumElems, bool Low,
2937                                   SelectionDAG &DAG) {
2938   unsigned NumZeros = 0;
2939   for (unsigned i = 0; i < NumElems; ++i) {
2940     unsigned Index = Low ? i : NumElems-i-1;
2941     SDValue Idx = Mask.getOperand(Index);
2942     if (Idx.getOpcode() == ISD::UNDEF) {
2943       ++NumZeros;
2944       continue;
2945     }
2946     SDValue Elt = DAG.getShuffleScalarElt(Op.Val, Index);
2947     if (Elt.Val && isZeroNode(Elt))
2948       ++NumZeros;
2949     else
2950       break;
2951   }
2952   return NumZeros;
2953 }
2954
2955 /// isVectorShift - Returns true if the shuffle can be implemented as a
2956 /// logical left or right shift of a vector.
2957 static bool isVectorShift(SDValue Op, SDValue Mask, SelectionDAG &DAG,
2958                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
2959   unsigned NumElems = Mask.getNumOperands();
2960
2961   isLeft = true;
2962   unsigned NumZeros= getNumOfConsecutiveZeros(Op, Mask, NumElems, true, DAG);
2963   if (!NumZeros) {
2964     isLeft = false;
2965     NumZeros = getNumOfConsecutiveZeros(Op, Mask, NumElems, false, DAG);
2966     if (!NumZeros)
2967       return false;
2968   }
2969
2970   bool SeenV1 = false;
2971   bool SeenV2 = false;
2972   for (unsigned i = NumZeros; i < NumElems; ++i) {
2973     unsigned Val = isLeft ? (i - NumZeros) : i;
2974     SDValue Idx = Mask.getOperand(isLeft ? i : (i - NumZeros));
2975     if (Idx.getOpcode() == ISD::UNDEF)
2976       continue;
2977     unsigned Index = cast<ConstantSDNode>(Idx)->getValue();
2978     if (Index < NumElems)
2979       SeenV1 = true;
2980     else {
2981       Index -= NumElems;
2982       SeenV2 = true;
2983     }
2984     if (Index != Val)
2985       return false;
2986   }
2987   if (SeenV1 && SeenV2)
2988     return false;
2989
2990   ShVal = SeenV1 ? Op.getOperand(0) : Op.getOperand(1);
2991   ShAmt = NumZeros;
2992   return true;
2993 }
2994
2995
2996 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
2997 ///
2998 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
2999                                        unsigned NumNonZero, unsigned NumZero,
3000                                        SelectionDAG &DAG, TargetLowering &TLI) {
3001   if (NumNonZero > 8)
3002     return SDValue();
3003
3004   SDValue V(0, 0);
3005   bool First = true;
3006   for (unsigned i = 0; i < 16; ++i) {
3007     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3008     if (ThisIsNonZero && First) {
3009       if (NumZero)
3010         V = getZeroVector(MVT::v8i16, true, DAG);
3011       else
3012         V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
3013       First = false;
3014     }
3015
3016     if ((i & 1) != 0) {
3017       SDValue ThisElt(0, 0), LastElt(0, 0);
3018       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3019       if (LastIsNonZero) {
3020         LastElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i-1));
3021       }
3022       if (ThisIsNonZero) {
3023         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i));
3024         ThisElt = DAG.getNode(ISD::SHL, MVT::i16,
3025                               ThisElt, DAG.getConstant(8, MVT::i8));
3026         if (LastIsNonZero)
3027           ThisElt = DAG.getNode(ISD::OR, MVT::i16, ThisElt, LastElt);
3028       } else
3029         ThisElt = LastElt;
3030
3031       if (ThisElt.Val)
3032         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, ThisElt,
3033                         DAG.getIntPtrConstant(i/2));
3034     }
3035   }
3036
3037   return DAG.getNode(ISD::BIT_CONVERT, MVT::v16i8, V);
3038 }
3039
3040 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3041 ///
3042 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3043                                        unsigned NumNonZero, unsigned NumZero,
3044                                        SelectionDAG &DAG, TargetLowering &TLI) {
3045   if (NumNonZero > 4)
3046     return SDValue();
3047
3048   SDValue V(0, 0);
3049   bool First = true;
3050   for (unsigned i = 0; i < 8; ++i) {
3051     bool isNonZero = (NonZeros & (1 << i)) != 0;
3052     if (isNonZero) {
3053       if (First) {
3054         if (NumZero)
3055           V = getZeroVector(MVT::v8i16, true, DAG);
3056         else
3057           V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
3058         First = false;
3059       }
3060       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, Op.getOperand(i),
3061                       DAG.getIntPtrConstant(i));
3062     }
3063   }
3064
3065   return V;
3066 }
3067
3068 /// getVShift - Return a vector logical shift node.
3069 ///
3070 static SDValue getVShift(bool isLeft, MVT VT, SDValue SrcOp,
3071                            unsigned NumBits, SelectionDAG &DAG,
3072                            const TargetLowering &TLI) {
3073   bool isMMX = VT.getSizeInBits() == 64;
3074   MVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
3075   unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3076   SrcOp = DAG.getNode(ISD::BIT_CONVERT, ShVT, SrcOp);
3077   return DAG.getNode(ISD::BIT_CONVERT, VT,
3078                      DAG.getNode(Opc, ShVT, SrcOp,
3079                               DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3080 }
3081
3082 SDValue
3083 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) {
3084   // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3085   if (ISD::isBuildVectorAllZeros(Op.Val) || ISD::isBuildVectorAllOnes(Op.Val)) {
3086     // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3087     // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3088     // eliminated on x86-32 hosts.
3089     if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3090       return Op;
3091
3092     if (ISD::isBuildVectorAllOnes(Op.Val))
3093       return getOnesVector(Op.getValueType(), DAG);
3094     return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG);
3095   }
3096
3097   MVT VT = Op.getValueType();
3098   MVT EVT = VT.getVectorElementType();
3099   unsigned EVTBits = EVT.getSizeInBits();
3100
3101   unsigned NumElems = Op.getNumOperands();
3102   unsigned NumZero  = 0;
3103   unsigned NumNonZero = 0;
3104   unsigned NonZeros = 0;
3105   bool IsAllConstants = true;
3106   SmallSet<SDValue, 8> Values;
3107   for (unsigned i = 0; i < NumElems; ++i) {
3108     SDValue Elt = Op.getOperand(i);
3109     if (Elt.getOpcode() == ISD::UNDEF)
3110       continue;
3111     Values.insert(Elt);
3112     if (Elt.getOpcode() != ISD::Constant &&
3113         Elt.getOpcode() != ISD::ConstantFP)
3114       IsAllConstants = false;
3115     if (isZeroNode(Elt))
3116       NumZero++;
3117     else {
3118       NonZeros |= (1 << i);
3119       NumNonZero++;
3120     }
3121   }
3122
3123   if (NumNonZero == 0) {
3124     // All undef vector. Return an UNDEF.  All zero vectors were handled above.
3125     return DAG.getNode(ISD::UNDEF, VT);
3126   }
3127
3128   // Special case for single non-zero, non-undef, element.
3129   if (NumNonZero == 1 && NumElems <= 4) {
3130     unsigned Idx = CountTrailingZeros_32(NonZeros);
3131     SDValue Item = Op.getOperand(Idx);
3132     
3133     // If this is an insertion of an i64 value on x86-32, and if the top bits of
3134     // the value are obviously zero, truncate the value to i32 and do the
3135     // insertion that way.  Only do this if the value is non-constant or if the
3136     // value is a constant being inserted into element 0.  It is cheaper to do
3137     // a constant pool load than it is to do a movd + shuffle.
3138     if (EVT == MVT::i64 && !Subtarget->is64Bit() &&
3139         (!IsAllConstants || Idx == 0)) {
3140       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3141         // Handle MMX and SSE both.
3142         MVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3143         unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
3144         
3145         // Truncate the value (which may itself be a constant) to i32, and
3146         // convert it to a vector with movd (S2V+shuffle to zero extend).
3147         Item = DAG.getNode(ISD::TRUNCATE, MVT::i32, Item);
3148         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VecVT, Item);
3149         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3150                                            Subtarget->hasSSE2(), DAG);
3151         
3152         // Now we have our 32-bit value zero extended in the low element of
3153         // a vector.  If Idx != 0, swizzle it into place.
3154         if (Idx != 0) {
3155           SDValue Ops[] = { 
3156             Item, DAG.getNode(ISD::UNDEF, Item.getValueType()),
3157             getSwapEltZeroMask(VecElts, Idx, DAG)
3158           };
3159           Item = DAG.getNode(ISD::VECTOR_SHUFFLE, VecVT, Ops, 3);
3160         }
3161         return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(), Item);
3162       }
3163     }
3164     
3165     // If we have a constant or non-constant insertion into the low element of
3166     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3167     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
3168     // depending on what the source datatype is.  Because we can only get here
3169     // when NumElems <= 4, this only needs to handle i32/f32/i64/f64.
3170     if (Idx == 0 &&
3171         // Don't do this for i64 values on x86-32.
3172         (EVT != MVT::i64 || Subtarget->is64Bit())) {
3173       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
3174       // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3175       return getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3176                                          Subtarget->hasSSE2(), DAG);
3177     }
3178
3179     // Is it a vector logical left shift?
3180     if (NumElems == 2 && Idx == 1 &&
3181         isZeroNode(Op.getOperand(0)) && !isZeroNode(Op.getOperand(1))) {
3182       unsigned NumBits = VT.getSizeInBits();
3183       return getVShift(true, VT,
3184                        DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(1)),
3185                        NumBits/2, DAG, *this);
3186     }
3187     
3188     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3189       return SDValue();
3190
3191     // Otherwise, if this is a vector with i32 or f32 elements, and the element
3192     // is a non-constant being inserted into an element other than the low one,
3193     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
3194     // movd/movss) to move this into the low element, then shuffle it into
3195     // place.
3196     if (EVTBits == 32) {
3197       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
3198       
3199       // Turn it into a shuffle of zero and zero-extended scalar to vector.
3200       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3201                                          Subtarget->hasSSE2(), DAG);
3202       MVT MaskVT  = MVT::getIntVectorWithNumElements(NumElems);
3203       MVT MaskEVT = MaskVT.getVectorElementType();
3204       SmallVector<SDValue, 8> MaskVec;
3205       for (unsigned i = 0; i < NumElems; i++)
3206         MaskVec.push_back(DAG.getConstant((i == Idx) ? 0 : 1, MaskEVT));
3207       SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3208                                    &MaskVec[0], MaskVec.size());
3209       return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Item,
3210                          DAG.getNode(ISD::UNDEF, VT), Mask);
3211     }
3212   }
3213
3214   // Splat is obviously ok. Let legalizer expand it to a shuffle.
3215   if (Values.size() == 1)
3216     return SDValue();
3217   
3218   // A vector full of immediates; various special cases are already
3219   // handled, so this is best done with a single constant-pool load.
3220   if (IsAllConstants)
3221     return SDValue();
3222
3223   // Let legalizer expand 2-wide build_vectors.
3224   if (EVTBits == 64) {
3225     if (NumNonZero == 1) {
3226       // One half is zero or undef.
3227       unsigned Idx = CountTrailingZeros_32(NonZeros);
3228       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT,
3229                                  Op.getOperand(Idx));
3230       return getShuffleVectorZeroOrUndef(V2, Idx, true,
3231                                          Subtarget->hasSSE2(), DAG);
3232     }
3233     return SDValue();
3234   }
3235
3236   // If element VT is < 32 bits, convert it to inserts into a zero vector.
3237   if (EVTBits == 8 && NumElems == 16) {
3238     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3239                                         *this);
3240     if (V.Val) return V;
3241   }
3242
3243   if (EVTBits == 16 && NumElems == 8) {
3244     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3245                                         *this);
3246     if (V.Val) return V;
3247   }
3248
3249   // If element VT is == 32 bits, turn it into a number of shuffles.
3250   SmallVector<SDValue, 8> V;
3251   V.resize(NumElems);
3252   if (NumElems == 4 && NumZero > 0) {
3253     for (unsigned i = 0; i < 4; ++i) {
3254       bool isZero = !(NonZeros & (1 << i));
3255       if (isZero)
3256         V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG);
3257       else
3258         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3259     }
3260
3261     for (unsigned i = 0; i < 2; ++i) {
3262       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3263         default: break;
3264         case 0:
3265           V[i] = V[i*2];  // Must be a zero vector.
3266           break;
3267         case 1:
3268           V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2+1], V[i*2],
3269                              getMOVLMask(NumElems, DAG));
3270           break;
3271         case 2:
3272           V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3273                              getMOVLMask(NumElems, DAG));
3274           break;
3275         case 3:
3276           V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3277                              getUnpacklMask(NumElems, DAG));
3278           break;
3279       }
3280     }
3281
3282     MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3283     MVT EVT = MaskVT.getVectorElementType();
3284     SmallVector<SDValue, 8> MaskVec;
3285     bool Reverse = (NonZeros & 0x3) == 2;
3286     for (unsigned i = 0; i < 2; ++i)
3287       if (Reverse)
3288         MaskVec.push_back(DAG.getConstant(1-i, EVT));
3289       else
3290         MaskVec.push_back(DAG.getConstant(i, EVT));
3291     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3292     for (unsigned i = 0; i < 2; ++i)
3293       if (Reverse)
3294         MaskVec.push_back(DAG.getConstant(1-i+NumElems, EVT));
3295       else
3296         MaskVec.push_back(DAG.getConstant(i+NumElems, EVT));
3297     SDValue ShufMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3298                                      &MaskVec[0], MaskVec.size());
3299     return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[0], V[1], ShufMask);
3300   }
3301
3302   if (Values.size() > 2) {
3303     // Expand into a number of unpckl*.
3304     // e.g. for v4f32
3305     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3306     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3307     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
3308     SDValue UnpckMask = getUnpacklMask(NumElems, DAG);
3309     for (unsigned i = 0; i < NumElems; ++i)
3310       V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3311     NumElems >>= 1;
3312     while (NumElems != 0) {
3313       for (unsigned i = 0; i < NumElems; ++i)
3314         V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i], V[i + NumElems],
3315                            UnpckMask);
3316       NumElems >>= 1;
3317     }
3318     return V[0];
3319   }
3320
3321   return SDValue();
3322 }
3323
3324 static
3325 SDValue LowerVECTOR_SHUFFLEv8i16(SDValue V1, SDValue V2,
3326                                    SDValue PermMask, SelectionDAG &DAG,
3327                                    TargetLowering &TLI) {
3328   SDValue NewV;
3329   MVT MaskVT = MVT::getIntVectorWithNumElements(8);
3330   MVT MaskEVT = MaskVT.getVectorElementType();
3331   MVT PtrVT = TLI.getPointerTy();
3332   SmallVector<SDValue, 8> MaskElts(PermMask.Val->op_begin(),
3333                                      PermMask.Val->op_end());
3334
3335   // First record which half of which vector the low elements come from.
3336   SmallVector<unsigned, 4> LowQuad(4);
3337   for (unsigned i = 0; i < 4; ++i) {
3338     SDValue Elt = MaskElts[i];
3339     if (Elt.getOpcode() == ISD::UNDEF)
3340       continue;
3341     unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3342     int QuadIdx = EltIdx / 4;
3343     ++LowQuad[QuadIdx];
3344   }
3345   int BestLowQuad = -1;
3346   unsigned MaxQuad = 1;
3347   for (unsigned i = 0; i < 4; ++i) {
3348     if (LowQuad[i] > MaxQuad) {
3349       BestLowQuad = i;
3350       MaxQuad = LowQuad[i];
3351     }
3352   }
3353
3354   // Record which half of which vector the high elements come from.
3355   SmallVector<unsigned, 4> HighQuad(4);
3356   for (unsigned i = 4; i < 8; ++i) {
3357     SDValue Elt = MaskElts[i];
3358     if (Elt.getOpcode() == ISD::UNDEF)
3359       continue;
3360     unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3361     int QuadIdx = EltIdx / 4;
3362     ++HighQuad[QuadIdx];
3363   }
3364   int BestHighQuad = -1;
3365   MaxQuad = 1;
3366   for (unsigned i = 0; i < 4; ++i) {
3367     if (HighQuad[i] > MaxQuad) {
3368       BestHighQuad = i;
3369       MaxQuad = HighQuad[i];
3370     }
3371   }
3372
3373   // If it's possible to sort parts of either half with PSHUF{H|L}W, then do it.
3374   if (BestLowQuad != -1 || BestHighQuad != -1) {
3375     // First sort the 4 chunks in order using shufpd.
3376     SmallVector<SDValue, 8> MaskVec;
3377     if (BestLowQuad != -1)
3378       MaskVec.push_back(DAG.getConstant(BestLowQuad, MVT::i32));
3379     else
3380       MaskVec.push_back(DAG.getConstant(0, MVT::i32));
3381     if (BestHighQuad != -1)
3382       MaskVec.push_back(DAG.getConstant(BestHighQuad, MVT::i32));
3383     else
3384       MaskVec.push_back(DAG.getConstant(1, MVT::i32));
3385     SDValue Mask= DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, &MaskVec[0],2);
3386     NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v2i64,
3387                        DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V1),
3388                        DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V2), Mask);
3389     NewV = DAG.getNode(ISD::BIT_CONVERT, MVT::v8i16, NewV);
3390
3391     // Now sort high and low parts separately.
3392     BitVector InOrder(8);
3393     if (BestLowQuad != -1) {
3394       // Sort lower half in order using PSHUFLW.
3395       MaskVec.clear();
3396       bool AnyOutOrder = false;
3397       for (unsigned i = 0; i != 4; ++i) {
3398         SDValue Elt = MaskElts[i];
3399         if (Elt.getOpcode() == ISD::UNDEF) {
3400           MaskVec.push_back(Elt);
3401           InOrder.set(i);
3402         } else {
3403           unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3404           if (EltIdx != i)
3405             AnyOutOrder = true;
3406           MaskVec.push_back(DAG.getConstant(EltIdx % 4, MaskEVT));
3407           // If this element is in the right place after this shuffle, then
3408           // remember it.
3409           if ((int)(EltIdx / 4) == BestLowQuad)
3410             InOrder.set(i);
3411         }
3412       }
3413       if (AnyOutOrder) {
3414         for (unsigned i = 4; i != 8; ++i)
3415           MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3416         SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3417         NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
3418       }
3419     }
3420
3421     if (BestHighQuad != -1) {
3422       // Sort high half in order using PSHUFHW if possible.
3423       MaskVec.clear();
3424       for (unsigned i = 0; i != 4; ++i)
3425         MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3426       bool AnyOutOrder = false;
3427       for (unsigned i = 4; i != 8; ++i) {
3428         SDValue Elt = MaskElts[i];
3429         if (Elt.getOpcode() == ISD::UNDEF) {
3430           MaskVec.push_back(Elt);
3431           InOrder.set(i);
3432         } else {
3433           unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3434           if (EltIdx != i)
3435             AnyOutOrder = true;
3436           MaskVec.push_back(DAG.getConstant((EltIdx % 4) + 4, MaskEVT));
3437           // If this element is in the right place after this shuffle, then
3438           // remember it.
3439           if ((int)(EltIdx / 4) == BestHighQuad)
3440             InOrder.set(i);
3441         }
3442       }
3443       if (AnyOutOrder) {
3444         SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3445         NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
3446       }
3447     }
3448
3449     // The other elements are put in the right place using pextrw and pinsrw.
3450     for (unsigned i = 0; i != 8; ++i) {
3451       if (InOrder[i])
3452         continue;
3453       SDValue Elt = MaskElts[i];
3454       unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3455       SDValue ExtOp = (EltIdx < 8)
3456         ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
3457                       DAG.getConstant(EltIdx, PtrVT))
3458         : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3459                       DAG.getConstant(EltIdx - 8, PtrVT));
3460       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3461                          DAG.getConstant(i, PtrVT));
3462     }
3463     return NewV;
3464   }
3465
3466   // PSHUF{H|L}W are not used. Lower into extracts and inserts but try to use
3467   ///as few as possible.
3468   // First, let's find out how many elements are already in the right order.
3469   unsigned V1InOrder = 0;
3470   unsigned V1FromV1 = 0;
3471   unsigned V2InOrder = 0;
3472   unsigned V2FromV2 = 0;
3473   SmallVector<SDValue, 8> V1Elts;
3474   SmallVector<SDValue, 8> V2Elts;
3475   for (unsigned i = 0; i < 8; ++i) {
3476     SDValue Elt = MaskElts[i];
3477     if (Elt.getOpcode() == ISD::UNDEF) {
3478       V1Elts.push_back(Elt);
3479       V2Elts.push_back(Elt);
3480       ++V1InOrder;
3481       ++V2InOrder;
3482       continue;
3483     }
3484     unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3485     if (EltIdx == i) {
3486       V1Elts.push_back(Elt);
3487       V2Elts.push_back(DAG.getConstant(i+8, MaskEVT));
3488       ++V1InOrder;
3489     } else if (EltIdx == i+8) {
3490       V1Elts.push_back(Elt);
3491       V2Elts.push_back(DAG.getConstant(i, MaskEVT));
3492       ++V2InOrder;
3493     } else if (EltIdx < 8) {
3494       V1Elts.push_back(Elt);
3495       ++V1FromV1;
3496     } else {
3497       V2Elts.push_back(DAG.getConstant(EltIdx-8, MaskEVT));
3498       ++V2FromV2;
3499     }
3500   }
3501
3502   if (V2InOrder > V1InOrder) {
3503     PermMask = CommuteVectorShuffleMask(PermMask, DAG);
3504     std::swap(V1, V2);
3505     std::swap(V1Elts, V2Elts);
3506     std::swap(V1FromV1, V2FromV2);
3507   }
3508
3509   if ((V1FromV1 + V1InOrder) != 8) {
3510     // Some elements are from V2.
3511     if (V1FromV1) {
3512       // If there are elements that are from V1 but out of place,
3513       // then first sort them in place
3514       SmallVector<SDValue, 8> MaskVec;
3515       for (unsigned i = 0; i < 8; ++i) {
3516         SDValue Elt = V1Elts[i];
3517         if (Elt.getOpcode() == ISD::UNDEF) {
3518           MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3519           continue;
3520         }
3521         unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3522         if (EltIdx >= 8)
3523           MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3524         else
3525           MaskVec.push_back(DAG.getConstant(EltIdx, MaskEVT));
3526       }
3527       SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3528       V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, V1, V1, Mask);
3529     }
3530
3531     NewV = V1;
3532     for (unsigned i = 0; i < 8; ++i) {
3533       SDValue Elt = V1Elts[i];
3534       if (Elt.getOpcode() == ISD::UNDEF)
3535         continue;
3536       unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3537       if (EltIdx < 8)
3538         continue;
3539       SDValue ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3540                                     DAG.getConstant(EltIdx - 8, PtrVT));
3541       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3542                          DAG.getConstant(i, PtrVT));
3543     }
3544     return NewV;
3545   } else {
3546     // All elements are from V1.
3547     NewV = V1;
3548     for (unsigned i = 0; i < 8; ++i) {
3549       SDValue Elt = V1Elts[i];
3550       if (Elt.getOpcode() == ISD::UNDEF)
3551         continue;
3552       unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3553       SDValue ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
3554                                     DAG.getConstant(EltIdx, PtrVT));
3555       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3556                          DAG.getConstant(i, PtrVT));
3557     }
3558     return NewV;
3559   }
3560 }
3561
3562 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
3563 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
3564 /// done when every pair / quad of shuffle mask elements point to elements in
3565 /// the right sequence. e.g.
3566 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
3567 static
3568 SDValue RewriteAsNarrowerShuffle(SDValue V1, SDValue V2,
3569                                 MVT VT,
3570                                 SDValue PermMask, SelectionDAG &DAG,
3571                                 TargetLowering &TLI) {
3572   unsigned NumElems = PermMask.getNumOperands();
3573   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
3574   MVT MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
3575   MVT MaskEltVT = MaskVT.getVectorElementType();
3576   MVT NewVT = MaskVT;
3577   switch (VT.getSimpleVT()) {
3578   default: assert(false && "Unexpected!");
3579   case MVT::v4f32: NewVT = MVT::v2f64; break;
3580   case MVT::v4i32: NewVT = MVT::v2i64; break;
3581   case MVT::v8i16: NewVT = MVT::v4i32; break;
3582   case MVT::v16i8: NewVT = MVT::v4i32; break;
3583   }
3584
3585   if (NewWidth == 2) {
3586     if (VT.isInteger())
3587       NewVT = MVT::v2i64;
3588     else
3589       NewVT = MVT::v2f64;
3590   }
3591   unsigned Scale = NumElems / NewWidth;
3592   SmallVector<SDValue, 8> MaskVec;
3593   for (unsigned i = 0; i < NumElems; i += Scale) {
3594     unsigned StartIdx = ~0U;
3595     for (unsigned j = 0; j < Scale; ++j) {
3596       SDValue Elt = PermMask.getOperand(i+j);
3597       if (Elt.getOpcode() == ISD::UNDEF)
3598         continue;
3599       unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3600       if (StartIdx == ~0U)
3601         StartIdx = EltIdx - (EltIdx % Scale);
3602       if (EltIdx != StartIdx + j)
3603         return SDValue();
3604     }
3605     if (StartIdx == ~0U)
3606       MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEltVT));
3607     else
3608       MaskVec.push_back(DAG.getConstant(StartIdx / Scale, MaskEltVT));
3609   }
3610
3611   V1 = DAG.getNode(ISD::BIT_CONVERT, NewVT, V1);
3612   V2 = DAG.getNode(ISD::BIT_CONVERT, NewVT, V2);
3613   return DAG.getNode(ISD::VECTOR_SHUFFLE, NewVT, V1, V2,
3614                      DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3615                                  &MaskVec[0], MaskVec.size()));
3616 }
3617
3618 /// getVZextMovL - Return a zero-extending vector move low node.
3619 ///
3620 static SDValue getVZextMovL(MVT VT, MVT OpVT,
3621                               SDValue SrcOp, SelectionDAG &DAG,
3622                               const X86Subtarget *Subtarget) {
3623   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
3624     LoadSDNode *LD = NULL;
3625     if (!isScalarLoadToVector(SrcOp.Val, &LD))
3626       LD = dyn_cast<LoadSDNode>(SrcOp);
3627     if (!LD) {
3628       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
3629       // instead.
3630       MVT EVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
3631       if ((EVT != MVT::i64 || Subtarget->is64Bit()) &&
3632           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
3633           SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
3634           SrcOp.getOperand(0).getOperand(0).getValueType() == EVT) {
3635         // PR2108
3636         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
3637         return DAG.getNode(ISD::BIT_CONVERT, VT,
3638                            DAG.getNode(X86ISD::VZEXT_MOVL, OpVT,
3639                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, OpVT,
3640                                                    SrcOp.getOperand(0).getOperand(0))));
3641       }
3642     }
3643   }
3644
3645   return DAG.getNode(ISD::BIT_CONVERT, VT,
3646                      DAG.getNode(X86ISD::VZEXT_MOVL, OpVT,
3647                                  DAG.getNode(ISD::BIT_CONVERT, OpVT, SrcOp)));
3648 }
3649
3650 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
3651 /// shuffles.
3652 static SDValue
3653 LowerVECTOR_SHUFFLE_4wide(SDValue V1, SDValue V2,
3654                           SDValue PermMask, MVT VT, SelectionDAG &DAG) {
3655   MVT MaskVT = PermMask.getValueType();
3656   MVT MaskEVT = MaskVT.getVectorElementType();
3657   SmallVector<std::pair<int, int>, 8> Locs;
3658   Locs.reserve(4);
3659   SmallVector<SDValue, 8> Mask1(4, DAG.getNode(ISD::UNDEF, MaskEVT));
3660   unsigned NumHi = 0;
3661   unsigned NumLo = 0;
3662   for (unsigned i = 0; i != 4; ++i) {
3663     SDValue Elt = PermMask.getOperand(i);
3664     if (Elt.getOpcode() == ISD::UNDEF) {
3665       Locs[i] = std::make_pair(-1, -1);
3666     } else {
3667       unsigned Val = cast<ConstantSDNode>(Elt)->getValue();
3668       assert(Val < 8 && "Invalid VECTOR_SHUFFLE index!");
3669       if (Val < 4) {
3670         Locs[i] = std::make_pair(0, NumLo);
3671         Mask1[NumLo] = Elt;
3672         NumLo++;
3673       } else {
3674         Locs[i] = std::make_pair(1, NumHi);
3675         if (2+NumHi < 4)
3676           Mask1[2+NumHi] = Elt;
3677         NumHi++;
3678       }
3679     }
3680   }
3681
3682   if (NumLo <= 2 && NumHi <= 2) {
3683     // If no more than two elements come from either vector. This can be
3684     // implemented with two shuffles. First shuffle gather the elements.
3685     // The second shuffle, which takes the first shuffle as both of its
3686     // vector operands, put the elements into the right order.
3687     V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3688                      DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3689                                  &Mask1[0], Mask1.size()));
3690
3691     SmallVector<SDValue, 8> Mask2(4, DAG.getNode(ISD::UNDEF, MaskEVT));
3692     for (unsigned i = 0; i != 4; ++i) {
3693       if (Locs[i].first == -1)
3694         continue;
3695       else {
3696         unsigned Idx = (i < 2) ? 0 : 4;
3697         Idx += Locs[i].first * 2 + Locs[i].second;
3698         Mask2[i] = DAG.getConstant(Idx, MaskEVT);
3699       }
3700     }
3701
3702     return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1,
3703                        DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3704                                    &Mask2[0], Mask2.size()));
3705   } else if (NumLo == 3 || NumHi == 3) {
3706     // Otherwise, we must have three elements from one vector, call it X, and
3707     // one element from the other, call it Y.  First, use a shufps to build an
3708     // intermediate vector with the one element from Y and the element from X
3709     // that will be in the same half in the final destination (the indexes don't
3710     // matter). Then, use a shufps to build the final vector, taking the half
3711     // containing the element from Y from the intermediate, and the other half
3712     // from X.
3713     if (NumHi == 3) {
3714       // Normalize it so the 3 elements come from V1.
3715       PermMask = CommuteVectorShuffleMask(PermMask, DAG);
3716       std::swap(V1, V2);
3717     }
3718
3719     // Find the element from V2.
3720     unsigned HiIndex;
3721     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
3722       SDValue Elt = PermMask.getOperand(HiIndex);
3723       if (Elt.getOpcode() == ISD::UNDEF)
3724         continue;
3725       unsigned Val = cast<ConstantSDNode>(Elt)->getValue();
3726       if (Val >= 4)
3727         break;
3728     }
3729
3730     Mask1[0] = PermMask.getOperand(HiIndex);
3731     Mask1[1] = DAG.getNode(ISD::UNDEF, MaskEVT);
3732     Mask1[2] = PermMask.getOperand(HiIndex^1);
3733     Mask1[3] = DAG.getNode(ISD::UNDEF, MaskEVT);
3734     V2 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3735                      DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &Mask1[0], 4));
3736
3737     if (HiIndex >= 2) {
3738       Mask1[0] = PermMask.getOperand(0);
3739       Mask1[1] = PermMask.getOperand(1);
3740       Mask1[2] = DAG.getConstant(HiIndex & 1 ? 6 : 4, MaskEVT);
3741       Mask1[3] = DAG.getConstant(HiIndex & 1 ? 4 : 6, MaskEVT);
3742       return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3743                          DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &Mask1[0], 4));
3744     } else {
3745       Mask1[0] = DAG.getConstant(HiIndex & 1 ? 2 : 0, MaskEVT);
3746       Mask1[1] = DAG.getConstant(HiIndex & 1 ? 0 : 2, MaskEVT);
3747       Mask1[2] = PermMask.getOperand(2);
3748       Mask1[3] = PermMask.getOperand(3);
3749       if (Mask1[2].getOpcode() != ISD::UNDEF)
3750         Mask1[2] = DAG.getConstant(cast<ConstantSDNode>(Mask1[2])->getValue()+4,
3751                                    MaskEVT);
3752       if (Mask1[3].getOpcode() != ISD::UNDEF)
3753         Mask1[3] = DAG.getConstant(cast<ConstantSDNode>(Mask1[3])->getValue()+4,
3754                                    MaskEVT);
3755       return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V2, V1,
3756                          DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &Mask1[0], 4));
3757     }
3758   }
3759
3760   // Break it into (shuffle shuffle_hi, shuffle_lo).
3761   Locs.clear();
3762   SmallVector<SDValue,8> LoMask(4, DAG.getNode(ISD::UNDEF, MaskEVT));
3763   SmallVector<SDValue,8> HiMask(4, DAG.getNode(ISD::UNDEF, MaskEVT));
3764   SmallVector<SDValue,8> *MaskPtr = &LoMask;
3765   unsigned MaskIdx = 0;
3766   unsigned LoIdx = 0;
3767   unsigned HiIdx = 2;
3768   for (unsigned i = 0; i != 4; ++i) {
3769     if (i == 2) {
3770       MaskPtr = &HiMask;
3771       MaskIdx = 1;
3772       LoIdx = 0;
3773       HiIdx = 2;
3774     }
3775     SDValue Elt = PermMask.getOperand(i);
3776     if (Elt.getOpcode() == ISD::UNDEF) {
3777       Locs[i] = std::make_pair(-1, -1);
3778     } else if (cast<ConstantSDNode>(Elt)->getValue() < 4) {
3779       Locs[i] = std::make_pair(MaskIdx, LoIdx);
3780       (*MaskPtr)[LoIdx] = Elt;
3781       LoIdx++;
3782     } else {
3783       Locs[i] = std::make_pair(MaskIdx, HiIdx);
3784       (*MaskPtr)[HiIdx] = Elt;
3785       HiIdx++;
3786     }
3787   }
3788
3789   SDValue LoShuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3790                                     DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3791                                                 &LoMask[0], LoMask.size()));
3792   SDValue HiShuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3793                                     DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3794                                                 &HiMask[0], HiMask.size()));
3795   SmallVector<SDValue, 8> MaskOps;
3796   for (unsigned i = 0; i != 4; ++i) {
3797     if (Locs[i].first == -1) {
3798       MaskOps.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3799     } else {
3800       unsigned Idx = Locs[i].first * 4 + Locs[i].second;
3801       MaskOps.push_back(DAG.getConstant(Idx, MaskEVT));
3802     }
3803   }
3804   return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, LoShuffle, HiShuffle,
3805                      DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3806                                  &MaskOps[0], MaskOps.size()));
3807 }
3808
3809 SDValue
3810 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
3811   SDValue V1 = Op.getOperand(0);
3812   SDValue V2 = Op.getOperand(1);
3813   SDValue PermMask = Op.getOperand(2);
3814   MVT VT = Op.getValueType();
3815   unsigned NumElems = PermMask.getNumOperands();
3816   bool isMMX = VT.getSizeInBits() == 64;
3817   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
3818   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
3819   bool V1IsSplat = false;
3820   bool V2IsSplat = false;
3821
3822   if (isUndefShuffle(Op.Val))
3823     return DAG.getNode(ISD::UNDEF, VT);
3824
3825   if (isZeroShuffle(Op.Val))
3826     return getZeroVector(VT, Subtarget->hasSSE2(), DAG);
3827
3828   if (isIdentityMask(PermMask.Val))
3829     return V1;
3830   else if (isIdentityMask(PermMask.Val, true))
3831     return V2;
3832
3833   if (isSplatMask(PermMask.Val)) {
3834     if (isMMX || NumElems < 4) return Op;
3835     // Promote it to a v4{if}32 splat.
3836     return PromoteSplat(Op, DAG, Subtarget->hasSSE2());
3837   }
3838
3839   // If the shuffle can be profitably rewritten as a narrower shuffle, then
3840   // do it!
3841   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
3842     SDValue NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG, *this);
3843     if (NewOp.Val)
3844       return DAG.getNode(ISD::BIT_CONVERT, VT, LowerVECTOR_SHUFFLE(NewOp, DAG));
3845   } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
3846     // FIXME: Figure out a cleaner way to do this.
3847     // Try to make use of movq to zero out the top part.
3848     if (ISD::isBuildVectorAllZeros(V2.Val)) {
3849       SDValue NewOp = RewriteAsNarrowerShuffle(V1, V2, VT, PermMask,
3850                                                  DAG, *this);
3851       if (NewOp.Val) {
3852         SDValue NewV1 = NewOp.getOperand(0);
3853         SDValue NewV2 = NewOp.getOperand(1);
3854         SDValue NewMask = NewOp.getOperand(2);
3855         if (isCommutedMOVL(NewMask.Val, true, false)) {
3856           NewOp = CommuteVectorShuffle(NewOp, NewV1, NewV2, NewMask, DAG);
3857           return getVZextMovL(VT, NewOp.getValueType(), NewV2, DAG, Subtarget);
3858         }
3859       }
3860     } else if (ISD::isBuildVectorAllZeros(V1.Val)) {
3861       SDValue NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask,
3862                                                 DAG, *this);
3863       if (NewOp.Val && X86::isMOVLMask(NewOp.getOperand(2).Val))
3864         return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
3865                              DAG, Subtarget);
3866     }
3867   }
3868
3869   // Check if this can be converted into a logical shift.
3870   bool isLeft = false;
3871   unsigned ShAmt = 0;
3872   SDValue ShVal;
3873   bool isShift = isVectorShift(Op, PermMask, DAG, isLeft, ShVal, ShAmt);
3874   if (isShift && ShVal.hasOneUse()) {
3875     // If the shifted value has multiple uses, it may be cheaper to use 
3876     // v_set0 + movlhps or movhlps, etc.
3877     MVT EVT = VT.getVectorElementType();
3878     ShAmt *= EVT.getSizeInBits();
3879     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this);
3880   }
3881
3882   if (X86::isMOVLMask(PermMask.Val)) {
3883     if (V1IsUndef)
3884       return V2;
3885     if (ISD::isBuildVectorAllZeros(V1.Val))
3886       return getVZextMovL(VT, VT, V2, DAG, Subtarget);
3887     if (!isMMX)
3888       return Op;
3889   }
3890
3891   if (!isMMX && (X86::isMOVSHDUPMask(PermMask.Val) ||
3892                  X86::isMOVSLDUPMask(PermMask.Val) ||
3893                  X86::isMOVHLPSMask(PermMask.Val) ||
3894                  X86::isMOVHPMask(PermMask.Val) ||
3895                  X86::isMOVLPMask(PermMask.Val)))
3896     return Op;
3897
3898   if (ShouldXformToMOVHLPS(PermMask.Val) ||
3899       ShouldXformToMOVLP(V1.Val, V2.Val, PermMask.Val))
3900     return CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3901
3902   if (isShift) {
3903     // No better options. Use a vshl / vsrl.
3904     MVT EVT = VT.getVectorElementType();
3905     ShAmt *= EVT.getSizeInBits();
3906     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this);
3907   }
3908
3909   bool Commuted = false;
3910   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
3911   // 1,1,1,1 -> v8i16 though.
3912   V1IsSplat = isSplatVector(V1.Val);
3913   V2IsSplat = isSplatVector(V2.Val);
3914   
3915   // Canonicalize the splat or undef, if present, to be on the RHS.
3916   if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
3917     Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3918     std::swap(V1IsSplat, V2IsSplat);
3919     std::swap(V1IsUndef, V2IsUndef);
3920     Commuted = true;
3921   }
3922
3923   // FIXME: Figure out a cleaner way to do this.
3924   if (isCommutedMOVL(PermMask.Val, V2IsSplat, V2IsUndef)) {
3925     if (V2IsUndef) return V1;
3926     Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3927     if (V2IsSplat) {
3928       // V2 is a splat, so the mask may be malformed. That is, it may point
3929       // to any V2 element. The instruction selectior won't like this. Get
3930       // a corrected mask and commute to form a proper MOVS{S|D}.
3931       SDValue NewMask = getMOVLMask(NumElems, DAG);
3932       if (NewMask.Val != PermMask.Val)
3933         Op = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3934     }
3935     return Op;
3936   }
3937
3938   if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
3939       X86::isUNPCKH_v_undef_Mask(PermMask.Val) ||
3940       X86::isUNPCKLMask(PermMask.Val) ||
3941       X86::isUNPCKHMask(PermMask.Val))
3942     return Op;
3943
3944   if (V2IsSplat) {
3945     // Normalize mask so all entries that point to V2 points to its first
3946     // element then try to match unpck{h|l} again. If match, return a
3947     // new vector_shuffle with the corrected mask.
3948     SDValue NewMask = NormalizeMask(PermMask, DAG);
3949     if (NewMask.Val != PermMask.Val) {
3950       if (X86::isUNPCKLMask(PermMask.Val, true)) {
3951         SDValue NewMask = getUnpacklMask(NumElems, DAG);
3952         return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3953       } else if (X86::isUNPCKHMask(PermMask.Val, true)) {
3954         SDValue NewMask = getUnpackhMask(NumElems, DAG);
3955         return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3956       }
3957     }
3958   }
3959
3960   // Normalize the node to match x86 shuffle ops if needed
3961   if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(PermMask.Val))
3962       Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3963
3964   if (Commuted) {
3965     // Commute is back and try unpck* again.
3966     Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3967     if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
3968         X86::isUNPCKH_v_undef_Mask(PermMask.Val) ||
3969         X86::isUNPCKLMask(PermMask.Val) ||
3970         X86::isUNPCKHMask(PermMask.Val))
3971       return Op;
3972   }
3973
3974   // Try PSHUF* first, then SHUFP*.
3975   // MMX doesn't have PSHUFD but it does have PSHUFW. While it's theoretically
3976   // possible to shuffle a v2i32 using PSHUFW, that's not yet implemented.
3977   if (isMMX && NumElems == 4 && X86::isPSHUFDMask(PermMask.Val)) {
3978     if (V2.getOpcode() != ISD::UNDEF)
3979       return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
3980                          DAG.getNode(ISD::UNDEF, VT), PermMask);
3981     return Op;
3982   }
3983
3984   if (!isMMX) {
3985     if (Subtarget->hasSSE2() &&
3986         (X86::isPSHUFDMask(PermMask.Val) ||
3987          X86::isPSHUFHWMask(PermMask.Val) ||
3988          X86::isPSHUFLWMask(PermMask.Val))) {
3989       MVT RVT = VT;
3990       if (VT == MVT::v4f32) {
3991         RVT = MVT::v4i32;
3992         Op = DAG.getNode(ISD::VECTOR_SHUFFLE, RVT,
3993                          DAG.getNode(ISD::BIT_CONVERT, RVT, V1),
3994                          DAG.getNode(ISD::UNDEF, RVT), PermMask);
3995       } else if (V2.getOpcode() != ISD::UNDEF)
3996         Op = DAG.getNode(ISD::VECTOR_SHUFFLE, RVT, V1,
3997                          DAG.getNode(ISD::UNDEF, RVT), PermMask);
3998       if (RVT != VT)
3999         Op = DAG.getNode(ISD::BIT_CONVERT, VT, Op);
4000       return Op;
4001     }
4002
4003     // Binary or unary shufps.
4004     if (X86::isSHUFPMask(PermMask.Val) ||
4005         (V2.getOpcode() == ISD::UNDEF && X86::isPSHUFDMask(PermMask.Val)))
4006       return Op;
4007   }
4008
4009   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
4010   if (VT == MVT::v8i16) {
4011     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(V1, V2, PermMask, DAG, *this);
4012     if (NewOp.Val)
4013       return NewOp;
4014   }
4015
4016   // Handle all 4 wide cases with a number of shuffles except for MMX.
4017   if (NumElems == 4 && !isMMX)
4018     return LowerVECTOR_SHUFFLE_4wide(V1, V2, PermMask, VT, DAG);
4019
4020   return SDValue();
4021 }
4022
4023 SDValue
4024 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
4025                                                 SelectionDAG &DAG) {
4026   MVT VT = Op.getValueType();
4027   if (VT.getSizeInBits() == 8) {
4028     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, MVT::i32,
4029                                     Op.getOperand(0), Op.getOperand(1));
4030     SDValue Assert  = DAG.getNode(ISD::AssertZext, MVT::i32, Extract,
4031                                     DAG.getValueType(VT));
4032     return DAG.getNode(ISD::TRUNCATE, VT, Assert);
4033   } else if (VT.getSizeInBits() == 16) {
4034     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, MVT::i32,
4035                                     Op.getOperand(0), Op.getOperand(1));
4036     SDValue Assert  = DAG.getNode(ISD::AssertZext, MVT::i32, Extract,
4037                                     DAG.getValueType(VT));
4038     return DAG.getNode(ISD::TRUNCATE, VT, Assert);
4039   } else if (VT == MVT::f32) {
4040     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
4041     // the result back to FR32 register. It's only worth matching if the
4042     // result has a single use which is a store or a bitcast to i32.
4043     if (!Op.hasOneUse())
4044       return SDValue();
4045     SDNode *User = *Op.Val->use_begin();
4046     if (User->getOpcode() != ISD::STORE &&
4047         (User->getOpcode() != ISD::BIT_CONVERT ||
4048          User->getValueType(0) != MVT::i32))
4049       return SDValue();
4050     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32,
4051                     DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, Op.getOperand(0)),
4052                                     Op.getOperand(1));
4053     return DAG.getNode(ISD::BIT_CONVERT, MVT::f32, Extract);
4054   }
4055   return SDValue();
4056 }
4057
4058
4059 SDValue
4060 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4061   if (!isa<ConstantSDNode>(Op.getOperand(1)))
4062     return SDValue();
4063
4064   if (Subtarget->hasSSE41()) {
4065     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
4066     if (Res.Val)
4067       return Res;
4068   }
4069
4070   MVT VT = Op.getValueType();
4071   // TODO: handle v16i8.
4072   if (VT.getSizeInBits() == 16) {
4073     SDValue Vec = Op.getOperand(0);
4074     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
4075     if (Idx == 0)
4076       return DAG.getNode(ISD::TRUNCATE, MVT::i16,
4077                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32,
4078                                  DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, Vec),
4079                                      Op.getOperand(1)));
4080     // Transform it so it match pextrw which produces a 32-bit result.
4081     MVT EVT = (MVT::SimpleValueType)(VT.getSimpleVT()+1);
4082     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, EVT,
4083                                     Op.getOperand(0), Op.getOperand(1));
4084     SDValue Assert  = DAG.getNode(ISD::AssertZext, EVT, Extract,
4085                                     DAG.getValueType(VT));
4086     return DAG.getNode(ISD::TRUNCATE, VT, Assert);
4087   } else if (VT.getSizeInBits() == 32) {
4088     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
4089     if (Idx == 0)
4090       return Op;
4091     // SHUFPS the element to the lowest double word, then movss.
4092     MVT MaskVT = MVT::getIntVectorWithNumElements(4);
4093     SmallVector<SDValue, 8> IdxVec;
4094     IdxVec.
4095       push_back(DAG.getConstant(Idx, MaskVT.getVectorElementType()));
4096     IdxVec.
4097       push_back(DAG.getNode(ISD::UNDEF, MaskVT.getVectorElementType()));
4098     IdxVec.
4099       push_back(DAG.getNode(ISD::UNDEF, MaskVT.getVectorElementType()));
4100     IdxVec.
4101       push_back(DAG.getNode(ISD::UNDEF, MaskVT.getVectorElementType()));
4102     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
4103                                  &IdxVec[0], IdxVec.size());
4104     SDValue Vec = Op.getOperand(0);
4105     Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
4106                       Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
4107     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
4108                        DAG.getIntPtrConstant(0));
4109   } else if (VT.getSizeInBits() == 64) {
4110     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
4111     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
4112     //        to match extract_elt for f64.
4113     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
4114     if (Idx == 0)
4115       return Op;
4116
4117     // UNPCKHPD the element to the lowest double word, then movsd.
4118     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
4119     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
4120     MVT MaskVT = MVT::getIntVectorWithNumElements(2);
4121     SmallVector<SDValue, 8> IdxVec;
4122     IdxVec.push_back(DAG.getConstant(1, MaskVT.getVectorElementType()));
4123     IdxVec.
4124       push_back(DAG.getNode(ISD::UNDEF, MaskVT.getVectorElementType()));
4125     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
4126                                  &IdxVec[0], IdxVec.size());
4127     SDValue Vec = Op.getOperand(0);
4128     Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
4129                       Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
4130     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
4131                        DAG.getIntPtrConstant(0));
4132   }
4133
4134   return SDValue();
4135 }
4136
4137 SDValue
4138 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG){
4139   MVT VT = Op.getValueType();
4140   MVT EVT = VT.getVectorElementType();
4141
4142   SDValue N0 = Op.getOperand(0);
4143   SDValue N1 = Op.getOperand(1);
4144   SDValue N2 = Op.getOperand(2);
4145
4146   if ((EVT.getSizeInBits() == 8 || EVT.getSizeInBits() == 16) &&
4147       isa<ConstantSDNode>(N2)) {
4148     unsigned Opc = (EVT.getSizeInBits() == 8) ? X86ISD::PINSRB
4149                                                   : X86ISD::PINSRW;
4150     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
4151     // argument.
4152     if (N1.getValueType() != MVT::i32)
4153       N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
4154     if (N2.getValueType() != MVT::i32)
4155       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getValue());
4156     return DAG.getNode(Opc, VT, N0, N1, N2);
4157   } else if (EVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
4158     // Bits [7:6] of the constant are the source select.  This will always be
4159     //  zero here.  The DAG Combiner may combine an extract_elt index into these
4160     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
4161     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
4162     // Bits [5:4] of the constant are the destination select.  This is the 
4163     //  value of the incoming immediate.
4164     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may 
4165     //   combine either bitwise AND or insert of float 0.0 to set these bits.
4166     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getValue() << 4);
4167     return DAG.getNode(X86ISD::INSERTPS, VT, N0, N1, N2);
4168   }
4169   return SDValue();
4170 }
4171
4172 SDValue
4173 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4174   MVT VT = Op.getValueType();
4175   MVT EVT = VT.getVectorElementType();
4176
4177   if (Subtarget->hasSSE41())
4178     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
4179
4180   if (EVT == MVT::i8)
4181     return SDValue();
4182
4183   SDValue N0 = Op.getOperand(0);
4184   SDValue N1 = Op.getOperand(1);
4185   SDValue N2 = Op.getOperand(2);
4186
4187   if (EVT.getSizeInBits() == 16) {
4188     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
4189     // as its second argument.
4190     if (N1.getValueType() != MVT::i32)
4191       N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
4192     if (N2.getValueType() != MVT::i32)
4193       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getValue());
4194     return DAG.getNode(X86ISD::PINSRW, VT, N0, N1, N2);
4195   }
4196   return SDValue();
4197 }
4198
4199 SDValue
4200 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
4201   if (Op.getValueType() == MVT::v2f32)
4202     return DAG.getNode(ISD::BIT_CONVERT, MVT::v2f32,
4203                        DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2i32,
4204                                    DAG.getNode(ISD::BIT_CONVERT, MVT::i32,
4205                                                Op.getOperand(0))));
4206
4207   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, Op.getOperand(0));
4208   MVT VT = MVT::v2i32;
4209   switch (Op.getValueType().getSimpleVT()) {
4210   default: break;
4211   case MVT::v16i8:
4212   case MVT::v8i16:
4213     VT = MVT::v4i32;
4214     break;
4215   }
4216   return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(),
4217                      DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, AnyExt));
4218 }
4219
4220 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
4221 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
4222 // one of the above mentioned nodes. It has to be wrapped because otherwise
4223 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
4224 // be used to form addressing mode. These wrapped nodes will be selected
4225 // into MOV32ri.
4226 SDValue
4227 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
4228   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4229   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(),
4230                                                getPointerTy(),
4231                                                CP->getAlignment());
4232   Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4233   // With PIC, the address is actually $g + Offset.
4234   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4235       !Subtarget->isPICStyleRIPRel()) {
4236     Result = DAG.getNode(ISD::ADD, getPointerTy(),
4237                          DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4238                          Result);
4239   }
4240
4241   return Result;
4242 }
4243
4244 SDValue
4245 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) {
4246   GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4247   SDValue Result = DAG.getTargetGlobalAddress(GV, getPointerTy());
4248   Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4249   // With PIC, the address is actually $g + Offset.
4250   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4251       !Subtarget->isPICStyleRIPRel()) {
4252     Result = DAG.getNode(ISD::ADD, getPointerTy(),
4253                          DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4254                          Result);
4255   }
4256   
4257   // For Darwin & Mingw32, external and weak symbols are indirect, so we want to
4258   // load the value at address GV, not the value of GV itself. This means that
4259   // the GlobalAddress must be in the base or index register of the address, not
4260   // the GV offset field. Platform check is inside GVRequiresExtraLoad() call
4261   // The same applies for external symbols during PIC codegen
4262   if (Subtarget->GVRequiresExtraLoad(GV, getTargetMachine(), false))
4263     Result = DAG.getLoad(getPointerTy(), DAG.getEntryNode(), Result,
4264                          PseudoSourceValue::getGOT(), 0);
4265
4266   return Result;
4267 }
4268
4269 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
4270 static SDValue
4271 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4272                                 const MVT PtrVT) {
4273   SDValue InFlag;
4274   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), X86::EBX,
4275                                      DAG.getNode(X86ISD::GlobalBaseReg,
4276                                                  PtrVT), InFlag);
4277   InFlag = Chain.getValue(1);
4278
4279   // emit leal symbol@TLSGD(,%ebx,1), %eax
4280   SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
4281   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4282                                              GA->getValueType(0),
4283                                              GA->getOffset());
4284   SDValue Ops[] = { Chain,  TGA, InFlag };
4285   SDValue Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 3);
4286   InFlag = Result.getValue(2);
4287   Chain = Result.getValue(1);
4288
4289   // call ___tls_get_addr. This function receives its argument in
4290   // the register EAX.
4291   Chain = DAG.getCopyToReg(Chain, X86::EAX, Result, InFlag);
4292   InFlag = Chain.getValue(1);
4293
4294   NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4295   SDValue Ops1[] = { Chain,
4296                       DAG.getTargetExternalSymbol("___tls_get_addr",
4297                                                   PtrVT),
4298                       DAG.getRegister(X86::EAX, PtrVT),
4299                       DAG.getRegister(X86::EBX, PtrVT),
4300                       InFlag };
4301   Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 5);
4302   InFlag = Chain.getValue(1);
4303
4304   return DAG.getCopyFromReg(Chain, X86::EAX, PtrVT, InFlag);
4305 }
4306
4307 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
4308 static SDValue
4309 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4310                                 const MVT PtrVT) {
4311   SDValue InFlag, Chain;
4312
4313   // emit leaq symbol@TLSGD(%rip), %rdi
4314   SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
4315   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4316                                              GA->getValueType(0),
4317                                              GA->getOffset());
4318   SDValue Ops[]  = { DAG.getEntryNode(), TGA};
4319   SDValue Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 2);
4320   Chain  = Result.getValue(1);
4321   InFlag = Result.getValue(2);
4322
4323   // call __tls_get_addr. This function receives its argument in
4324   // the register RDI.
4325   Chain = DAG.getCopyToReg(Chain, X86::RDI, Result, InFlag);
4326   InFlag = Chain.getValue(1);
4327
4328   NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4329   SDValue Ops1[] = { Chain,
4330                       DAG.getTargetExternalSymbol("__tls_get_addr",
4331                                                   PtrVT),
4332                       DAG.getRegister(X86::RDI, PtrVT),
4333                       InFlag };
4334   Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 4);
4335   InFlag = Chain.getValue(1);
4336
4337   return DAG.getCopyFromReg(Chain, X86::RAX, PtrVT, InFlag);
4338 }
4339
4340 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
4341 // "local exec" model.
4342 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4343                                      const MVT PtrVT) {
4344   // Get the Thread Pointer
4345   SDValue ThreadPointer = DAG.getNode(X86ISD::THREAD_POINTER, PtrVT);
4346   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
4347   // exec)
4348   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4349                                              GA->getValueType(0),
4350                                              GA->getOffset());
4351   SDValue Offset = DAG.getNode(X86ISD::Wrapper, PtrVT, TGA);
4352
4353   if (GA->getGlobal()->isDeclaration()) // initial exec TLS model
4354     Offset = DAG.getLoad(PtrVT, DAG.getEntryNode(), Offset,
4355                          PseudoSourceValue::getGOT(), 0);
4356
4357   // The address of the thread local variable is the add of the thread
4358   // pointer with the offset of the variable.
4359   return DAG.getNode(ISD::ADD, PtrVT, ThreadPointer, Offset);
4360 }
4361
4362 SDValue
4363 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) {
4364   // TODO: implement the "local dynamic" model
4365   // TODO: implement the "initial exec"model for pic executables
4366   assert(Subtarget->isTargetELF() &&
4367          "TLS not implemented for non-ELF targets");
4368   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4369   // If the relocation model is PIC, use the "General Dynamic" TLS Model,
4370   // otherwise use the "Local Exec"TLS Model
4371   if (Subtarget->is64Bit()) {
4372     return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
4373   } else {
4374     if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
4375       return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
4376     else
4377       return LowerToTLSExecModel(GA, DAG, getPointerTy());
4378   }
4379 }
4380
4381 SDValue
4382 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) {
4383   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
4384   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy());
4385   Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4386   // With PIC, the address is actually $g + Offset.
4387   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4388       !Subtarget->isPICStyleRIPRel()) {
4389     Result = DAG.getNode(ISD::ADD, getPointerTy(),
4390                          DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4391                          Result);
4392   }
4393
4394   return Result;
4395 }
4396
4397 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) {
4398   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4399   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy());
4400   Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4401   // With PIC, the address is actually $g + Offset.
4402   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4403       !Subtarget->isPICStyleRIPRel()) {
4404     Result = DAG.getNode(ISD::ADD, getPointerTy(),
4405                          DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4406                          Result);
4407   }
4408
4409   return Result;
4410 }
4411
4412 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
4413 /// take a 2 x i32 value to shift plus a shift amount. 
4414 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) {
4415   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4416   MVT VT = Op.getValueType();
4417   unsigned VTBits = VT.getSizeInBits();
4418   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
4419   SDValue ShOpLo = Op.getOperand(0);
4420   SDValue ShOpHi = Op.getOperand(1);
4421   SDValue ShAmt  = Op.getOperand(2);
4422   SDValue Tmp1 = isSRA ?
4423     DAG.getNode(ISD::SRA, VT, ShOpHi, DAG.getConstant(VTBits - 1, MVT::i8)) :
4424     DAG.getConstant(0, VT);
4425
4426   SDValue Tmp2, Tmp3;
4427   if (Op.getOpcode() == ISD::SHL_PARTS) {
4428     Tmp2 = DAG.getNode(X86ISD::SHLD, VT, ShOpHi, ShOpLo, ShAmt);
4429     Tmp3 = DAG.getNode(ISD::SHL, VT, ShOpLo, ShAmt);
4430   } else {
4431     Tmp2 = DAG.getNode(X86ISD::SHRD, VT, ShOpLo, ShOpHi, ShAmt);
4432     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, VT, ShOpHi, ShAmt);
4433   }
4434
4435   SDValue AndNode = DAG.getNode(ISD::AND, MVT::i8, ShAmt,
4436                                   DAG.getConstant(VTBits, MVT::i8));
4437   SDValue Cond = DAG.getNode(X86ISD::CMP, VT,
4438                                AndNode, DAG.getConstant(0, MVT::i8));
4439
4440   SDValue Hi, Lo;
4441   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4442   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
4443   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
4444
4445   if (Op.getOpcode() == ISD::SHL_PARTS) {
4446     Hi = DAG.getNode(X86ISD::CMOV, VT, Ops0, 4);
4447     Lo = DAG.getNode(X86ISD::CMOV, VT, Ops1, 4);
4448   } else {
4449     Lo = DAG.getNode(X86ISD::CMOV, VT, Ops0, 4);
4450     Hi = DAG.getNode(X86ISD::CMOV, VT, Ops1, 4);
4451   }
4452
4453   SDValue Ops[2] = { Lo, Hi };
4454   return DAG.getMergeValues(Ops, 2);
4455 }
4456
4457 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4458   MVT SrcVT = Op.getOperand(0).getValueType();
4459   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
4460          "Unknown SINT_TO_FP to lower!");
4461   
4462   // These are really Legal; caller falls through into that case.
4463   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
4464     return SDValue();
4465   if (SrcVT == MVT::i64 && Op.getValueType() != MVT::f80 && 
4466       Subtarget->is64Bit())
4467     return SDValue();
4468   
4469   unsigned Size = SrcVT.getSizeInBits()/8;
4470   MachineFunction &MF = DAG.getMachineFunction();
4471   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
4472   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4473   SDValue Chain = DAG.getStore(DAG.getEntryNode(), Op.getOperand(0),
4474                                  StackSlot,
4475                                  PseudoSourceValue::getFixedStack(SSFI), 0);
4476
4477   // Build the FILD
4478   SDVTList Tys;
4479   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
4480   if (useSSE)
4481     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
4482   else
4483     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
4484   SmallVector<SDValue, 8> Ops;
4485   Ops.push_back(Chain);
4486   Ops.push_back(StackSlot);
4487   Ops.push_back(DAG.getValueType(SrcVT));
4488   SDValue Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD,
4489                                  Tys, &Ops[0], Ops.size());
4490
4491   if (useSSE) {
4492     Chain = Result.getValue(1);
4493     SDValue InFlag = Result.getValue(2);
4494
4495     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
4496     // shouldn't be necessary except that RFP cannot be live across
4497     // multiple blocks. When stackifier is fixed, they can be uncoupled.
4498     MachineFunction &MF = DAG.getMachineFunction();
4499     int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
4500     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4501     Tys = DAG.getVTList(MVT::Other);
4502     SmallVector<SDValue, 8> Ops;
4503     Ops.push_back(Chain);
4504     Ops.push_back(Result);
4505     Ops.push_back(StackSlot);
4506     Ops.push_back(DAG.getValueType(Op.getValueType()));
4507     Ops.push_back(InFlag);
4508     Chain = DAG.getNode(X86ISD::FST, Tys, &Ops[0], Ops.size());
4509     Result = DAG.getLoad(Op.getValueType(), Chain, StackSlot,
4510                          PseudoSourceValue::getFixedStack(SSFI), 0);
4511   }
4512
4513   return Result;
4514 }
4515
4516 std::pair<SDValue,SDValue> X86TargetLowering::
4517 FP_TO_SINTHelper(SDValue Op, SelectionDAG &DAG) {
4518   assert(Op.getValueType().getSimpleVT() <= MVT::i64 &&
4519          Op.getValueType().getSimpleVT() >= MVT::i16 &&
4520          "Unknown FP_TO_SINT to lower!");
4521
4522   // These are really Legal.
4523   if (Op.getValueType() == MVT::i32 && 
4524       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
4525     return std::make_pair(SDValue(), SDValue());
4526   if (Subtarget->is64Bit() &&
4527       Op.getValueType() == MVT::i64 &&
4528       Op.getOperand(0).getValueType() != MVT::f80)
4529     return std::make_pair(SDValue(), SDValue());
4530
4531   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
4532   // stack slot.
4533   MachineFunction &MF = DAG.getMachineFunction();
4534   unsigned MemSize = Op.getValueType().getSizeInBits()/8;
4535   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4536   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4537   unsigned Opc;
4538   switch (Op.getValueType().getSimpleVT()) {
4539   default: assert(0 && "Invalid FP_TO_SINT to lower!");
4540   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
4541   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
4542   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
4543   }
4544
4545   SDValue Chain = DAG.getEntryNode();
4546   SDValue Value = Op.getOperand(0);
4547   if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
4548     assert(Op.getValueType() == MVT::i64 && "Invalid FP_TO_SINT to lower!");
4549     Chain = DAG.getStore(Chain, Value, StackSlot,
4550                          PseudoSourceValue::getFixedStack(SSFI), 0);
4551     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
4552     SDValue Ops[] = {
4553       Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
4554     };
4555     Value = DAG.getNode(X86ISD::FLD, Tys, Ops, 3);
4556     Chain = Value.getValue(1);
4557     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4558     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4559   }
4560
4561   // Build the FP_TO_INT*_IN_MEM
4562   SDValue Ops[] = { Chain, Value, StackSlot };
4563   SDValue FIST = DAG.getNode(Opc, MVT::Other, Ops, 3);
4564
4565   return std::make_pair(FIST, StackSlot);
4566 }
4567
4568 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) {
4569   std::pair<SDValue,SDValue> Vals = FP_TO_SINTHelper(Op, DAG);
4570   SDValue FIST = Vals.first, StackSlot = Vals.second;
4571   if (FIST.Val == 0) return SDValue();
4572   
4573   // Load the result.
4574   return DAG.getLoad(Op.getValueType(), FIST, StackSlot, NULL, 0);
4575 }
4576
4577 SDNode *X86TargetLowering::ExpandFP_TO_SINT(SDNode *N, SelectionDAG &DAG) {
4578   std::pair<SDValue,SDValue> Vals = FP_TO_SINTHelper(SDValue(N, 0), DAG);
4579   SDValue FIST = Vals.first, StackSlot = Vals.second;
4580   if (FIST.Val == 0) return 0;
4581
4582   MVT VT = N->getValueType(0);
4583
4584   // Return a load from the stack slot.
4585   SDValue Res = DAG.getLoad(VT, FIST, StackSlot, NULL, 0);
4586
4587   // Use MERGE_VALUES to drop the chain result value and get a node with one
4588   // result.  This requires turning off getMergeValues simplification, since
4589   // otherwise it will give us Res back.
4590   return DAG.getMergeValues(&Res, 1, false).Val;
4591 }
4592
4593 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) {
4594   MVT VT = Op.getValueType();
4595   MVT EltVT = VT;
4596   if (VT.isVector())
4597     EltVT = VT.getVectorElementType();
4598   std::vector<Constant*> CV;
4599   if (EltVT == MVT::f64) {
4600     Constant *C = ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63))));
4601     CV.push_back(C);
4602     CV.push_back(C);
4603   } else {
4604     Constant *C = ConstantFP::get(APFloat(APInt(32, ~(1U << 31))));
4605     CV.push_back(C);
4606     CV.push_back(C);
4607     CV.push_back(C);
4608     CV.push_back(C);
4609   }
4610   Constant *C = ConstantVector::get(CV);
4611   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4612   SDValue Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4613                                PseudoSourceValue::getConstantPool(), 0,
4614                                false, 16);
4615   return DAG.getNode(X86ISD::FAND, VT, Op.getOperand(0), Mask);
4616 }
4617
4618 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) {
4619   MVT VT = Op.getValueType();
4620   MVT EltVT = VT;
4621   unsigned EltNum = 1;
4622   if (VT.isVector()) {
4623     EltVT = VT.getVectorElementType();
4624     EltNum = VT.getVectorNumElements();
4625   }
4626   std::vector<Constant*> CV;
4627   if (EltVT == MVT::f64) {
4628     Constant *C = ConstantFP::get(APFloat(APInt(64, 1ULL << 63)));
4629     CV.push_back(C);
4630     CV.push_back(C);
4631   } else {
4632     Constant *C = ConstantFP::get(APFloat(APInt(32, 1U << 31)));
4633     CV.push_back(C);
4634     CV.push_back(C);
4635     CV.push_back(C);
4636     CV.push_back(C);
4637   }
4638   Constant *C = ConstantVector::get(CV);
4639   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4640   SDValue Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4641                                PseudoSourceValue::getConstantPool(), 0,
4642                                false, 16);
4643   if (VT.isVector()) {
4644     return DAG.getNode(ISD::BIT_CONVERT, VT,
4645                        DAG.getNode(ISD::XOR, MVT::v2i64,
4646                     DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Op.getOperand(0)),
4647                     DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Mask)));
4648   } else {
4649     return DAG.getNode(X86ISD::FXOR, VT, Op.getOperand(0), Mask);
4650   }
4651 }
4652
4653 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
4654   SDValue Op0 = Op.getOperand(0);
4655   SDValue Op1 = Op.getOperand(1);
4656   MVT VT = Op.getValueType();
4657   MVT SrcVT = Op1.getValueType();
4658
4659   // If second operand is smaller, extend it first.
4660   if (SrcVT.bitsLT(VT)) {
4661     Op1 = DAG.getNode(ISD::FP_EXTEND, VT, Op1);
4662     SrcVT = VT;
4663   }
4664   // And if it is bigger, shrink it first.
4665   if (SrcVT.bitsGT(VT)) {
4666     Op1 = DAG.getNode(ISD::FP_ROUND, VT, Op1, DAG.getIntPtrConstant(1));
4667     SrcVT = VT;
4668   }
4669
4670   // At this point the operands and the result should have the same
4671   // type, and that won't be f80 since that is not custom lowered.
4672
4673   // First get the sign bit of second operand.
4674   std::vector<Constant*> CV;
4675   if (SrcVT == MVT::f64) {
4676     CV.push_back(ConstantFP::get(APFloat(APInt(64, 1ULL << 63))));
4677     CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
4678   } else {
4679     CV.push_back(ConstantFP::get(APFloat(APInt(32, 1U << 31))));
4680     CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4681     CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4682     CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4683   }
4684   Constant *C = ConstantVector::get(CV);
4685   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4686   SDValue Mask1 = DAG.getLoad(SrcVT, DAG.getEntryNode(), CPIdx,
4687                                 PseudoSourceValue::getConstantPool(), 0,
4688                                 false, 16);
4689   SDValue SignBit = DAG.getNode(X86ISD::FAND, SrcVT, Op1, Mask1);
4690
4691   // Shift sign bit right or left if the two operands have different types.
4692   if (SrcVT.bitsGT(VT)) {
4693     // Op0 is MVT::f32, Op1 is MVT::f64.
4694     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2f64, SignBit);
4695     SignBit = DAG.getNode(X86ISD::FSRL, MVT::v2f64, SignBit,
4696                           DAG.getConstant(32, MVT::i32));
4697     SignBit = DAG.getNode(ISD::BIT_CONVERT, MVT::v4f32, SignBit);
4698     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::f32, SignBit,
4699                           DAG.getIntPtrConstant(0));
4700   }
4701
4702   // Clear first operand sign bit.
4703   CV.clear();
4704   if (VT == MVT::f64) {
4705     CV.push_back(ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63)))));
4706     CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
4707   } else {
4708     CV.push_back(ConstantFP::get(APFloat(APInt(32, ~(1U << 31)))));
4709     CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4710     CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4711     CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4712   }
4713   C = ConstantVector::get(CV);
4714   CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4715   SDValue Mask2 = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4716                                 PseudoSourceValue::getConstantPool(), 0,
4717                                 false, 16);
4718   SDValue Val = DAG.getNode(X86ISD::FAND, VT, Op0, Mask2);
4719
4720   // Or the value with the sign bit.
4721   return DAG.getNode(X86ISD::FOR, VT, Val, SignBit);
4722 }
4723
4724 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) {
4725   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
4726   SDValue Cond;
4727   SDValue Op0 = Op.getOperand(0);
4728   SDValue Op1 = Op.getOperand(1);
4729   SDValue CC = Op.getOperand(2);
4730   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4731   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
4732   unsigned X86CC;
4733
4734   if (translateX86CC(cast<CondCodeSDNode>(CC)->get(), isFP, X86CC,
4735                      Op0, Op1, DAG)) {
4736     Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
4737     return DAG.getNode(X86ISD::SETCC, MVT::i8,
4738                        DAG.getConstant(X86CC, MVT::i8), Cond);
4739   }
4740
4741   assert(isFP && "Illegal integer SetCC!");
4742
4743   Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
4744   switch (SetCCOpcode) {
4745   default: assert(false && "Illegal floating point SetCC!");
4746   case ISD::SETOEQ: {  // !PF & ZF
4747     SDValue Tmp1 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4748                                  DAG.getConstant(X86::COND_NP, MVT::i8), Cond);
4749     SDValue Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4750                                  DAG.getConstant(X86::COND_E, MVT::i8), Cond);
4751     return DAG.getNode(ISD::AND, MVT::i8, Tmp1, Tmp2);
4752   }
4753   case ISD::SETUNE: {  // PF | !ZF
4754     SDValue Tmp1 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4755                                  DAG.getConstant(X86::COND_P, MVT::i8), Cond);
4756     SDValue Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4757                                  DAG.getConstant(X86::COND_NE, MVT::i8), Cond);
4758     return DAG.getNode(ISD::OR, MVT::i8, Tmp1, Tmp2);
4759   }
4760   }
4761 }
4762
4763 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4764   SDValue Cond;
4765   SDValue Op0 = Op.getOperand(0);
4766   SDValue Op1 = Op.getOperand(1);
4767   SDValue CC = Op.getOperand(2);
4768   MVT VT = Op.getValueType();
4769   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4770   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
4771
4772   if (isFP) {
4773     unsigned SSECC = 8;
4774     MVT VT0 = Op0.getValueType();
4775     assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
4776     unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
4777     bool Swap = false;
4778
4779     switch (SetCCOpcode) {
4780     default: break;
4781     case ISD::SETOEQ:
4782     case ISD::SETEQ:  SSECC = 0; break;
4783     case ISD::SETOGT: 
4784     case ISD::SETGT: Swap = true; // Fallthrough
4785     case ISD::SETLT:
4786     case ISD::SETOLT: SSECC = 1; break;
4787     case ISD::SETOGE:
4788     case ISD::SETGE: Swap = true; // Fallthrough
4789     case ISD::SETLE:
4790     case ISD::SETOLE: SSECC = 2; break;
4791     case ISD::SETUO:  SSECC = 3; break;
4792     case ISD::SETUNE:
4793     case ISD::SETNE:  SSECC = 4; break;
4794     case ISD::SETULE: Swap = true;
4795     case ISD::SETUGE: SSECC = 5; break;
4796     case ISD::SETULT: Swap = true;
4797     case ISD::SETUGT: SSECC = 6; break;
4798     case ISD::SETO:   SSECC = 7; break;
4799     }
4800     if (Swap)
4801       std::swap(Op0, Op1);
4802
4803     // In the two special cases we can't handle, emit two comparisons.
4804     if (SSECC == 8) {
4805       if (SetCCOpcode == ISD::SETUEQ) {
4806         SDValue UNORD, EQ;
4807         UNORD = DAG.getNode(Opc, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
4808         EQ = DAG.getNode(Opc, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
4809         return DAG.getNode(ISD::OR, VT, UNORD, EQ);
4810       }
4811       else if (SetCCOpcode == ISD::SETONE) {
4812         SDValue ORD, NEQ;
4813         ORD = DAG.getNode(Opc, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
4814         NEQ = DAG.getNode(Opc, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
4815         return DAG.getNode(ISD::AND, VT, ORD, NEQ);
4816       }
4817       assert(0 && "Illegal FP comparison");
4818     }
4819     // Handle all other FP comparisons here.
4820     return DAG.getNode(Opc, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
4821   }
4822   
4823   // We are handling one of the integer comparisons here.  Since SSE only has
4824   // GT and EQ comparisons for integer, swapping operands and multiple
4825   // operations may be required for some comparisons.
4826   unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
4827   bool Swap = false, Invert = false, FlipSigns = false;
4828   
4829   switch (VT.getSimpleVT()) {
4830   default: break;
4831   case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
4832   case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
4833   case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
4834   case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
4835   }
4836   
4837   switch (SetCCOpcode) {
4838   default: break;
4839   case ISD::SETNE:  Invert = true;
4840   case ISD::SETEQ:  Opc = EQOpc; break;
4841   case ISD::SETLT:  Swap = true;
4842   case ISD::SETGT:  Opc = GTOpc; break;
4843   case ISD::SETGE:  Swap = true;
4844   case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
4845   case ISD::SETULT: Swap = true;
4846   case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
4847   case ISD::SETUGE: Swap = true;
4848   case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
4849   }
4850   if (Swap)
4851     std::swap(Op0, Op1);
4852   
4853   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
4854   // bits of the inputs before performing those operations.
4855   if (FlipSigns) {
4856     MVT EltVT = VT.getVectorElementType();
4857     SDValue SignBit = DAG.getConstant(EltVT.getIntegerVTSignBit(), EltVT);
4858     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
4859     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, VT, &SignBits[0],
4860                                     SignBits.size());
4861     Op0 = DAG.getNode(ISD::XOR, VT, Op0, SignVec);
4862     Op1 = DAG.getNode(ISD::XOR, VT, Op1, SignVec);
4863   }
4864   
4865   SDValue Result = DAG.getNode(Opc, VT, Op0, Op1);
4866
4867   // If the logical-not of the result is required, perform that now.
4868   if (Invert) {
4869     MVT EltVT = VT.getVectorElementType();
4870     SDValue NegOne = DAG.getConstant(EltVT.getIntegerVTBitMask(), EltVT);
4871     std::vector<SDValue> NegOnes(VT.getVectorNumElements(), NegOne);
4872     SDValue NegOneV = DAG.getNode(ISD::BUILD_VECTOR, VT, &NegOnes[0],
4873                                     NegOnes.size());
4874     Result = DAG.getNode(ISD::XOR, VT, Result, NegOneV);
4875   }
4876   return Result;
4877 }
4878
4879 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) {
4880   bool addTest = true;
4881   SDValue Cond  = Op.getOperand(0);
4882   SDValue CC;
4883
4884   if (Cond.getOpcode() == ISD::SETCC)
4885     Cond = LowerSETCC(Cond, DAG);
4886
4887   // If condition flag is set by a X86ISD::CMP, then use it as the condition
4888   // setting operand in place of the X86ISD::SETCC.
4889   if (Cond.getOpcode() == X86ISD::SETCC) {
4890     CC = Cond.getOperand(0);
4891
4892     SDValue Cmp = Cond.getOperand(1);
4893     unsigned Opc = Cmp.getOpcode();
4894     MVT VT = Op.getValueType();
4895     
4896     bool IllegalFPCMov = false;
4897     if (VT.isFloatingPoint() && !VT.isVector() &&
4898         !isScalarFPTypeInSSEReg(VT))  // FPStack?
4899       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSignExtended());
4900     
4901     if ((Opc == X86ISD::CMP ||
4902          Opc == X86ISD::COMI ||
4903          Opc == X86ISD::UCOMI) && !IllegalFPCMov) {
4904       Cond = Cmp;
4905       addTest = false;
4906     }
4907   }
4908
4909   if (addTest) {
4910     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4911     Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
4912   }
4913
4914   const MVT *VTs = DAG.getNodeValueTypes(Op.getValueType(),
4915                                                     MVT::Flag);
4916   SmallVector<SDValue, 4> Ops;
4917   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
4918   // condition is true.
4919   Ops.push_back(Op.getOperand(2));
4920   Ops.push_back(Op.getOperand(1));
4921   Ops.push_back(CC);
4922   Ops.push_back(Cond);
4923   return DAG.getNode(X86ISD::CMOV, VTs, 2, &Ops[0], Ops.size());
4924 }
4925
4926 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) {
4927   bool addTest = true;
4928   SDValue Chain = Op.getOperand(0);
4929   SDValue Cond  = Op.getOperand(1);
4930   SDValue Dest  = Op.getOperand(2);
4931   SDValue CC;
4932
4933   if (Cond.getOpcode() == ISD::SETCC)
4934     Cond = LowerSETCC(Cond, DAG);
4935
4936   // If condition flag is set by a X86ISD::CMP, then use it as the condition
4937   // setting operand in place of the X86ISD::SETCC.
4938   if (Cond.getOpcode() == X86ISD::SETCC) {
4939     CC = Cond.getOperand(0);
4940
4941     SDValue Cmp = Cond.getOperand(1);
4942     unsigned Opc = Cmp.getOpcode();
4943     if (Opc == X86ISD::CMP ||
4944         Opc == X86ISD::COMI ||
4945         Opc == X86ISD::UCOMI) {
4946       Cond = Cmp;
4947       addTest = false;
4948     }
4949   }
4950
4951   if (addTest) {
4952     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4953     Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
4954   }
4955   return DAG.getNode(X86ISD::BRCOND, Op.getValueType(),
4956                      Chain, Op.getOperand(2), CC, Cond);
4957 }
4958
4959
4960 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
4961 // Calls to _alloca is needed to probe the stack when allocating more than 4k
4962 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
4963 // that the guard pages used by the OS virtual memory manager are allocated in
4964 // correct sequence.
4965 SDValue
4966 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
4967                                            SelectionDAG &DAG) {
4968   assert(Subtarget->isTargetCygMing() &&
4969          "This should be used only on Cygwin/Mingw targets");
4970
4971   // Get the inputs.
4972   SDValue Chain = Op.getOperand(0);
4973   SDValue Size  = Op.getOperand(1);
4974   // FIXME: Ensure alignment here
4975
4976   SDValue Flag;
4977
4978   MVT IntPtr = getPointerTy();
4979   MVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
4980
4981   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0));
4982
4983   Chain = DAG.getCopyToReg(Chain, X86::EAX, Size, Flag);
4984   Flag = Chain.getValue(1);
4985
4986   SDVTList  NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4987   SDValue Ops[] = { Chain,
4988                       DAG.getTargetExternalSymbol("_alloca", IntPtr),
4989                       DAG.getRegister(X86::EAX, IntPtr),
4990                       DAG.getRegister(X86StackPtr, SPTy),
4991                       Flag };
4992   Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops, 5);
4993   Flag = Chain.getValue(1);
4994
4995   Chain = DAG.getCALLSEQ_END(Chain,
4996                              DAG.getIntPtrConstant(0),
4997                              DAG.getIntPtrConstant(0),
4998                              Flag);
4999
5000   Chain = DAG.getCopyFromReg(Chain, X86StackPtr, SPTy).getValue(1);
5001
5002   SDValue Ops1[2] = { Chain.getValue(0), Chain };
5003   return DAG.getMergeValues(Ops1, 2);
5004 }
5005
5006 SDValue
5007 X86TargetLowering::EmitTargetCodeForMemset(SelectionDAG &DAG,
5008                                            SDValue Chain,
5009                                            SDValue Dst, SDValue Src,
5010                                            SDValue Size, unsigned Align,
5011                                         const Value *DstSV, uint64_t DstSVOff) {
5012   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5013
5014   /// If not DWORD aligned or size is more than the threshold, call the library.
5015   /// The libc version is likely to be faster for these cases. It can use the
5016   /// address value and run time information about the CPU.
5017   if ((Align & 3) == 0 ||
5018       !ConstantSize ||
5019       ConstantSize->getValue() > getSubtarget()->getMaxInlineSizeThreshold()) {
5020     SDValue InFlag(0, 0);
5021
5022     // Check to see if there is a specialized entry-point for memory zeroing.
5023     ConstantSDNode *V = dyn_cast<ConstantSDNode>(Src);
5024     if (const char *bzeroEntry = 
5025           V && V->isNullValue() ? Subtarget->getBZeroEntry() : 0) {
5026       MVT IntPtr = getPointerTy();
5027       const Type *IntPtrTy = getTargetData()->getIntPtrType();
5028       TargetLowering::ArgListTy Args; 
5029       TargetLowering::ArgListEntry Entry;
5030       Entry.Node = Dst;
5031       Entry.Ty = IntPtrTy;
5032       Args.push_back(Entry);
5033       Entry.Node = Size;
5034       Args.push_back(Entry);
5035       std::pair<SDValue,SDValue> CallResult =
5036         LowerCallTo(Chain, Type::VoidTy, false, false, false, CallingConv::C,
5037                     false, DAG.getExternalSymbol(bzeroEntry, IntPtr),
5038                     Args, DAG);
5039       return CallResult.second;
5040     }
5041
5042     // Otherwise have the target-independent code call memset.
5043     return SDValue();
5044   }
5045
5046   uint64_t SizeVal = ConstantSize->getValue();
5047   SDValue InFlag(0, 0);
5048   MVT AVT;
5049   SDValue Count;
5050   ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Src);
5051   unsigned BytesLeft = 0;
5052   bool TwoRepStos = false;
5053   if (ValC) {
5054     unsigned ValReg;
5055     uint64_t Val = ValC->getValue() & 255;
5056
5057     // If the value is a constant, then we can potentially use larger sets.
5058     switch (Align & 3) {
5059       case 2:   // WORD aligned
5060         AVT = MVT::i16;
5061         ValReg = X86::AX;
5062         Val = (Val << 8) | Val;
5063         break;
5064       case 0:  // DWORD aligned
5065         AVT = MVT::i32;
5066         ValReg = X86::EAX;
5067         Val = (Val << 8)  | Val;
5068         Val = (Val << 16) | Val;
5069         if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) {  // QWORD aligned
5070           AVT = MVT::i64;
5071           ValReg = X86::RAX;
5072           Val = (Val << 32) | Val;
5073         }
5074         break;
5075       default:  // Byte aligned
5076         AVT = MVT::i8;
5077         ValReg = X86::AL;
5078         Count = DAG.getIntPtrConstant(SizeVal);
5079         break;
5080     }
5081
5082     if (AVT.bitsGT(MVT::i8)) {
5083       unsigned UBytes = AVT.getSizeInBits() / 8;
5084       Count = DAG.getIntPtrConstant(SizeVal / UBytes);
5085       BytesLeft = SizeVal % UBytes;
5086     }
5087
5088     Chain  = DAG.getCopyToReg(Chain, ValReg, DAG.getConstant(Val, AVT),
5089                               InFlag);
5090     InFlag = Chain.getValue(1);
5091   } else {
5092     AVT = MVT::i8;
5093     Count  = DAG.getIntPtrConstant(SizeVal);
5094     Chain  = DAG.getCopyToReg(Chain, X86::AL, Src, InFlag);
5095     InFlag = Chain.getValue(1);
5096   }
5097
5098   Chain  = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
5099                             Count, InFlag);
5100   InFlag = Chain.getValue(1);
5101   Chain  = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
5102                             Dst, InFlag);
5103   InFlag = Chain.getValue(1);
5104
5105   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5106   SmallVector<SDValue, 8> Ops;
5107   Ops.push_back(Chain);
5108   Ops.push_back(DAG.getValueType(AVT));
5109   Ops.push_back(InFlag);
5110   Chain  = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
5111
5112   if (TwoRepStos) {
5113     InFlag = Chain.getValue(1);
5114     Count  = Size;
5115     MVT CVT = Count.getValueType();
5116     SDValue Left = DAG.getNode(ISD::AND, CVT, Count,
5117                                DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
5118     Chain  = DAG.getCopyToReg(Chain, (CVT == MVT::i64) ? X86::RCX : X86::ECX,
5119                               Left, InFlag);
5120     InFlag = Chain.getValue(1);
5121     Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5122     Ops.clear();
5123     Ops.push_back(Chain);
5124     Ops.push_back(DAG.getValueType(MVT::i8));
5125     Ops.push_back(InFlag);
5126     Chain  = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
5127   } else if (BytesLeft) {
5128     // Handle the last 1 - 7 bytes.
5129     unsigned Offset = SizeVal - BytesLeft;
5130     MVT AddrVT = Dst.getValueType();
5131     MVT SizeVT = Size.getValueType();
5132
5133     Chain = DAG.getMemset(Chain,
5134                           DAG.getNode(ISD::ADD, AddrVT, Dst,
5135                                       DAG.getConstant(Offset, AddrVT)),
5136                           Src,
5137                           DAG.getConstant(BytesLeft, SizeVT),
5138                           Align, DstSV, DstSVOff + Offset);
5139   }
5140
5141   // TODO: Use a Tokenfactor, as in memcpy, instead of a single chain.
5142   return Chain;
5143 }
5144
5145 SDValue
5146 X86TargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG,
5147                                            SDValue Chain,
5148                                            SDValue Dst, SDValue Src,
5149                                            SDValue Size, unsigned Align,
5150                                            bool AlwaysInline,
5151                                            const Value *DstSV, uint64_t DstSVOff,
5152                                            const Value *SrcSV, uint64_t SrcSVOff){
5153   
5154   // This requires the copy size to be a constant, preferrably
5155   // within a subtarget-specific limit.
5156   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5157   if (!ConstantSize)
5158     return SDValue();
5159   uint64_t SizeVal = ConstantSize->getValue();
5160   if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
5161     return SDValue();
5162
5163   MVT AVT;
5164   unsigned BytesLeft = 0;
5165   if (Align >= 8 && Subtarget->is64Bit())
5166     AVT = MVT::i64;
5167   else if (Align >= 4)
5168     AVT = MVT::i32;
5169   else if (Align >= 2)
5170     AVT = MVT::i16;
5171   else
5172     AVT = MVT::i8;
5173
5174   unsigned UBytes = AVT.getSizeInBits() / 8;
5175   unsigned CountVal = SizeVal / UBytes;
5176   SDValue Count = DAG.getIntPtrConstant(CountVal);
5177   BytesLeft = SizeVal % UBytes;
5178
5179   SDValue InFlag(0, 0);
5180   Chain  = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
5181                             Count, InFlag);
5182   InFlag = Chain.getValue(1);
5183   Chain  = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
5184                             Dst, InFlag);
5185   InFlag = Chain.getValue(1);
5186   Chain  = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RSI : X86::ESI,
5187                             Src, InFlag);
5188   InFlag = Chain.getValue(1);
5189
5190   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5191   SmallVector<SDValue, 8> Ops;
5192   Ops.push_back(Chain);
5193   Ops.push_back(DAG.getValueType(AVT));
5194   Ops.push_back(InFlag);
5195   SDValue RepMovs = DAG.getNode(X86ISD::REP_MOVS, Tys, &Ops[0], Ops.size());
5196
5197   SmallVector<SDValue, 4> Results;
5198   Results.push_back(RepMovs);
5199   if (BytesLeft) {
5200     // Handle the last 1 - 7 bytes.
5201     unsigned Offset = SizeVal - BytesLeft;
5202     MVT DstVT = Dst.getValueType();
5203     MVT SrcVT = Src.getValueType();
5204     MVT SizeVT = Size.getValueType();
5205     Results.push_back(DAG.getMemcpy(Chain,
5206                                     DAG.getNode(ISD::ADD, DstVT, Dst,
5207                                                 DAG.getConstant(Offset, DstVT)),
5208                                     DAG.getNode(ISD::ADD, SrcVT, Src,
5209                                                 DAG.getConstant(Offset, SrcVT)),
5210                                     DAG.getConstant(BytesLeft, SizeVT),
5211                                     Align, AlwaysInline,
5212                                     DstSV, DstSVOff + Offset,
5213                                     SrcSV, SrcSVOff + Offset));
5214   }
5215
5216   return DAG.getNode(ISD::TokenFactor, MVT::Other, &Results[0], Results.size());
5217 }
5218
5219 /// Expand the result of: i64,outchain = READCYCLECOUNTER inchain
5220 SDNode *X86TargetLowering::ExpandREADCYCLECOUNTER(SDNode *N, SelectionDAG &DAG){
5221   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5222   SDValue TheChain = N->getOperand(0);
5223   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, Tys, &TheChain, 1);
5224   if (Subtarget->is64Bit()) {
5225     SDValue rax = DAG.getCopyFromReg(rd, X86::RAX, MVT::i64, rd.getValue(1));
5226     SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), X86::RDX,
5227                                        MVT::i64, rax.getValue(2));
5228     SDValue Tmp = DAG.getNode(ISD::SHL, MVT::i64, rdx,
5229                                 DAG.getConstant(32, MVT::i8));
5230     SDValue Ops[] = {
5231       DAG.getNode(ISD::OR, MVT::i64, rax, Tmp), rdx.getValue(1)
5232     };
5233     
5234     return DAG.getMergeValues(Ops, 2).Val;
5235   }
5236   
5237   SDValue eax = DAG.getCopyFromReg(rd, X86::EAX, MVT::i32, rd.getValue(1));
5238   SDValue edx = DAG.getCopyFromReg(eax.getValue(1), X86::EDX,
5239                                        MVT::i32, eax.getValue(2));
5240   // Use a buildpair to merge the two 32-bit values into a 64-bit one. 
5241   SDValue Ops[] = { eax, edx };
5242   Ops[0] = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, Ops, 2);
5243
5244   // Use a MERGE_VALUES to return the value and chain.
5245   Ops[1] = edx.getValue(1);
5246   return DAG.getMergeValues(Ops, 2).Val;
5247 }
5248
5249 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) {
5250   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5251
5252   if (!Subtarget->is64Bit()) {
5253     // vastart just stores the address of the VarArgsFrameIndex slot into the
5254     // memory location argument.
5255     SDValue FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
5256     return DAG.getStore(Op.getOperand(0), FR,Op.getOperand(1), SV, 0);
5257   }
5258
5259   // __va_list_tag:
5260   //   gp_offset         (0 - 6 * 8)
5261   //   fp_offset         (48 - 48 + 8 * 16)
5262   //   overflow_arg_area (point to parameters coming in memory).
5263   //   reg_save_area
5264   SmallVector<SDValue, 8> MemOps;
5265   SDValue FIN = Op.getOperand(1);
5266   // Store gp_offset
5267   SDValue Store = DAG.getStore(Op.getOperand(0),
5268                                  DAG.getConstant(VarArgsGPOffset, MVT::i32),
5269                                  FIN, SV, 0);
5270   MemOps.push_back(Store);
5271
5272   // Store fp_offset
5273   FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(4));
5274   Store = DAG.getStore(Op.getOperand(0),
5275                        DAG.getConstant(VarArgsFPOffset, MVT::i32),
5276                        FIN, SV, 0);
5277   MemOps.push_back(Store);
5278
5279   // Store ptr to overflow_arg_area
5280   FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(4));
5281   SDValue OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
5282   Store = DAG.getStore(Op.getOperand(0), OVFIN, FIN, SV, 0);
5283   MemOps.push_back(Store);
5284
5285   // Store ptr to reg_save_area.
5286   FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(8));
5287   SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
5288   Store = DAG.getStore(Op.getOperand(0), RSFIN, FIN, SV, 0);
5289   MemOps.push_back(Store);
5290   return DAG.getNode(ISD::TokenFactor, MVT::Other, &MemOps[0], MemOps.size());
5291 }
5292
5293 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) {
5294   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
5295   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
5296   SDValue Chain = Op.getOperand(0);
5297   SDValue SrcPtr = Op.getOperand(1);
5298   SDValue SrcSV = Op.getOperand(2);
5299
5300   assert(0 && "VAArgInst is not yet implemented for x86-64!");
5301   abort();
5302   return SDValue();
5303 }
5304
5305 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) {
5306   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
5307   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
5308   SDValue Chain = Op.getOperand(0);
5309   SDValue DstPtr = Op.getOperand(1);
5310   SDValue SrcPtr = Op.getOperand(2);
5311   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
5312   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5313
5314   return DAG.getMemcpy(Chain, DstPtr, SrcPtr,
5315                        DAG.getIntPtrConstant(24), 8, false,
5316                        DstSV, 0, SrcSV, 0);
5317 }
5318
5319 SDValue
5320 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
5321   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getValue();
5322   switch (IntNo) {
5323   default: return SDValue();    // Don't custom lower most intrinsics.
5324   // Comparison intrinsics.
5325   case Intrinsic::x86_sse_comieq_ss:
5326   case Intrinsic::x86_sse_comilt_ss:
5327   case Intrinsic::x86_sse_comile_ss:
5328   case Intrinsic::x86_sse_comigt_ss:
5329   case Intrinsic::x86_sse_comige_ss:
5330   case Intrinsic::x86_sse_comineq_ss:
5331   case Intrinsic::x86_sse_ucomieq_ss:
5332   case Intrinsic::x86_sse_ucomilt_ss:
5333   case Intrinsic::x86_sse_ucomile_ss:
5334   case Intrinsic::x86_sse_ucomigt_ss:
5335   case Intrinsic::x86_sse_ucomige_ss:
5336   case Intrinsic::x86_sse_ucomineq_ss:
5337   case Intrinsic::x86_sse2_comieq_sd:
5338   case Intrinsic::x86_sse2_comilt_sd:
5339   case Intrinsic::x86_sse2_comile_sd:
5340   case Intrinsic::x86_sse2_comigt_sd:
5341   case Intrinsic::x86_sse2_comige_sd:
5342   case Intrinsic::x86_sse2_comineq_sd:
5343   case Intrinsic::x86_sse2_ucomieq_sd:
5344   case Intrinsic::x86_sse2_ucomilt_sd:
5345   case Intrinsic::x86_sse2_ucomile_sd:
5346   case Intrinsic::x86_sse2_ucomigt_sd:
5347   case Intrinsic::x86_sse2_ucomige_sd:
5348   case Intrinsic::x86_sse2_ucomineq_sd: {
5349     unsigned Opc = 0;
5350     ISD::CondCode CC = ISD::SETCC_INVALID;
5351     switch (IntNo) {
5352     default: break;
5353     case Intrinsic::x86_sse_comieq_ss:
5354     case Intrinsic::x86_sse2_comieq_sd:
5355       Opc = X86ISD::COMI;
5356       CC = ISD::SETEQ;
5357       break;
5358     case Intrinsic::x86_sse_comilt_ss:
5359     case Intrinsic::x86_sse2_comilt_sd:
5360       Opc = X86ISD::COMI;
5361       CC = ISD::SETLT;
5362       break;
5363     case Intrinsic::x86_sse_comile_ss:
5364     case Intrinsic::x86_sse2_comile_sd:
5365       Opc = X86ISD::COMI;
5366       CC = ISD::SETLE;
5367       break;
5368     case Intrinsic::x86_sse_comigt_ss:
5369     case Intrinsic::x86_sse2_comigt_sd:
5370       Opc = X86ISD::COMI;
5371       CC = ISD::SETGT;
5372       break;
5373     case Intrinsic::x86_sse_comige_ss:
5374     case Intrinsic::x86_sse2_comige_sd:
5375       Opc = X86ISD::COMI;
5376       CC = ISD::SETGE;
5377       break;
5378     case Intrinsic::x86_sse_comineq_ss:
5379     case Intrinsic::x86_sse2_comineq_sd:
5380       Opc = X86ISD::COMI;
5381       CC = ISD::SETNE;
5382       break;
5383     case Intrinsic::x86_sse_ucomieq_ss:
5384     case Intrinsic::x86_sse2_ucomieq_sd:
5385       Opc = X86ISD::UCOMI;
5386       CC = ISD::SETEQ;
5387       break;
5388     case Intrinsic::x86_sse_ucomilt_ss:
5389     case Intrinsic::x86_sse2_ucomilt_sd:
5390       Opc = X86ISD::UCOMI;
5391       CC = ISD::SETLT;
5392       break;
5393     case Intrinsic::x86_sse_ucomile_ss:
5394     case Intrinsic::x86_sse2_ucomile_sd:
5395       Opc = X86ISD::UCOMI;
5396       CC = ISD::SETLE;
5397       break;
5398     case Intrinsic::x86_sse_ucomigt_ss:
5399     case Intrinsic::x86_sse2_ucomigt_sd:
5400       Opc = X86ISD::UCOMI;
5401       CC = ISD::SETGT;
5402       break;
5403     case Intrinsic::x86_sse_ucomige_ss:
5404     case Intrinsic::x86_sse2_ucomige_sd:
5405       Opc = X86ISD::UCOMI;
5406       CC = ISD::SETGE;
5407       break;
5408     case Intrinsic::x86_sse_ucomineq_ss:
5409     case Intrinsic::x86_sse2_ucomineq_sd:
5410       Opc = X86ISD::UCOMI;
5411       CC = ISD::SETNE;
5412       break;
5413     }
5414
5415     unsigned X86CC;
5416     SDValue LHS = Op.getOperand(1);
5417     SDValue RHS = Op.getOperand(2);
5418     translateX86CC(CC, true, X86CC, LHS, RHS, DAG);
5419
5420     SDValue Cond = DAG.getNode(Opc, MVT::i32, LHS, RHS);
5421     SDValue SetCC = DAG.getNode(X86ISD::SETCC, MVT::i8,
5422                                 DAG.getConstant(X86CC, MVT::i8), Cond);
5423     return DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, SetCC);
5424   }
5425
5426   // Fix vector shift instructions where the last operand is a non-immediate
5427   // i32 value.
5428   case Intrinsic::x86_sse2_pslli_w:
5429   case Intrinsic::x86_sse2_pslli_d:
5430   case Intrinsic::x86_sse2_pslli_q:
5431   case Intrinsic::x86_sse2_psrli_w:
5432   case Intrinsic::x86_sse2_psrli_d:
5433   case Intrinsic::x86_sse2_psrli_q:
5434   case Intrinsic::x86_sse2_psrai_w:
5435   case Intrinsic::x86_sse2_psrai_d:
5436   case Intrinsic::x86_mmx_pslli_w:
5437   case Intrinsic::x86_mmx_pslli_d:
5438   case Intrinsic::x86_mmx_pslli_q:
5439   case Intrinsic::x86_mmx_psrli_w:
5440   case Intrinsic::x86_mmx_psrli_d:
5441   case Intrinsic::x86_mmx_psrli_q:
5442   case Intrinsic::x86_mmx_psrai_w:
5443   case Intrinsic::x86_mmx_psrai_d: {
5444     SDValue ShAmt = Op.getOperand(2);
5445     if (isa<ConstantSDNode>(ShAmt))
5446       return SDValue();
5447
5448     unsigned NewIntNo = 0;
5449     MVT ShAmtVT = MVT::v4i32;
5450     switch (IntNo) {
5451     case Intrinsic::x86_sse2_pslli_w:
5452       NewIntNo = Intrinsic::x86_sse2_psll_w;
5453       break;
5454     case Intrinsic::x86_sse2_pslli_d:
5455       NewIntNo = Intrinsic::x86_sse2_psll_d;
5456       break;
5457     case Intrinsic::x86_sse2_pslli_q:
5458       NewIntNo = Intrinsic::x86_sse2_psll_q;
5459       break;
5460     case Intrinsic::x86_sse2_psrli_w:
5461       NewIntNo = Intrinsic::x86_sse2_psrl_w;
5462       break;
5463     case Intrinsic::x86_sse2_psrli_d:
5464       NewIntNo = Intrinsic::x86_sse2_psrl_d;
5465       break;
5466     case Intrinsic::x86_sse2_psrli_q:
5467       NewIntNo = Intrinsic::x86_sse2_psrl_q;
5468       break;
5469     case Intrinsic::x86_sse2_psrai_w:
5470       NewIntNo = Intrinsic::x86_sse2_psra_w;
5471       break;
5472     case Intrinsic::x86_sse2_psrai_d:
5473       NewIntNo = Intrinsic::x86_sse2_psra_d;
5474       break;
5475     default: {
5476       ShAmtVT = MVT::v2i32;
5477       switch (IntNo) {
5478       case Intrinsic::x86_mmx_pslli_w:
5479         NewIntNo = Intrinsic::x86_mmx_psll_w;
5480         break;
5481       case Intrinsic::x86_mmx_pslli_d:
5482         NewIntNo = Intrinsic::x86_mmx_psll_d;
5483         break;
5484       case Intrinsic::x86_mmx_pslli_q:
5485         NewIntNo = Intrinsic::x86_mmx_psll_q;
5486         break;
5487       case Intrinsic::x86_mmx_psrli_w:
5488         NewIntNo = Intrinsic::x86_mmx_psrl_w;
5489         break;
5490       case Intrinsic::x86_mmx_psrli_d:
5491         NewIntNo = Intrinsic::x86_mmx_psrl_d;
5492         break;
5493       case Intrinsic::x86_mmx_psrli_q:
5494         NewIntNo = Intrinsic::x86_mmx_psrl_q;
5495         break;
5496       case Intrinsic::x86_mmx_psrai_w:
5497         NewIntNo = Intrinsic::x86_mmx_psra_w;
5498         break;
5499       case Intrinsic::x86_mmx_psrai_d:
5500         NewIntNo = Intrinsic::x86_mmx_psra_d;
5501         break;
5502       default: abort();  // Can't reach here.
5503       }
5504       break;
5505     }
5506     }
5507     MVT VT = Op.getValueType();
5508     ShAmt = DAG.getNode(ISD::BIT_CONVERT, VT,
5509                         DAG.getNode(ISD::SCALAR_TO_VECTOR, ShAmtVT, ShAmt));
5510     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
5511                        DAG.getConstant(NewIntNo, MVT::i32),
5512                        Op.getOperand(1), ShAmt);
5513   }
5514   }
5515 }
5516
5517 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) {
5518   // Depths > 0 not supported yet!
5519   if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
5520     return SDValue();
5521   
5522   // Just load the return address
5523   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
5524   return DAG.getLoad(getPointerTy(), DAG.getEntryNode(), RetAddrFI, NULL, 0);
5525 }
5526
5527 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
5528   // Depths > 0 not supported yet!
5529   if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
5530     return SDValue();
5531     
5532   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
5533   return DAG.getNode(ISD::SUB, getPointerTy(), RetAddrFI, 
5534                      DAG.getIntPtrConstant(!Subtarget->is64Bit() ? 4 : 8));
5535 }
5536
5537 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
5538                                                        SelectionDAG &DAG) {
5539   // Is not yet supported on x86-64
5540   if (Subtarget->is64Bit())
5541     return SDValue();
5542   
5543   return DAG.getIntPtrConstant(8);
5544 }
5545
5546 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
5547 {
5548   assert(!Subtarget->is64Bit() &&
5549          "Lowering of eh_return builtin is not supported yet on x86-64");
5550     
5551   MachineFunction &MF = DAG.getMachineFunction();
5552   SDValue Chain     = Op.getOperand(0);
5553   SDValue Offset    = Op.getOperand(1);
5554   SDValue Handler   = Op.getOperand(2);
5555
5556   SDValue Frame = DAG.getRegister(RegInfo->getFrameRegister(MF),
5557                                     getPointerTy());
5558
5559   SDValue StoreAddr = DAG.getNode(ISD::SUB, getPointerTy(), Frame,
5560                                     DAG.getIntPtrConstant(-4UL));
5561   StoreAddr = DAG.getNode(ISD::ADD, getPointerTy(), StoreAddr, Offset);
5562   Chain = DAG.getStore(Chain, Handler, StoreAddr, NULL, 0);
5563   Chain = DAG.getCopyToReg(Chain, X86::ECX, StoreAddr);
5564   MF.getRegInfo().addLiveOut(X86::ECX);
5565
5566   return DAG.getNode(X86ISD::EH_RETURN, MVT::Other,
5567                      Chain, DAG.getRegister(X86::ECX, getPointerTy()));
5568 }
5569
5570 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
5571                                              SelectionDAG &DAG) {
5572   SDValue Root = Op.getOperand(0);
5573   SDValue Trmp = Op.getOperand(1); // trampoline
5574   SDValue FPtr = Op.getOperand(2); // nested function
5575   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
5576
5577   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5578
5579   const X86InstrInfo *TII =
5580     ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
5581
5582   if (Subtarget->is64Bit()) {
5583     SDValue OutChains[6];
5584
5585     // Large code-model.
5586
5587     const unsigned char JMP64r  = TII->getBaseOpcodeFor(X86::JMP64r);
5588     const unsigned char MOV64ri = TII->getBaseOpcodeFor(X86::MOV64ri);
5589
5590     const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
5591     const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
5592
5593     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
5594
5595     // Load the pointer to the nested function into R11.
5596     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
5597     SDValue Addr = Trmp;
5598     OutChains[0] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5599                                 TrmpAddr, 0);
5600
5601     Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(2, MVT::i64));
5602     OutChains[1] = DAG.getStore(Root, FPtr, Addr, TrmpAddr, 2, false, 2);
5603
5604     // Load the 'nest' parameter value into R10.
5605     // R10 is specified in X86CallingConv.td
5606     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
5607     Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(10, MVT::i64));
5608     OutChains[2] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5609                                 TrmpAddr, 10);
5610
5611     Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(12, MVT::i64));
5612     OutChains[3] = DAG.getStore(Root, Nest, Addr, TrmpAddr, 12, false, 2);
5613
5614     // Jump to the nested function.
5615     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
5616     Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(20, MVT::i64));
5617     OutChains[4] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5618                                 TrmpAddr, 20);
5619
5620     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
5621     Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(22, MVT::i64));
5622     OutChains[5] = DAG.getStore(Root, DAG.getConstant(ModRM, MVT::i8), Addr,
5623                                 TrmpAddr, 22);
5624
5625     SDValue Ops[] =
5626       { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 6) };
5627     return DAG.getMergeValues(Ops, 2);
5628   } else {
5629     const Function *Func =
5630       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
5631     unsigned CC = Func->getCallingConv();
5632     unsigned NestReg;
5633
5634     switch (CC) {
5635     default:
5636       assert(0 && "Unsupported calling convention");
5637     case CallingConv::C:
5638     case CallingConv::X86_StdCall: {
5639       // Pass 'nest' parameter in ECX.
5640       // Must be kept in sync with X86CallingConv.td
5641       NestReg = X86::ECX;
5642
5643       // Check that ECX wasn't needed by an 'inreg' parameter.
5644       const FunctionType *FTy = Func->getFunctionType();
5645       const PAListPtr &Attrs = Func->getParamAttrs();
5646
5647       if (!Attrs.isEmpty() && !Func->isVarArg()) {
5648         unsigned InRegCount = 0;
5649         unsigned Idx = 1;
5650
5651         for (FunctionType::param_iterator I = FTy->param_begin(),
5652              E = FTy->param_end(); I != E; ++I, ++Idx)
5653           if (Attrs.paramHasAttr(Idx, ParamAttr::InReg))
5654             // FIXME: should only count parameters that are lowered to integers.
5655             InRegCount += (getTargetData()->getTypeSizeInBits(*I) + 31) / 32;
5656
5657         if (InRegCount > 2) {
5658           cerr << "Nest register in use - reduce number of inreg parameters!\n";
5659           abort();
5660         }
5661       }
5662       break;
5663     }
5664     case CallingConv::X86_FastCall:
5665       // Pass 'nest' parameter in EAX.
5666       // Must be kept in sync with X86CallingConv.td
5667       NestReg = X86::EAX;
5668       break;
5669     }
5670
5671     SDValue OutChains[4];
5672     SDValue Addr, Disp;
5673
5674     Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(10, MVT::i32));
5675     Disp = DAG.getNode(ISD::SUB, MVT::i32, FPtr, Addr);
5676
5677     const unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
5678     const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
5679     OutChains[0] = DAG.getStore(Root, DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
5680                                 Trmp, TrmpAddr, 0);
5681
5682     Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(1, MVT::i32));
5683     OutChains[1] = DAG.getStore(Root, Nest, Addr, TrmpAddr, 1, false, 1);
5684
5685     const unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
5686     Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(5, MVT::i32));
5687     OutChains[2] = DAG.getStore(Root, DAG.getConstant(JMP, MVT::i8), Addr,
5688                                 TrmpAddr, 5, false, 1);
5689
5690     Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(6, MVT::i32));
5691     OutChains[3] = DAG.getStore(Root, Disp, Addr, TrmpAddr, 6, false, 1);
5692
5693     SDValue Ops[] =
5694       { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 4) };
5695     return DAG.getMergeValues(Ops, 2);
5696   }
5697 }
5698
5699 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op, SelectionDAG &DAG) {
5700   /*
5701    The rounding mode is in bits 11:10 of FPSR, and has the following
5702    settings:
5703      00 Round to nearest
5704      01 Round to -inf
5705      10 Round to +inf
5706      11 Round to 0
5707
5708   FLT_ROUNDS, on the other hand, expects the following:
5709     -1 Undefined
5710      0 Round to 0
5711      1 Round to nearest
5712      2 Round to +inf
5713      3 Round to -inf
5714
5715   To perform the conversion, we do:
5716     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
5717   */
5718
5719   MachineFunction &MF = DAG.getMachineFunction();
5720   const TargetMachine &TM = MF.getTarget();
5721   const TargetFrameInfo &TFI = *TM.getFrameInfo();
5722   unsigned StackAlignment = TFI.getStackAlignment();
5723   MVT VT = Op.getValueType();
5724
5725   // Save FP Control Word to stack slot
5726   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment);
5727   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5728
5729   SDValue Chain = DAG.getNode(X86ISD::FNSTCW16m, MVT::Other,
5730                                 DAG.getEntryNode(), StackSlot);
5731
5732   // Load FP Control Word from stack slot
5733   SDValue CWD = DAG.getLoad(MVT::i16, Chain, StackSlot, NULL, 0);
5734
5735   // Transform as necessary
5736   SDValue CWD1 =
5737     DAG.getNode(ISD::SRL, MVT::i16,
5738                 DAG.getNode(ISD::AND, MVT::i16,
5739                             CWD, DAG.getConstant(0x800, MVT::i16)),
5740                 DAG.getConstant(11, MVT::i8));
5741   SDValue CWD2 =
5742     DAG.getNode(ISD::SRL, MVT::i16,
5743                 DAG.getNode(ISD::AND, MVT::i16,
5744                             CWD, DAG.getConstant(0x400, MVT::i16)),
5745                 DAG.getConstant(9, MVT::i8));
5746
5747   SDValue RetVal =
5748     DAG.getNode(ISD::AND, MVT::i16,
5749                 DAG.getNode(ISD::ADD, MVT::i16,
5750                             DAG.getNode(ISD::OR, MVT::i16, CWD1, CWD2),
5751                             DAG.getConstant(1, MVT::i16)),
5752                 DAG.getConstant(3, MVT::i16));
5753
5754
5755   return DAG.getNode((VT.getSizeInBits() < 16 ?
5756                       ISD::TRUNCATE : ISD::ZERO_EXTEND), VT, RetVal);
5757 }
5758
5759 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
5760   MVT VT = Op.getValueType();
5761   MVT OpVT = VT;
5762   unsigned NumBits = VT.getSizeInBits();
5763
5764   Op = Op.getOperand(0);
5765   if (VT == MVT::i8) {
5766     // Zero extend to i32 since there is not an i8 bsr.
5767     OpVT = MVT::i32;
5768     Op = DAG.getNode(ISD::ZERO_EXTEND, OpVT, Op);
5769   }
5770
5771   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
5772   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
5773   Op = DAG.getNode(X86ISD::BSR, VTs, Op);
5774
5775   // If src is zero (i.e. bsr sets ZF), returns NumBits.
5776   SmallVector<SDValue, 4> Ops;
5777   Ops.push_back(Op);
5778   Ops.push_back(DAG.getConstant(NumBits+NumBits-1, OpVT));
5779   Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
5780   Ops.push_back(Op.getValue(1));
5781   Op = DAG.getNode(X86ISD::CMOV, OpVT, &Ops[0], 4);
5782
5783   // Finally xor with NumBits-1.
5784   Op = DAG.getNode(ISD::XOR, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
5785
5786   if (VT == MVT::i8)
5787     Op = DAG.getNode(ISD::TRUNCATE, MVT::i8, Op);
5788   return Op;
5789 }
5790
5791 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
5792   MVT VT = Op.getValueType();
5793   MVT OpVT = VT;
5794   unsigned NumBits = VT.getSizeInBits();
5795
5796   Op = Op.getOperand(0);
5797   if (VT == MVT::i8) {
5798     OpVT = MVT::i32;
5799     Op = DAG.getNode(ISD::ZERO_EXTEND, OpVT, Op);
5800   }
5801
5802   // Issue a bsf (scan bits forward) which also sets EFLAGS.
5803   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
5804   Op = DAG.getNode(X86ISD::BSF, VTs, Op);
5805
5806   // If src is zero (i.e. bsf sets ZF), returns NumBits.
5807   SmallVector<SDValue, 4> Ops;
5808   Ops.push_back(Op);
5809   Ops.push_back(DAG.getConstant(NumBits, OpVT));
5810   Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
5811   Ops.push_back(Op.getValue(1));
5812   Op = DAG.getNode(X86ISD::CMOV, OpVT, &Ops[0], 4);
5813
5814   if (VT == MVT::i8)
5815     Op = DAG.getNode(ISD::TRUNCATE, MVT::i8, Op);
5816   return Op;
5817 }
5818
5819 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) {
5820   MVT T = Op.getValueType();
5821   unsigned Reg = 0;
5822   unsigned size = 0;
5823   switch(T.getSimpleVT()) {
5824   default:
5825     assert(false && "Invalid value type!");
5826   case MVT::i8:  Reg = X86::AL;  size = 1; break;
5827   case MVT::i16: Reg = X86::AX;  size = 2; break;
5828   case MVT::i32: Reg = X86::EAX; size = 4; break;
5829   case MVT::i64: 
5830     if (Subtarget->is64Bit()) {
5831       Reg = X86::RAX; size = 8;
5832     } else //Should go away when LowerType stuff lands
5833       return SDValue(ExpandATOMIC_CMP_SWAP(Op.Val, DAG), 0);
5834     break;
5835   };
5836   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), Reg,
5837                                     Op.getOperand(3), SDValue());
5838   SDValue Ops[] = { cpIn.getValue(0),
5839                       Op.getOperand(1),
5840                       Op.getOperand(2),
5841                       DAG.getTargetConstant(size, MVT::i8),
5842                       cpIn.getValue(1) };
5843   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5844   SDValue Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, Tys, Ops, 5);
5845   SDValue cpOut = 
5846     DAG.getCopyFromReg(Result.getValue(0), Reg, T, Result.getValue(1));
5847   return cpOut;
5848 }
5849
5850 SDNode* X86TargetLowering::ExpandATOMIC_CMP_SWAP(SDNode* Op, SelectionDAG &DAG) {
5851   MVT T = Op->getValueType(0);
5852   assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
5853   SDValue cpInL, cpInH;
5854   cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(3),
5855                       DAG.getConstant(0, MVT::i32));
5856   cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(3),
5857                       DAG.getConstant(1, MVT::i32));
5858   cpInL = DAG.getCopyToReg(Op->getOperand(0), X86::EAX,
5859                            cpInL, SDValue());
5860   cpInH = DAG.getCopyToReg(cpInL.getValue(0), X86::EDX,
5861                            cpInH, cpInL.getValue(1));
5862   SDValue swapInL, swapInH;
5863   swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(2),
5864                         DAG.getConstant(0, MVT::i32));
5865   swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(2),
5866                         DAG.getConstant(1, MVT::i32));
5867   swapInL = DAG.getCopyToReg(cpInH.getValue(0), X86::EBX,
5868                              swapInL, cpInH.getValue(1));
5869   swapInH = DAG.getCopyToReg(swapInL.getValue(0), X86::ECX,
5870                              swapInH, swapInL.getValue(1));
5871   SDValue Ops[] = { swapInH.getValue(0),
5872                       Op->getOperand(1),
5873                       swapInH.getValue(1)};
5874   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5875   SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, Tys, Ops, 3);
5876   SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), X86::EAX, MVT::i32, 
5877                                         Result.getValue(1));
5878   SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), X86::EDX, MVT::i32, 
5879                                         cpOutL.getValue(2));
5880   SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
5881   SDValue ResultVal = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, OpsF, 2);
5882   SDValue Vals[2] = { ResultVal, cpOutH.getValue(1) };
5883   return DAG.getMergeValues(Vals, 2).Val;
5884 }
5885
5886 SDNode* X86TargetLowering::ExpandATOMIC_LOAD_SUB(SDNode* Op, SelectionDAG &DAG) {
5887   MVT T = Op->getValueType(0);
5888   SDValue negOp = DAG.getNode(ISD::SUB, T,
5889                                 DAG.getConstant(0, T), Op->getOperand(2));
5890   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, Op->getOperand(0),
5891                        Op->getOperand(1), negOp,
5892                        cast<AtomicSDNode>(Op)->getSrcValue(),
5893                        cast<AtomicSDNode>(Op)->getAlignment()).Val;
5894 }
5895
5896 /// LowerOperation - Provide custom lowering hooks for some operations.
5897 ///
5898 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
5899   switch (Op.getOpcode()) {
5900   default: assert(0 && "Should not custom lower this!");
5901   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
5902   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
5903   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
5904   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5905   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
5906   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
5907   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
5908   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
5909   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
5910   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
5911   case ISD::SHL_PARTS:
5912   case ISD::SRA_PARTS:
5913   case ISD::SRL_PARTS:          return LowerShift(Op, DAG);
5914   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
5915   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
5916   case ISD::FABS:               return LowerFABS(Op, DAG);
5917   case ISD::FNEG:               return LowerFNEG(Op, DAG);
5918   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
5919   case ISD::SETCC:              return LowerSETCC(Op, DAG);
5920   case ISD::VSETCC:             return LowerVSETCC(Op, DAG);
5921   case ISD::SELECT:             return LowerSELECT(Op, DAG);
5922   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
5923   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
5924   case ISD::CALL:               return LowerCALL(Op, DAG);
5925   case ISD::RET:                return LowerRET(Op, DAG);
5926   case ISD::FORMAL_ARGUMENTS:   return LowerFORMAL_ARGUMENTS(Op, DAG);
5927   case ISD::VASTART:            return LowerVASTART(Op, DAG);
5928   case ISD::VAARG:              return LowerVAARG(Op, DAG);
5929   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
5930   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
5931   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
5932   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
5933   case ISD::FRAME_TO_ARGS_OFFSET:
5934                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
5935   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
5936   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
5937   case ISD::TRAMPOLINE:         return LowerTRAMPOLINE(Op, DAG);
5938   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
5939   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
5940   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
5941       
5942   // FIXME: REMOVE THIS WHEN LegalizeDAGTypes lands.
5943   case ISD::READCYCLECOUNTER:
5944     return SDValue(ExpandREADCYCLECOUNTER(Op.Val, DAG), 0);
5945   }
5946 }
5947
5948 /// ReplaceNodeResults - Replace a node with an illegal result type
5949 /// with a new node built out of custom code.
5950 SDNode *X86TargetLowering::ReplaceNodeResults(SDNode *N, SelectionDAG &DAG) {
5951   switch (N->getOpcode()) {
5952   default: assert(0 && "Should not custom lower this!");
5953   case ISD::FP_TO_SINT:         return ExpandFP_TO_SINT(N, DAG);
5954   case ISD::READCYCLECOUNTER:   return ExpandREADCYCLECOUNTER(N, DAG);
5955   case ISD::ATOMIC_CMP_SWAP:    return ExpandATOMIC_CMP_SWAP(N, DAG);
5956   case ISD::ATOMIC_LOAD_SUB:    return ExpandATOMIC_LOAD_SUB(N,DAG);
5957   }
5958 }
5959
5960 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
5961   switch (Opcode) {
5962   default: return NULL;
5963   case X86ISD::BSF:                return "X86ISD::BSF";
5964   case X86ISD::BSR:                return "X86ISD::BSR";
5965   case X86ISD::SHLD:               return "X86ISD::SHLD";
5966   case X86ISD::SHRD:               return "X86ISD::SHRD";
5967   case X86ISD::FAND:               return "X86ISD::FAND";
5968   case X86ISD::FOR:                return "X86ISD::FOR";
5969   case X86ISD::FXOR:               return "X86ISD::FXOR";
5970   case X86ISD::FSRL:               return "X86ISD::FSRL";
5971   case X86ISD::FILD:               return "X86ISD::FILD";
5972   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
5973   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
5974   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
5975   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
5976   case X86ISD::FLD:                return "X86ISD::FLD";
5977   case X86ISD::FST:                return "X86ISD::FST";
5978   case X86ISD::CALL:               return "X86ISD::CALL";
5979   case X86ISD::TAILCALL:           return "X86ISD::TAILCALL";
5980   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
5981   case X86ISD::CMP:                return "X86ISD::CMP";
5982   case X86ISD::COMI:               return "X86ISD::COMI";
5983   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
5984   case X86ISD::SETCC:              return "X86ISD::SETCC";
5985   case X86ISD::CMOV:               return "X86ISD::CMOV";
5986   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
5987   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
5988   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
5989   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
5990   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
5991   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
5992   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
5993   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
5994   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
5995   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
5996   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
5997   case X86ISD::FMAX:               return "X86ISD::FMAX";
5998   case X86ISD::FMIN:               return "X86ISD::FMIN";
5999   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
6000   case X86ISD::FRCP:               return "X86ISD::FRCP";
6001   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
6002   case X86ISD::THREAD_POINTER:     return "X86ISD::THREAD_POINTER";
6003   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
6004   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
6005   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
6006   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
6007   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
6008   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
6009   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
6010   case X86ISD::VSHL:               return "X86ISD::VSHL";
6011   case X86ISD::VSRL:               return "X86ISD::VSRL";
6012   case X86ISD::CMPPD:              return "X86ISD::CMPPD";
6013   case X86ISD::CMPPS:              return "X86ISD::CMPPS";
6014   case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
6015   case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
6016   case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
6017   case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
6018   case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
6019   case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
6020   case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
6021   case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
6022   }
6023 }
6024
6025 // isLegalAddressingMode - Return true if the addressing mode represented
6026 // by AM is legal for this target, for a load/store of the specified type.
6027 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM, 
6028                                               const Type *Ty) const {
6029   // X86 supports extremely general addressing modes.
6030   
6031   // X86 allows a sign-extended 32-bit immediate field as a displacement.
6032   if (AM.BaseOffs <= -(1LL << 32) || AM.BaseOffs >= (1LL << 32)-1)
6033     return false;
6034   
6035   if (AM.BaseGV) {
6036     // We can only fold this if we don't need an extra load.
6037     if (Subtarget->GVRequiresExtraLoad(AM.BaseGV, getTargetMachine(), false))
6038       return false;
6039
6040     // X86-64 only supports addr of globals in small code model.
6041     if (Subtarget->is64Bit()) {
6042       if (getTargetMachine().getCodeModel() != CodeModel::Small)
6043         return false;
6044       // If lower 4G is not available, then we must use rip-relative addressing.
6045       if (AM.BaseOffs || AM.Scale > 1)
6046         return false;
6047     }
6048   }
6049   
6050   switch (AM.Scale) {
6051   case 0:
6052   case 1:
6053   case 2:
6054   case 4:
6055   case 8:
6056     // These scales always work.
6057     break;
6058   case 3:
6059   case 5:
6060   case 9:
6061     // These scales are formed with basereg+scalereg.  Only accept if there is
6062     // no basereg yet.
6063     if (AM.HasBaseReg)
6064       return false;
6065     break;
6066   default:  // Other stuff never works.
6067     return false;
6068   }
6069   
6070   return true;
6071 }
6072
6073
6074 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
6075   if (!Ty1->isInteger() || !Ty2->isInteger())
6076     return false;
6077   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6078   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
6079   if (NumBits1 <= NumBits2)
6080     return false;
6081   return Subtarget->is64Bit() || NumBits1 < 64;
6082 }
6083
6084 bool X86TargetLowering::isTruncateFree(MVT VT1, MVT VT2) const {
6085   if (!VT1.isInteger() || !VT2.isInteger())
6086     return false;
6087   unsigned NumBits1 = VT1.getSizeInBits();
6088   unsigned NumBits2 = VT2.getSizeInBits();
6089   if (NumBits1 <= NumBits2)
6090     return false;
6091   return Subtarget->is64Bit() || NumBits1 < 64;
6092 }
6093
6094 /// isShuffleMaskLegal - Targets can use this to indicate that they only
6095 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
6096 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
6097 /// are assumed to be legal.
6098 bool
6099 X86TargetLowering::isShuffleMaskLegal(SDValue Mask, MVT VT) const {
6100   // Only do shuffles on 128-bit vector types for now.
6101   if (VT.getSizeInBits() == 64) return false;
6102   return (Mask.Val->getNumOperands() <= 4 ||
6103           isIdentityMask(Mask.Val) ||
6104           isIdentityMask(Mask.Val, true) ||
6105           isSplatMask(Mask.Val)  ||
6106           isPSHUFHW_PSHUFLWMask(Mask.Val) ||
6107           X86::isUNPCKLMask(Mask.Val) ||
6108           X86::isUNPCKHMask(Mask.Val) ||
6109           X86::isUNPCKL_v_undef_Mask(Mask.Val) ||
6110           X86::isUNPCKH_v_undef_Mask(Mask.Val));
6111 }
6112
6113 bool
6114 X86TargetLowering::isVectorClearMaskLegal(const std::vector<SDValue> &BVOps,
6115                                           MVT EVT, SelectionDAG &DAG) const {
6116   unsigned NumElts = BVOps.size();
6117   // Only do shuffles on 128-bit vector types for now.
6118   if (EVT.getSizeInBits() * NumElts == 64) return false;
6119   if (NumElts == 2) return true;
6120   if (NumElts == 4) {
6121     return (isMOVLMask(&BVOps[0], 4)  ||
6122             isCommutedMOVL(&BVOps[0], 4, true) ||
6123             isSHUFPMask(&BVOps[0], 4) || 
6124             isCommutedSHUFP(&BVOps[0], 4));
6125   }
6126   return false;
6127 }
6128
6129 //===----------------------------------------------------------------------===//
6130 //                           X86 Scheduler Hooks
6131 //===----------------------------------------------------------------------===//
6132
6133 // private utility function
6134 MachineBasicBlock *
6135 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
6136                                                        MachineBasicBlock *MBB,
6137                                                        unsigned regOpc,
6138                                                        unsigned immOpc,
6139                                                        unsigned LoadOpc,
6140                                                        unsigned CXchgOpc,
6141                                                        unsigned copyOpc,
6142                                                        unsigned notOpc,
6143                                                        unsigned EAXreg,
6144                                                        TargetRegisterClass *RC,
6145                                                        bool invSrc) {
6146   // For the atomic bitwise operator, we generate
6147   //   thisMBB:
6148   //   newMBB:
6149   //     ld  t1 = [bitinstr.addr]
6150   //     op  t2 = t1, [bitinstr.val]
6151   //     mov EAX = t1
6152   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
6153   //     bz  newMBB
6154   //     fallthrough -->nextMBB
6155   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6156   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
6157   MachineFunction::iterator MBBIter = MBB;
6158   ++MBBIter;
6159   
6160   /// First build the CFG
6161   MachineFunction *F = MBB->getParent();
6162   MachineBasicBlock *thisMBB = MBB;
6163   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
6164   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
6165   F->insert(MBBIter, newMBB);
6166   F->insert(MBBIter, nextMBB);
6167   
6168   // Move all successors to thisMBB to nextMBB
6169   nextMBB->transferSuccessors(thisMBB);
6170     
6171   // Update thisMBB to fall through to newMBB
6172   thisMBB->addSuccessor(newMBB);
6173   
6174   // newMBB jumps to itself and fall through to nextMBB
6175   newMBB->addSuccessor(nextMBB);
6176   newMBB->addSuccessor(newMBB);
6177   
6178   // Insert instructions into newMBB based on incoming instruction
6179   assert(bInstr->getNumOperands() < 8 && "unexpected number of operands");
6180   MachineOperand& destOper = bInstr->getOperand(0);
6181   MachineOperand* argOpers[6];
6182   int numArgs = bInstr->getNumOperands() - 1;
6183   for (int i=0; i < numArgs; ++i)
6184     argOpers[i] = &bInstr->getOperand(i+1);
6185
6186   // x86 address has 4 operands: base, index, scale, and displacement
6187   int lastAddrIndx = 3; // [0,3]
6188   int valArgIndx = 4;
6189   
6190   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
6191   MachineInstrBuilder MIB = BuildMI(newMBB, TII->get(LoadOpc), t1);
6192   for (int i=0; i <= lastAddrIndx; ++i)
6193     (*MIB).addOperand(*argOpers[i]);
6194
6195   unsigned tt = F->getRegInfo().createVirtualRegister(RC);
6196   if (invSrc) {
6197     MIB = BuildMI(newMBB, TII->get(notOpc), tt).addReg(t1);
6198   }
6199   else 
6200     tt = t1;
6201
6202   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
6203   assert(   (argOpers[valArgIndx]->isReg() || argOpers[valArgIndx]->isImm())
6204          && "invalid operand");
6205   if (argOpers[valArgIndx]->isReg())
6206     MIB = BuildMI(newMBB, TII->get(regOpc), t2);
6207   else
6208     MIB = BuildMI(newMBB, TII->get(immOpc), t2);
6209   MIB.addReg(tt);
6210   (*MIB).addOperand(*argOpers[valArgIndx]);
6211
6212   MIB = BuildMI(newMBB, TII->get(copyOpc), EAXreg);
6213   MIB.addReg(t1);
6214   
6215   MIB = BuildMI(newMBB, TII->get(CXchgOpc));
6216   for (int i=0; i <= lastAddrIndx; ++i)
6217     (*MIB).addOperand(*argOpers[i]);
6218   MIB.addReg(t2);
6219   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
6220   (*MIB).addMemOperand(*F, *bInstr->memoperands_begin());
6221
6222   MIB = BuildMI(newMBB, TII->get(copyOpc), destOper.getReg());
6223   MIB.addReg(EAXreg);
6224   
6225   // insert branch
6226   BuildMI(newMBB, TII->get(X86::JNE)).addMBB(newMBB);
6227
6228   F->DeleteMachineInstr(bInstr);   // The pseudo instruction is gone now.
6229   return nextMBB;
6230 }
6231
6232 // private utility function
6233 MachineBasicBlock *
6234 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
6235                                                       MachineBasicBlock *MBB,
6236                                                       unsigned cmovOpc) {
6237   // For the atomic min/max operator, we generate
6238   //   thisMBB:
6239   //   newMBB:
6240   //     ld t1 = [min/max.addr]
6241   //     mov t2 = [min/max.val] 
6242   //     cmp  t1, t2
6243   //     cmov[cond] t2 = t1
6244   //     mov EAX = t1
6245   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
6246   //     bz   newMBB
6247   //     fallthrough -->nextMBB
6248   //
6249   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6250   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
6251   MachineFunction::iterator MBBIter = MBB;
6252   ++MBBIter;
6253   
6254   /// First build the CFG
6255   MachineFunction *F = MBB->getParent();
6256   MachineBasicBlock *thisMBB = MBB;
6257   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
6258   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
6259   F->insert(MBBIter, newMBB);
6260   F->insert(MBBIter, nextMBB);
6261   
6262   // Move all successors to thisMBB to nextMBB
6263   nextMBB->transferSuccessors(thisMBB);
6264   
6265   // Update thisMBB to fall through to newMBB
6266   thisMBB->addSuccessor(newMBB);
6267   
6268   // newMBB jumps to newMBB and fall through to nextMBB
6269   newMBB->addSuccessor(nextMBB);
6270   newMBB->addSuccessor(newMBB);
6271   
6272   // Insert instructions into newMBB based on incoming instruction
6273   assert(mInstr->getNumOperands() < 8 && "unexpected number of operands");
6274   MachineOperand& destOper = mInstr->getOperand(0);
6275   MachineOperand* argOpers[6];
6276   int numArgs = mInstr->getNumOperands() - 1;
6277   for (int i=0; i < numArgs; ++i)
6278     argOpers[i] = &mInstr->getOperand(i+1);
6279   
6280   // x86 address has 4 operands: base, index, scale, and displacement
6281   int lastAddrIndx = 3; // [0,3]
6282   int valArgIndx = 4;
6283   
6284   unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
6285   MachineInstrBuilder MIB = BuildMI(newMBB, TII->get(X86::MOV32rm), t1);
6286   for (int i=0; i <= lastAddrIndx; ++i)
6287     (*MIB).addOperand(*argOpers[i]);
6288
6289   // We only support register and immediate values
6290   assert(   (argOpers[valArgIndx]->isReg() || argOpers[valArgIndx]->isImm())
6291          && "invalid operand");
6292   
6293   unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);  
6294   if (argOpers[valArgIndx]->isReg())
6295     MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), t2);
6296   else 
6297     MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), t2);
6298   (*MIB).addOperand(*argOpers[valArgIndx]);
6299
6300   MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), X86::EAX);
6301   MIB.addReg(t1);
6302
6303   MIB = BuildMI(newMBB, TII->get(X86::CMP32rr));
6304   MIB.addReg(t1);
6305   MIB.addReg(t2);
6306
6307   // Generate movc
6308   unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
6309   MIB = BuildMI(newMBB, TII->get(cmovOpc),t3);
6310   MIB.addReg(t2);
6311   MIB.addReg(t1);
6312
6313   // Cmp and exchange if none has modified the memory location
6314   MIB = BuildMI(newMBB, TII->get(X86::LCMPXCHG32));
6315   for (int i=0; i <= lastAddrIndx; ++i)
6316     (*MIB).addOperand(*argOpers[i]);
6317   MIB.addReg(t3);
6318   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
6319   (*MIB).addMemOperand(*F, *mInstr->memoperands_begin());
6320   
6321   MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), destOper.getReg());
6322   MIB.addReg(X86::EAX);
6323   
6324   // insert branch
6325   BuildMI(newMBB, TII->get(X86::JNE)).addMBB(newMBB);
6326
6327   F->DeleteMachineInstr(mInstr);   // The pseudo instruction is gone now.
6328   return nextMBB;
6329 }
6330
6331
6332 MachineBasicBlock *
6333 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
6334                                                MachineBasicBlock *BB) {
6335   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6336   switch (MI->getOpcode()) {
6337   default: assert(false && "Unexpected instr type to insert");
6338   case X86::CMOV_FR32:
6339   case X86::CMOV_FR64:
6340   case X86::CMOV_V4F32:
6341   case X86::CMOV_V2F64:
6342   case X86::CMOV_V2I64: {
6343     // To "insert" a SELECT_CC instruction, we actually have to insert the
6344     // diamond control-flow pattern.  The incoming instruction knows the
6345     // destination vreg to set, the condition code register to branch on, the
6346     // true/false values to select between, and a branch opcode to use.
6347     const BasicBlock *LLVM_BB = BB->getBasicBlock();
6348     MachineFunction::iterator It = BB;
6349     ++It;
6350
6351     //  thisMBB:
6352     //  ...
6353     //   TrueVal = ...
6354     //   cmpTY ccX, r1, r2
6355     //   bCC copy1MBB
6356     //   fallthrough --> copy0MBB
6357     MachineBasicBlock *thisMBB = BB;
6358     MachineFunction *F = BB->getParent();
6359     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
6360     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
6361     unsigned Opc =
6362       X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
6363     BuildMI(BB, TII->get(Opc)).addMBB(sinkMBB);
6364     F->insert(It, copy0MBB);
6365     F->insert(It, sinkMBB);
6366     // Update machine-CFG edges by transferring all successors of the current
6367     // block to the new block which will contain the Phi node for the select.
6368     sinkMBB->transferSuccessors(BB);
6369
6370     // Add the true and fallthrough blocks as its successors.
6371     BB->addSuccessor(copy0MBB);
6372     BB->addSuccessor(sinkMBB);
6373
6374     //  copy0MBB:
6375     //   %FalseValue = ...
6376     //   # fallthrough to sinkMBB
6377     BB = copy0MBB;
6378
6379     // Update machine-CFG edges
6380     BB->addSuccessor(sinkMBB);
6381
6382     //  sinkMBB:
6383     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
6384     //  ...
6385     BB = sinkMBB;
6386     BuildMI(BB, TII->get(X86::PHI), MI->getOperand(0).getReg())
6387       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
6388       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
6389
6390     F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
6391     return BB;
6392   }
6393
6394   case X86::FP32_TO_INT16_IN_MEM:
6395   case X86::FP32_TO_INT32_IN_MEM:
6396   case X86::FP32_TO_INT64_IN_MEM:
6397   case X86::FP64_TO_INT16_IN_MEM:
6398   case X86::FP64_TO_INT32_IN_MEM:
6399   case X86::FP64_TO_INT64_IN_MEM:
6400   case X86::FP80_TO_INT16_IN_MEM:
6401   case X86::FP80_TO_INT32_IN_MEM:
6402   case X86::FP80_TO_INT64_IN_MEM: {
6403     // Change the floating point control register to use "round towards zero"
6404     // mode when truncating to an integer value.
6405     MachineFunction *F = BB->getParent();
6406     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
6407     addFrameReference(BuildMI(BB, TII->get(X86::FNSTCW16m)), CWFrameIdx);
6408
6409     // Load the old value of the high byte of the control word...
6410     unsigned OldCW =
6411       F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
6412     addFrameReference(BuildMI(BB, TII->get(X86::MOV16rm), OldCW), CWFrameIdx);
6413
6414     // Set the high part to be round to zero...
6415     addFrameReference(BuildMI(BB, TII->get(X86::MOV16mi)), CWFrameIdx)
6416       .addImm(0xC7F);
6417
6418     // Reload the modified control word now...
6419     addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
6420
6421     // Restore the memory image of control word to original value
6422     addFrameReference(BuildMI(BB, TII->get(X86::MOV16mr)), CWFrameIdx)
6423       .addReg(OldCW);
6424
6425     // Get the X86 opcode to use.
6426     unsigned Opc;
6427     switch (MI->getOpcode()) {
6428     default: assert(0 && "illegal opcode!");
6429     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
6430     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
6431     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
6432     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
6433     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
6434     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
6435     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
6436     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
6437     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
6438     }
6439
6440     X86AddressMode AM;
6441     MachineOperand &Op = MI->getOperand(0);
6442     if (Op.isRegister()) {
6443       AM.BaseType = X86AddressMode::RegBase;
6444       AM.Base.Reg = Op.getReg();
6445     } else {
6446       AM.BaseType = X86AddressMode::FrameIndexBase;
6447       AM.Base.FrameIndex = Op.getIndex();
6448     }
6449     Op = MI->getOperand(1);
6450     if (Op.isImmediate())
6451       AM.Scale = Op.getImm();
6452     Op = MI->getOperand(2);
6453     if (Op.isImmediate())
6454       AM.IndexReg = Op.getImm();
6455     Op = MI->getOperand(3);
6456     if (Op.isGlobalAddress()) {
6457       AM.GV = Op.getGlobal();
6458     } else {
6459       AM.Disp = Op.getImm();
6460     }
6461     addFullAddress(BuildMI(BB, TII->get(Opc)), AM)
6462                       .addReg(MI->getOperand(4).getReg());
6463
6464     // Reload the original control word now.
6465     addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
6466
6467     F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
6468     return BB;
6469   }
6470   case X86::ATOMAND32:
6471     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
6472                                                X86::AND32ri, X86::MOV32rm, 
6473                                                X86::LCMPXCHG32, X86::MOV32rr,
6474                                                X86::NOT32r, X86::EAX,
6475                                                X86::GR32RegisterClass);
6476   case X86::ATOMOR32:
6477     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr, 
6478                                                X86::OR32ri, X86::MOV32rm, 
6479                                                X86::LCMPXCHG32, X86::MOV32rr,
6480                                                X86::NOT32r, X86::EAX,
6481                                                X86::GR32RegisterClass);
6482   case X86::ATOMXOR32:
6483     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
6484                                                X86::XOR32ri, X86::MOV32rm, 
6485                                                X86::LCMPXCHG32, X86::MOV32rr,
6486                                                X86::NOT32r, X86::EAX,
6487                                                X86::GR32RegisterClass);
6488   case X86::ATOMNAND32:
6489     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
6490                                                X86::AND32ri, X86::MOV32rm,
6491                                                X86::LCMPXCHG32, X86::MOV32rr,
6492                                                X86::NOT32r, X86::EAX,
6493                                                X86::GR32RegisterClass, true);
6494   case X86::ATOMMIN32:
6495     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
6496   case X86::ATOMMAX32:
6497     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
6498   case X86::ATOMUMIN32:
6499     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
6500   case X86::ATOMUMAX32:
6501     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
6502
6503   case X86::ATOMAND16:
6504     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
6505                                                X86::AND16ri, X86::MOV16rm,
6506                                                X86::LCMPXCHG16, X86::MOV16rr,
6507                                                X86::NOT16r, X86::AX,
6508                                                X86::GR16RegisterClass);
6509   case X86::ATOMOR16:
6510     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr, 
6511                                                X86::OR16ri, X86::MOV16rm,
6512                                                X86::LCMPXCHG16, X86::MOV16rr,
6513                                                X86::NOT16r, X86::AX,
6514                                                X86::GR16RegisterClass);
6515   case X86::ATOMXOR16:
6516     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
6517                                                X86::XOR16ri, X86::MOV16rm,
6518                                                X86::LCMPXCHG16, X86::MOV16rr,
6519                                                X86::NOT16r, X86::AX,
6520                                                X86::GR16RegisterClass);
6521   case X86::ATOMNAND16:
6522     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
6523                                                X86::AND16ri, X86::MOV16rm,
6524                                                X86::LCMPXCHG16, X86::MOV16rr,
6525                                                X86::NOT16r, X86::AX,
6526                                                X86::GR16RegisterClass, true);
6527   case X86::ATOMMIN16:
6528     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
6529   case X86::ATOMMAX16:
6530     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
6531   case X86::ATOMUMIN16:
6532     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
6533   case X86::ATOMUMAX16:
6534     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
6535
6536   case X86::ATOMAND8:
6537     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
6538                                                X86::AND8ri, X86::MOV8rm,
6539                                                X86::LCMPXCHG8, X86::MOV8rr,
6540                                                X86::NOT8r, X86::AL,
6541                                                X86::GR8RegisterClass);
6542   case X86::ATOMOR8:
6543     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr, 
6544                                                X86::OR8ri, X86::MOV8rm,
6545                                                X86::LCMPXCHG8, X86::MOV8rr,
6546                                                X86::NOT8r, X86::AL,
6547                                                X86::GR8RegisterClass);
6548   case X86::ATOMXOR8:
6549     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
6550                                                X86::XOR8ri, X86::MOV8rm,
6551                                                X86::LCMPXCHG8, X86::MOV8rr,
6552                                                X86::NOT8r, X86::AL,
6553                                                X86::GR8RegisterClass);
6554   case X86::ATOMNAND8:
6555     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
6556                                                X86::AND8ri, X86::MOV8rm,
6557                                                X86::LCMPXCHG8, X86::MOV8rr,
6558                                                X86::NOT8r, X86::AL,
6559                                                X86::GR8RegisterClass, true);
6560   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
6561   }
6562 }
6563
6564 //===----------------------------------------------------------------------===//
6565 //                           X86 Optimization Hooks
6566 //===----------------------------------------------------------------------===//
6567
6568 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
6569                                                        const APInt &Mask,
6570                                                        APInt &KnownZero,
6571                                                        APInt &KnownOne,
6572                                                        const SelectionDAG &DAG,
6573                                                        unsigned Depth) const {
6574   unsigned Opc = Op.getOpcode();
6575   assert((Opc >= ISD::BUILTIN_OP_END ||
6576           Opc == ISD::INTRINSIC_WO_CHAIN ||
6577           Opc == ISD::INTRINSIC_W_CHAIN ||
6578           Opc == ISD::INTRINSIC_VOID) &&
6579          "Should use MaskedValueIsZero if you don't know whether Op"
6580          " is a target node!");
6581
6582   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
6583   switch (Opc) {
6584   default: break;
6585   case X86ISD::SETCC:
6586     KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
6587                                        Mask.getBitWidth() - 1);
6588     break;
6589   }
6590 }
6591
6592 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
6593 /// node is a GlobalAddress + offset.
6594 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
6595                                        GlobalValue* &GA, int64_t &Offset) const{
6596   if (N->getOpcode() == X86ISD::Wrapper) {
6597     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
6598       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
6599       return true;
6600     }
6601   }
6602   return TargetLowering::isGAPlusOffset(N, GA, Offset);
6603 }
6604
6605 static bool isBaseAlignmentOfN(unsigned N, SDNode *Base,
6606                                const TargetLowering &TLI) {
6607   GlobalValue *GV;
6608   int64_t Offset = 0;
6609   if (TLI.isGAPlusOffset(Base, GV, Offset))
6610     return (GV->getAlignment() >= N && (Offset % N) == 0);
6611   // DAG combine handles the stack object case.
6612   return false;
6613 }
6614
6615 static bool EltsFromConsecutiveLoads(SDNode *N, SDValue PermMask,
6616                                      unsigned NumElems, MVT EVT,
6617                                      SDNode *&Base,
6618                                      SelectionDAG &DAG, MachineFrameInfo *MFI,
6619                                      const TargetLowering &TLI) {
6620   Base = NULL;
6621   for (unsigned i = 0; i < NumElems; ++i) {
6622     SDValue Idx = PermMask.getOperand(i);
6623     if (Idx.getOpcode() == ISD::UNDEF) {
6624       if (!Base)
6625         return false;
6626       continue;
6627     }
6628
6629     SDValue Elt = DAG.getShuffleScalarElt(N, i);
6630     if (!Elt.Val ||
6631         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.Val)))
6632       return false;
6633     if (!Base) {
6634       Base = Elt.Val;
6635       if (Base->getOpcode() == ISD::UNDEF)
6636         return false;
6637       continue;
6638     }
6639     if (Elt.getOpcode() == ISD::UNDEF)
6640       continue;
6641
6642     if (!TLI.isConsecutiveLoad(Elt.Val, Base,
6643                                EVT.getSizeInBits()/8, i, MFI))
6644       return false;
6645   }
6646   return true;
6647 }
6648
6649 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
6650 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
6651 /// if the load addresses are consecutive, non-overlapping, and in the right
6652 /// order.
6653 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
6654                                        const TargetLowering &TLI) {
6655   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6656   MVT VT = N->getValueType(0);
6657   MVT EVT = VT.getVectorElementType();
6658   SDValue PermMask = N->getOperand(2);
6659   unsigned NumElems = PermMask.getNumOperands();
6660   SDNode *Base = NULL;
6661   if (!EltsFromConsecutiveLoads(N, PermMask, NumElems, EVT, Base,
6662                                 DAG, MFI, TLI))
6663     return SDValue();
6664
6665   LoadSDNode *LD = cast<LoadSDNode>(Base);
6666   if (isBaseAlignmentOfN(16, Base->getOperand(1).Val, TLI))
6667     return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
6668                        LD->getSrcValueOffset(), LD->isVolatile());
6669   return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
6670                      LD->getSrcValueOffset(), LD->isVolatile(),
6671                      LD->getAlignment());
6672 }
6673
6674 /// PerformBuildVectorCombine - build_vector 0,(load i64 / f64) -> movq / movsd.
6675 static SDValue PerformBuildVectorCombine(SDNode *N, SelectionDAG &DAG,
6676                                            const X86Subtarget *Subtarget,
6677                                            const TargetLowering &TLI) {
6678   unsigned NumOps = N->getNumOperands();
6679
6680   // Ignore single operand BUILD_VECTOR.
6681   if (NumOps == 1)
6682     return SDValue();
6683
6684   MVT VT = N->getValueType(0);
6685   MVT EVT = VT.getVectorElementType();
6686   if ((EVT != MVT::i64 && EVT != MVT::f64) || Subtarget->is64Bit())
6687     // We are looking for load i64 and zero extend. We want to transform
6688     // it before legalizer has a chance to expand it. Also look for i64
6689     // BUILD_PAIR bit casted to f64.
6690     return SDValue();
6691   // This must be an insertion into a zero vector.
6692   SDValue HighElt = N->getOperand(1);
6693   if (!isZeroNode(HighElt))
6694     return SDValue();
6695
6696   // Value must be a load.
6697   SDNode *Base = N->getOperand(0).Val;
6698   if (!isa<LoadSDNode>(Base)) {
6699     if (Base->getOpcode() != ISD::BIT_CONVERT)
6700       return SDValue();
6701     Base = Base->getOperand(0).Val;
6702     if (!isa<LoadSDNode>(Base))
6703       return SDValue();
6704   }
6705
6706   // Transform it into VZEXT_LOAD addr.
6707   LoadSDNode *LD = cast<LoadSDNode>(Base);
6708   
6709   // Load must not be an extload.
6710   if (LD->getExtensionType() != ISD::NON_EXTLOAD)
6711     return SDValue();
6712   
6713   return DAG.getNode(X86ISD::VZEXT_LOAD, VT, LD->getChain(), LD->getBasePtr());
6714 }                                           
6715
6716 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
6717 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
6718                                       const X86Subtarget *Subtarget) {
6719   SDValue Cond = N->getOperand(0);
6720
6721   // If we have SSE[12] support, try to form min/max nodes.
6722   if (Subtarget->hasSSE2() &&
6723       (N->getValueType(0) == MVT::f32 || N->getValueType(0) == MVT::f64)) {
6724     if (Cond.getOpcode() == ISD::SETCC) {
6725       // Get the LHS/RHS of the select.
6726       SDValue LHS = N->getOperand(1);
6727       SDValue RHS = N->getOperand(2);
6728       ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
6729
6730       unsigned Opcode = 0;
6731       if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
6732         switch (CC) {
6733         default: break;
6734         case ISD::SETOLE: // (X <= Y) ? X : Y -> min
6735         case ISD::SETULE:
6736         case ISD::SETLE:
6737           if (!UnsafeFPMath) break;
6738           // FALL THROUGH.
6739         case ISD::SETOLT:  // (X olt/lt Y) ? X : Y -> min
6740         case ISD::SETLT:
6741           Opcode = X86ISD::FMIN;
6742           break;
6743
6744         case ISD::SETOGT: // (X > Y) ? X : Y -> max
6745         case ISD::SETUGT:
6746         case ISD::SETGT:
6747           if (!UnsafeFPMath) break;
6748           // FALL THROUGH.
6749         case ISD::SETUGE:  // (X uge/ge Y) ? X : Y -> max
6750         case ISD::SETGE:
6751           Opcode = X86ISD::FMAX;
6752           break;
6753         }
6754       } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
6755         switch (CC) {
6756         default: break;
6757         case ISD::SETOGT: // (X > Y) ? Y : X -> min
6758         case ISD::SETUGT:
6759         case ISD::SETGT:
6760           if (!UnsafeFPMath) break;
6761           // FALL THROUGH.
6762         case ISD::SETUGE:  // (X uge/ge Y) ? Y : X -> min
6763         case ISD::SETGE:
6764           Opcode = X86ISD::FMIN;
6765           break;
6766
6767         case ISD::SETOLE:   // (X <= Y) ? Y : X -> max
6768         case ISD::SETULE:
6769         case ISD::SETLE:
6770           if (!UnsafeFPMath) break;
6771           // FALL THROUGH.
6772         case ISD::SETOLT:   // (X olt/lt Y) ? Y : X -> max
6773         case ISD::SETLT:
6774           Opcode = X86ISD::FMAX;
6775           break;
6776         }
6777       }
6778
6779       if (Opcode)
6780         return DAG.getNode(Opcode, N->getValueType(0), LHS, RHS);
6781     }
6782
6783   }
6784
6785   return SDValue();
6786 }
6787
6788 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
6789 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
6790                                      const X86Subtarget *Subtarget) {
6791   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
6792   // the FP state in cases where an emms may be missing.
6793   // A preferable solution to the general problem is to figure out the right
6794   // places to insert EMMS.  This qualifies as a quick hack.
6795   StoreSDNode *St = cast<StoreSDNode>(N);
6796   if (St->getValue().getValueType().isVector() &&
6797       St->getValue().getValueType().getSizeInBits() == 64 &&
6798       isa<LoadSDNode>(St->getValue()) &&
6799       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
6800       St->getChain().hasOneUse() && !St->isVolatile()) {
6801     SDNode* LdVal = St->getValue().Val;
6802     LoadSDNode *Ld = 0;
6803     int TokenFactorIndex = -1;
6804     SmallVector<SDValue, 8> Ops;
6805     SDNode* ChainVal = St->getChain().Val;
6806     // Must be a store of a load.  We currently handle two cases:  the load
6807     // is a direct child, and it's under an intervening TokenFactor.  It is
6808     // possible to dig deeper under nested TokenFactors.
6809     if (ChainVal == LdVal)
6810       Ld = cast<LoadSDNode>(St->getChain());
6811     else if (St->getValue().hasOneUse() &&
6812              ChainVal->getOpcode() == ISD::TokenFactor) {
6813       for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
6814         if (ChainVal->getOperand(i).Val == LdVal) {
6815           TokenFactorIndex = i;
6816           Ld = cast<LoadSDNode>(St->getValue());
6817         } else
6818           Ops.push_back(ChainVal->getOperand(i));
6819       }
6820     }
6821     if (Ld) {
6822       // If we are a 64-bit capable x86, lower to a single movq load/store pair.
6823       if (Subtarget->is64Bit()) {
6824         SDValue NewLd = DAG.getLoad(MVT::i64, Ld->getChain(), 
6825                                       Ld->getBasePtr(), Ld->getSrcValue(), 
6826                                       Ld->getSrcValueOffset(), Ld->isVolatile(),
6827                                       Ld->getAlignment());
6828         SDValue NewChain = NewLd.getValue(1);
6829         if (TokenFactorIndex != -1) {
6830           Ops.push_back(NewChain);
6831           NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0], 
6832                                  Ops.size());
6833         }
6834         return DAG.getStore(NewChain, NewLd, St->getBasePtr(),
6835                             St->getSrcValue(), St->getSrcValueOffset(),
6836                             St->isVolatile(), St->getAlignment());
6837       }
6838
6839       // Otherwise, lower to two 32-bit copies.
6840       SDValue LoAddr = Ld->getBasePtr();
6841       SDValue HiAddr = DAG.getNode(ISD::ADD, MVT::i32, LoAddr,
6842                                      DAG.getConstant(4, MVT::i32));
6843
6844       SDValue LoLd = DAG.getLoad(MVT::i32, Ld->getChain(), LoAddr,
6845                                    Ld->getSrcValue(), Ld->getSrcValueOffset(),
6846                                    Ld->isVolatile(), Ld->getAlignment());
6847       SDValue HiLd = DAG.getLoad(MVT::i32, Ld->getChain(), HiAddr,
6848                                    Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
6849                                    Ld->isVolatile(), 
6850                                    MinAlign(Ld->getAlignment(), 4));
6851
6852       SDValue NewChain = LoLd.getValue(1);
6853       if (TokenFactorIndex != -1) {
6854         Ops.push_back(LoLd);
6855         Ops.push_back(HiLd);
6856         NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0], 
6857                                Ops.size());
6858       }
6859
6860       LoAddr = St->getBasePtr();
6861       HiAddr = DAG.getNode(ISD::ADD, MVT::i32, LoAddr,
6862                            DAG.getConstant(4, MVT::i32));
6863
6864       SDValue LoSt = DAG.getStore(NewChain, LoLd, LoAddr,
6865                           St->getSrcValue(), St->getSrcValueOffset(),
6866                           St->isVolatile(), St->getAlignment());
6867       SDValue HiSt = DAG.getStore(NewChain, HiLd, HiAddr,
6868                                     St->getSrcValue(), St->getSrcValueOffset()+4,
6869                                     St->isVolatile(), 
6870                                     MinAlign(St->getAlignment(), 4));
6871       return DAG.getNode(ISD::TokenFactor, MVT::Other, LoSt, HiSt);
6872     }
6873   }
6874   return SDValue();
6875 }
6876
6877 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
6878 /// X86ISD::FXOR nodes.
6879 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
6880   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
6881   // F[X]OR(0.0, x) -> x
6882   // F[X]OR(x, 0.0) -> x
6883   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
6884     if (C->getValueAPF().isPosZero())
6885       return N->getOperand(1);
6886   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
6887     if (C->getValueAPF().isPosZero())
6888       return N->getOperand(0);
6889   return SDValue();
6890 }
6891
6892 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
6893 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
6894   // FAND(0.0, x) -> 0.0
6895   // FAND(x, 0.0) -> 0.0
6896   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
6897     if (C->getValueAPF().isPosZero())
6898       return N->getOperand(0);
6899   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
6900     if (C->getValueAPF().isPosZero())
6901       return N->getOperand(1);
6902   return SDValue();
6903 }
6904
6905
6906 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
6907                                                DAGCombinerInfo &DCI) const {
6908   SelectionDAG &DAG = DCI.DAG;
6909   switch (N->getOpcode()) {
6910   default: break;
6911   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
6912   case ISD::BUILD_VECTOR:
6913     return PerformBuildVectorCombine(N, DAG, Subtarget, *this);
6914   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
6915   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
6916   case X86ISD::FXOR:
6917   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
6918   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
6919   }
6920
6921   return SDValue();
6922 }
6923
6924 //===----------------------------------------------------------------------===//
6925 //                           X86 Inline Assembly Support
6926 //===----------------------------------------------------------------------===//
6927
6928 /// getConstraintType - Given a constraint letter, return the type of
6929 /// constraint it is for this target.
6930 X86TargetLowering::ConstraintType
6931 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
6932   if (Constraint.size() == 1) {
6933     switch (Constraint[0]) {
6934     case 'A':
6935     case 'f':
6936     case 'r':
6937     case 'R':
6938     case 'l':
6939     case 'q':
6940     case 'Q':
6941     case 'x':
6942     case 'y':
6943     case 'Y':
6944       return C_RegisterClass;
6945     default:
6946       break;
6947     }
6948   }
6949   return TargetLowering::getConstraintType(Constraint);
6950 }
6951
6952 /// LowerXConstraint - try to replace an X constraint, which matches anything,
6953 /// with another that has more specific requirements based on the type of the
6954 /// corresponding operand.
6955 const char *X86TargetLowering::
6956 LowerXConstraint(MVT ConstraintVT) const {
6957   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
6958   // 'f' like normal targets.
6959   if (ConstraintVT.isFloatingPoint()) {
6960     if (Subtarget->hasSSE2())
6961       return "Y";
6962     if (Subtarget->hasSSE1())
6963       return "x";
6964   }
6965   
6966   return TargetLowering::LowerXConstraint(ConstraintVT);
6967 }
6968
6969 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
6970 /// vector.  If it is invalid, don't add anything to Ops.
6971 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
6972                                                      char Constraint,
6973                                                      std::vector<SDValue>&Ops,
6974                                                      SelectionDAG &DAG) const {
6975   SDValue Result(0, 0);
6976   
6977   switch (Constraint) {
6978   default: break;
6979   case 'I':
6980     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
6981       if (C->getValue() <= 31) {
6982         Result = DAG.getTargetConstant(C->getValue(), Op.getValueType());
6983         break;
6984       }
6985     }
6986     return;
6987   case 'N':
6988     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
6989       if (C->getValue() <= 255) {
6990         Result = DAG.getTargetConstant(C->getValue(), Op.getValueType());
6991         break;
6992       }
6993     }
6994     return;
6995   case 'i': {
6996     // Literal immediates are always ok.
6997     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
6998       Result = DAG.getTargetConstant(CST->getValue(), Op.getValueType());
6999       break;
7000     }
7001
7002     // If we are in non-pic codegen mode, we allow the address of a global (with
7003     // an optional displacement) to be used with 'i'.
7004     GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
7005     int64_t Offset = 0;
7006     
7007     // Match either (GA) or (GA+C)
7008     if (GA) {
7009       Offset = GA->getOffset();
7010     } else if (Op.getOpcode() == ISD::ADD) {
7011       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7012       GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
7013       if (C && GA) {
7014         Offset = GA->getOffset()+C->getValue();
7015       } else {
7016         C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7017         GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
7018         if (C && GA)
7019           Offset = GA->getOffset()+C->getValue();
7020         else
7021           C = 0, GA = 0;
7022       }
7023     }
7024     
7025     if (GA) {
7026       // If addressing this global requires a load (e.g. in PIC mode), we can't
7027       // match.
7028       if (Subtarget->GVRequiresExtraLoad(GA->getGlobal(), getTargetMachine(),
7029                                          false))
7030         return;
7031
7032       Op = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
7033                                       Offset);
7034       Result = Op;
7035       break;
7036     }
7037
7038     // Otherwise, not valid for this mode.
7039     return;
7040   }
7041   }
7042   
7043   if (Result.Val) {
7044     Ops.push_back(Result);
7045     return;
7046   }
7047   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
7048 }
7049
7050 std::vector<unsigned> X86TargetLowering::
7051 getRegClassForInlineAsmConstraint(const std::string &Constraint,
7052                                   MVT VT) const {
7053   if (Constraint.size() == 1) {
7054     // FIXME: not handling fp-stack yet!
7055     switch (Constraint[0]) {      // GCC X86 Constraint Letters
7056     default: break;  // Unknown constraint letter
7057     case 'A':   // EAX/EDX
7058       if (VT == MVT::i32 || VT == MVT::i64)
7059         return make_vector<unsigned>(X86::EAX, X86::EDX, 0);
7060       break;
7061     case 'q':   // Q_REGS (GENERAL_REGS in 64-bit mode)
7062     case 'Q':   // Q_REGS
7063       if (VT == MVT::i32)
7064         return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
7065       else if (VT == MVT::i16)
7066         return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
7067       else if (VT == MVT::i8)
7068         return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
7069       else if (VT == MVT::i64)
7070         return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
7071       break;
7072     }
7073   }
7074
7075   return std::vector<unsigned>();
7076 }
7077
7078 std::pair<unsigned, const TargetRegisterClass*>
7079 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
7080                                                 MVT VT) const {
7081   // First, see if this is a constraint that directly corresponds to an LLVM
7082   // register class.
7083   if (Constraint.size() == 1) {
7084     // GCC Constraint Letters
7085     switch (Constraint[0]) {
7086     default: break;
7087     case 'r':   // GENERAL_REGS
7088     case 'R':   // LEGACY_REGS
7089     case 'l':   // INDEX_REGS
7090       if (VT == MVT::i64 && Subtarget->is64Bit())
7091         return std::make_pair(0U, X86::GR64RegisterClass);
7092       if (VT == MVT::i32)
7093         return std::make_pair(0U, X86::GR32RegisterClass);
7094       else if (VT == MVT::i16)
7095         return std::make_pair(0U, X86::GR16RegisterClass);
7096       else if (VT == MVT::i8)
7097         return std::make_pair(0U, X86::GR8RegisterClass);
7098       break;
7099     case 'f':  // FP Stack registers.
7100       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
7101       // value to the correct fpstack register class.
7102       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
7103         return std::make_pair(0U, X86::RFP32RegisterClass);
7104       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
7105         return std::make_pair(0U, X86::RFP64RegisterClass);
7106       return std::make_pair(0U, X86::RFP80RegisterClass);
7107     case 'y':   // MMX_REGS if MMX allowed.
7108       if (!Subtarget->hasMMX()) break;
7109       return std::make_pair(0U, X86::VR64RegisterClass);
7110       break;
7111     case 'Y':   // SSE_REGS if SSE2 allowed
7112       if (!Subtarget->hasSSE2()) break;
7113       // FALL THROUGH.
7114     case 'x':   // SSE_REGS if SSE1 allowed
7115       if (!Subtarget->hasSSE1()) break;
7116
7117       switch (VT.getSimpleVT()) {
7118       default: break;
7119       // Scalar SSE types.
7120       case MVT::f32:
7121       case MVT::i32:
7122         return std::make_pair(0U, X86::FR32RegisterClass);
7123       case MVT::f64:
7124       case MVT::i64:
7125         return std::make_pair(0U, X86::FR64RegisterClass);
7126       // Vector types.
7127       case MVT::v16i8:
7128       case MVT::v8i16:
7129       case MVT::v4i32:
7130       case MVT::v2i64:
7131       case MVT::v4f32:
7132       case MVT::v2f64:
7133         return std::make_pair(0U, X86::VR128RegisterClass);
7134       }
7135       break;
7136     }
7137   }
7138   
7139   // Use the default implementation in TargetLowering to convert the register
7140   // constraint into a member of a register class.
7141   std::pair<unsigned, const TargetRegisterClass*> Res;
7142   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
7143
7144   // Not found as a standard register?
7145   if (Res.second == 0) {
7146     // GCC calls "st(0)" just plain "st".
7147     if (StringsEqualNoCase("{st}", Constraint)) {
7148       Res.first = X86::ST0;
7149       Res.second = X86::RFP80RegisterClass;
7150     }
7151
7152     return Res;
7153   }
7154
7155   // Otherwise, check to see if this is a register class of the wrong value
7156   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
7157   // turn into {ax},{dx}.
7158   if (Res.second->hasType(VT))
7159     return Res;   // Correct type already, nothing to do.
7160
7161   // All of the single-register GCC register classes map their values onto
7162   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
7163   // really want an 8-bit or 32-bit register, map to the appropriate register
7164   // class and return the appropriate register.
7165   if (Res.second != X86::GR16RegisterClass)
7166     return Res;
7167
7168   if (VT == MVT::i8) {
7169     unsigned DestReg = 0;
7170     switch (Res.first) {
7171     default: break;
7172     case X86::AX: DestReg = X86::AL; break;
7173     case X86::DX: DestReg = X86::DL; break;
7174     case X86::CX: DestReg = X86::CL; break;
7175     case X86::BX: DestReg = X86::BL; break;
7176     }
7177     if (DestReg) {
7178       Res.first = DestReg;
7179       Res.second = Res.second = X86::GR8RegisterClass;
7180     }
7181   } else if (VT == MVT::i32) {
7182     unsigned DestReg = 0;
7183     switch (Res.first) {
7184     default: break;
7185     case X86::AX: DestReg = X86::EAX; break;
7186     case X86::DX: DestReg = X86::EDX; break;
7187     case X86::CX: DestReg = X86::ECX; break;
7188     case X86::BX: DestReg = X86::EBX; break;
7189     case X86::SI: DestReg = X86::ESI; break;
7190     case X86::DI: DestReg = X86::EDI; break;
7191     case X86::BP: DestReg = X86::EBP; break;
7192     case X86::SP: DestReg = X86::ESP; break;
7193     }
7194     if (DestReg) {
7195       Res.first = DestReg;
7196       Res.second = Res.second = X86::GR32RegisterClass;
7197     }
7198   } else if (VT == MVT::i64) {
7199     unsigned DestReg = 0;
7200     switch (Res.first) {
7201     default: break;
7202     case X86::AX: DestReg = X86::RAX; break;
7203     case X86::DX: DestReg = X86::RDX; break;
7204     case X86::CX: DestReg = X86::RCX; break;
7205     case X86::BX: DestReg = X86::RBX; break;
7206     case X86::SI: DestReg = X86::RSI; break;
7207     case X86::DI: DestReg = X86::RDI; break;
7208     case X86::BP: DestReg = X86::RBP; break;
7209     case X86::SP: DestReg = X86::RSP; break;
7210     }
7211     if (DestReg) {
7212       Res.first = DestReg;
7213       Res.second = Res.second = X86::GR64RegisterClass;
7214     }
7215   }
7216
7217   return Res;
7218 }