Implement "general dynamic", "initial exec" and "local exec" TLS models for
[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 was developed by Chris Lattner and is distributed under
6 // the University of Illinois Open Source 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/VectorExtras.h"
27 #include "llvm/Analysis/ScalarEvolutionExpressions.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/SelectionDAG.h"
33 #include "llvm/CodeGen/SSARegMap.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Target/TargetOptions.h"
36 #include "llvm/ADT/StringExtras.h"
37 using namespace llvm;
38
39 X86TargetLowering::X86TargetLowering(TargetMachine &TM)
40   : TargetLowering(TM) {
41   Subtarget = &TM.getSubtarget<X86Subtarget>();
42   X86ScalarSSE = Subtarget->hasSSE2();
43   X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
44
45   // Set up the TargetLowering object.
46
47   // X86 is weird, it always uses i8 for shift amounts and setcc results.
48   setShiftAmountType(MVT::i8);
49   setSetCCResultType(MVT::i8);
50   setSetCCResultContents(ZeroOrOneSetCCResult);
51   setSchedulingPreference(SchedulingForRegPressure);
52   setShiftAmountFlavor(Mask);   // shl X, 32 == shl X, 0
53   setStackPointerRegisterToSaveRestore(X86StackPtr);
54
55   if (Subtarget->isTargetDarwin()) {
56     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
57     setUseUnderscoreSetJmp(false);
58     setUseUnderscoreLongJmp(false);
59   } else if (Subtarget->isTargetMingw()) {
60     // MS runtime is weird: it exports _setjmp, but longjmp!
61     setUseUnderscoreSetJmp(true);
62     setUseUnderscoreLongJmp(false);
63   } else {
64     setUseUnderscoreSetJmp(true);
65     setUseUnderscoreLongJmp(true);
66   }
67   
68   // Set up the register classes.
69   addRegisterClass(MVT::i8, X86::GR8RegisterClass);
70   addRegisterClass(MVT::i16, X86::GR16RegisterClass);
71   addRegisterClass(MVT::i32, X86::GR32RegisterClass);
72   if (Subtarget->is64Bit())
73     addRegisterClass(MVT::i64, X86::GR64RegisterClass);
74
75   setLoadXAction(ISD::SEXTLOAD, MVT::i1, Expand);
76
77   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
78   // operation.
79   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
80   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
81   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
82
83   if (Subtarget->is64Bit()) {
84     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Expand);
85     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
86   } else {
87     if (X86ScalarSSE)
88       // If SSE i64 SINT_TO_FP is not available, expand i32 UINT_TO_FP.
89       setOperationAction(ISD::UINT_TO_FP   , MVT::i32  , Expand);
90     else
91       setOperationAction(ISD::UINT_TO_FP   , MVT::i32  , Promote);
92   }
93
94   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
95   // this operation.
96   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
97   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
98   // SSE has no i16 to fp conversion, only i32
99   if (X86ScalarSSE)
100     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
101   else {
102     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
103     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
104   }
105
106   if (!Subtarget->is64Bit()) {
107     // Custom lower SINT_TO_FP and FP_TO_SINT from/to i64 in 32-bit mode.
108     setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
109     setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
110   }
111
112   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
113   // this operation.
114   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
115   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
116
117   if (X86ScalarSSE) {
118     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
119   } else {
120     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
121     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
122   }
123
124   // Handle FP_TO_UINT by promoting the destination to a larger signed
125   // conversion.
126   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
127   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
128   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
129
130   if (Subtarget->is64Bit()) {
131     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
132     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
133   } else {
134     if (X86ScalarSSE && !Subtarget->hasSSE3())
135       // Expand FP_TO_UINT into a select.
136       // FIXME: We would like to use a Custom expander here eventually to do
137       // the optimal thing for SSE vs. the default expansion in the legalizer.
138       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
139     else
140       // With SSE3 we can use fisttpll to convert to a signed i64.
141       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Promote);
142   }
143
144   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
145   if (!X86ScalarSSE) {
146     setOperationAction(ISD::BIT_CONVERT      , MVT::f32  , Expand);
147     setOperationAction(ISD::BIT_CONVERT      , MVT::i32  , Expand);
148   }
149
150   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
151   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
152   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
153   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
154   setOperationAction(ISD::MEMMOVE          , MVT::Other, Expand);
155   if (Subtarget->is64Bit())
156     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Expand);
157   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Expand);
158   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Expand);
159   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
160   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
161   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
162
163   setOperationAction(ISD::CTPOP            , MVT::i8   , Expand);
164   setOperationAction(ISD::CTTZ             , MVT::i8   , Expand);
165   setOperationAction(ISD::CTLZ             , MVT::i8   , Expand);
166   setOperationAction(ISD::CTPOP            , MVT::i16  , Expand);
167   setOperationAction(ISD::CTTZ             , MVT::i16  , Expand);
168   setOperationAction(ISD::CTLZ             , MVT::i16  , Expand);
169   setOperationAction(ISD::CTPOP            , MVT::i32  , Expand);
170   setOperationAction(ISD::CTTZ             , MVT::i32  , Expand);
171   setOperationAction(ISD::CTLZ             , MVT::i32  , Expand);
172   if (Subtarget->is64Bit()) {
173     setOperationAction(ISD::CTPOP          , MVT::i64  , Expand);
174     setOperationAction(ISD::CTTZ           , MVT::i64  , Expand);
175     setOperationAction(ISD::CTLZ           , MVT::i64  , Expand);
176   }
177
178   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
179   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
180
181   // These should be promoted to a larger select which is supported.
182   setOperationAction(ISD::SELECT           , MVT::i1   , Promote);
183   setOperationAction(ISD::SELECT           , MVT::i8   , Promote);
184   // X86 wants to expand cmov itself.
185   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
186   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
187   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
188   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
189   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
190   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
191   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
192   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
193   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
194   if (Subtarget->is64Bit()) {
195     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
196     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
197   }
198   // X86 ret instruction may pop stack.
199   setOperationAction(ISD::RET             , MVT::Other, Custom);
200   // Darwin ABI issue.
201   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
202   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
203   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
204   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
205   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
206   if (Subtarget->is64Bit()) {
207     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
208     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
209     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
210     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
211   }
212   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
213   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
214   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
215   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
216   // X86 wants to expand memset / memcpy itself.
217   setOperationAction(ISD::MEMSET          , MVT::Other, Custom);
218   setOperationAction(ISD::MEMCPY          , MVT::Other, Custom);
219
220   // We don't have line number support yet.
221   setOperationAction(ISD::LOCATION, MVT::Other, Expand);
222   setOperationAction(ISD::DEBUG_LOC, MVT::Other, Expand);
223   // FIXME - use subtarget debug flags
224   if (!Subtarget->isTargetDarwin() &&
225       !Subtarget->isTargetELF() &&
226       !Subtarget->isTargetCygMing())
227     setOperationAction(ISD::LABEL, MVT::Other, Expand);
228
229   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
230   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
231   setOperationAction(ISD::VAARG             , MVT::Other, Expand);
232   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
233   if (Subtarget->is64Bit())
234     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
235   else
236     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
237
238   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
239   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
240   if (Subtarget->is64Bit())
241     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
242   if (Subtarget->isTargetCygMing())
243     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
244   else
245     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
246
247   if (X86ScalarSSE) {
248     // Set up the FP register classes.
249     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
250     addRegisterClass(MVT::f64, X86::FR64RegisterClass);
251
252     // Use ANDPD to simulate FABS.
253     setOperationAction(ISD::FABS , MVT::f64, Custom);
254     setOperationAction(ISD::FABS , MVT::f32, Custom);
255
256     // Use XORP to simulate FNEG.
257     setOperationAction(ISD::FNEG , MVT::f64, Custom);
258     setOperationAction(ISD::FNEG , MVT::f32, Custom);
259
260     // Use ANDPD and ORPD to simulate FCOPYSIGN.
261     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
262     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
263
264     // We don't support sin/cos/fmod
265     setOperationAction(ISD::FSIN , MVT::f64, Expand);
266     setOperationAction(ISD::FCOS , MVT::f64, Expand);
267     setOperationAction(ISD::FREM , MVT::f64, Expand);
268     setOperationAction(ISD::FSIN , MVT::f32, Expand);
269     setOperationAction(ISD::FCOS , MVT::f32, Expand);
270     setOperationAction(ISD::FREM , MVT::f32, Expand);
271
272     // Expand FP immediates into loads from the stack, except for the special
273     // cases we handle.
274     setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
275     setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
276     addLegalFPImmediate(+0.0); // xorps / xorpd
277   } else {
278     // Set up the FP register classes.
279     addRegisterClass(MVT::f64, X86::RFPRegisterClass);
280
281     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
282     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
283     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
284
285     if (!UnsafeFPMath) {
286       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
287       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
288     }
289
290     setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
291     addLegalFPImmediate(+0.0); // FLD0
292     addLegalFPImmediate(+1.0); // FLD1
293     addLegalFPImmediate(-0.0); // FLD0/FCHS
294     addLegalFPImmediate(-1.0); // FLD1/FCHS
295   }
296
297   // First set operation action for all vector types to expand. Then we
298   // will selectively turn on ones that can be effectively codegen'd.
299   for (unsigned VT = (unsigned)MVT::Vector + 1;
300        VT != (unsigned)MVT::LAST_VALUETYPE; VT++) {
301     setOperationAction(ISD::ADD , (MVT::ValueType)VT, Expand);
302     setOperationAction(ISD::SUB , (MVT::ValueType)VT, Expand);
303     setOperationAction(ISD::FADD, (MVT::ValueType)VT, Expand);
304     setOperationAction(ISD::FSUB, (MVT::ValueType)VT, Expand);
305     setOperationAction(ISD::MUL , (MVT::ValueType)VT, Expand);
306     setOperationAction(ISD::FMUL, (MVT::ValueType)VT, Expand);
307     setOperationAction(ISD::SDIV, (MVT::ValueType)VT, Expand);
308     setOperationAction(ISD::UDIV, (MVT::ValueType)VT, Expand);
309     setOperationAction(ISD::FDIV, (MVT::ValueType)VT, Expand);
310     setOperationAction(ISD::SREM, (MVT::ValueType)VT, Expand);
311     setOperationAction(ISD::UREM, (MVT::ValueType)VT, Expand);
312     setOperationAction(ISD::LOAD, (MVT::ValueType)VT, Expand);
313     setOperationAction(ISD::VECTOR_SHUFFLE,     (MVT::ValueType)VT, Expand);
314     setOperationAction(ISD::EXTRACT_VECTOR_ELT, (MVT::ValueType)VT, Expand);
315     setOperationAction(ISD::INSERT_VECTOR_ELT,  (MVT::ValueType)VT, Expand);
316   }
317
318   if (Subtarget->hasMMX()) {
319     addRegisterClass(MVT::v8i8,  X86::VR64RegisterClass);
320     addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
321     addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
322     addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
323
324     // FIXME: add MMX packed arithmetics
325
326     setOperationAction(ISD::ADD,                MVT::v8i8,  Legal);
327     setOperationAction(ISD::ADD,                MVT::v4i16, Legal);
328     setOperationAction(ISD::ADD,                MVT::v2i32, Legal);
329     setOperationAction(ISD::ADD,                MVT::v1i64, Legal);
330
331     setOperationAction(ISD::SUB,                MVT::v8i8,  Legal);
332     setOperationAction(ISD::SUB,                MVT::v4i16, Legal);
333     setOperationAction(ISD::SUB,                MVT::v2i32, Legal);
334
335     setOperationAction(ISD::MULHS,              MVT::v4i16, Legal);
336     setOperationAction(ISD::MUL,                MVT::v4i16, Legal);
337
338     setOperationAction(ISD::AND,                MVT::v8i8,  Promote);
339     AddPromotedToType (ISD::AND,                MVT::v8i8,  MVT::v1i64);
340     setOperationAction(ISD::AND,                MVT::v4i16, Promote);
341     AddPromotedToType (ISD::AND,                MVT::v4i16, MVT::v1i64);
342     setOperationAction(ISD::AND,                MVT::v2i32, Promote);
343     AddPromotedToType (ISD::AND,                MVT::v2i32, MVT::v1i64);
344     setOperationAction(ISD::AND,                MVT::v1i64, Legal);
345
346     setOperationAction(ISD::OR,                 MVT::v8i8,  Promote);
347     AddPromotedToType (ISD::OR,                 MVT::v8i8,  MVT::v1i64);
348     setOperationAction(ISD::OR,                 MVT::v4i16, Promote);
349     AddPromotedToType (ISD::OR,                 MVT::v4i16, MVT::v1i64);
350     setOperationAction(ISD::OR,                 MVT::v2i32, Promote);
351     AddPromotedToType (ISD::OR,                 MVT::v2i32, MVT::v1i64);
352     setOperationAction(ISD::OR,                 MVT::v1i64, Legal);
353
354     setOperationAction(ISD::XOR,                MVT::v8i8,  Promote);
355     AddPromotedToType (ISD::XOR,                MVT::v8i8,  MVT::v1i64);
356     setOperationAction(ISD::XOR,                MVT::v4i16, Promote);
357     AddPromotedToType (ISD::XOR,                MVT::v4i16, MVT::v1i64);
358     setOperationAction(ISD::XOR,                MVT::v2i32, Promote);
359     AddPromotedToType (ISD::XOR,                MVT::v2i32, MVT::v1i64);
360     setOperationAction(ISD::XOR,                MVT::v1i64, Legal);
361
362     setOperationAction(ISD::LOAD,               MVT::v8i8,  Promote);
363     AddPromotedToType (ISD::LOAD,               MVT::v8i8,  MVT::v1i64);
364     setOperationAction(ISD::LOAD,               MVT::v4i16, Promote);
365     AddPromotedToType (ISD::LOAD,               MVT::v4i16, MVT::v1i64);
366     setOperationAction(ISD::LOAD,               MVT::v2i32, Promote);
367     AddPromotedToType (ISD::LOAD,               MVT::v2i32, MVT::v1i64);
368     setOperationAction(ISD::LOAD,               MVT::v1i64, Legal);
369
370     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i8,  Custom);
371     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i16, Custom);
372     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i32, Custom);
373     setOperationAction(ISD::BUILD_VECTOR,       MVT::v1i64, Custom);
374
375     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8i8,  Custom);
376     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i16, Custom);
377     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i32, Custom);
378     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v1i64, Custom);
379
380     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Custom);
381     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Custom);
382   }
383
384   if (Subtarget->hasSSE1()) {
385     addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
386
387     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
388     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
389     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
390     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
391     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
392     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
393     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
394     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
395     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
396   }
397
398   if (Subtarget->hasSSE2()) {
399     addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
400     addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
401     addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
402     addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
403     addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
404
405     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
406     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
407     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
408     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
409     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
410     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
411     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
412     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
413     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
414     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
415     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
416     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
417     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
418
419     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
420     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
421     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
422     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
423     // Implement v4f32 insert_vector_elt in terms of SSE2 v8i16 ones.
424     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
425
426     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
427     for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
428       setOperationAction(ISD::BUILD_VECTOR,        (MVT::ValueType)VT, Custom);
429       setOperationAction(ISD::VECTOR_SHUFFLE,      (MVT::ValueType)VT, Custom);
430       setOperationAction(ISD::EXTRACT_VECTOR_ELT,  (MVT::ValueType)VT, Custom);
431     }
432     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
433     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
434     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
435     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
436     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
437     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
438
439     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
440     for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
441       setOperationAction(ISD::AND,    (MVT::ValueType)VT, Promote);
442       AddPromotedToType (ISD::AND,    (MVT::ValueType)VT, MVT::v2i64);
443       setOperationAction(ISD::OR,     (MVT::ValueType)VT, Promote);
444       AddPromotedToType (ISD::OR,     (MVT::ValueType)VT, MVT::v2i64);
445       setOperationAction(ISD::XOR,    (MVT::ValueType)VT, Promote);
446       AddPromotedToType (ISD::XOR,    (MVT::ValueType)VT, MVT::v2i64);
447       setOperationAction(ISD::LOAD,   (MVT::ValueType)VT, Promote);
448       AddPromotedToType (ISD::LOAD,   (MVT::ValueType)VT, MVT::v2i64);
449       setOperationAction(ISD::SELECT, (MVT::ValueType)VT, Promote);
450       AddPromotedToType (ISD::SELECT, (MVT::ValueType)VT, MVT::v2i64);
451     }
452
453     // Custom lower v2i64 and v2f64 selects.
454     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
455     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
456     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
457     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
458   }
459
460   // We want to custom lower some of our intrinsics.
461   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
462
463   // We have target-specific dag combine patterns for the following nodes:
464   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
465   setTargetDAGCombine(ISD::SELECT);
466
467   computeRegisterProperties();
468
469   // FIXME: These should be based on subtarget info. Plus, the values should
470   // be smaller when we are in optimizing for size mode.
471   maxStoresPerMemset = 16; // For %llvm.memset -> sequence of stores
472   maxStoresPerMemcpy = 16; // For %llvm.memcpy -> sequence of stores
473   maxStoresPerMemmove = 16; // For %llvm.memmove -> sequence of stores
474   allowUnalignedMemoryAccesses = true; // x86 supports it!
475 }
476
477
478 //===----------------------------------------------------------------------===//
479 //               Return Value Calling Convention Implementation
480 //===----------------------------------------------------------------------===//
481
482 #include "X86GenCallingConv.inc"
483     
484 /// LowerRET - Lower an ISD::RET node.
485 SDOperand X86TargetLowering::LowerRET(SDOperand Op, SelectionDAG &DAG) {
486   assert((Op.getNumOperands() & 1) == 1 && "ISD::RET should have odd # args");
487   
488   SmallVector<CCValAssign, 16> RVLocs;
489   unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
490   CCState CCInfo(CC, getTargetMachine(), RVLocs);
491   CCInfo.AnalyzeReturn(Op.Val, RetCC_X86);
492   
493   
494   // If this is the first return lowered for this function, add the regs to the
495   // liveout set for the function.
496   if (DAG.getMachineFunction().liveout_empty()) {
497     for (unsigned i = 0; i != RVLocs.size(); ++i)
498       if (RVLocs[i].isRegLoc())
499         DAG.getMachineFunction().addLiveOut(RVLocs[i].getLocReg());
500   }
501   
502   SDOperand Chain = Op.getOperand(0);
503   SDOperand Flag;
504   
505   // Copy the result values into the output registers.
506   if (RVLocs.size() != 1 || !RVLocs[0].isRegLoc() ||
507       RVLocs[0].getLocReg() != X86::ST0) {
508     for (unsigned i = 0; i != RVLocs.size(); ++i) {
509       CCValAssign &VA = RVLocs[i];
510       assert(VA.isRegLoc() && "Can only return in registers!");
511       Chain = DAG.getCopyToReg(Chain, VA.getLocReg(), Op.getOperand(i*2+1),
512                                Flag);
513       Flag = Chain.getValue(1);
514     }
515   } else {
516     // We need to handle a destination of ST0 specially, because it isn't really
517     // a register.
518     SDOperand Value = Op.getOperand(1);
519     
520     // If this is an FP return with ScalarSSE, we need to move the value from
521     // an XMM register onto the fp-stack.
522     if (X86ScalarSSE) {
523       SDOperand MemLoc;
524       
525       // If this is a load into a scalarsse value, don't store the loaded value
526       // back to the stack, only to reload it: just replace the scalar-sse load.
527       if (ISD::isNON_EXTLoad(Value.Val) &&
528           (Chain == Value.getValue(1) || Chain == Value.getOperand(0))) {
529         Chain  = Value.getOperand(0);
530         MemLoc = Value.getOperand(1);
531       } else {
532         // Spill the value to memory and reload it into top of stack.
533         unsigned Size = MVT::getSizeInBits(RVLocs[0].getValVT())/8;
534         MachineFunction &MF = DAG.getMachineFunction();
535         int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
536         MemLoc = DAG.getFrameIndex(SSFI, getPointerTy());
537         Chain = DAG.getStore(Op.getOperand(0), Value, MemLoc, NULL, 0);
538       }
539       SDVTList Tys = DAG.getVTList(MVT::f64, MVT::Other);
540       SDOperand Ops[] = {Chain, MemLoc, DAG.getValueType(RVLocs[0].getValVT())};
541       Value = DAG.getNode(X86ISD::FLD, Tys, Ops, 3);
542       Chain = Value.getValue(1);
543     }
544     
545     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
546     SDOperand Ops[] = { Chain, Value };
547     Chain = DAG.getNode(X86ISD::FP_SET_RESULT, Tys, Ops, 2);
548     Flag = Chain.getValue(1);
549   }
550   
551   SDOperand BytesToPop = DAG.getConstant(getBytesToPopOnReturn(), MVT::i16);
552   if (Flag.Val)
553     return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, Chain, BytesToPop, Flag);
554   else
555     return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, Chain, BytesToPop);
556 }
557
558
559 /// LowerCallResult - Lower the result values of an ISD::CALL into the
560 /// appropriate copies out of appropriate physical registers.  This assumes that
561 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
562 /// being lowered.  The returns a SDNode with the same number of values as the
563 /// ISD::CALL.
564 SDNode *X86TargetLowering::
565 LowerCallResult(SDOperand Chain, SDOperand InFlag, SDNode *TheCall, 
566                 unsigned CallingConv, SelectionDAG &DAG) {
567   
568   // Assign locations to each value returned by this call.
569   SmallVector<CCValAssign, 16> RVLocs;
570   CCState CCInfo(CallingConv, getTargetMachine(), RVLocs);
571   CCInfo.AnalyzeCallResult(TheCall, RetCC_X86);
572
573   
574   SmallVector<SDOperand, 8> ResultVals;
575   
576   // Copy all of the result registers out of their specified physreg.
577   if (RVLocs.size() != 1 || RVLocs[0].getLocReg() != X86::ST0) {
578     for (unsigned i = 0; i != RVLocs.size(); ++i) {
579       Chain = DAG.getCopyFromReg(Chain, RVLocs[i].getLocReg(),
580                                  RVLocs[i].getValVT(), InFlag).getValue(1);
581       InFlag = Chain.getValue(2);
582       ResultVals.push_back(Chain.getValue(0));
583     }
584   } else {
585     // Copies from the FP stack are special, as ST0 isn't a valid register
586     // before the fp stackifier runs.
587     
588     // Copy ST0 into an RFP register with FP_GET_RESULT.
589     SDVTList Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
590     SDOperand GROps[] = { Chain, InFlag };
591     SDOperand RetVal = DAG.getNode(X86ISD::FP_GET_RESULT, Tys, GROps, 2);
592     Chain  = RetVal.getValue(1);
593     InFlag = RetVal.getValue(2);
594     
595     // If we are using ScalarSSE, store ST(0) to the stack and reload it into
596     // an XMM register.
597     if (X86ScalarSSE) {
598       // FIXME: Currently the FST is flagged to the FP_GET_RESULT. This
599       // shouldn't be necessary except that RFP cannot be live across
600       // multiple blocks. When stackifier is fixed, they can be uncoupled.
601       MachineFunction &MF = DAG.getMachineFunction();
602       int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
603       SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
604       SDOperand Ops[] = {
605         Chain, RetVal, StackSlot, DAG.getValueType(RVLocs[0].getValVT()), InFlag
606       };
607       Chain = DAG.getNode(X86ISD::FST, MVT::Other, Ops, 5);
608       RetVal = DAG.getLoad(RVLocs[0].getValVT(), Chain, StackSlot, NULL, 0);
609       Chain = RetVal.getValue(1);
610     }
611     
612     if (RVLocs[0].getValVT() == MVT::f32 && !X86ScalarSSE)
613       // FIXME: we would really like to remember that this FP_ROUND
614       // operation is okay to eliminate if we allow excess FP precision.
615       RetVal = DAG.getNode(ISD::FP_ROUND, MVT::f32, RetVal);
616     ResultVals.push_back(RetVal);
617   }
618   
619   // Merge everything together with a MERGE_VALUES node.
620   ResultVals.push_back(Chain);
621   return DAG.getNode(ISD::MERGE_VALUES, TheCall->getVTList(),
622                      &ResultVals[0], ResultVals.size()).Val;
623 }
624
625
626 //===----------------------------------------------------------------------===//
627 //                C & StdCall Calling Convention implementation
628 //===----------------------------------------------------------------------===//
629 //  StdCall calling convention seems to be standard for many Windows' API
630 //  routines and around. It differs from C calling convention just a little:
631 //  callee should clean up the stack, not caller. Symbols should be also
632 //  decorated in some fancy way :) It doesn't support any vector arguments.
633
634 /// AddLiveIn - This helper function adds the specified physical register to the
635 /// MachineFunction as a live in value.  It also creates a corresponding virtual
636 /// register for it.
637 static unsigned AddLiveIn(MachineFunction &MF, unsigned PReg,
638                           const TargetRegisterClass *RC) {
639   assert(RC->contains(PReg) && "Not the correct regclass!");
640   unsigned VReg = MF.getSSARegMap()->createVirtualRegister(RC);
641   MF.addLiveIn(PReg, VReg);
642   return VReg;
643 }
644
645 SDOperand X86TargetLowering::LowerCCCArguments(SDOperand Op, SelectionDAG &DAG,
646                                                bool isStdCall) {
647   unsigned NumArgs = Op.Val->getNumValues() - 1;
648   MachineFunction &MF = DAG.getMachineFunction();
649   MachineFrameInfo *MFI = MF.getFrameInfo();
650   SDOperand Root = Op.getOperand(0);
651   bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
652
653   // Assign locations to all of the incoming arguments.
654   SmallVector<CCValAssign, 16> ArgLocs;
655   CCState CCInfo(MF.getFunction()->getCallingConv(), getTargetMachine(),
656                  ArgLocs);
657   CCInfo.AnalyzeFormalArguments(Op.Val, CC_X86_32_C);
658    
659   SmallVector<SDOperand, 8> ArgValues;
660   unsigned LastVal = ~0U;
661   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
662     CCValAssign &VA = ArgLocs[i];
663     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
664     // places.
665     assert(VA.getValNo() != LastVal &&
666            "Don't support value assigned to multiple locs yet");
667     LastVal = VA.getValNo();
668     
669     if (VA.isRegLoc()) {
670       MVT::ValueType RegVT = VA.getLocVT();
671       TargetRegisterClass *RC;
672       if (RegVT == MVT::i32)
673         RC = X86::GR32RegisterClass;
674       else {
675         assert(MVT::isVector(RegVT));
676         RC = X86::VR128RegisterClass;
677       }
678       
679       unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
680       SDOperand ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
681       
682       // If this is an 8 or 16-bit value, it is really passed promoted to 32
683       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
684       // right size.
685       if (VA.getLocInfo() == CCValAssign::SExt)
686         ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
687                                DAG.getValueType(VA.getValVT()));
688       else if (VA.getLocInfo() == CCValAssign::ZExt)
689         ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
690                                DAG.getValueType(VA.getValVT()));
691       
692       if (VA.getLocInfo() != CCValAssign::Full)
693         ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
694       
695       ArgValues.push_back(ArgValue);
696     } else {
697       assert(VA.isMemLoc());
698       
699       // Create the nodes corresponding to a load from this parameter slot.
700       int FI = MFI->CreateFixedObject(MVT::getSizeInBits(VA.getValVT())/8,
701                                       VA.getLocMemOffset());
702       SDOperand FIN = DAG.getFrameIndex(FI, getPointerTy());
703       ArgValues.push_back(DAG.getLoad(VA.getValVT(), Root, FIN, NULL, 0));
704     }
705   }
706   
707   unsigned StackSize = CCInfo.getNextStackOffset();
708
709   ArgValues.push_back(Root);
710
711   // If the function takes variable number of arguments, make a frame index for
712   // the start of the first vararg value... for expansion of llvm.va_start.
713   if (isVarArg)
714     VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
715
716   if (isStdCall && !isVarArg) {
717     BytesToPopOnReturn  = StackSize;    // Callee pops everything..
718     BytesCallerReserves = 0;
719   } else {
720     BytesToPopOnReturn  = 0; // Callee pops nothing.
721     
722     // If this is an sret function, the return should pop the hidden pointer.
723     if (NumArgs &&
724         (cast<ConstantSDNode>(Op.getOperand(3))->getValue() &
725          ISD::ParamFlags::StructReturn))
726       BytesToPopOnReturn = 4;  
727     
728     BytesCallerReserves = StackSize;
729   }
730   
731   RegSaveFrameIndex = 0xAAAAAAA;  // X86-64 only.
732   ReturnAddrIndex = 0;            // No return address slot generated yet.
733
734   MF.getInfo<X86MachineFunctionInfo>()
735     ->setBytesToPopOnReturn(BytesToPopOnReturn);
736
737   // Return the new list of results.
738   return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(),
739                      &ArgValues[0], ArgValues.size()).getValue(Op.ResNo);
740 }
741
742 SDOperand X86TargetLowering::LowerCCCCallTo(SDOperand Op, SelectionDAG &DAG,
743                                             unsigned CC) {
744   SDOperand Chain     = Op.getOperand(0);
745   bool isVarArg       = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
746   bool isTailCall     = cast<ConstantSDNode>(Op.getOperand(3))->getValue() != 0;
747   SDOperand Callee    = Op.getOperand(4);
748   unsigned NumOps     = (Op.getNumOperands() - 5) / 2;
749
750   // Analyze operands of the call, assigning locations to each operand.
751   SmallVector<CCValAssign, 16> ArgLocs;
752   CCState CCInfo(CC, getTargetMachine(), ArgLocs);
753   CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_32_C);
754   
755   // Get a count of how many bytes are to be pushed on the stack.
756   unsigned NumBytes = CCInfo.getNextStackOffset();
757
758   Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes, getPointerTy()));
759
760   SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
761   SmallVector<SDOperand, 8> MemOpChains;
762
763   SDOperand StackPtr;
764
765   // Walk the register/memloc assignments, inserting copies/loads.
766   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
767     CCValAssign &VA = ArgLocs[i];
768     SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
769     
770     // Promote the value if needed.
771     switch (VA.getLocInfo()) {
772     default: assert(0 && "Unknown loc info!");
773     case CCValAssign::Full: break;
774     case CCValAssign::SExt:
775       Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
776       break;
777     case CCValAssign::ZExt:
778       Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
779       break;
780     case CCValAssign::AExt:
781       Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
782       break;
783     }
784     
785     if (VA.isRegLoc()) {
786       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
787     } else {
788       assert(VA.isMemLoc());
789       if (StackPtr.Val == 0)
790         StackPtr = DAG.getRegister(getStackPtrReg(), getPointerTy());
791       SDOperand PtrOff = DAG.getConstant(VA.getLocMemOffset(), getPointerTy());
792       PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
793       MemOpChains.push_back(DAG.getStore(Chain, Arg, PtrOff, NULL, 0));
794     }
795   }
796
797   // If the first argument is an sret pointer, remember it.
798   bool isSRet = NumOps &&
799     (cast<ConstantSDNode>(Op.getOperand(6))->getValue() &
800      ISD::ParamFlags::StructReturn);
801   
802   if (!MemOpChains.empty())
803     Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
804                         &MemOpChains[0], MemOpChains.size());
805
806   // Build a sequence of copy-to-reg nodes chained together with token chain
807   // and flag operands which copy the outgoing args into registers.
808   SDOperand InFlag;
809   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
810     Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
811                              InFlag);
812     InFlag = Chain.getValue(1);
813   }
814
815   // ELF / PIC requires GOT in the EBX register before function calls via PLT
816   // GOT pointer.
817   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
818       Subtarget->isPICStyleGOT()) {
819     Chain = DAG.getCopyToReg(Chain, X86::EBX,
820                              DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
821                              InFlag);
822     InFlag = Chain.getValue(1);
823   }
824   
825   // If the callee is a GlobalAddress node (quite common, every direct call is)
826   // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
827   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
828     // We should use extra load for direct calls to dllimported functions in
829     // non-JIT mode.
830     if (!Subtarget->GVRequiresExtraLoad(G->getGlobal(),
831                                         getTargetMachine(), true))
832       Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
833   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
834     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
835
836   // Returns a chain & a flag for retval copy to use.
837   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
838   SmallVector<SDOperand, 8> Ops;
839   Ops.push_back(Chain);
840   Ops.push_back(Callee);
841
842   // Add argument registers to the end of the list so that they are known live
843   // into the call.
844   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
845     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
846                                   RegsToPass[i].second.getValueType()));
847
848   // Add an implicit use GOT pointer in EBX.
849   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
850       Subtarget->isPICStyleGOT())
851     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
852   
853   if (InFlag.Val)
854     Ops.push_back(InFlag);
855
856   Chain = DAG.getNode(isTailCall ? X86ISD::TAILCALL : X86ISD::CALL,
857                       NodeTys, &Ops[0], Ops.size());
858   InFlag = Chain.getValue(1);
859
860   // Create the CALLSEQ_END node.
861   unsigned NumBytesForCalleeToPush = 0;
862
863   if (CC == CallingConv::X86_StdCall) {
864     if (isVarArg)
865       NumBytesForCalleeToPush = isSRet ? 4 : 0;
866     else
867       NumBytesForCalleeToPush = NumBytes;
868   } else {
869     // If this is is a call to a struct-return function, the callee
870     // pops the hidden struct pointer, so we have to push it back.
871     // This is common for Darwin/X86, Linux & Mingw32 targets.
872     NumBytesForCalleeToPush = isSRet ? 4 : 0;
873   }
874   
875   NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
876   Ops.clear();
877   Ops.push_back(Chain);
878   Ops.push_back(DAG.getConstant(NumBytes, getPointerTy()));
879   Ops.push_back(DAG.getConstant(NumBytesForCalleeToPush, getPointerTy()));
880   Ops.push_back(InFlag);
881   Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
882   InFlag = Chain.getValue(1);
883
884   // Handle result values, copying them out of physregs into vregs that we
885   // return.
886   return SDOperand(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
887 }
888
889
890 //===----------------------------------------------------------------------===//
891 //                   FastCall Calling Convention implementation
892 //===----------------------------------------------------------------------===//
893 //
894 // The X86 'fastcall' calling convention passes up to two integer arguments in
895 // registers (an appropriate portion of ECX/EDX), passes arguments in C order,
896 // and requires that the callee pop its arguments off the stack (allowing proper
897 // tail calls), and has the same return value conventions as C calling convs.
898 //
899 // This calling convention always arranges for the callee pop value to be 8n+4
900 // bytes, which is needed for tail recursion elimination and stack alignment
901 // reasons.
902 SDOperand
903 X86TargetLowering::LowerFastCCArguments(SDOperand Op, SelectionDAG &DAG) {
904   MachineFunction &MF = DAG.getMachineFunction();
905   MachineFrameInfo *MFI = MF.getFrameInfo();
906   SDOperand Root = Op.getOperand(0);
907
908   // Assign locations to all of the incoming arguments.
909   SmallVector<CCValAssign, 16> ArgLocs;
910   CCState CCInfo(MF.getFunction()->getCallingConv(), getTargetMachine(),
911                  ArgLocs);
912   CCInfo.AnalyzeFormalArguments(Op.Val, CC_X86_32_FastCall);
913   
914   SmallVector<SDOperand, 8> ArgValues;
915   unsigned LastVal = ~0U;
916   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
917     CCValAssign &VA = ArgLocs[i];
918     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
919     // places.
920     assert(VA.getValNo() != LastVal &&
921            "Don't support value assigned to multiple locs yet");
922     LastVal = VA.getValNo();
923     
924     if (VA.isRegLoc()) {
925       MVT::ValueType RegVT = VA.getLocVT();
926       TargetRegisterClass *RC;
927       if (RegVT == MVT::i32)
928         RC = X86::GR32RegisterClass;
929       else {
930         assert(MVT::isVector(RegVT));
931         RC = X86::VR128RegisterClass;
932       }
933       
934       unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
935       SDOperand ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
936       
937       // If this is an 8 or 16-bit value, it is really passed promoted to 32
938       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
939       // right size.
940       if (VA.getLocInfo() == CCValAssign::SExt)
941         ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
942                                DAG.getValueType(VA.getValVT()));
943       else if (VA.getLocInfo() == CCValAssign::ZExt)
944         ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
945                                DAG.getValueType(VA.getValVT()));
946       
947       if (VA.getLocInfo() != CCValAssign::Full)
948         ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
949       
950       ArgValues.push_back(ArgValue);
951     } else {
952       assert(VA.isMemLoc());
953       
954       // Create the nodes corresponding to a load from this parameter slot.
955       int FI = MFI->CreateFixedObject(MVT::getSizeInBits(VA.getValVT())/8,
956                                       VA.getLocMemOffset());
957       SDOperand FIN = DAG.getFrameIndex(FI, getPointerTy());
958       ArgValues.push_back(DAG.getLoad(VA.getValVT(), Root, FIN, NULL, 0));
959     }
960   }
961   
962   ArgValues.push_back(Root);
963
964   unsigned StackSize = CCInfo.getNextStackOffset();
965
966   if (!Subtarget->isTargetCygMing() && !Subtarget->isTargetWindows()) {
967     // Make sure the instruction takes 8n+4 bytes to make sure the start of the
968     // arguments and the arguments after the retaddr has been pushed are aligned.
969     if ((StackSize & 7) == 0)
970       StackSize += 4;
971   }
972
973   VarArgsFrameIndex = 0xAAAAAAA;   // fastcc functions can't have varargs.
974   RegSaveFrameIndex = 0xAAAAAAA;   // X86-64 only.
975   ReturnAddrIndex = 0;             // No return address slot generated yet.
976   BytesToPopOnReturn = StackSize;  // Callee pops all stack arguments.
977   BytesCallerReserves = 0;
978
979   MF.getInfo<X86MachineFunctionInfo>()
980     ->setBytesToPopOnReturn(BytesToPopOnReturn);
981
982   // Return the new list of results.
983   return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(),
984                      &ArgValues[0], ArgValues.size()).getValue(Op.ResNo);
985 }
986
987 SDOperand X86TargetLowering::LowerFastCCCallTo(SDOperand Op, SelectionDAG &DAG,
988                                                unsigned CC) {
989   SDOperand Chain     = Op.getOperand(0);
990   bool isTailCall     = cast<ConstantSDNode>(Op.getOperand(3))->getValue() != 0;
991   SDOperand Callee    = Op.getOperand(4);
992
993   // Analyze operands of the call, assigning locations to each operand.
994   SmallVector<CCValAssign, 16> ArgLocs;
995   CCState CCInfo(CC, getTargetMachine(), ArgLocs);
996   CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_32_FastCall);
997   
998   // Get a count of how many bytes are to be pushed on the stack.
999   unsigned NumBytes = CCInfo.getNextStackOffset();
1000
1001   if (!Subtarget->isTargetCygMing() && !Subtarget->isTargetWindows()) {
1002     // Make sure the instruction takes 8n+4 bytes to make sure the start of the
1003     // arguments and the arguments after the retaddr has been pushed are aligned.
1004     if ((NumBytes & 7) == 0)
1005       NumBytes += 4;
1006   }
1007
1008   Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes, getPointerTy()));
1009   
1010   SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
1011   SmallVector<SDOperand, 8> MemOpChains;
1012   
1013   SDOperand StackPtr;
1014   
1015   // Walk the register/memloc assignments, inserting copies/loads.
1016   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1017     CCValAssign &VA = ArgLocs[i];
1018     SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1019     
1020     // Promote the value if needed.
1021     switch (VA.getLocInfo()) {
1022       default: assert(0 && "Unknown loc info!");
1023       case CCValAssign::Full: break;
1024       case CCValAssign::SExt:
1025         Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1026         break;
1027       case CCValAssign::ZExt:
1028         Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1029         break;
1030       case CCValAssign::AExt:
1031         Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1032         break;
1033     }
1034     
1035     if (VA.isRegLoc()) {
1036       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1037     } else {
1038       assert(VA.isMemLoc());
1039       if (StackPtr.Val == 0)
1040         StackPtr = DAG.getRegister(getStackPtrReg(), getPointerTy());
1041       SDOperand PtrOff = DAG.getConstant(VA.getLocMemOffset(), getPointerTy());
1042       PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
1043       MemOpChains.push_back(DAG.getStore(Chain, Arg, PtrOff, NULL, 0));
1044     }
1045   }
1046
1047   if (!MemOpChains.empty())
1048     Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1049                         &MemOpChains[0], MemOpChains.size());
1050
1051   // Build a sequence of copy-to-reg nodes chained together with token chain
1052   // and flag operands which copy the outgoing args into registers.
1053   SDOperand InFlag;
1054   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1055     Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1056                              InFlag);
1057     InFlag = Chain.getValue(1);
1058   }
1059
1060   // If the callee is a GlobalAddress node (quite common, every direct call is)
1061   // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1062   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1063     // We should use extra load for direct calls to dllimported functions in
1064     // non-JIT mode.
1065     if (!Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1066                                         getTargetMachine(), true))
1067       Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1068   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
1069     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1070
1071   // ELF / PIC requires GOT in the EBX register before function calls via PLT
1072   // GOT pointer.
1073   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1074       Subtarget->isPICStyleGOT()) {
1075     Chain = DAG.getCopyToReg(Chain, X86::EBX,
1076                              DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
1077                              InFlag);
1078     InFlag = Chain.getValue(1);
1079   }
1080
1081   // Returns a chain & a flag for retval copy to use.
1082   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1083   SmallVector<SDOperand, 8> Ops;
1084   Ops.push_back(Chain);
1085   Ops.push_back(Callee);
1086
1087   // Add argument registers to the end of the list so that they are known live
1088   // into the call.
1089   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1090     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1091                                   RegsToPass[i].second.getValueType()));
1092
1093   // Add an implicit use GOT pointer in EBX.
1094   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1095       Subtarget->isPICStyleGOT())
1096     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1097
1098   if (InFlag.Val)
1099     Ops.push_back(InFlag);
1100
1101   // FIXME: Do not generate X86ISD::TAILCALL for now.
1102   Chain = DAG.getNode(isTailCall ? X86ISD::TAILCALL : X86ISD::CALL,
1103                       NodeTys, &Ops[0], Ops.size());
1104   InFlag = Chain.getValue(1);
1105
1106   // Returns a flag for retval copy to use.
1107   NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1108   Ops.clear();
1109   Ops.push_back(Chain);
1110   Ops.push_back(DAG.getConstant(NumBytes, getPointerTy()));
1111   Ops.push_back(DAG.getConstant(NumBytes, getPointerTy()));
1112   Ops.push_back(InFlag);
1113   Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
1114   InFlag = Chain.getValue(1);
1115
1116   // Handle result values, copying them out of physregs into vregs that we
1117   // return.
1118   return SDOperand(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
1119 }
1120
1121
1122 //===----------------------------------------------------------------------===//
1123 //                 X86-64 C Calling Convention implementation
1124 //===----------------------------------------------------------------------===//
1125
1126 SDOperand
1127 X86TargetLowering::LowerX86_64CCCArguments(SDOperand Op, SelectionDAG &DAG) {
1128   MachineFunction &MF = DAG.getMachineFunction();
1129   MachineFrameInfo *MFI = MF.getFrameInfo();
1130   SDOperand Root = Op.getOperand(0);
1131   bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1132
1133   static const unsigned GPR64ArgRegs[] = {
1134     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8,  X86::R9
1135   };
1136   static const unsigned XMMArgRegs[] = {
1137     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1138     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1139   };
1140
1141   
1142   // Assign locations to all of the incoming arguments.
1143   SmallVector<CCValAssign, 16> ArgLocs;
1144   CCState CCInfo(MF.getFunction()->getCallingConv(), getTargetMachine(),
1145                  ArgLocs);
1146   CCInfo.AnalyzeFormalArguments(Op.Val, CC_X86_64_C);
1147   
1148   SmallVector<SDOperand, 8> ArgValues;
1149   unsigned LastVal = ~0U;
1150   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1151     CCValAssign &VA = ArgLocs[i];
1152     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1153     // places.
1154     assert(VA.getValNo() != LastVal &&
1155            "Don't support value assigned to multiple locs yet");
1156     LastVal = VA.getValNo();
1157     
1158     if (VA.isRegLoc()) {
1159       MVT::ValueType RegVT = VA.getLocVT();
1160       TargetRegisterClass *RC;
1161       if (RegVT == MVT::i32)
1162         RC = X86::GR32RegisterClass;
1163       else if (RegVT == MVT::i64)
1164         RC = X86::GR64RegisterClass;
1165       else if (RegVT == MVT::f32)
1166         RC = X86::FR32RegisterClass;
1167       else if (RegVT == MVT::f64)
1168         RC = X86::FR64RegisterClass;
1169       else {
1170         assert(MVT::isVector(RegVT));
1171         RC = X86::VR128RegisterClass;
1172       }
1173
1174       unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
1175       SDOperand ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
1176       
1177       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1178       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1179       // right size.
1180       if (VA.getLocInfo() == CCValAssign::SExt)
1181         ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
1182                                DAG.getValueType(VA.getValVT()));
1183       else if (VA.getLocInfo() == CCValAssign::ZExt)
1184         ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
1185                                DAG.getValueType(VA.getValVT()));
1186       
1187       if (VA.getLocInfo() != CCValAssign::Full)
1188         ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
1189       
1190       ArgValues.push_back(ArgValue);
1191     } else {
1192       assert(VA.isMemLoc());
1193     
1194       // Create the nodes corresponding to a load from this parameter slot.
1195       int FI = MFI->CreateFixedObject(MVT::getSizeInBits(VA.getValVT())/8,
1196                                       VA.getLocMemOffset());
1197       SDOperand FIN = DAG.getFrameIndex(FI, getPointerTy());
1198       ArgValues.push_back(DAG.getLoad(VA.getValVT(), Root, FIN, NULL, 0));
1199     }
1200   }
1201   
1202   unsigned StackSize = CCInfo.getNextStackOffset();
1203   
1204   // If the function takes variable number of arguments, make a frame index for
1205   // the start of the first vararg value... for expansion of llvm.va_start.
1206   if (isVarArg) {
1207     unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs, 6);
1208     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1209     
1210     // For X86-64, if there are vararg parameters that are passed via
1211     // registers, then we must store them to their spots on the stack so they
1212     // may be loaded by deferencing the result of va_next.
1213     VarArgsGPOffset = NumIntRegs * 8;
1214     VarArgsFPOffset = 6 * 8 + NumXMMRegs * 16;
1215     VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
1216     RegSaveFrameIndex = MFI->CreateStackObject(6 * 8 + 8 * 16, 16);
1217
1218     // Store the integer parameter registers.
1219     SmallVector<SDOperand, 8> MemOps;
1220     SDOperand RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1221     SDOperand FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1222                               DAG.getConstant(VarArgsGPOffset, getPointerTy()));
1223     for (; NumIntRegs != 6; ++NumIntRegs) {
1224       unsigned VReg = AddLiveIn(MF, GPR64ArgRegs[NumIntRegs],
1225                                 X86::GR64RegisterClass);
1226       SDOperand Val = DAG.getCopyFromReg(Root, VReg, MVT::i64);
1227       SDOperand Store = DAG.getStore(Val.getValue(1), Val, FIN, NULL, 0);
1228       MemOps.push_back(Store);
1229       FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1230                         DAG.getConstant(8, getPointerTy()));
1231     }
1232
1233     // Now store the XMM (fp + vector) parameter registers.
1234     FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1235                       DAG.getConstant(VarArgsFPOffset, getPointerTy()));
1236     for (; NumXMMRegs != 8; ++NumXMMRegs) {
1237       unsigned VReg = AddLiveIn(MF, XMMArgRegs[NumXMMRegs],
1238                                 X86::VR128RegisterClass);
1239       SDOperand Val = DAG.getCopyFromReg(Root, VReg, MVT::v4f32);
1240       SDOperand Store = DAG.getStore(Val.getValue(1), Val, FIN, NULL, 0);
1241       MemOps.push_back(Store);
1242       FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1243                         DAG.getConstant(16, getPointerTy()));
1244     }
1245     if (!MemOps.empty())
1246         Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
1247                            &MemOps[0], MemOps.size());
1248   }
1249
1250   ArgValues.push_back(Root);
1251
1252   ReturnAddrIndex = 0;     // No return address slot generated yet.
1253   BytesToPopOnReturn = 0;  // Callee pops nothing.
1254   BytesCallerReserves = StackSize;
1255
1256   // Return the new list of results.
1257   return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(),
1258                      &ArgValues[0], ArgValues.size()).getValue(Op.ResNo);
1259 }
1260
1261 SDOperand
1262 X86TargetLowering::LowerX86_64CCCCallTo(SDOperand Op, SelectionDAG &DAG,
1263                                         unsigned CC) {
1264   SDOperand Chain     = Op.getOperand(0);
1265   bool isVarArg       = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1266   bool isTailCall     = cast<ConstantSDNode>(Op.getOperand(3))->getValue() != 0;
1267   SDOperand Callee    = Op.getOperand(4);
1268   
1269   // Analyze operands of the call, assigning locations to each operand.
1270   SmallVector<CCValAssign, 16> ArgLocs;
1271   CCState CCInfo(CC, getTargetMachine(), ArgLocs);
1272   CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_64_C);
1273     
1274   // Get a count of how many bytes are to be pushed on the stack.
1275   unsigned NumBytes = CCInfo.getNextStackOffset();
1276   Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes, getPointerTy()));
1277
1278   SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
1279   SmallVector<SDOperand, 8> MemOpChains;
1280
1281   SDOperand StackPtr;
1282   
1283   // Walk the register/memloc assignments, inserting copies/loads.
1284   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1285     CCValAssign &VA = ArgLocs[i];
1286     SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1287     
1288     // Promote the value if needed.
1289     switch (VA.getLocInfo()) {
1290     default: assert(0 && "Unknown loc info!");
1291     case CCValAssign::Full: break;
1292     case CCValAssign::SExt:
1293       Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1294       break;
1295     case CCValAssign::ZExt:
1296       Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1297       break;
1298     case CCValAssign::AExt:
1299       Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1300       break;
1301     }
1302     
1303     if (VA.isRegLoc()) {
1304       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1305     } else {
1306       assert(VA.isMemLoc());
1307       if (StackPtr.Val == 0)
1308         StackPtr = DAG.getRegister(getStackPtrReg(), getPointerTy());
1309       SDOperand PtrOff = DAG.getConstant(VA.getLocMemOffset(), getPointerTy());
1310       PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
1311       MemOpChains.push_back(DAG.getStore(Chain, Arg, PtrOff, NULL, 0));
1312     }
1313   }
1314   
1315   if (!MemOpChains.empty())
1316     Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1317                         &MemOpChains[0], MemOpChains.size());
1318
1319   // Build a sequence of copy-to-reg nodes chained together with token chain
1320   // and flag operands which copy the outgoing args into registers.
1321   SDOperand InFlag;
1322   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1323     Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1324                              InFlag);
1325     InFlag = Chain.getValue(1);
1326   }
1327
1328   if (isVarArg) {
1329     // From AMD64 ABI document:
1330     // For calls that may call functions that use varargs or stdargs
1331     // (prototype-less calls or calls to functions containing ellipsis (...) in
1332     // the declaration) %al is used as hidden argument to specify the number
1333     // of SSE registers used. The contents of %al do not need to match exactly
1334     // the number of registers, but must be an ubound on the number of SSE
1335     // registers used and is in the range 0 - 8 inclusive.
1336     
1337     // Count the number of XMM registers allocated.
1338     static const unsigned XMMArgRegs[] = {
1339       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1340       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1341     };
1342     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1343     
1344     Chain = DAG.getCopyToReg(Chain, X86::AL,
1345                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1346     InFlag = Chain.getValue(1);
1347   }
1348
1349   // If the callee is a GlobalAddress node (quite common, every direct call is)
1350   // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1351   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1352     // We should use extra load for direct calls to dllimported functions in
1353     // non-JIT mode.
1354     if (getTargetMachine().getCodeModel() != CodeModel::Large
1355         && !Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1356                                            getTargetMachine(), true))
1357       Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1358   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
1359     if (getTargetMachine().getCodeModel() != CodeModel::Large)
1360       Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1361
1362   // Returns a chain & a flag for retval copy to use.
1363   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1364   SmallVector<SDOperand, 8> Ops;
1365   Ops.push_back(Chain);
1366   Ops.push_back(Callee);
1367
1368   // Add argument registers to the end of the list so that they are known live
1369   // into the call.
1370   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1371     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1372                                   RegsToPass[i].second.getValueType()));
1373
1374   if (InFlag.Val)
1375     Ops.push_back(InFlag);
1376
1377   // FIXME: Do not generate X86ISD::TAILCALL for now.
1378   Chain = DAG.getNode(isTailCall ? X86ISD::TAILCALL : X86ISD::CALL,
1379                       NodeTys, &Ops[0], Ops.size());
1380   InFlag = Chain.getValue(1);
1381
1382   // Returns a flag for retval copy to use.
1383   NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1384   Ops.clear();
1385   Ops.push_back(Chain);
1386   Ops.push_back(DAG.getConstant(NumBytes, getPointerTy()));
1387   Ops.push_back(DAG.getConstant(0, getPointerTy()));
1388   Ops.push_back(InFlag);
1389   Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
1390   InFlag = Chain.getValue(1);
1391   
1392   // Handle result values, copying them out of physregs into vregs that we
1393   // return.
1394   return SDOperand(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
1395 }
1396
1397
1398 //===----------------------------------------------------------------------===//
1399 //                           Other Lowering Hooks
1400 //===----------------------------------------------------------------------===//
1401
1402
1403 SDOperand X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
1404   if (ReturnAddrIndex == 0) {
1405     // Set up a frame object for the return address.
1406     MachineFunction &MF = DAG.getMachineFunction();
1407     if (Subtarget->is64Bit())
1408       ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(8, -8);
1409     else
1410       ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(4, -4);
1411   }
1412
1413   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
1414 }
1415
1416
1417
1418 /// translateX86CC - do a one to one translation of a ISD::CondCode to the X86
1419 /// specific condition code. It returns a false if it cannot do a direct
1420 /// translation. X86CC is the translated CondCode.  LHS/RHS are modified as
1421 /// needed.
1422 static bool translateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
1423                            unsigned &X86CC, SDOperand &LHS, SDOperand &RHS,
1424                            SelectionDAG &DAG) {
1425   X86CC = X86::COND_INVALID;
1426   if (!isFP) {
1427     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
1428       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
1429         // X > -1   -> X == 0, jump !sign.
1430         RHS = DAG.getConstant(0, RHS.getValueType());
1431         X86CC = X86::COND_NS;
1432         return true;
1433       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
1434         // X < 0   -> X == 0, jump on sign.
1435         X86CC = X86::COND_S;
1436         return true;
1437       }
1438     }
1439
1440     switch (SetCCOpcode) {
1441     default: break;
1442     case ISD::SETEQ:  X86CC = X86::COND_E;  break;
1443     case ISD::SETGT:  X86CC = X86::COND_G;  break;
1444     case ISD::SETGE:  X86CC = X86::COND_GE; break;
1445     case ISD::SETLT:  X86CC = X86::COND_L;  break;
1446     case ISD::SETLE:  X86CC = X86::COND_LE; break;
1447     case ISD::SETNE:  X86CC = X86::COND_NE; break;
1448     case ISD::SETULT: X86CC = X86::COND_B;  break;
1449     case ISD::SETUGT: X86CC = X86::COND_A;  break;
1450     case ISD::SETULE: X86CC = X86::COND_BE; break;
1451     case ISD::SETUGE: X86CC = X86::COND_AE; break;
1452     }
1453   } else {
1454     // On a floating point condition, the flags are set as follows:
1455     // ZF  PF  CF   op
1456     //  0 | 0 | 0 | X > Y
1457     //  0 | 0 | 1 | X < Y
1458     //  1 | 0 | 0 | X == Y
1459     //  1 | 1 | 1 | unordered
1460     bool Flip = false;
1461     switch (SetCCOpcode) {
1462     default: break;
1463     case ISD::SETUEQ:
1464     case ISD::SETEQ: X86CC = X86::COND_E;  break;
1465     case ISD::SETOLT: Flip = true; // Fallthrough
1466     case ISD::SETOGT:
1467     case ISD::SETGT: X86CC = X86::COND_A;  break;
1468     case ISD::SETOLE: Flip = true; // Fallthrough
1469     case ISD::SETOGE:
1470     case ISD::SETGE: X86CC = X86::COND_AE; break;
1471     case ISD::SETUGT: Flip = true; // Fallthrough
1472     case ISD::SETULT:
1473     case ISD::SETLT: X86CC = X86::COND_B;  break;
1474     case ISD::SETUGE: Flip = true; // Fallthrough
1475     case ISD::SETULE:
1476     case ISD::SETLE: X86CC = X86::COND_BE; break;
1477     case ISD::SETONE:
1478     case ISD::SETNE: X86CC = X86::COND_NE; break;
1479     case ISD::SETUO: X86CC = X86::COND_P;  break;
1480     case ISD::SETO:  X86CC = X86::COND_NP; break;
1481     }
1482     if (Flip)
1483       std::swap(LHS, RHS);
1484   }
1485
1486   return X86CC != X86::COND_INVALID;
1487 }
1488
1489 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
1490 /// code. Current x86 isa includes the following FP cmov instructions:
1491 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
1492 static bool hasFPCMov(unsigned X86CC) {
1493   switch (X86CC) {
1494   default:
1495     return false;
1496   case X86::COND_B:
1497   case X86::COND_BE:
1498   case X86::COND_E:
1499   case X86::COND_P:
1500   case X86::COND_A:
1501   case X86::COND_AE:
1502   case X86::COND_NE:
1503   case X86::COND_NP:
1504     return true;
1505   }
1506 }
1507
1508 /// isUndefOrInRange - Op is either an undef node or a ConstantSDNode.  Return
1509 /// true if Op is undef or if its value falls within the specified range (L, H].
1510 static bool isUndefOrInRange(SDOperand Op, unsigned Low, unsigned Hi) {
1511   if (Op.getOpcode() == ISD::UNDEF)
1512     return true;
1513
1514   unsigned Val = cast<ConstantSDNode>(Op)->getValue();
1515   return (Val >= Low && Val < Hi);
1516 }
1517
1518 /// isUndefOrEqual - Op is either an undef node or a ConstantSDNode.  Return
1519 /// true if Op is undef or if its value equal to the specified value.
1520 static bool isUndefOrEqual(SDOperand Op, unsigned Val) {
1521   if (Op.getOpcode() == ISD::UNDEF)
1522     return true;
1523   return cast<ConstantSDNode>(Op)->getValue() == Val;
1524 }
1525
1526 /// isPSHUFDMask - Return true if the specified VECTOR_SHUFFLE operand
1527 /// specifies a shuffle of elements that is suitable for input to PSHUFD.
1528 bool X86::isPSHUFDMask(SDNode *N) {
1529   assert(N->getOpcode() == ISD::BUILD_VECTOR);
1530
1531   if (N->getNumOperands() != 4)
1532     return false;
1533
1534   // Check if the value doesn't reference the second vector.
1535   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1536     SDOperand Arg = N->getOperand(i);
1537     if (Arg.getOpcode() == ISD::UNDEF) continue;
1538     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1539     if (cast<ConstantSDNode>(Arg)->getValue() >= 4)
1540       return false;
1541   }
1542
1543   return true;
1544 }
1545
1546 /// isPSHUFHWMask - Return true if the specified VECTOR_SHUFFLE operand
1547 /// specifies a shuffle of elements that is suitable for input to PSHUFHW.
1548 bool X86::isPSHUFHWMask(SDNode *N) {
1549   assert(N->getOpcode() == ISD::BUILD_VECTOR);
1550
1551   if (N->getNumOperands() != 8)
1552     return false;
1553
1554   // Lower quadword copied in order.
1555   for (unsigned i = 0; i != 4; ++i) {
1556     SDOperand Arg = N->getOperand(i);
1557     if (Arg.getOpcode() == ISD::UNDEF) continue;
1558     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1559     if (cast<ConstantSDNode>(Arg)->getValue() != i)
1560       return false;
1561   }
1562
1563   // Upper quadword shuffled.
1564   for (unsigned i = 4; i != 8; ++i) {
1565     SDOperand Arg = N->getOperand(i);
1566     if (Arg.getOpcode() == ISD::UNDEF) continue;
1567     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1568     unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
1569     if (Val < 4 || Val > 7)
1570       return false;
1571   }
1572
1573   return true;
1574 }
1575
1576 /// isPSHUFLWMask - Return true if the specified VECTOR_SHUFFLE operand
1577 /// specifies a shuffle of elements that is suitable for input to PSHUFLW.
1578 bool X86::isPSHUFLWMask(SDNode *N) {
1579   assert(N->getOpcode() == ISD::BUILD_VECTOR);
1580
1581   if (N->getNumOperands() != 8)
1582     return false;
1583
1584   // Upper quadword copied in order.
1585   for (unsigned i = 4; i != 8; ++i)
1586     if (!isUndefOrEqual(N->getOperand(i), i))
1587       return false;
1588
1589   // Lower quadword shuffled.
1590   for (unsigned i = 0; i != 4; ++i)
1591     if (!isUndefOrInRange(N->getOperand(i), 0, 4))
1592       return false;
1593
1594   return true;
1595 }
1596
1597 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
1598 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
1599 static bool isSHUFPMask(const SDOperand *Elems, unsigned NumElems) {
1600   if (NumElems != 2 && NumElems != 4) return false;
1601
1602   unsigned Half = NumElems / 2;
1603   for (unsigned i = 0; i < Half; ++i)
1604     if (!isUndefOrInRange(Elems[i], 0, NumElems))
1605       return false;
1606   for (unsigned i = Half; i < NumElems; ++i)
1607     if (!isUndefOrInRange(Elems[i], NumElems, NumElems*2))
1608       return false;
1609
1610   return true;
1611 }
1612
1613 bool X86::isSHUFPMask(SDNode *N) {
1614   assert(N->getOpcode() == ISD::BUILD_VECTOR);
1615   return ::isSHUFPMask(N->op_begin(), N->getNumOperands());
1616 }
1617
1618 /// isCommutedSHUFP - Returns true if the shuffle mask is except
1619 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
1620 /// half elements to come from vector 1 (which would equal the dest.) and
1621 /// the upper half to come from vector 2.
1622 static bool isCommutedSHUFP(const SDOperand *Ops, unsigned NumOps) {
1623   if (NumOps != 2 && NumOps != 4) return false;
1624
1625   unsigned Half = NumOps / 2;
1626   for (unsigned i = 0; i < Half; ++i)
1627     if (!isUndefOrInRange(Ops[i], NumOps, NumOps*2))
1628       return false;
1629   for (unsigned i = Half; i < NumOps; ++i)
1630     if (!isUndefOrInRange(Ops[i], 0, NumOps))
1631       return false;
1632   return true;
1633 }
1634
1635 static bool isCommutedSHUFP(SDNode *N) {
1636   assert(N->getOpcode() == ISD::BUILD_VECTOR);
1637   return isCommutedSHUFP(N->op_begin(), N->getNumOperands());
1638 }
1639
1640 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
1641 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
1642 bool X86::isMOVHLPSMask(SDNode *N) {
1643   assert(N->getOpcode() == ISD::BUILD_VECTOR);
1644
1645   if (N->getNumOperands() != 4)
1646     return false;
1647
1648   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
1649   return isUndefOrEqual(N->getOperand(0), 6) &&
1650          isUndefOrEqual(N->getOperand(1), 7) &&
1651          isUndefOrEqual(N->getOperand(2), 2) &&
1652          isUndefOrEqual(N->getOperand(3), 3);
1653 }
1654
1655 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
1656 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
1657 /// <2, 3, 2, 3>
1658 bool X86::isMOVHLPS_v_undef_Mask(SDNode *N) {
1659   assert(N->getOpcode() == ISD::BUILD_VECTOR);
1660
1661   if (N->getNumOperands() != 4)
1662     return false;
1663
1664   // Expect bit0 == 2, bit1 == 3, bit2 == 2, bit3 == 3
1665   return isUndefOrEqual(N->getOperand(0), 2) &&
1666          isUndefOrEqual(N->getOperand(1), 3) &&
1667          isUndefOrEqual(N->getOperand(2), 2) &&
1668          isUndefOrEqual(N->getOperand(3), 3);
1669 }
1670
1671 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
1672 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
1673 bool X86::isMOVLPMask(SDNode *N) {
1674   assert(N->getOpcode() == ISD::BUILD_VECTOR);
1675
1676   unsigned NumElems = N->getNumOperands();
1677   if (NumElems != 2 && NumElems != 4)
1678     return false;
1679
1680   for (unsigned i = 0; i < NumElems/2; ++i)
1681     if (!isUndefOrEqual(N->getOperand(i), i + NumElems))
1682       return false;
1683
1684   for (unsigned i = NumElems/2; i < NumElems; ++i)
1685     if (!isUndefOrEqual(N->getOperand(i), i))
1686       return false;
1687
1688   return true;
1689 }
1690
1691 /// isMOVHPMask - Return true if the specified VECTOR_SHUFFLE operand
1692 /// specifies a shuffle of elements that is suitable for input to MOVHP{S|D}
1693 /// and MOVLHPS.
1694 bool X86::isMOVHPMask(SDNode *N) {
1695   assert(N->getOpcode() == ISD::BUILD_VECTOR);
1696
1697   unsigned NumElems = N->getNumOperands();
1698   if (NumElems != 2 && NumElems != 4)
1699     return false;
1700
1701   for (unsigned i = 0; i < NumElems/2; ++i)
1702     if (!isUndefOrEqual(N->getOperand(i), i))
1703       return false;
1704
1705   for (unsigned i = 0; i < NumElems/2; ++i) {
1706     SDOperand Arg = N->getOperand(i + NumElems/2);
1707     if (!isUndefOrEqual(Arg, i + NumElems))
1708       return false;
1709   }
1710
1711   return true;
1712 }
1713
1714 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
1715 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
1716 bool static isUNPCKLMask(const SDOperand *Elts, unsigned NumElts,
1717                          bool V2IsSplat = false) {
1718   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
1719     return false;
1720
1721   for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
1722     SDOperand BitI  = Elts[i];
1723     SDOperand BitI1 = Elts[i+1];
1724     if (!isUndefOrEqual(BitI, j))
1725       return false;
1726     if (V2IsSplat) {
1727       if (isUndefOrEqual(BitI1, NumElts))
1728         return false;
1729     } else {
1730       if (!isUndefOrEqual(BitI1, j + NumElts))
1731         return false;
1732     }
1733   }
1734
1735   return true;
1736 }
1737
1738 bool X86::isUNPCKLMask(SDNode *N, bool V2IsSplat) {
1739   assert(N->getOpcode() == ISD::BUILD_VECTOR);
1740   return ::isUNPCKLMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
1741 }
1742
1743 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
1744 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
1745 bool static isUNPCKHMask(const SDOperand *Elts, unsigned NumElts,
1746                          bool V2IsSplat = false) {
1747   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
1748     return false;
1749
1750   for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
1751     SDOperand BitI  = Elts[i];
1752     SDOperand BitI1 = Elts[i+1];
1753     if (!isUndefOrEqual(BitI, j + NumElts/2))
1754       return false;
1755     if (V2IsSplat) {
1756       if (isUndefOrEqual(BitI1, NumElts))
1757         return false;
1758     } else {
1759       if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
1760         return false;
1761     }
1762   }
1763
1764   return true;
1765 }
1766
1767 bool X86::isUNPCKHMask(SDNode *N, bool V2IsSplat) {
1768   assert(N->getOpcode() == ISD::BUILD_VECTOR);
1769   return ::isUNPCKHMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
1770 }
1771
1772 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
1773 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
1774 /// <0, 0, 1, 1>
1775 bool X86::isUNPCKL_v_undef_Mask(SDNode *N) {
1776   assert(N->getOpcode() == ISD::BUILD_VECTOR);
1777
1778   unsigned NumElems = N->getNumOperands();
1779   if (NumElems != 4 && NumElems != 8 && NumElems != 16)
1780     return false;
1781
1782   for (unsigned i = 0, j = 0; i != NumElems; i += 2, ++j) {
1783     SDOperand BitI  = N->getOperand(i);
1784     SDOperand BitI1 = N->getOperand(i+1);
1785
1786     if (!isUndefOrEqual(BitI, j))
1787       return false;
1788     if (!isUndefOrEqual(BitI1, j))
1789       return false;
1790   }
1791
1792   return true;
1793 }
1794
1795 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
1796 /// specifies a shuffle of elements that is suitable for input to MOVSS,
1797 /// MOVSD, and MOVD, i.e. setting the lowest element.
1798 static bool isMOVLMask(const SDOperand *Elts, unsigned NumElts) {
1799   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
1800     return false;
1801
1802   if (!isUndefOrEqual(Elts[0], NumElts))
1803     return false;
1804
1805   for (unsigned i = 1; i < NumElts; ++i) {
1806     if (!isUndefOrEqual(Elts[i], i))
1807       return false;
1808   }
1809
1810   return true;
1811 }
1812
1813 bool X86::isMOVLMask(SDNode *N) {
1814   assert(N->getOpcode() == ISD::BUILD_VECTOR);
1815   return ::isMOVLMask(N->op_begin(), N->getNumOperands());
1816 }
1817
1818 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
1819 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
1820 /// element of vector 2 and the other elements to come from vector 1 in order.
1821 static bool isCommutedMOVL(const SDOperand *Ops, unsigned NumOps,
1822                            bool V2IsSplat = false,
1823                            bool V2IsUndef = false) {
1824   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
1825     return false;
1826
1827   if (!isUndefOrEqual(Ops[0], 0))
1828     return false;
1829
1830   for (unsigned i = 1; i < NumOps; ++i) {
1831     SDOperand Arg = Ops[i];
1832     if (!(isUndefOrEqual(Arg, i+NumOps) ||
1833           (V2IsUndef && isUndefOrInRange(Arg, NumOps, NumOps*2)) ||
1834           (V2IsSplat && isUndefOrEqual(Arg, NumOps))))
1835       return false;
1836   }
1837
1838   return true;
1839 }
1840
1841 static bool isCommutedMOVL(SDNode *N, bool V2IsSplat = false,
1842                            bool V2IsUndef = false) {
1843   assert(N->getOpcode() == ISD::BUILD_VECTOR);
1844   return isCommutedMOVL(N->op_begin(), N->getNumOperands(),
1845                         V2IsSplat, V2IsUndef);
1846 }
1847
1848 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
1849 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
1850 bool X86::isMOVSHDUPMask(SDNode *N) {
1851   assert(N->getOpcode() == ISD::BUILD_VECTOR);
1852
1853   if (N->getNumOperands() != 4)
1854     return false;
1855
1856   // Expect 1, 1, 3, 3
1857   for (unsigned i = 0; i < 2; ++i) {
1858     SDOperand Arg = N->getOperand(i);
1859     if (Arg.getOpcode() == ISD::UNDEF) continue;
1860     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1861     unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
1862     if (Val != 1) return false;
1863   }
1864
1865   bool HasHi = false;
1866   for (unsigned i = 2; i < 4; ++i) {
1867     SDOperand Arg = N->getOperand(i);
1868     if (Arg.getOpcode() == ISD::UNDEF) continue;
1869     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1870     unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
1871     if (Val != 3) return false;
1872     HasHi = true;
1873   }
1874
1875   // Don't use movshdup if it can be done with a shufps.
1876   return HasHi;
1877 }
1878
1879 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
1880 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
1881 bool X86::isMOVSLDUPMask(SDNode *N) {
1882   assert(N->getOpcode() == ISD::BUILD_VECTOR);
1883
1884   if (N->getNumOperands() != 4)
1885     return false;
1886
1887   // Expect 0, 0, 2, 2
1888   for (unsigned i = 0; i < 2; ++i) {
1889     SDOperand Arg = N->getOperand(i);
1890     if (Arg.getOpcode() == ISD::UNDEF) continue;
1891     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1892     unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
1893     if (Val != 0) return false;
1894   }
1895
1896   bool HasHi = false;
1897   for (unsigned i = 2; i < 4; ++i) {
1898     SDOperand Arg = N->getOperand(i);
1899     if (Arg.getOpcode() == ISD::UNDEF) continue;
1900     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1901     unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
1902     if (Val != 2) return false;
1903     HasHi = true;
1904   }
1905
1906   // Don't use movshdup if it can be done with a shufps.
1907   return HasHi;
1908 }
1909
1910 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
1911 /// a splat of a single element.
1912 static bool isSplatMask(SDNode *N) {
1913   assert(N->getOpcode() == ISD::BUILD_VECTOR);
1914
1915   // This is a splat operation if each element of the permute is the same, and
1916   // if the value doesn't reference the second vector.
1917   unsigned NumElems = N->getNumOperands();
1918   SDOperand ElementBase;
1919   unsigned i = 0;
1920   for (; i != NumElems; ++i) {
1921     SDOperand Elt = N->getOperand(i);
1922     if (isa<ConstantSDNode>(Elt)) {
1923       ElementBase = Elt;
1924       break;
1925     }
1926   }
1927
1928   if (!ElementBase.Val)
1929     return false;
1930
1931   for (; i != NumElems; ++i) {
1932     SDOperand Arg = N->getOperand(i);
1933     if (Arg.getOpcode() == ISD::UNDEF) continue;
1934     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1935     if (Arg != ElementBase) return false;
1936   }
1937
1938   // Make sure it is a splat of the first vector operand.
1939   return cast<ConstantSDNode>(ElementBase)->getValue() < NumElems;
1940 }
1941
1942 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
1943 /// a splat of a single element and it's a 2 or 4 element mask.
1944 bool X86::isSplatMask(SDNode *N) {
1945   assert(N->getOpcode() == ISD::BUILD_VECTOR);
1946
1947   // We can only splat 64-bit, and 32-bit quantities with a single instruction.
1948   if (N->getNumOperands() != 4 && N->getNumOperands() != 2)
1949     return false;
1950   return ::isSplatMask(N);
1951 }
1952
1953 /// isSplatLoMask - Return true if the specified VECTOR_SHUFFLE operand
1954 /// specifies a splat of zero element.
1955 bool X86::isSplatLoMask(SDNode *N) {
1956   assert(N->getOpcode() == ISD::BUILD_VECTOR);
1957
1958   for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i)
1959     if (!isUndefOrEqual(N->getOperand(i), 0))
1960       return false;
1961   return true;
1962 }
1963
1964 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
1965 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUF* and SHUFP*
1966 /// instructions.
1967 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
1968   unsigned NumOperands = N->getNumOperands();
1969   unsigned Shift = (NumOperands == 4) ? 2 : 1;
1970   unsigned Mask = 0;
1971   for (unsigned i = 0; i < NumOperands; ++i) {
1972     unsigned Val = 0;
1973     SDOperand Arg = N->getOperand(NumOperands-i-1);
1974     if (Arg.getOpcode() != ISD::UNDEF)
1975       Val = cast<ConstantSDNode>(Arg)->getValue();
1976     if (Val >= NumOperands) Val -= NumOperands;
1977     Mask |= Val;
1978     if (i != NumOperands - 1)
1979       Mask <<= Shift;
1980   }
1981
1982   return Mask;
1983 }
1984
1985 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
1986 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFHW
1987 /// instructions.
1988 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
1989   unsigned Mask = 0;
1990   // 8 nodes, but we only care about the last 4.
1991   for (unsigned i = 7; i >= 4; --i) {
1992     unsigned Val = 0;
1993     SDOperand Arg = N->getOperand(i);
1994     if (Arg.getOpcode() != ISD::UNDEF)
1995       Val = cast<ConstantSDNode>(Arg)->getValue();
1996     Mask |= (Val - 4);
1997     if (i != 4)
1998       Mask <<= 2;
1999   }
2000
2001   return Mask;
2002 }
2003
2004 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2005 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFLW
2006 /// instructions.
2007 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2008   unsigned Mask = 0;
2009   // 8 nodes, but we only care about the first 4.
2010   for (int i = 3; i >= 0; --i) {
2011     unsigned Val = 0;
2012     SDOperand Arg = N->getOperand(i);
2013     if (Arg.getOpcode() != ISD::UNDEF)
2014       Val = cast<ConstantSDNode>(Arg)->getValue();
2015     Mask |= Val;
2016     if (i != 0)
2017       Mask <<= 2;
2018   }
2019
2020   return Mask;
2021 }
2022
2023 /// isPSHUFHW_PSHUFLWMask - true if the specified VECTOR_SHUFFLE operand
2024 /// specifies a 8 element shuffle that can be broken into a pair of
2025 /// PSHUFHW and PSHUFLW.
2026 static bool isPSHUFHW_PSHUFLWMask(SDNode *N) {
2027   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2028
2029   if (N->getNumOperands() != 8)
2030     return false;
2031
2032   // Lower quadword shuffled.
2033   for (unsigned i = 0; i != 4; ++i) {
2034     SDOperand Arg = N->getOperand(i);
2035     if (Arg.getOpcode() == ISD::UNDEF) continue;
2036     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2037     unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2038     if (Val > 4)
2039       return false;
2040   }
2041
2042   // Upper quadword shuffled.
2043   for (unsigned i = 4; i != 8; ++i) {
2044     SDOperand Arg = N->getOperand(i);
2045     if (Arg.getOpcode() == ISD::UNDEF) continue;
2046     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2047     unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2048     if (Val < 4 || Val > 7)
2049       return false;
2050   }
2051
2052   return true;
2053 }
2054
2055 /// CommuteVectorShuffle - Swap vector_shuffle operandsas well as
2056 /// values in ther permute mask.
2057 static SDOperand CommuteVectorShuffle(SDOperand Op, SDOperand &V1,
2058                                       SDOperand &V2, SDOperand &Mask,
2059                                       SelectionDAG &DAG) {
2060   MVT::ValueType VT = Op.getValueType();
2061   MVT::ValueType MaskVT = Mask.getValueType();
2062   MVT::ValueType EltVT = MVT::getVectorBaseType(MaskVT);
2063   unsigned NumElems = Mask.getNumOperands();
2064   SmallVector<SDOperand, 8> MaskVec;
2065
2066   for (unsigned i = 0; i != NumElems; ++i) {
2067     SDOperand Arg = Mask.getOperand(i);
2068     if (Arg.getOpcode() == ISD::UNDEF) {
2069       MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2070       continue;
2071     }
2072     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2073     unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2074     if (Val < NumElems)
2075       MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2076     else
2077       MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2078   }
2079
2080   std::swap(V1, V2);
2081   Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2082   return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2083 }
2084
2085 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2086 /// match movhlps. The lower half elements should come from upper half of
2087 /// V1 (and in order), and the upper half elements should come from the upper
2088 /// half of V2 (and in order).
2089 static bool ShouldXformToMOVHLPS(SDNode *Mask) {
2090   unsigned NumElems = Mask->getNumOperands();
2091   if (NumElems != 4)
2092     return false;
2093   for (unsigned i = 0, e = 2; i != e; ++i)
2094     if (!isUndefOrEqual(Mask->getOperand(i), i+2))
2095       return false;
2096   for (unsigned i = 2; i != 4; ++i)
2097     if (!isUndefOrEqual(Mask->getOperand(i), i+4))
2098       return false;
2099   return true;
2100 }
2101
2102 /// isScalarLoadToVector - Returns true if the node is a scalar load that
2103 /// is promoted to a vector.
2104 static inline bool isScalarLoadToVector(SDNode *N) {
2105   if (N->getOpcode() == ISD::SCALAR_TO_VECTOR) {
2106     N = N->getOperand(0).Val;
2107     return ISD::isNON_EXTLoad(N);
2108   }
2109   return false;
2110 }
2111
2112 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
2113 /// match movlp{s|d}. The lower half elements should come from lower half of
2114 /// V1 (and in order), and the upper half elements should come from the upper
2115 /// half of V2 (and in order). And since V1 will become the source of the
2116 /// MOVLP, it must be either a vector load or a scalar load to vector.
2117 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2, SDNode *Mask) {
2118   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
2119     return false;
2120   // Is V2 is a vector load, don't do this transformation. We will try to use
2121   // load folding shufps op.
2122   if (ISD::isNON_EXTLoad(V2))
2123     return false;
2124
2125   unsigned NumElems = Mask->getNumOperands();
2126   if (NumElems != 2 && NumElems != 4)
2127     return false;
2128   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
2129     if (!isUndefOrEqual(Mask->getOperand(i), i))
2130       return false;
2131   for (unsigned i = NumElems/2; i != NumElems; ++i)
2132     if (!isUndefOrEqual(Mask->getOperand(i), i+NumElems))
2133       return false;
2134   return true;
2135 }
2136
2137 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
2138 /// all the same.
2139 static bool isSplatVector(SDNode *N) {
2140   if (N->getOpcode() != ISD::BUILD_VECTOR)
2141     return false;
2142
2143   SDOperand SplatValue = N->getOperand(0);
2144   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
2145     if (N->getOperand(i) != SplatValue)
2146       return false;
2147   return true;
2148 }
2149
2150 /// isUndefShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2151 /// to an undef.
2152 static bool isUndefShuffle(SDNode *N) {
2153   if (N->getOpcode() != ISD::BUILD_VECTOR)
2154     return false;
2155
2156   SDOperand V1 = N->getOperand(0);
2157   SDOperand V2 = N->getOperand(1);
2158   SDOperand Mask = N->getOperand(2);
2159   unsigned NumElems = Mask.getNumOperands();
2160   for (unsigned i = 0; i != NumElems; ++i) {
2161     SDOperand Arg = Mask.getOperand(i);
2162     if (Arg.getOpcode() != ISD::UNDEF) {
2163       unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2164       if (Val < NumElems && V1.getOpcode() != ISD::UNDEF)
2165         return false;
2166       else if (Val >= NumElems && V2.getOpcode() != ISD::UNDEF)
2167         return false;
2168     }
2169   }
2170   return true;
2171 }
2172
2173 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
2174 /// that point to V2 points to its first element.
2175 static SDOperand NormalizeMask(SDOperand Mask, SelectionDAG &DAG) {
2176   assert(Mask.getOpcode() == ISD::BUILD_VECTOR);
2177
2178   bool Changed = false;
2179   SmallVector<SDOperand, 8> MaskVec;
2180   unsigned NumElems = Mask.getNumOperands();
2181   for (unsigned i = 0; i != NumElems; ++i) {
2182     SDOperand Arg = Mask.getOperand(i);
2183     if (Arg.getOpcode() != ISD::UNDEF) {
2184       unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2185       if (Val > NumElems) {
2186         Arg = DAG.getConstant(NumElems, Arg.getValueType());
2187         Changed = true;
2188       }
2189     }
2190     MaskVec.push_back(Arg);
2191   }
2192
2193   if (Changed)
2194     Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getValueType(),
2195                        &MaskVec[0], MaskVec.size());
2196   return Mask;
2197 }
2198
2199 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
2200 /// operation of specified width.
2201 static SDOperand getMOVLMask(unsigned NumElems, SelectionDAG &DAG) {
2202   MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2203   MVT::ValueType BaseVT = MVT::getVectorBaseType(MaskVT);
2204
2205   SmallVector<SDOperand, 8> MaskVec;
2206   MaskVec.push_back(DAG.getConstant(NumElems, BaseVT));
2207   for (unsigned i = 1; i != NumElems; ++i)
2208     MaskVec.push_back(DAG.getConstant(i, BaseVT));
2209   return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2210 }
2211
2212 /// getUnpacklMask - Returns a vector_shuffle mask for an unpackl operation
2213 /// of specified width.
2214 static SDOperand getUnpacklMask(unsigned NumElems, SelectionDAG &DAG) {
2215   MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2216   MVT::ValueType BaseVT = MVT::getVectorBaseType(MaskVT);
2217   SmallVector<SDOperand, 8> MaskVec;
2218   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
2219     MaskVec.push_back(DAG.getConstant(i,            BaseVT));
2220     MaskVec.push_back(DAG.getConstant(i + NumElems, BaseVT));
2221   }
2222   return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2223 }
2224
2225 /// getUnpackhMask - Returns a vector_shuffle mask for an unpackh operation
2226 /// of specified width.
2227 static SDOperand getUnpackhMask(unsigned NumElems, SelectionDAG &DAG) {
2228   MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2229   MVT::ValueType BaseVT = MVT::getVectorBaseType(MaskVT);
2230   unsigned Half = NumElems/2;
2231   SmallVector<SDOperand, 8> MaskVec;
2232   for (unsigned i = 0; i != Half; ++i) {
2233     MaskVec.push_back(DAG.getConstant(i + Half,            BaseVT));
2234     MaskVec.push_back(DAG.getConstant(i + NumElems + Half, BaseVT));
2235   }
2236   return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2237 }
2238
2239 /// getZeroVector - Returns a vector of specified type with all zero elements.
2240 ///
2241 static SDOperand getZeroVector(MVT::ValueType VT, SelectionDAG &DAG) {
2242   assert(MVT::isVector(VT) && "Expected a vector type");
2243   unsigned NumElems = getVectorNumElements(VT);
2244   MVT::ValueType EVT = MVT::getVectorBaseType(VT);
2245   bool isFP = MVT::isFloatingPoint(EVT);
2246   SDOperand Zero = isFP ? DAG.getConstantFP(0.0, EVT) : DAG.getConstant(0, EVT);
2247   SmallVector<SDOperand, 8> ZeroVec(NumElems, Zero);
2248   return DAG.getNode(ISD::BUILD_VECTOR, VT, &ZeroVec[0], ZeroVec.size());
2249 }
2250
2251 /// PromoteSplat - Promote a splat of v8i16 or v16i8 to v4i32.
2252 ///
2253 static SDOperand PromoteSplat(SDOperand Op, SelectionDAG &DAG) {
2254   SDOperand V1 = Op.getOperand(0);
2255   SDOperand Mask = Op.getOperand(2);
2256   MVT::ValueType VT = Op.getValueType();
2257   unsigned NumElems = Mask.getNumOperands();
2258   Mask = getUnpacklMask(NumElems, DAG);
2259   while (NumElems != 4) {
2260     V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1, Mask);
2261     NumElems >>= 1;
2262   }
2263   V1 = DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, V1);
2264
2265   MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
2266   Mask = getZeroVector(MaskVT, DAG);
2267   SDOperand Shuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v4i32, V1,
2268                                   DAG.getNode(ISD::UNDEF, MVT::v4i32), Mask);
2269   return DAG.getNode(ISD::BIT_CONVERT, VT, Shuffle);
2270 }
2271
2272 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
2273 /// constant +0.0.
2274 static inline bool isZeroNode(SDOperand Elt) {
2275   return ((isa<ConstantSDNode>(Elt) &&
2276            cast<ConstantSDNode>(Elt)->getValue() == 0) ||
2277           (isa<ConstantFPSDNode>(Elt) &&
2278            cast<ConstantFPSDNode>(Elt)->isExactlyValue(0.0)));
2279 }
2280
2281 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
2282 /// vector and zero or undef vector.
2283 static SDOperand getShuffleVectorZeroOrUndef(SDOperand V2, MVT::ValueType VT,
2284                                              unsigned NumElems, unsigned Idx,
2285                                              bool isZero, SelectionDAG &DAG) {
2286   SDOperand V1 = isZero ? getZeroVector(VT, DAG) : DAG.getNode(ISD::UNDEF, VT);
2287   MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2288   MVT::ValueType EVT = MVT::getVectorBaseType(MaskVT);
2289   SDOperand Zero = DAG.getConstant(0, EVT);
2290   SmallVector<SDOperand, 8> MaskVec(NumElems, Zero);
2291   MaskVec[Idx] = DAG.getConstant(NumElems, EVT);
2292   SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2293                                &MaskVec[0], MaskVec.size());
2294   return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2295 }
2296
2297 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
2298 ///
2299 static SDOperand LowerBuildVectorv16i8(SDOperand Op, unsigned NonZeros,
2300                                        unsigned NumNonZero, unsigned NumZero,
2301                                        SelectionDAG &DAG, TargetLowering &TLI) {
2302   if (NumNonZero > 8)
2303     return SDOperand();
2304
2305   SDOperand V(0, 0);
2306   bool First = true;
2307   for (unsigned i = 0; i < 16; ++i) {
2308     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
2309     if (ThisIsNonZero && First) {
2310       if (NumZero)
2311         V = getZeroVector(MVT::v8i16, DAG);
2312       else
2313         V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
2314       First = false;
2315     }
2316
2317     if ((i & 1) != 0) {
2318       SDOperand ThisElt(0, 0), LastElt(0, 0);
2319       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
2320       if (LastIsNonZero) {
2321         LastElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i-1));
2322       }
2323       if (ThisIsNonZero) {
2324         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i));
2325         ThisElt = DAG.getNode(ISD::SHL, MVT::i16,
2326                               ThisElt, DAG.getConstant(8, MVT::i8));
2327         if (LastIsNonZero)
2328           ThisElt = DAG.getNode(ISD::OR, MVT::i16, ThisElt, LastElt);
2329       } else
2330         ThisElt = LastElt;
2331
2332       if (ThisElt.Val)
2333         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, ThisElt,
2334                         DAG.getConstant(i/2, TLI.getPointerTy()));
2335     }
2336   }
2337
2338   return DAG.getNode(ISD::BIT_CONVERT, MVT::v16i8, V);
2339 }
2340
2341 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
2342 ///
2343 static SDOperand LowerBuildVectorv8i16(SDOperand Op, unsigned NonZeros,
2344                                        unsigned NumNonZero, unsigned NumZero,
2345                                        SelectionDAG &DAG, TargetLowering &TLI) {
2346   if (NumNonZero > 4)
2347     return SDOperand();
2348
2349   SDOperand V(0, 0);
2350   bool First = true;
2351   for (unsigned i = 0; i < 8; ++i) {
2352     bool isNonZero = (NonZeros & (1 << i)) != 0;
2353     if (isNonZero) {
2354       if (First) {
2355         if (NumZero)
2356           V = getZeroVector(MVT::v8i16, DAG);
2357         else
2358           V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
2359         First = false;
2360       }
2361       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, Op.getOperand(i),
2362                       DAG.getConstant(i, TLI.getPointerTy()));
2363     }
2364   }
2365
2366   return V;
2367 }
2368
2369 SDOperand
2370 X86TargetLowering::LowerBUILD_VECTOR(SDOperand Op, SelectionDAG &DAG) {
2371   // All zero's are handled with pxor.
2372   if (ISD::isBuildVectorAllZeros(Op.Val))
2373     return Op;
2374
2375   // All one's are handled with pcmpeqd.
2376   if (ISD::isBuildVectorAllOnes(Op.Val))
2377     return Op;
2378
2379   MVT::ValueType VT = Op.getValueType();
2380   MVT::ValueType EVT = MVT::getVectorBaseType(VT);
2381   unsigned EVTBits = MVT::getSizeInBits(EVT);
2382
2383   unsigned NumElems = Op.getNumOperands();
2384   unsigned NumZero  = 0;
2385   unsigned NumNonZero = 0;
2386   unsigned NonZeros = 0;
2387   std::set<SDOperand> Values;
2388   for (unsigned i = 0; i < NumElems; ++i) {
2389     SDOperand Elt = Op.getOperand(i);
2390     if (Elt.getOpcode() != ISD::UNDEF) {
2391       Values.insert(Elt);
2392       if (isZeroNode(Elt))
2393         NumZero++;
2394       else {
2395         NonZeros |= (1 << i);
2396         NumNonZero++;
2397       }
2398     }
2399   }
2400
2401   if (NumNonZero == 0)
2402     // Must be a mix of zero and undef. Return a zero vector.
2403     return getZeroVector(VT, DAG);
2404
2405   // Splat is obviously ok. Let legalizer expand it to a shuffle.
2406   if (Values.size() == 1)
2407     return SDOperand();
2408
2409   // Special case for single non-zero element.
2410   if (NumNonZero == 1) {
2411     unsigned Idx = CountTrailingZeros_32(NonZeros);
2412     SDOperand Item = Op.getOperand(Idx);
2413     Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
2414     if (Idx == 0)
2415       // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
2416       return getShuffleVectorZeroOrUndef(Item, VT, NumElems, Idx,
2417                                          NumZero > 0, DAG);
2418
2419     if (EVTBits == 32) {
2420       // Turn it into a shuffle of zero and zero-extended scalar to vector.
2421       Item = getShuffleVectorZeroOrUndef(Item, VT, NumElems, 0, NumZero > 0,
2422                                          DAG);
2423       MVT::ValueType MaskVT  = MVT::getIntVectorWithNumElements(NumElems);
2424       MVT::ValueType MaskEVT = MVT::getVectorBaseType(MaskVT);
2425       SmallVector<SDOperand, 8> MaskVec;
2426       for (unsigned i = 0; i < NumElems; i++)
2427         MaskVec.push_back(DAG.getConstant((i == Idx) ? 0 : 1, MaskEVT));
2428       SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2429                                    &MaskVec[0], MaskVec.size());
2430       return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Item,
2431                          DAG.getNode(ISD::UNDEF, VT), Mask);
2432     }
2433   }
2434
2435   // Let legalizer expand 2-wide build_vector's.
2436   if (EVTBits == 64)
2437     return SDOperand();
2438
2439   // If element VT is < 32 bits, convert it to inserts into a zero vector.
2440   if (EVTBits == 8 && NumElems == 16) {
2441     SDOperand V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
2442                                         *this);
2443     if (V.Val) return V;
2444   }
2445
2446   if (EVTBits == 16 && NumElems == 8) {
2447     SDOperand V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
2448                                         *this);
2449     if (V.Val) return V;
2450   }
2451
2452   // If element VT is == 32 bits, turn it into a number of shuffles.
2453   SmallVector<SDOperand, 8> V;
2454   V.resize(NumElems);
2455   if (NumElems == 4 && NumZero > 0) {
2456     for (unsigned i = 0; i < 4; ++i) {
2457       bool isZero = !(NonZeros & (1 << i));
2458       if (isZero)
2459         V[i] = getZeroVector(VT, DAG);
2460       else
2461         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
2462     }
2463
2464     for (unsigned i = 0; i < 2; ++i) {
2465       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
2466         default: break;
2467         case 0:
2468           V[i] = V[i*2];  // Must be a zero vector.
2469           break;
2470         case 1:
2471           V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2+1], V[i*2],
2472                              getMOVLMask(NumElems, DAG));
2473           break;
2474         case 2:
2475           V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
2476                              getMOVLMask(NumElems, DAG));
2477           break;
2478         case 3:
2479           V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
2480                              getUnpacklMask(NumElems, DAG));
2481           break;
2482       }
2483     }
2484
2485     // Take advantage of the fact GR32 to VR128 scalar_to_vector (i.e. movd)
2486     // clears the upper bits.
2487     // FIXME: we can do the same for v4f32 case when we know both parts of
2488     // the lower half come from scalar_to_vector (loadf32). We should do
2489     // that in post legalizer dag combiner with target specific hooks.
2490     if (MVT::isInteger(EVT) && (NonZeros & (0x3 << 2)) == 0)
2491       return V[0];
2492     MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2493     MVT::ValueType EVT = MVT::getVectorBaseType(MaskVT);
2494     SmallVector<SDOperand, 8> MaskVec;
2495     bool Reverse = (NonZeros & 0x3) == 2;
2496     for (unsigned i = 0; i < 2; ++i)
2497       if (Reverse)
2498         MaskVec.push_back(DAG.getConstant(1-i, EVT));
2499       else
2500         MaskVec.push_back(DAG.getConstant(i, EVT));
2501     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
2502     for (unsigned i = 0; i < 2; ++i)
2503       if (Reverse)
2504         MaskVec.push_back(DAG.getConstant(1-i+NumElems, EVT));
2505       else
2506         MaskVec.push_back(DAG.getConstant(i+NumElems, EVT));
2507     SDOperand ShufMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2508                                      &MaskVec[0], MaskVec.size());
2509     return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[0], V[1], ShufMask);
2510   }
2511
2512   if (Values.size() > 2) {
2513     // Expand into a number of unpckl*.
2514     // e.g. for v4f32
2515     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
2516     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
2517     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
2518     SDOperand UnpckMask = getUnpacklMask(NumElems, DAG);
2519     for (unsigned i = 0; i < NumElems; ++i)
2520       V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
2521     NumElems >>= 1;
2522     while (NumElems != 0) {
2523       for (unsigned i = 0; i < NumElems; ++i)
2524         V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i], V[i + NumElems],
2525                            UnpckMask);
2526       NumElems >>= 1;
2527     }
2528     return V[0];
2529   }
2530
2531   return SDOperand();
2532 }
2533
2534 SDOperand
2535 X86TargetLowering::LowerVECTOR_SHUFFLE(SDOperand Op, SelectionDAG &DAG) {
2536   SDOperand V1 = Op.getOperand(0);
2537   SDOperand V2 = Op.getOperand(1);
2538   SDOperand PermMask = Op.getOperand(2);
2539   MVT::ValueType VT = Op.getValueType();
2540   unsigned NumElems = PermMask.getNumOperands();
2541   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
2542   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
2543   bool V1IsSplat = false;
2544   bool V2IsSplat = false;
2545
2546   if (isUndefShuffle(Op.Val))
2547     return DAG.getNode(ISD::UNDEF, VT);
2548
2549   if (isSplatMask(PermMask.Val)) {
2550     if (NumElems <= 4) return Op;
2551     // Promote it to a v4i32 splat.
2552     return PromoteSplat(Op, DAG);
2553   }
2554
2555   if (X86::isMOVLMask(PermMask.Val))
2556     return (V1IsUndef) ? V2 : Op;
2557
2558   if (X86::isMOVSHDUPMask(PermMask.Val) ||
2559       X86::isMOVSLDUPMask(PermMask.Val) ||
2560       X86::isMOVHLPSMask(PermMask.Val) ||
2561       X86::isMOVHPMask(PermMask.Val) ||
2562       X86::isMOVLPMask(PermMask.Val))
2563     return Op;
2564
2565   if (ShouldXformToMOVHLPS(PermMask.Val) ||
2566       ShouldXformToMOVLP(V1.Val, V2.Val, PermMask.Val))
2567     return CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
2568
2569   bool Commuted = false;
2570   V1IsSplat = isSplatVector(V1.Val);
2571   V2IsSplat = isSplatVector(V2.Val);
2572   if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
2573     Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
2574     std::swap(V1IsSplat, V2IsSplat);
2575     std::swap(V1IsUndef, V2IsUndef);
2576     Commuted = true;
2577   }
2578
2579   if (isCommutedMOVL(PermMask.Val, V2IsSplat, V2IsUndef)) {
2580     if (V2IsUndef) return V1;
2581     Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
2582     if (V2IsSplat) {
2583       // V2 is a splat, so the mask may be malformed. That is, it may point
2584       // to any V2 element. The instruction selectior won't like this. Get
2585       // a corrected mask and commute to form a proper MOVS{S|D}.
2586       SDOperand NewMask = getMOVLMask(NumElems, DAG);
2587       if (NewMask.Val != PermMask.Val)
2588         Op = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
2589     }
2590     return Op;
2591   }
2592
2593   if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
2594       X86::isUNPCKLMask(PermMask.Val) ||
2595       X86::isUNPCKHMask(PermMask.Val))
2596     return Op;
2597
2598   if (V2IsSplat) {
2599     // Normalize mask so all entries that point to V2 points to its first
2600     // element then try to match unpck{h|l} again. If match, return a
2601     // new vector_shuffle with the corrected mask.
2602     SDOperand NewMask = NormalizeMask(PermMask, DAG);
2603     if (NewMask.Val != PermMask.Val) {
2604       if (X86::isUNPCKLMask(PermMask.Val, true)) {
2605         SDOperand NewMask = getUnpacklMask(NumElems, DAG);
2606         return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
2607       } else if (X86::isUNPCKHMask(PermMask.Val, true)) {
2608         SDOperand NewMask = getUnpackhMask(NumElems, DAG);
2609         return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
2610       }
2611     }
2612   }
2613
2614   // Normalize the node to match x86 shuffle ops if needed
2615   if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(PermMask.Val))
2616       Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
2617
2618   if (Commuted) {
2619     // Commute is back and try unpck* again.
2620     Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
2621     if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
2622         X86::isUNPCKLMask(PermMask.Val) ||
2623         X86::isUNPCKHMask(PermMask.Val))
2624       return Op;
2625   }
2626
2627   // If VT is integer, try PSHUF* first, then SHUFP*.
2628   if (MVT::isInteger(VT)) {
2629     if (X86::isPSHUFDMask(PermMask.Val) ||
2630         X86::isPSHUFHWMask(PermMask.Val) ||
2631         X86::isPSHUFLWMask(PermMask.Val)) {
2632       if (V2.getOpcode() != ISD::UNDEF)
2633         return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
2634                            DAG.getNode(ISD::UNDEF, V1.getValueType()),PermMask);
2635       return Op;
2636     }
2637
2638     if (X86::isSHUFPMask(PermMask.Val))
2639       return Op;
2640
2641     // Handle v8i16 shuffle high / low shuffle node pair.
2642     if (VT == MVT::v8i16 && isPSHUFHW_PSHUFLWMask(PermMask.Val)) {
2643       MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2644       MVT::ValueType BaseVT = MVT::getVectorBaseType(MaskVT);
2645       SmallVector<SDOperand, 8> MaskVec;
2646       for (unsigned i = 0; i != 4; ++i)
2647         MaskVec.push_back(PermMask.getOperand(i));
2648       for (unsigned i = 4; i != 8; ++i)
2649         MaskVec.push_back(DAG.getConstant(i, BaseVT));
2650       SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2651                                    &MaskVec[0], MaskVec.size());
2652       V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2653       MaskVec.clear();
2654       for (unsigned i = 0; i != 4; ++i)
2655         MaskVec.push_back(DAG.getConstant(i, BaseVT));
2656       for (unsigned i = 4; i != 8; ++i)
2657         MaskVec.push_back(PermMask.getOperand(i));
2658       Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0],MaskVec.size());
2659       return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2660     }
2661   } else {
2662     // Floating point cases in the other order.
2663     if (X86::isSHUFPMask(PermMask.Val))
2664       return Op;
2665     if (X86::isPSHUFDMask(PermMask.Val) ||
2666         X86::isPSHUFHWMask(PermMask.Val) ||
2667         X86::isPSHUFLWMask(PermMask.Val)) {
2668       if (V2.getOpcode() != ISD::UNDEF)
2669         return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
2670                            DAG.getNode(ISD::UNDEF, V1.getValueType()),PermMask);
2671       return Op;
2672     }
2673   }
2674
2675   if (NumElems == 4) {
2676     MVT::ValueType MaskVT = PermMask.getValueType();
2677     MVT::ValueType MaskEVT = MVT::getVectorBaseType(MaskVT);
2678     SmallVector<std::pair<int, int>, 8> Locs;
2679     Locs.reserve(NumElems);
2680     SmallVector<SDOperand, 8> Mask1(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
2681     SmallVector<SDOperand, 8> Mask2(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
2682     unsigned NumHi = 0;
2683     unsigned NumLo = 0;
2684     // If no more than two elements come from either vector. This can be
2685     // implemented with two shuffles. First shuffle gather the elements.
2686     // The second shuffle, which takes the first shuffle as both of its
2687     // vector operands, put the elements into the right order.
2688     for (unsigned i = 0; i != NumElems; ++i) {
2689       SDOperand Elt = PermMask.getOperand(i);
2690       if (Elt.getOpcode() == ISD::UNDEF) {
2691         Locs[i] = std::make_pair(-1, -1);
2692       } else {
2693         unsigned Val = cast<ConstantSDNode>(Elt)->getValue();
2694         if (Val < NumElems) {
2695           Locs[i] = std::make_pair(0, NumLo);
2696           Mask1[NumLo] = Elt;
2697           NumLo++;
2698         } else {
2699           Locs[i] = std::make_pair(1, NumHi);
2700           if (2+NumHi < NumElems)
2701             Mask1[2+NumHi] = Elt;
2702           NumHi++;
2703         }
2704       }
2705     }
2706     if (NumLo <= 2 && NumHi <= 2) {
2707       V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
2708                        DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2709                                    &Mask1[0], Mask1.size()));
2710       for (unsigned i = 0; i != NumElems; ++i) {
2711         if (Locs[i].first == -1)
2712           continue;
2713         else {
2714           unsigned Idx = (i < NumElems/2) ? 0 : NumElems;
2715           Idx += Locs[i].first * (NumElems/2) + Locs[i].second;
2716           Mask2[i] = DAG.getConstant(Idx, MaskEVT);
2717         }
2718       }
2719
2720       return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1,
2721                          DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2722                                      &Mask2[0], Mask2.size()));
2723     }
2724
2725     // Break it into (shuffle shuffle_hi, shuffle_lo).
2726     Locs.clear();
2727     SmallVector<SDOperand,8> LoMask(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
2728     SmallVector<SDOperand,8> HiMask(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
2729     SmallVector<SDOperand,8> *MaskPtr = &LoMask;
2730     unsigned MaskIdx = 0;
2731     unsigned LoIdx = 0;
2732     unsigned HiIdx = NumElems/2;
2733     for (unsigned i = 0; i != NumElems; ++i) {
2734       if (i == NumElems/2) {
2735         MaskPtr = &HiMask;
2736         MaskIdx = 1;
2737         LoIdx = 0;
2738         HiIdx = NumElems/2;
2739       }
2740       SDOperand Elt = PermMask.getOperand(i);
2741       if (Elt.getOpcode() == ISD::UNDEF) {
2742         Locs[i] = std::make_pair(-1, -1);
2743       } else if (cast<ConstantSDNode>(Elt)->getValue() < NumElems) {
2744         Locs[i] = std::make_pair(MaskIdx, LoIdx);
2745         (*MaskPtr)[LoIdx] = Elt;
2746         LoIdx++;
2747       } else {
2748         Locs[i] = std::make_pair(MaskIdx, HiIdx);
2749         (*MaskPtr)[HiIdx] = Elt;
2750         HiIdx++;
2751       }
2752     }
2753
2754     SDOperand LoShuffle =
2755       DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
2756                   DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2757                               &LoMask[0], LoMask.size()));
2758     SDOperand HiShuffle =
2759       DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
2760                   DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2761                               &HiMask[0], HiMask.size()));
2762     SmallVector<SDOperand, 8> MaskOps;
2763     for (unsigned i = 0; i != NumElems; ++i) {
2764       if (Locs[i].first == -1) {
2765         MaskOps.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
2766       } else {
2767         unsigned Idx = Locs[i].first * NumElems + Locs[i].second;
2768         MaskOps.push_back(DAG.getConstant(Idx, MaskEVT));
2769       }
2770     }
2771     return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, LoShuffle, HiShuffle,
2772                        DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2773                                    &MaskOps[0], MaskOps.size()));
2774   }
2775
2776   return SDOperand();
2777 }
2778
2779 SDOperand
2780 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDOperand Op, SelectionDAG &DAG) {
2781   if (!isa<ConstantSDNode>(Op.getOperand(1)))
2782     return SDOperand();
2783
2784   MVT::ValueType VT = Op.getValueType();
2785   // TODO: handle v16i8.
2786   if (MVT::getSizeInBits(VT) == 16) {
2787     // Transform it so it match pextrw which produces a 32-bit result.
2788     MVT::ValueType EVT = (MVT::ValueType)(VT+1);
2789     SDOperand Extract = DAG.getNode(X86ISD::PEXTRW, EVT,
2790                                     Op.getOperand(0), Op.getOperand(1));
2791     SDOperand Assert  = DAG.getNode(ISD::AssertZext, EVT, Extract,
2792                                     DAG.getValueType(VT));
2793     return DAG.getNode(ISD::TRUNCATE, VT, Assert);
2794   } else if (MVT::getSizeInBits(VT) == 32) {
2795     SDOperand Vec = Op.getOperand(0);
2796     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
2797     if (Idx == 0)
2798       return Op;
2799     // SHUFPS the element to the lowest double word, then movss.
2800     MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
2801     SmallVector<SDOperand, 8> IdxVec;
2802     IdxVec.push_back(DAG.getConstant(Idx, MVT::getVectorBaseType(MaskVT)));
2803     IdxVec.push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorBaseType(MaskVT)));
2804     IdxVec.push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorBaseType(MaskVT)));
2805     IdxVec.push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorBaseType(MaskVT)));
2806     SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2807                                  &IdxVec[0], IdxVec.size());
2808     Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
2809                       Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
2810     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
2811                        DAG.getConstant(0, getPointerTy()));
2812   } else if (MVT::getSizeInBits(VT) == 64) {
2813     SDOperand Vec = Op.getOperand(0);
2814     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
2815     if (Idx == 0)
2816       return Op;
2817
2818     // UNPCKHPD the element to the lowest double word, then movsd.
2819     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
2820     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
2821     MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
2822     SmallVector<SDOperand, 8> IdxVec;
2823     IdxVec.push_back(DAG.getConstant(1, MVT::getVectorBaseType(MaskVT)));
2824     IdxVec.push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorBaseType(MaskVT)));
2825     SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2826                                  &IdxVec[0], IdxVec.size());
2827     Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
2828                       Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
2829     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
2830                        DAG.getConstant(0, getPointerTy()));
2831   }
2832
2833   return SDOperand();
2834 }
2835
2836 SDOperand
2837 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDOperand Op, SelectionDAG &DAG) {
2838   // Transform it so it match pinsrw which expects a 16-bit value in a GR32
2839   // as its second argument.
2840   MVT::ValueType VT = Op.getValueType();
2841   MVT::ValueType BaseVT = MVT::getVectorBaseType(VT);
2842   SDOperand N0 = Op.getOperand(0);
2843   SDOperand N1 = Op.getOperand(1);
2844   SDOperand N2 = Op.getOperand(2);
2845   if (MVT::getSizeInBits(BaseVT) == 16) {
2846     if (N1.getValueType() != MVT::i32)
2847       N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
2848     if (N2.getValueType() != MVT::i32)
2849       N2 = DAG.getConstant(cast<ConstantSDNode>(N2)->getValue(), MVT::i32);
2850     return DAG.getNode(X86ISD::PINSRW, VT, N0, N1, N2);
2851   } else if (MVT::getSizeInBits(BaseVT) == 32) {
2852     unsigned Idx = cast<ConstantSDNode>(N2)->getValue();
2853     if (Idx == 0) {
2854       // Use a movss.
2855       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, N1);
2856       MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
2857       MVT::ValueType BaseVT = MVT::getVectorBaseType(MaskVT);
2858       SmallVector<SDOperand, 8> MaskVec;
2859       MaskVec.push_back(DAG.getConstant(4, BaseVT));
2860       for (unsigned i = 1; i <= 3; ++i)
2861         MaskVec.push_back(DAG.getConstant(i, BaseVT));
2862       return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, N0, N1,
2863                          DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2864                                      &MaskVec[0], MaskVec.size()));
2865     } else {
2866       // Use two pinsrw instructions to insert a 32 bit value.
2867       Idx <<= 1;
2868       if (MVT::isFloatingPoint(N1.getValueType())) {
2869         if (ISD::isNON_EXTLoad(N1.Val)) {
2870           // Just load directly from f32mem to GR32.
2871           LoadSDNode *LD = cast<LoadSDNode>(N1);
2872           N1 = DAG.getLoad(MVT::i32, LD->getChain(), LD->getBasePtr(),
2873                            LD->getSrcValue(), LD->getSrcValueOffset());
2874         } else {
2875           N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v4f32, N1);
2876           N1 = DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, N1);
2877           N1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32, N1,
2878                            DAG.getConstant(0, getPointerTy()));
2879         }
2880       }
2881       N0 = DAG.getNode(ISD::BIT_CONVERT, MVT::v8i16, N0);
2882       N0 = DAG.getNode(X86ISD::PINSRW, MVT::v8i16, N0, N1,
2883                        DAG.getConstant(Idx, getPointerTy()));
2884       N1 = DAG.getNode(ISD::SRL, MVT::i32, N1, DAG.getConstant(16, MVT::i8));
2885       N0 = DAG.getNode(X86ISD::PINSRW, MVT::v8i16, N0, N1,
2886                        DAG.getConstant(Idx+1, getPointerTy()));
2887       return DAG.getNode(ISD::BIT_CONVERT, VT, N0);
2888     }
2889   }
2890
2891   return SDOperand();
2892 }
2893
2894 SDOperand
2895 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDOperand Op, SelectionDAG &DAG) {
2896   SDOperand AnyExt = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, Op.getOperand(0));
2897   return DAG.getNode(X86ISD::S2VEC, Op.getValueType(), AnyExt);
2898 }
2899
2900 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2901 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
2902 // one of the above mentioned nodes. It has to be wrapped because otherwise
2903 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2904 // be used to form addressing mode. These wrapped nodes will be selected
2905 // into MOV32ri.
2906 SDOperand
2907 X86TargetLowering::LowerConstantPool(SDOperand Op, SelectionDAG &DAG) {
2908   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2909   SDOperand Result = DAG.getTargetConstantPool(CP->getConstVal(),
2910                                                getPointerTy(),
2911                                                CP->getAlignment());
2912   Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
2913   // With PIC, the address is actually $g + Offset.
2914   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2915       !Subtarget->isPICStyleRIPRel()) {
2916     Result = DAG.getNode(ISD::ADD, getPointerTy(),
2917                          DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
2918                          Result);
2919   }
2920
2921   return Result;
2922 }
2923
2924 SDOperand
2925 X86TargetLowering::LowerGlobalAddress(SDOperand Op, SelectionDAG &DAG) {
2926   GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2927   SDOperand Result = DAG.getTargetGlobalAddress(GV, getPointerTy());
2928   Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
2929   // With PIC, the address is actually $g + Offset.
2930   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2931       !Subtarget->isPICStyleRIPRel()) {
2932     Result = DAG.getNode(ISD::ADD, getPointerTy(),
2933                          DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
2934                          Result);
2935   }
2936   
2937   // For Darwin & Mingw32, external and weak symbols are indirect, so we want to
2938   // load the value at address GV, not the value of GV itself. This means that
2939   // the GlobalAddress must be in the base or index register of the address, not
2940   // the GV offset field. Platform check is inside GVRequiresExtraLoad() call
2941   // The same applies for external symbols during PIC codegen
2942   if (Subtarget->GVRequiresExtraLoad(GV, getTargetMachine(), false))
2943     Result = DAG.getLoad(getPointerTy(), DAG.getEntryNode(), Result, NULL, 0);
2944
2945   return Result;
2946 }
2947
2948 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2949 static SDOperand
2950 LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
2951                               const MVT::ValueType PtrVT) {
2952   SDOperand InFlag;
2953   SDOperand Chain = DAG.getCopyToReg(DAG.getEntryNode(), X86::EBX,
2954                                      DAG.getNode(X86ISD::GlobalBaseReg,
2955                                                  PtrVT), InFlag);
2956   InFlag = Chain.getValue(1);
2957
2958   // emit leal symbol@TLSGD(,%ebx,1), %eax
2959   SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
2960   SDOperand TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
2961                                              GA->getValueType(0),
2962                                              GA->getOffset());
2963   SDOperand Ops[] = { Chain,  TGA, InFlag };
2964   SDOperand Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 3);
2965   InFlag = Result.getValue(2);
2966   Chain = Result.getValue(1);
2967
2968   // call ___tls_get_addr. This function receives its argument in
2969   // the register EAX.
2970   Chain = DAG.getCopyToReg(Chain, X86::EAX, Result, InFlag);
2971   InFlag = Chain.getValue(1);
2972
2973   NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
2974   SDOperand Ops1[] = { Chain,
2975                       DAG.getTargetExternalSymbol("___tls_get_addr",
2976                                                   PtrVT),
2977                       DAG.getRegister(X86::EAX, PtrVT),
2978                       DAG.getRegister(X86::EBX, PtrVT),
2979                       InFlag };
2980   Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 5);
2981   InFlag = Chain.getValue(1);
2982
2983   return DAG.getCopyFromReg(Chain, X86::EAX, PtrVT, InFlag);
2984 }
2985
2986 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
2987 // "local exec" model.
2988 static SDOperand
2989 LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
2990                          const MVT::ValueType PtrVT) {
2991   // Get the Thread Pointer
2992   SDOperand ThreadPointer = DAG.getNode(X86ISD::THREAD_POINTER, PtrVT);
2993   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
2994   // exec)
2995   SDOperand TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
2996                                              GA->getValueType(0),
2997                                              GA->getOffset());
2998   SDOperand Offset = DAG.getNode(X86ISD::Wrapper, PtrVT, TGA);
2999   // The address of the thread local variable is the add of the thread
3000   // pointer with the offset of the variable.
3001   return DAG.getNode(ISD::ADD, PtrVT, ThreadPointer, Offset);
3002 }
3003
3004 SDOperand
3005 X86TargetLowering::LowerGlobalTLSAddress(SDOperand Op, SelectionDAG &DAG) {
3006   // TODO: implement the "local dynamic" model
3007   // TODO: implement the "initial exec"model for pic executables 
3008   assert(!Subtarget->is64Bit() && "TLS not implemented for X86_64");
3009   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3010   // If the relocation model is PIC, use the "General Dynamic" TLS Model,
3011   // otherwise use the "Local Exec"TLS Model
3012   if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
3013     return LowerToTLSGeneralDynamicModel(GA, DAG, getPointerTy());
3014   else
3015     return LowerToTLSExecModel(GA, DAG, getPointerTy());
3016 }
3017
3018 SDOperand
3019 X86TargetLowering::LowerExternalSymbol(SDOperand Op, SelectionDAG &DAG) {
3020   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
3021   SDOperand Result = DAG.getTargetExternalSymbol(Sym, getPointerTy());
3022   Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
3023   // With PIC, the address is actually $g + Offset.
3024   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
3025       !Subtarget->isPICStyleRIPRel()) {
3026     Result = DAG.getNode(ISD::ADD, getPointerTy(),
3027                          DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
3028                          Result);
3029   }
3030
3031   return Result;
3032 }
3033
3034 SDOperand X86TargetLowering::LowerJumpTable(SDOperand Op, SelectionDAG &DAG) {
3035   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
3036   SDOperand Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy());
3037   Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
3038   // With PIC, the address is actually $g + Offset.
3039   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
3040       !Subtarget->isPICStyleRIPRel()) {
3041     Result = DAG.getNode(ISD::ADD, getPointerTy(),
3042                          DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
3043                          Result);
3044   }
3045
3046   return Result;
3047 }
3048
3049 SDOperand X86TargetLowering::LowerShift(SDOperand Op, SelectionDAG &DAG) {
3050     assert(Op.getNumOperands() == 3 && Op.getValueType() == MVT::i32 &&
3051            "Not an i64 shift!");
3052     bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
3053     SDOperand ShOpLo = Op.getOperand(0);
3054     SDOperand ShOpHi = Op.getOperand(1);
3055     SDOperand ShAmt  = Op.getOperand(2);
3056     SDOperand Tmp1 = isSRA ?
3057       DAG.getNode(ISD::SRA, MVT::i32, ShOpHi, DAG.getConstant(31, MVT::i8)) :
3058       DAG.getConstant(0, MVT::i32);
3059
3060     SDOperand Tmp2, Tmp3;
3061     if (Op.getOpcode() == ISD::SHL_PARTS) {
3062       Tmp2 = DAG.getNode(X86ISD::SHLD, MVT::i32, ShOpHi, ShOpLo, ShAmt);
3063       Tmp3 = DAG.getNode(ISD::SHL, MVT::i32, ShOpLo, ShAmt);
3064     } else {
3065       Tmp2 = DAG.getNode(X86ISD::SHRD, MVT::i32, ShOpLo, ShOpHi, ShAmt);
3066       Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, MVT::i32, ShOpHi, ShAmt);
3067     }
3068
3069     const MVT::ValueType *VTs = DAG.getNodeValueTypes(MVT::Other, MVT::Flag);
3070     SDOperand AndNode = DAG.getNode(ISD::AND, MVT::i8, ShAmt,
3071                                     DAG.getConstant(32, MVT::i8));
3072     SDOperand COps[]={DAG.getEntryNode(), AndNode, DAG.getConstant(0, MVT::i8)};
3073     SDOperand InFlag = DAG.getNode(X86ISD::CMP, VTs, 2, COps, 3).getValue(1);
3074
3075     SDOperand Hi, Lo;
3076     SDOperand CC = DAG.getConstant(X86::COND_NE, MVT::i8);
3077
3078     VTs = DAG.getNodeValueTypes(MVT::i32, MVT::Flag);
3079     SmallVector<SDOperand, 4> Ops;
3080     if (Op.getOpcode() == ISD::SHL_PARTS) {
3081       Ops.push_back(Tmp2);
3082       Ops.push_back(Tmp3);
3083       Ops.push_back(CC);
3084       Ops.push_back(InFlag);
3085       Hi = DAG.getNode(X86ISD::CMOV, VTs, 2, &Ops[0], Ops.size());
3086       InFlag = Hi.getValue(1);
3087
3088       Ops.clear();
3089       Ops.push_back(Tmp3);
3090       Ops.push_back(Tmp1);
3091       Ops.push_back(CC);
3092       Ops.push_back(InFlag);
3093       Lo = DAG.getNode(X86ISD::CMOV, VTs, 2, &Ops[0], Ops.size());
3094     } else {
3095       Ops.push_back(Tmp2);
3096       Ops.push_back(Tmp3);
3097       Ops.push_back(CC);
3098       Ops.push_back(InFlag);
3099       Lo = DAG.getNode(X86ISD::CMOV, VTs, 2, &Ops[0], Ops.size());
3100       InFlag = Lo.getValue(1);
3101
3102       Ops.clear();
3103       Ops.push_back(Tmp3);
3104       Ops.push_back(Tmp1);
3105       Ops.push_back(CC);
3106       Ops.push_back(InFlag);
3107       Hi = DAG.getNode(X86ISD::CMOV, VTs, 2, &Ops[0], Ops.size());
3108     }
3109
3110     VTs = DAG.getNodeValueTypes(MVT::i32, MVT::i32);
3111     Ops.clear();
3112     Ops.push_back(Lo);
3113     Ops.push_back(Hi);
3114     return DAG.getNode(ISD::MERGE_VALUES, VTs, 2, &Ops[0], Ops.size());
3115 }
3116
3117 SDOperand X86TargetLowering::LowerSINT_TO_FP(SDOperand Op, SelectionDAG &DAG) {
3118   assert(Op.getOperand(0).getValueType() <= MVT::i64 &&
3119          Op.getOperand(0).getValueType() >= MVT::i16 &&
3120          "Unknown SINT_TO_FP to lower!");
3121
3122   SDOperand Result;
3123   MVT::ValueType SrcVT = Op.getOperand(0).getValueType();
3124   unsigned Size = MVT::getSizeInBits(SrcVT)/8;
3125   MachineFunction &MF = DAG.getMachineFunction();
3126   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
3127   SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
3128   SDOperand Chain = DAG.getStore(DAG.getEntryNode(), Op.getOperand(0),
3129                                  StackSlot, NULL, 0);
3130
3131   // Build the FILD
3132   SDVTList Tys;
3133   if (X86ScalarSSE)
3134     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
3135   else
3136     Tys = DAG.getVTList(MVT::f64, MVT::Other);
3137   SmallVector<SDOperand, 8> Ops;
3138   Ops.push_back(Chain);
3139   Ops.push_back(StackSlot);
3140   Ops.push_back(DAG.getValueType(SrcVT));
3141   Result = DAG.getNode(X86ScalarSSE ? X86ISD::FILD_FLAG :X86ISD::FILD,
3142                        Tys, &Ops[0], Ops.size());
3143
3144   if (X86ScalarSSE) {
3145     Chain = Result.getValue(1);
3146     SDOperand InFlag = Result.getValue(2);
3147
3148     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
3149     // shouldn't be necessary except that RFP cannot be live across
3150     // multiple blocks. When stackifier is fixed, they can be uncoupled.
3151     MachineFunction &MF = DAG.getMachineFunction();
3152     int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
3153     SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
3154     Tys = DAG.getVTList(MVT::Other);
3155     SmallVector<SDOperand, 8> Ops;
3156     Ops.push_back(Chain);
3157     Ops.push_back(Result);
3158     Ops.push_back(StackSlot);
3159     Ops.push_back(DAG.getValueType(Op.getValueType()));
3160     Ops.push_back(InFlag);
3161     Chain = DAG.getNode(X86ISD::FST, Tys, &Ops[0], Ops.size());
3162     Result = DAG.getLoad(Op.getValueType(), Chain, StackSlot, NULL, 0);
3163   }
3164
3165   return Result;
3166 }
3167
3168 SDOperand X86TargetLowering::LowerFP_TO_SINT(SDOperand Op, SelectionDAG &DAG) {
3169   assert(Op.getValueType() <= MVT::i64 && Op.getValueType() >= MVT::i16 &&
3170          "Unknown FP_TO_SINT to lower!");
3171   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
3172   // stack slot.
3173   MachineFunction &MF = DAG.getMachineFunction();
3174   unsigned MemSize = MVT::getSizeInBits(Op.getValueType())/8;
3175   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
3176   SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
3177
3178   unsigned Opc;
3179   switch (Op.getValueType()) {
3180     default: assert(0 && "Invalid FP_TO_SINT to lower!");
3181     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
3182     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
3183     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
3184   }
3185
3186   SDOperand Chain = DAG.getEntryNode();
3187   SDOperand Value = Op.getOperand(0);
3188   if (X86ScalarSSE) {
3189     assert(Op.getValueType() == MVT::i64 && "Invalid FP_TO_SINT to lower!");
3190     Chain = DAG.getStore(Chain, Value, StackSlot, NULL, 0);
3191     SDVTList Tys = DAG.getVTList(MVT::f64, MVT::Other);
3192     SDOperand Ops[] = {
3193       Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
3194     };
3195     Value = DAG.getNode(X86ISD::FLD, Tys, Ops, 3);
3196     Chain = Value.getValue(1);
3197     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
3198     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
3199   }
3200
3201   // Build the FP_TO_INT*_IN_MEM
3202   SDOperand Ops[] = { Chain, Value, StackSlot };
3203   SDOperand FIST = DAG.getNode(Opc, MVT::Other, Ops, 3);
3204
3205   // Load the result.
3206   return DAG.getLoad(Op.getValueType(), FIST, StackSlot, NULL, 0);
3207 }
3208
3209 SDOperand X86TargetLowering::LowerFABS(SDOperand Op, SelectionDAG &DAG) {
3210   MVT::ValueType VT = Op.getValueType();
3211   const Type *OpNTy =  MVT::getTypeForValueType(VT);
3212   std::vector<Constant*> CV;
3213   if (VT == MVT::f64) {
3214     CV.push_back(ConstantFP::get(OpNTy, BitsToDouble(~(1ULL << 63))));
3215     CV.push_back(ConstantFP::get(OpNTy, 0.0));
3216   } else {
3217     CV.push_back(ConstantFP::get(OpNTy, BitsToFloat(~(1U << 31))));
3218     CV.push_back(ConstantFP::get(OpNTy, 0.0));
3219     CV.push_back(ConstantFP::get(OpNTy, 0.0));
3220     CV.push_back(ConstantFP::get(OpNTy, 0.0));
3221   }
3222   Constant *CS = ConstantStruct::get(CV);
3223   SDOperand CPIdx = DAG.getConstantPool(CS, getPointerTy(), 4);
3224   SDVTList Tys = DAG.getVTList(VT, MVT::Other);
3225   SmallVector<SDOperand, 3> Ops;
3226   Ops.push_back(DAG.getEntryNode());
3227   Ops.push_back(CPIdx);
3228   Ops.push_back(DAG.getSrcValue(NULL));
3229   SDOperand Mask = DAG.getNode(X86ISD::LOAD_PACK, Tys, &Ops[0], Ops.size());
3230   return DAG.getNode(X86ISD::FAND, VT, Op.getOperand(0), Mask);
3231 }
3232
3233 SDOperand X86TargetLowering::LowerFNEG(SDOperand Op, SelectionDAG &DAG) {
3234   MVT::ValueType VT = Op.getValueType();
3235   const Type *OpNTy =  MVT::getTypeForValueType(VT);
3236   std::vector<Constant*> CV;
3237   if (VT == MVT::f64) {
3238     CV.push_back(ConstantFP::get(OpNTy, BitsToDouble(1ULL << 63)));
3239     CV.push_back(ConstantFP::get(OpNTy, 0.0));
3240   } else {
3241     CV.push_back(ConstantFP::get(OpNTy, BitsToFloat(1U << 31)));
3242     CV.push_back(ConstantFP::get(OpNTy, 0.0));
3243     CV.push_back(ConstantFP::get(OpNTy, 0.0));
3244     CV.push_back(ConstantFP::get(OpNTy, 0.0));
3245   }
3246   Constant *CS = ConstantStruct::get(CV);
3247   SDOperand CPIdx = DAG.getConstantPool(CS, getPointerTy(), 4);
3248   SDVTList Tys = DAG.getVTList(VT, MVT::Other);
3249   SmallVector<SDOperand, 3> Ops;
3250   Ops.push_back(DAG.getEntryNode());
3251   Ops.push_back(CPIdx);
3252   Ops.push_back(DAG.getSrcValue(NULL));
3253   SDOperand Mask = DAG.getNode(X86ISD::LOAD_PACK, Tys, &Ops[0], Ops.size());
3254   return DAG.getNode(X86ISD::FXOR, VT, Op.getOperand(0), Mask);
3255 }
3256
3257 SDOperand X86TargetLowering::LowerFCOPYSIGN(SDOperand Op, SelectionDAG &DAG) {
3258   SDOperand Op0 = Op.getOperand(0);
3259   SDOperand Op1 = Op.getOperand(1);
3260   MVT::ValueType VT = Op.getValueType();
3261   MVT::ValueType SrcVT = Op1.getValueType();
3262   const Type *SrcTy =  MVT::getTypeForValueType(SrcVT);
3263
3264   // If second operand is smaller, extend it first.
3265   if (MVT::getSizeInBits(SrcVT) < MVT::getSizeInBits(VT)) {
3266     Op1 = DAG.getNode(ISD::FP_EXTEND, VT, Op1);
3267     SrcVT = VT;
3268   }
3269
3270   // First get the sign bit of second operand.
3271   std::vector<Constant*> CV;
3272   if (SrcVT == MVT::f64) {
3273     CV.push_back(ConstantFP::get(SrcTy, BitsToDouble(1ULL << 63)));
3274     CV.push_back(ConstantFP::get(SrcTy, 0.0));
3275   } else {
3276     CV.push_back(ConstantFP::get(SrcTy, BitsToFloat(1U << 31)));
3277     CV.push_back(ConstantFP::get(SrcTy, 0.0));
3278     CV.push_back(ConstantFP::get(SrcTy, 0.0));
3279     CV.push_back(ConstantFP::get(SrcTy, 0.0));
3280   }
3281   Constant *CS = ConstantStruct::get(CV);
3282   SDOperand CPIdx = DAG.getConstantPool(CS, getPointerTy(), 4);
3283   SDVTList Tys = DAG.getVTList(SrcVT, MVT::Other);
3284   SmallVector<SDOperand, 3> Ops;
3285   Ops.push_back(DAG.getEntryNode());
3286   Ops.push_back(CPIdx);
3287   Ops.push_back(DAG.getSrcValue(NULL));
3288   SDOperand Mask1 = DAG.getNode(X86ISD::LOAD_PACK, Tys, &Ops[0], Ops.size());
3289   SDOperand SignBit = DAG.getNode(X86ISD::FAND, SrcVT, Op1, Mask1);
3290
3291   // Shift sign bit right or left if the two operands have different types.
3292   if (MVT::getSizeInBits(SrcVT) > MVT::getSizeInBits(VT)) {
3293     // Op0 is MVT::f32, Op1 is MVT::f64.
3294     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2f64, SignBit);
3295     SignBit = DAG.getNode(X86ISD::FSRL, MVT::v2f64, SignBit,
3296                           DAG.getConstant(32, MVT::i32));
3297     SignBit = DAG.getNode(ISD::BIT_CONVERT, MVT::v4f32, SignBit);
3298     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::f32, SignBit,
3299                           DAG.getConstant(0, getPointerTy()));
3300   }
3301
3302   // Clear first operand sign bit.
3303   CV.clear();
3304   if (VT == MVT::f64) {
3305     CV.push_back(ConstantFP::get(SrcTy, BitsToDouble(~(1ULL << 63))));
3306     CV.push_back(ConstantFP::get(SrcTy, 0.0));
3307   } else {
3308     CV.push_back(ConstantFP::get(SrcTy, BitsToFloat(~(1U << 31))));
3309     CV.push_back(ConstantFP::get(SrcTy, 0.0));
3310     CV.push_back(ConstantFP::get(SrcTy, 0.0));
3311     CV.push_back(ConstantFP::get(SrcTy, 0.0));
3312   }
3313   CS = ConstantStruct::get(CV);
3314   CPIdx = DAG.getConstantPool(CS, getPointerTy(), 4);
3315   Tys = DAG.getVTList(VT, MVT::Other);
3316   Ops.clear();
3317   Ops.push_back(DAG.getEntryNode());
3318   Ops.push_back(CPIdx);
3319   Ops.push_back(DAG.getSrcValue(NULL));
3320   SDOperand Mask2 = DAG.getNode(X86ISD::LOAD_PACK, Tys, &Ops[0], Ops.size());
3321   SDOperand Val = DAG.getNode(X86ISD::FAND, VT, Op0, Mask2);
3322
3323   // Or the value with the sign bit.
3324   return DAG.getNode(X86ISD::FOR, VT, Val, SignBit);
3325 }
3326
3327 SDOperand X86TargetLowering::LowerSETCC(SDOperand Op, SelectionDAG &DAG,
3328                                         SDOperand Chain) {
3329   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
3330   SDOperand Cond;
3331   SDOperand Op0 = Op.getOperand(0);
3332   SDOperand Op1 = Op.getOperand(1);
3333   SDOperand CC = Op.getOperand(2);
3334   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
3335   const MVT::ValueType *VTs1 = DAG.getNodeValueTypes(MVT::Other, MVT::Flag);
3336   const MVT::ValueType *VTs2 = DAG.getNodeValueTypes(MVT::i8, MVT::Flag);
3337   bool isFP = MVT::isFloatingPoint(Op.getOperand(1).getValueType());
3338   unsigned X86CC;
3339
3340   if (translateX86CC(cast<CondCodeSDNode>(CC)->get(), isFP, X86CC,
3341                      Op0, Op1, DAG)) {
3342     SDOperand Ops1[] = { Chain, Op0, Op1 };
3343     Cond = DAG.getNode(X86ISD::CMP, VTs1, 2, Ops1, 3).getValue(1);
3344     SDOperand Ops2[] = { DAG.getConstant(X86CC, MVT::i8), Cond };
3345     return DAG.getNode(X86ISD::SETCC, VTs2, 2, Ops2, 2);
3346   }
3347
3348   assert(isFP && "Illegal integer SetCC!");
3349
3350   SDOperand COps[] = { Chain, Op0, Op1 };
3351   Cond = DAG.getNode(X86ISD::CMP, VTs1, 2, COps, 3).getValue(1);
3352
3353   switch (SetCCOpcode) {
3354   default: assert(false && "Illegal floating point SetCC!");
3355   case ISD::SETOEQ: {  // !PF & ZF
3356     SDOperand Ops1[] = { DAG.getConstant(X86::COND_NP, MVT::i8), Cond };
3357     SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, VTs2, 2, Ops1, 2);
3358     SDOperand Ops2[] = { DAG.getConstant(X86::COND_E, MVT::i8),
3359                          Tmp1.getValue(1) };
3360     SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, VTs2, 2, Ops2, 2);
3361     return DAG.getNode(ISD::AND, MVT::i8, Tmp1, Tmp2);
3362   }
3363   case ISD::SETUNE: {  // PF | !ZF
3364     SDOperand Ops1[] = { DAG.getConstant(X86::COND_P, MVT::i8), Cond };
3365     SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, VTs2, 2, Ops1, 2);
3366     SDOperand Ops2[] = { DAG.getConstant(X86::COND_NE, MVT::i8),
3367                          Tmp1.getValue(1) };
3368     SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, VTs2, 2, Ops2, 2);
3369     return DAG.getNode(ISD::OR, MVT::i8, Tmp1, Tmp2);
3370   }
3371   }
3372 }
3373
3374 SDOperand X86TargetLowering::LowerSELECT(SDOperand Op, SelectionDAG &DAG) {
3375   bool addTest = true;
3376   SDOperand Chain = DAG.getEntryNode();
3377   SDOperand Cond  = Op.getOperand(0);
3378   SDOperand CC;
3379   const MVT::ValueType *VTs = DAG.getNodeValueTypes(MVT::Other, MVT::Flag);
3380
3381   if (Cond.getOpcode() == ISD::SETCC)
3382     Cond = LowerSETCC(Cond, DAG, Chain);
3383
3384   if (Cond.getOpcode() == X86ISD::SETCC) {
3385     CC = Cond.getOperand(0);
3386
3387     // If condition flag is set by a X86ISD::CMP, then make a copy of it
3388     // (since flag operand cannot be shared). Use it as the condition setting
3389     // operand in place of the X86ISD::SETCC.
3390     // If the X86ISD::SETCC has more than one use, then perhaps it's better
3391     // to use a test instead of duplicating the X86ISD::CMP (for register
3392     // pressure reason)?
3393     SDOperand Cmp = Cond.getOperand(1);
3394     unsigned Opc = Cmp.getOpcode();
3395     bool IllegalFPCMov = !X86ScalarSSE &&
3396       MVT::isFloatingPoint(Op.getValueType()) &&
3397       !hasFPCMov(cast<ConstantSDNode>(CC)->getSignExtended());
3398     if ((Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI) &&
3399         !IllegalFPCMov) {
3400       SDOperand Ops[] = { Chain, Cmp.getOperand(1), Cmp.getOperand(2) };
3401       Cond = DAG.getNode(Opc, VTs, 2, Ops, 3);
3402       addTest = false;
3403     }
3404   }
3405
3406   if (addTest) {
3407     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
3408     SDOperand Ops[] = { Chain, Cond, DAG.getConstant(0, MVT::i8) };
3409     Cond = DAG.getNode(X86ISD::CMP, VTs, 2, Ops, 3);
3410   }
3411
3412   VTs = DAG.getNodeValueTypes(Op.getValueType(), MVT::Flag);
3413   SmallVector<SDOperand, 4> Ops;
3414   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
3415   // condition is true.
3416   Ops.push_back(Op.getOperand(2));
3417   Ops.push_back(Op.getOperand(1));
3418   Ops.push_back(CC);
3419   Ops.push_back(Cond.getValue(1));
3420   return DAG.getNode(X86ISD::CMOV, VTs, 2, &Ops[0], Ops.size());
3421 }
3422
3423 SDOperand X86TargetLowering::LowerBRCOND(SDOperand Op, SelectionDAG &DAG) {
3424   bool addTest = true;
3425   SDOperand Chain = Op.getOperand(0);
3426   SDOperand Cond  = Op.getOperand(1);
3427   SDOperand Dest  = Op.getOperand(2);
3428   SDOperand CC;
3429   const MVT::ValueType *VTs = DAG.getNodeValueTypes(MVT::Other, MVT::Flag);
3430
3431   if (Cond.getOpcode() == ISD::SETCC)
3432     Cond = LowerSETCC(Cond, DAG, Chain);
3433
3434   if (Cond.getOpcode() == X86ISD::SETCC) {
3435     CC = Cond.getOperand(0);
3436
3437     // If condition flag is set by a X86ISD::CMP, then make a copy of it
3438     // (since flag operand cannot be shared). Use it as the condition setting
3439     // operand in place of the X86ISD::SETCC.
3440     // If the X86ISD::SETCC has more than one use, then perhaps it's better
3441     // to use a test instead of duplicating the X86ISD::CMP (for register
3442     // pressure reason)?
3443     SDOperand Cmp = Cond.getOperand(1);
3444     unsigned Opc = Cmp.getOpcode();
3445     if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI) {
3446       SDOperand Ops[] = { Chain, Cmp.getOperand(1), Cmp.getOperand(2) };
3447       Cond = DAG.getNode(Opc, VTs, 2, Ops, 3);
3448       addTest = false;
3449     }
3450   }
3451
3452   if (addTest) {
3453     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
3454     SDOperand Ops[] = { Chain, Cond, DAG.getConstant(0, MVT::i8) };
3455     Cond = DAG.getNode(X86ISD::CMP, VTs, 2, Ops, 3);
3456   }
3457   return DAG.getNode(X86ISD::BRCOND, Op.getValueType(),
3458                      Cond, Op.getOperand(2), CC, Cond.getValue(1));
3459 }
3460
3461 SDOperand X86TargetLowering::LowerCALL(SDOperand Op, SelectionDAG &DAG) {
3462   unsigned CallingConv= cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3463
3464   if (Subtarget->is64Bit())
3465     return LowerX86_64CCCCallTo(Op, DAG, CallingConv);
3466   else
3467     switch (CallingConv) {
3468     default:
3469       assert(0 && "Unsupported calling convention");
3470     case CallingConv::Fast:
3471       // TODO: Implement fastcc
3472       // Falls through
3473     case CallingConv::C:
3474     case CallingConv::X86_StdCall:
3475       return LowerCCCCallTo(Op, DAG, CallingConv);
3476     case CallingConv::X86_FastCall:
3477       return LowerFastCCCallTo(Op, DAG, CallingConv);
3478     }
3479 }
3480
3481
3482 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
3483 // Calls to _alloca is needed to probe the stack when allocating more than 4k
3484 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
3485 // that the guard pages used by the OS virtual memory manager are allocated in
3486 // correct sequence.
3487 SDOperand X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDOperand Op,
3488                                                      SelectionDAG &DAG) {
3489   assert(Subtarget->isTargetCygMing() &&
3490          "This should be used only on Cygwin/Mingw targets");
3491   
3492   // Get the inputs.
3493   SDOperand Chain = Op.getOperand(0);
3494   SDOperand Size  = Op.getOperand(1);
3495   // FIXME: Ensure alignment here
3496
3497   TargetLowering::ArgListTy Args; 
3498   TargetLowering::ArgListEntry Entry;
3499   MVT::ValueType IntPtr = getPointerTy();
3500   MVT::ValueType SPTy = (Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
3501   const Type *IntPtrTy = getTargetData()->getIntPtrType();
3502   
3503   Entry.Node    = Size;
3504   Entry.Ty      = IntPtrTy;
3505   Entry.isInReg = true; // Should pass in EAX
3506   Args.push_back(Entry);
3507   std::pair<SDOperand, SDOperand> CallResult =
3508     LowerCallTo(Chain, IntPtrTy, false, false, CallingConv::C, false,
3509                 DAG.getExternalSymbol("_alloca", IntPtr), Args, DAG);
3510
3511   SDOperand SP = DAG.getCopyFromReg(CallResult.second, X86StackPtr, SPTy);
3512   
3513   std::vector<MVT::ValueType> Tys;
3514   Tys.push_back(SPTy);
3515   Tys.push_back(MVT::Other);
3516   SDOperand Ops[2] = { SP, CallResult.second };
3517   return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops, 2);
3518 }
3519
3520 SDOperand
3521 X86TargetLowering::LowerFORMAL_ARGUMENTS(SDOperand Op, SelectionDAG &DAG) {
3522   MachineFunction &MF = DAG.getMachineFunction();
3523   const Function* Fn = MF.getFunction();
3524   if (Fn->hasExternalLinkage() &&
3525       Subtarget->isTargetCygMing() &&
3526       Fn->getName() == "main")
3527     MF.getInfo<X86MachineFunctionInfo>()->setForceFramePointer(true);
3528
3529   unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3530   if (Subtarget->is64Bit())
3531     return LowerX86_64CCCArguments(Op, DAG);
3532   else
3533     switch(CC) {
3534     default:
3535       assert(0 && "Unsupported calling convention");
3536     case CallingConv::Fast:
3537       // TODO: implement fastcc.
3538       
3539       // Falls through
3540     case CallingConv::C:
3541       return LowerCCCArguments(Op, DAG);
3542     case CallingConv::X86_StdCall:
3543       MF.getInfo<X86MachineFunctionInfo>()->setDecorationStyle(StdCall);
3544       return LowerCCCArguments(Op, DAG, true);
3545     case CallingConv::X86_FastCall:
3546       MF.getInfo<X86MachineFunctionInfo>()->setDecorationStyle(FastCall);
3547       return LowerFastCCArguments(Op, DAG);
3548     }
3549 }
3550
3551 SDOperand X86TargetLowering::LowerMEMSET(SDOperand Op, SelectionDAG &DAG) {
3552   SDOperand InFlag(0, 0);
3553   SDOperand Chain = Op.getOperand(0);
3554   unsigned Align =
3555     (unsigned)cast<ConstantSDNode>(Op.getOperand(4))->getValue();
3556   if (Align == 0) Align = 1;
3557
3558   ConstantSDNode *I = dyn_cast<ConstantSDNode>(Op.getOperand(3));
3559   // If not DWORD aligned, call memset if size is less than the threshold.
3560   // It knows how to align to the right boundary first.
3561   if ((Align & 3) != 0 ||
3562       (I && I->getValue() < Subtarget->getMinRepStrSizeThreshold())) {
3563     MVT::ValueType IntPtr = getPointerTy();
3564     const Type *IntPtrTy = getTargetData()->getIntPtrType();
3565     TargetLowering::ArgListTy Args; 
3566     TargetLowering::ArgListEntry Entry;
3567     Entry.Node = Op.getOperand(1);
3568     Entry.Ty = IntPtrTy;
3569     Args.push_back(Entry);
3570     // Extend the unsigned i8 argument to be an int value for the call.
3571     Entry.Node = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Op.getOperand(2));
3572     Entry.Ty = IntPtrTy;
3573     Args.push_back(Entry);
3574     Entry.Node = Op.getOperand(3);
3575     Args.push_back(Entry);
3576     std::pair<SDOperand,SDOperand> CallResult =
3577       LowerCallTo(Chain, Type::VoidTy, false, false, CallingConv::C, false,
3578                   DAG.getExternalSymbol("memset", IntPtr), Args, DAG);
3579     return CallResult.second;
3580   }
3581
3582   MVT::ValueType AVT;
3583   SDOperand Count;
3584   ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Op.getOperand(2));
3585   unsigned BytesLeft = 0;
3586   bool TwoRepStos = false;
3587   if (ValC) {
3588     unsigned ValReg;
3589     uint64_t Val = ValC->getValue() & 255;
3590
3591     // If the value is a constant, then we can potentially use larger sets.
3592     switch (Align & 3) {
3593       case 2:   // WORD aligned
3594         AVT = MVT::i16;
3595         ValReg = X86::AX;
3596         Val = (Val << 8) | Val;
3597         break;
3598       case 0:  // DWORD aligned
3599         AVT = MVT::i32;
3600         ValReg = X86::EAX;
3601         Val = (Val << 8)  | Val;
3602         Val = (Val << 16) | Val;
3603         if (Subtarget->is64Bit() && ((Align & 0xF) == 0)) {  // QWORD aligned
3604           AVT = MVT::i64;
3605           ValReg = X86::RAX;
3606           Val = (Val << 32) | Val;
3607         }
3608         break;
3609       default:  // Byte aligned
3610         AVT = MVT::i8;
3611         ValReg = X86::AL;
3612         Count = Op.getOperand(3);
3613         break;
3614     }
3615
3616     if (AVT > MVT::i8) {
3617       if (I) {
3618         unsigned UBytes = MVT::getSizeInBits(AVT) / 8;
3619         Count = DAG.getConstant(I->getValue() / UBytes, getPointerTy());
3620         BytesLeft = I->getValue() % UBytes;
3621       } else {
3622         assert(AVT >= MVT::i32 &&
3623                "Do not use rep;stos if not at least DWORD aligned");
3624         Count = DAG.getNode(ISD::SRL, Op.getOperand(3).getValueType(),
3625                             Op.getOperand(3), DAG.getConstant(2, MVT::i8));
3626         TwoRepStos = true;
3627       }
3628     }
3629
3630     Chain  = DAG.getCopyToReg(Chain, ValReg, DAG.getConstant(Val, AVT),
3631                               InFlag);
3632     InFlag = Chain.getValue(1);
3633   } else {
3634     AVT = MVT::i8;
3635     Count  = Op.getOperand(3);
3636     Chain  = DAG.getCopyToReg(Chain, X86::AL, Op.getOperand(2), InFlag);
3637     InFlag = Chain.getValue(1);
3638   }
3639
3640   Chain  = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
3641                             Count, InFlag);
3642   InFlag = Chain.getValue(1);
3643   Chain  = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
3644                             Op.getOperand(1), InFlag);
3645   InFlag = Chain.getValue(1);
3646
3647   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
3648   SmallVector<SDOperand, 8> Ops;
3649   Ops.push_back(Chain);
3650   Ops.push_back(DAG.getValueType(AVT));
3651   Ops.push_back(InFlag);
3652   Chain  = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
3653
3654   if (TwoRepStos) {
3655     InFlag = Chain.getValue(1);
3656     Count = Op.getOperand(3);
3657     MVT::ValueType CVT = Count.getValueType();
3658     SDOperand Left = DAG.getNode(ISD::AND, CVT, Count,
3659                                DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
3660     Chain  = DAG.getCopyToReg(Chain, (CVT == MVT::i64) ? X86::RCX : X86::ECX,
3661                               Left, InFlag);
3662     InFlag = Chain.getValue(1);
3663     Tys = DAG.getVTList(MVT::Other, MVT::Flag);
3664     Ops.clear();
3665     Ops.push_back(Chain);
3666     Ops.push_back(DAG.getValueType(MVT::i8));
3667     Ops.push_back(InFlag);
3668     Chain  = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
3669   } else if (BytesLeft) {
3670     // Issue stores for the last 1 - 7 bytes.
3671     SDOperand Value;
3672     unsigned Val = ValC->getValue() & 255;
3673     unsigned Offset = I->getValue() - BytesLeft;
3674     SDOperand DstAddr = Op.getOperand(1);
3675     MVT::ValueType AddrVT = DstAddr.getValueType();
3676     if (BytesLeft >= 4) {
3677       Val = (Val << 8)  | Val;
3678       Val = (Val << 16) | Val;
3679       Value = DAG.getConstant(Val, MVT::i32);
3680       Chain = DAG.getStore(Chain, Value,
3681                            DAG.getNode(ISD::ADD, AddrVT, DstAddr,
3682                                        DAG.getConstant(Offset, AddrVT)),
3683                            NULL, 0);
3684       BytesLeft -= 4;
3685       Offset += 4;
3686     }
3687     if (BytesLeft >= 2) {
3688       Value = DAG.getConstant((Val << 8) | Val, MVT::i16);
3689       Chain = DAG.getStore(Chain, Value,
3690                            DAG.getNode(ISD::ADD, AddrVT, DstAddr,
3691                                        DAG.getConstant(Offset, AddrVT)),
3692                            NULL, 0);
3693       BytesLeft -= 2;
3694       Offset += 2;
3695     }
3696     if (BytesLeft == 1) {
3697       Value = DAG.getConstant(Val, MVT::i8);
3698       Chain = DAG.getStore(Chain, Value,
3699                            DAG.getNode(ISD::ADD, AddrVT, DstAddr,
3700                                        DAG.getConstant(Offset, AddrVT)),
3701                            NULL, 0);
3702     }
3703   }
3704
3705   return Chain;
3706 }
3707
3708 SDOperand X86TargetLowering::LowerMEMCPY(SDOperand Op, SelectionDAG &DAG) {
3709   SDOperand Chain = Op.getOperand(0);
3710   unsigned Align =
3711     (unsigned)cast<ConstantSDNode>(Op.getOperand(4))->getValue();
3712   if (Align == 0) Align = 1;
3713
3714   ConstantSDNode *I = dyn_cast<ConstantSDNode>(Op.getOperand(3));
3715   // If not DWORD aligned, call memcpy if size is less than the threshold.
3716   // It knows how to align to the right boundary first.
3717   if ((Align & 3) != 0 ||
3718       (I && I->getValue() < Subtarget->getMinRepStrSizeThreshold())) {
3719     MVT::ValueType IntPtr = getPointerTy();
3720     TargetLowering::ArgListTy Args;
3721     TargetLowering::ArgListEntry Entry;
3722     Entry.Ty = getTargetData()->getIntPtrType();
3723     Entry.Node = Op.getOperand(1); Args.push_back(Entry);
3724     Entry.Node = Op.getOperand(2); Args.push_back(Entry);
3725     Entry.Node = Op.getOperand(3); Args.push_back(Entry);
3726     std::pair<SDOperand,SDOperand> CallResult =
3727       LowerCallTo(Chain, Type::VoidTy, false, false, CallingConv::C, false,
3728                   DAG.getExternalSymbol("memcpy", IntPtr), Args, DAG);
3729     return CallResult.second;
3730   }
3731
3732   MVT::ValueType AVT;
3733   SDOperand Count;
3734   unsigned BytesLeft = 0;
3735   bool TwoRepMovs = false;
3736   switch (Align & 3) {
3737     case 2:   // WORD aligned
3738       AVT = MVT::i16;
3739       break;
3740     case 0:  // DWORD aligned
3741       AVT = MVT::i32;
3742       if (Subtarget->is64Bit() && ((Align & 0xF) == 0))  // QWORD aligned
3743         AVT = MVT::i64;
3744       break;
3745     default:  // Byte aligned
3746       AVT = MVT::i8;
3747       Count = Op.getOperand(3);
3748       break;
3749   }
3750
3751   if (AVT > MVT::i8) {
3752     if (I) {
3753       unsigned UBytes = MVT::getSizeInBits(AVT) / 8;
3754       Count = DAG.getConstant(I->getValue() / UBytes, getPointerTy());
3755       BytesLeft = I->getValue() % UBytes;
3756     } else {
3757       assert(AVT >= MVT::i32 &&
3758              "Do not use rep;movs if not at least DWORD aligned");
3759       Count = DAG.getNode(ISD::SRL, Op.getOperand(3).getValueType(),
3760                           Op.getOperand(3), DAG.getConstant(2, MVT::i8));
3761       TwoRepMovs = true;
3762     }
3763   }
3764
3765   SDOperand InFlag(0, 0);
3766   Chain  = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
3767                             Count, InFlag);
3768   InFlag = Chain.getValue(1);
3769   Chain  = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
3770                             Op.getOperand(1), InFlag);
3771   InFlag = Chain.getValue(1);
3772   Chain  = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RSI : X86::ESI,
3773                             Op.getOperand(2), InFlag);
3774   InFlag = Chain.getValue(1);
3775
3776   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
3777   SmallVector<SDOperand, 8> Ops;
3778   Ops.push_back(Chain);
3779   Ops.push_back(DAG.getValueType(AVT));
3780   Ops.push_back(InFlag);
3781   Chain = DAG.getNode(X86ISD::REP_MOVS, Tys, &Ops[0], Ops.size());
3782
3783   if (TwoRepMovs) {
3784     InFlag = Chain.getValue(1);
3785     Count = Op.getOperand(3);
3786     MVT::ValueType CVT = Count.getValueType();
3787     SDOperand Left = DAG.getNode(ISD::AND, CVT, Count,
3788                                DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
3789     Chain  = DAG.getCopyToReg(Chain, (CVT == MVT::i64) ? X86::RCX : X86::ECX,
3790                               Left, InFlag);
3791     InFlag = Chain.getValue(1);
3792     Tys = DAG.getVTList(MVT::Other, MVT::Flag);
3793     Ops.clear();
3794     Ops.push_back(Chain);
3795     Ops.push_back(DAG.getValueType(MVT::i8));
3796     Ops.push_back(InFlag);
3797     Chain = DAG.getNode(X86ISD::REP_MOVS, Tys, &Ops[0], Ops.size());
3798   } else if (BytesLeft) {
3799     // Issue loads and stores for the last 1 - 7 bytes.
3800     unsigned Offset = I->getValue() - BytesLeft;
3801     SDOperand DstAddr = Op.getOperand(1);
3802     MVT::ValueType DstVT = DstAddr.getValueType();
3803     SDOperand SrcAddr = Op.getOperand(2);
3804     MVT::ValueType SrcVT = SrcAddr.getValueType();
3805     SDOperand Value;
3806     if (BytesLeft >= 4) {
3807       Value = DAG.getLoad(MVT::i32, Chain,
3808                           DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
3809                                       DAG.getConstant(Offset, SrcVT)),
3810                           NULL, 0);
3811       Chain = Value.getValue(1);
3812       Chain = DAG.getStore(Chain, Value,
3813                            DAG.getNode(ISD::ADD, DstVT, DstAddr,
3814                                        DAG.getConstant(Offset, DstVT)),
3815                            NULL, 0);
3816       BytesLeft -= 4;
3817       Offset += 4;
3818     }
3819     if (BytesLeft >= 2) {
3820       Value = DAG.getLoad(MVT::i16, Chain,
3821                           DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
3822                                       DAG.getConstant(Offset, SrcVT)),
3823                           NULL, 0);
3824       Chain = Value.getValue(1);
3825       Chain = DAG.getStore(Chain, Value,
3826                            DAG.getNode(ISD::ADD, DstVT, DstAddr,
3827                                        DAG.getConstant(Offset, DstVT)),
3828                            NULL, 0);
3829       BytesLeft -= 2;
3830       Offset += 2;
3831     }
3832
3833     if (BytesLeft == 1) {
3834       Value = DAG.getLoad(MVT::i8, Chain,
3835                           DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
3836                                       DAG.getConstant(Offset, SrcVT)),
3837                           NULL, 0);
3838       Chain = Value.getValue(1);
3839       Chain = DAG.getStore(Chain, Value,
3840                            DAG.getNode(ISD::ADD, DstVT, DstAddr,
3841                                        DAG.getConstant(Offset, DstVT)),
3842                            NULL, 0);
3843     }
3844   }
3845
3846   return Chain;
3847 }
3848
3849 SDOperand
3850 X86TargetLowering::LowerREADCYCLCECOUNTER(SDOperand Op, SelectionDAG &DAG) {
3851   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
3852   SDOperand TheOp = Op.getOperand(0);
3853   SDOperand rd = DAG.getNode(X86ISD::RDTSC_DAG, Tys, &TheOp, 1);
3854   if (Subtarget->is64Bit()) {
3855     SDOperand Copy1 = DAG.getCopyFromReg(rd, X86::RAX, MVT::i64, rd.getValue(1));
3856     SDOperand Copy2 = DAG.getCopyFromReg(Copy1.getValue(1), X86::RDX,
3857                                          MVT::i64, Copy1.getValue(2));
3858     SDOperand Tmp = DAG.getNode(ISD::SHL, MVT::i64, Copy2,
3859                                 DAG.getConstant(32, MVT::i8));
3860     SDOperand Ops[] = {
3861       DAG.getNode(ISD::OR, MVT::i64, Copy1, Tmp), Copy2.getValue(1)
3862     };
3863     
3864     Tys = DAG.getVTList(MVT::i64, MVT::Other);
3865     return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops, 2);
3866   }
3867   
3868   SDOperand Copy1 = DAG.getCopyFromReg(rd, X86::EAX, MVT::i32, rd.getValue(1));
3869   SDOperand Copy2 = DAG.getCopyFromReg(Copy1.getValue(1), X86::EDX,
3870                                        MVT::i32, Copy1.getValue(2));
3871   SDOperand Ops[] = { Copy1, Copy2, Copy2.getValue(1) };
3872   Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
3873   return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops, 3);
3874 }
3875
3876 SDOperand X86TargetLowering::LowerVASTART(SDOperand Op, SelectionDAG &DAG) {
3877   SrcValueSDNode *SV = cast<SrcValueSDNode>(Op.getOperand(2));
3878
3879   if (!Subtarget->is64Bit()) {
3880     // vastart just stores the address of the VarArgsFrameIndex slot into the
3881     // memory location argument.
3882     SDOperand FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
3883     return DAG.getStore(Op.getOperand(0), FR,Op.getOperand(1), SV->getValue(),
3884                         SV->getOffset());
3885   }
3886
3887   // __va_list_tag:
3888   //   gp_offset         (0 - 6 * 8)
3889   //   fp_offset         (48 - 48 + 8 * 16)
3890   //   overflow_arg_area (point to parameters coming in memory).
3891   //   reg_save_area
3892   SmallVector<SDOperand, 8> MemOps;
3893   SDOperand FIN = Op.getOperand(1);
3894   // Store gp_offset
3895   SDOperand Store = DAG.getStore(Op.getOperand(0),
3896                                  DAG.getConstant(VarArgsGPOffset, MVT::i32),
3897                                  FIN, SV->getValue(), SV->getOffset());
3898   MemOps.push_back(Store);
3899
3900   // Store fp_offset
3901   FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
3902                     DAG.getConstant(4, getPointerTy()));
3903   Store = DAG.getStore(Op.getOperand(0),
3904                        DAG.getConstant(VarArgsFPOffset, MVT::i32),
3905                        FIN, SV->getValue(), SV->getOffset());
3906   MemOps.push_back(Store);
3907
3908   // Store ptr to overflow_arg_area
3909   FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
3910                     DAG.getConstant(4, getPointerTy()));
3911   SDOperand OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
3912   Store = DAG.getStore(Op.getOperand(0), OVFIN, FIN, SV->getValue(),
3913                        SV->getOffset());
3914   MemOps.push_back(Store);
3915
3916   // Store ptr to reg_save_area.
3917   FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
3918                     DAG.getConstant(8, getPointerTy()));
3919   SDOperand RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
3920   Store = DAG.getStore(Op.getOperand(0), RSFIN, FIN, SV->getValue(),
3921                        SV->getOffset());
3922   MemOps.push_back(Store);
3923   return DAG.getNode(ISD::TokenFactor, MVT::Other, &MemOps[0], MemOps.size());
3924 }
3925
3926 SDOperand X86TargetLowering::LowerVACOPY(SDOperand Op, SelectionDAG &DAG) {
3927   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
3928   SDOperand Chain = Op.getOperand(0);
3929   SDOperand DstPtr = Op.getOperand(1);
3930   SDOperand SrcPtr = Op.getOperand(2);
3931   SrcValueSDNode *DstSV = cast<SrcValueSDNode>(Op.getOperand(3));
3932   SrcValueSDNode *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4));
3933
3934   SrcPtr = DAG.getLoad(getPointerTy(), Chain, SrcPtr,
3935                        SrcSV->getValue(), SrcSV->getOffset());
3936   Chain = SrcPtr.getValue(1);
3937   for (unsigned i = 0; i < 3; ++i) {
3938     SDOperand Val = DAG.getLoad(MVT::i64, Chain, SrcPtr,
3939                                 SrcSV->getValue(), SrcSV->getOffset());
3940     Chain = Val.getValue(1);
3941     Chain = DAG.getStore(Chain, Val, DstPtr,
3942                          DstSV->getValue(), DstSV->getOffset());
3943     if (i == 2)
3944       break;
3945     SrcPtr = DAG.getNode(ISD::ADD, getPointerTy(), SrcPtr, 
3946                          DAG.getConstant(8, getPointerTy()));
3947     DstPtr = DAG.getNode(ISD::ADD, getPointerTy(), DstPtr, 
3948                          DAG.getConstant(8, getPointerTy()));
3949   }
3950   return Chain;
3951 }
3952
3953 SDOperand
3954 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDOperand Op, SelectionDAG &DAG) {
3955   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getValue();
3956   switch (IntNo) {
3957   default: return SDOperand();    // Don't custom lower most intrinsics.
3958     // Comparison intrinsics.
3959   case Intrinsic::x86_sse_comieq_ss:
3960   case Intrinsic::x86_sse_comilt_ss:
3961   case Intrinsic::x86_sse_comile_ss:
3962   case Intrinsic::x86_sse_comigt_ss:
3963   case Intrinsic::x86_sse_comige_ss:
3964   case Intrinsic::x86_sse_comineq_ss:
3965   case Intrinsic::x86_sse_ucomieq_ss:
3966   case Intrinsic::x86_sse_ucomilt_ss:
3967   case Intrinsic::x86_sse_ucomile_ss:
3968   case Intrinsic::x86_sse_ucomigt_ss:
3969   case Intrinsic::x86_sse_ucomige_ss:
3970   case Intrinsic::x86_sse_ucomineq_ss:
3971   case Intrinsic::x86_sse2_comieq_sd:
3972   case Intrinsic::x86_sse2_comilt_sd:
3973   case Intrinsic::x86_sse2_comile_sd:
3974   case Intrinsic::x86_sse2_comigt_sd:
3975   case Intrinsic::x86_sse2_comige_sd:
3976   case Intrinsic::x86_sse2_comineq_sd:
3977   case Intrinsic::x86_sse2_ucomieq_sd:
3978   case Intrinsic::x86_sse2_ucomilt_sd:
3979   case Intrinsic::x86_sse2_ucomile_sd:
3980   case Intrinsic::x86_sse2_ucomigt_sd:
3981   case Intrinsic::x86_sse2_ucomige_sd:
3982   case Intrinsic::x86_sse2_ucomineq_sd: {
3983     unsigned Opc = 0;
3984     ISD::CondCode CC = ISD::SETCC_INVALID;
3985     switch (IntNo) {
3986     default: break;
3987     case Intrinsic::x86_sse_comieq_ss:
3988     case Intrinsic::x86_sse2_comieq_sd:
3989       Opc = X86ISD::COMI;
3990       CC = ISD::SETEQ;
3991       break;
3992     case Intrinsic::x86_sse_comilt_ss:
3993     case Intrinsic::x86_sse2_comilt_sd:
3994       Opc = X86ISD::COMI;
3995       CC = ISD::SETLT;
3996       break;
3997     case Intrinsic::x86_sse_comile_ss:
3998     case Intrinsic::x86_sse2_comile_sd:
3999       Opc = X86ISD::COMI;
4000       CC = ISD::SETLE;
4001       break;
4002     case Intrinsic::x86_sse_comigt_ss:
4003     case Intrinsic::x86_sse2_comigt_sd:
4004       Opc = X86ISD::COMI;
4005       CC = ISD::SETGT;
4006       break;
4007     case Intrinsic::x86_sse_comige_ss:
4008     case Intrinsic::x86_sse2_comige_sd:
4009       Opc = X86ISD::COMI;
4010       CC = ISD::SETGE;
4011       break;
4012     case Intrinsic::x86_sse_comineq_ss:
4013     case Intrinsic::x86_sse2_comineq_sd:
4014       Opc = X86ISD::COMI;
4015       CC = ISD::SETNE;
4016       break;
4017     case Intrinsic::x86_sse_ucomieq_ss:
4018     case Intrinsic::x86_sse2_ucomieq_sd:
4019       Opc = X86ISD::UCOMI;
4020       CC = ISD::SETEQ;
4021       break;
4022     case Intrinsic::x86_sse_ucomilt_ss:
4023     case Intrinsic::x86_sse2_ucomilt_sd:
4024       Opc = X86ISD::UCOMI;
4025       CC = ISD::SETLT;
4026       break;
4027     case Intrinsic::x86_sse_ucomile_ss:
4028     case Intrinsic::x86_sse2_ucomile_sd:
4029       Opc = X86ISD::UCOMI;
4030       CC = ISD::SETLE;
4031       break;
4032     case Intrinsic::x86_sse_ucomigt_ss:
4033     case Intrinsic::x86_sse2_ucomigt_sd:
4034       Opc = X86ISD::UCOMI;
4035       CC = ISD::SETGT;
4036       break;
4037     case Intrinsic::x86_sse_ucomige_ss:
4038     case Intrinsic::x86_sse2_ucomige_sd:
4039       Opc = X86ISD::UCOMI;
4040       CC = ISD::SETGE;
4041       break;
4042     case Intrinsic::x86_sse_ucomineq_ss:
4043     case Intrinsic::x86_sse2_ucomineq_sd:
4044       Opc = X86ISD::UCOMI;
4045       CC = ISD::SETNE;
4046       break;
4047     }
4048
4049     unsigned X86CC;
4050     SDOperand LHS = Op.getOperand(1);
4051     SDOperand RHS = Op.getOperand(2);
4052     translateX86CC(CC, true, X86CC, LHS, RHS, DAG);
4053
4054     const MVT::ValueType *VTs = DAG.getNodeValueTypes(MVT::Other, MVT::Flag);
4055     SDOperand Ops1[] = { DAG.getEntryNode(), LHS, RHS };
4056     SDOperand Cond = DAG.getNode(Opc, VTs, 2, Ops1, 3);
4057     VTs = DAG.getNodeValueTypes(MVT::i8, MVT::Flag);
4058     SDOperand Ops2[] = { DAG.getConstant(X86CC, MVT::i8), Cond };
4059     SDOperand SetCC = DAG.getNode(X86ISD::SETCC, VTs, 2, Ops2, 2);
4060     return DAG.getNode(ISD::ANY_EXTEND, MVT::i32, SetCC);
4061   }
4062   }
4063 }
4064
4065 SDOperand X86TargetLowering::LowerRETURNADDR(SDOperand Op, SelectionDAG &DAG) {
4066   // Depths > 0 not supported yet!
4067   if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
4068     return SDOperand();
4069   
4070   // Just load the return address
4071   SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
4072   return DAG.getLoad(getPointerTy(), DAG.getEntryNode(), RetAddrFI, NULL, 0);
4073 }
4074
4075 SDOperand X86TargetLowering::LowerFRAMEADDR(SDOperand Op, SelectionDAG &DAG) {
4076   // Depths > 0 not supported yet!
4077   if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
4078     return SDOperand();
4079     
4080   SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
4081   return DAG.getNode(ISD::SUB, getPointerTy(), RetAddrFI, 
4082                      DAG.getConstant(4, getPointerTy()));
4083 }
4084
4085 /// LowerOperation - Provide custom lowering hooks for some operations.
4086 ///
4087 SDOperand X86TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
4088   switch (Op.getOpcode()) {
4089   default: assert(0 && "Should not custom lower this!");
4090   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
4091   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
4092   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
4093   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
4094   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
4095   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
4096   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
4097   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
4098   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
4099   case ISD::SHL_PARTS:
4100   case ISD::SRA_PARTS:
4101   case ISD::SRL_PARTS:          return LowerShift(Op, DAG);
4102   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
4103   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
4104   case ISD::FABS:               return LowerFABS(Op, DAG);
4105   case ISD::FNEG:               return LowerFNEG(Op, DAG);
4106   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
4107   case ISD::SETCC:              return LowerSETCC(Op, DAG, DAG.getEntryNode());
4108   case ISD::SELECT:             return LowerSELECT(Op, DAG);
4109   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
4110   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
4111   case ISD::CALL:               return LowerCALL(Op, DAG);
4112   case ISD::RET:                return LowerRET(Op, DAG);
4113   case ISD::FORMAL_ARGUMENTS:   return LowerFORMAL_ARGUMENTS(Op, DAG);
4114   case ISD::MEMSET:             return LowerMEMSET(Op, DAG);
4115   case ISD::MEMCPY:             return LowerMEMCPY(Op, DAG);
4116   case ISD::READCYCLECOUNTER:   return LowerREADCYCLCECOUNTER(Op, DAG);
4117   case ISD::VASTART:            return LowerVASTART(Op, DAG);
4118   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
4119   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
4120   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
4121   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
4122   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
4123   }
4124   return SDOperand();
4125 }
4126
4127 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
4128   switch (Opcode) {
4129   default: return NULL;
4130   case X86ISD::SHLD:               return "X86ISD::SHLD";
4131   case X86ISD::SHRD:               return "X86ISD::SHRD";
4132   case X86ISD::FAND:               return "X86ISD::FAND";
4133   case X86ISD::FOR:                return "X86ISD::FOR";
4134   case X86ISD::FXOR:               return "X86ISD::FXOR";
4135   case X86ISD::FSRL:               return "X86ISD::FSRL";
4136   case X86ISD::FILD:               return "X86ISD::FILD";
4137   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
4138   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
4139   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
4140   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
4141   case X86ISD::FLD:                return "X86ISD::FLD";
4142   case X86ISD::FST:                return "X86ISD::FST";
4143   case X86ISD::FP_GET_RESULT:      return "X86ISD::FP_GET_RESULT";
4144   case X86ISD::FP_SET_RESULT:      return "X86ISD::FP_SET_RESULT";
4145   case X86ISD::CALL:               return "X86ISD::CALL";
4146   case X86ISD::TAILCALL:           return "X86ISD::TAILCALL";
4147   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
4148   case X86ISD::CMP:                return "X86ISD::CMP";
4149   case X86ISD::COMI:               return "X86ISD::COMI";
4150   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
4151   case X86ISD::SETCC:              return "X86ISD::SETCC";
4152   case X86ISD::CMOV:               return "X86ISD::CMOV";
4153   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
4154   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
4155   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
4156   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
4157   case X86ISD::LOAD_PACK:          return "X86ISD::LOAD_PACK";
4158   case X86ISD::LOAD_UA:            return "X86ISD::LOAD_UA";
4159   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
4160   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
4161   case X86ISD::S2VEC:              return "X86ISD::S2VEC";
4162   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
4163   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
4164   case X86ISD::FMAX:               return "X86ISD::FMAX";
4165   case X86ISD::FMIN:               return "X86ISD::FMIN";
4166   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
4167   case X86ISD::THREAD_POINTER:     return "X86ISD::THREAD_POINTER";
4168   }
4169 }
4170
4171 // isLegalAddressingMode - Return true if the addressing mode represented
4172 // by AM is legal for this target, for a load/store of the specified type.
4173 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM, 
4174                                               const Type *Ty) const {
4175   // X86 supports extremely general addressing modes.
4176   
4177   // X86 allows a sign-extended 32-bit immediate field as a displacement.
4178   if (AM.BaseOffs <= -(1LL << 32) || AM.BaseOffs >= (1LL << 32)-1)
4179     return false;
4180   
4181   if (AM.BaseGV) {
4182     // X86-64 only supports addr of globals in small code model.
4183     if (Subtarget->is64Bit() &&
4184         getTargetMachine().getCodeModel() != CodeModel::Small)
4185       return false;
4186     
4187     // We can only fold this if we don't need a load either.
4188     if (Subtarget->GVRequiresExtraLoad(AM.BaseGV, getTargetMachine(), false))
4189       return false;
4190   }
4191   
4192   switch (AM.Scale) {
4193   case 0:
4194   case 1:
4195   case 2:
4196   case 4:
4197   case 8:
4198     // These scales always work.
4199     break;
4200   case 3:
4201   case 5:
4202   case 9:
4203     // These scales are formed with basereg+scalereg.  Only accept if there is
4204     // no basereg yet.
4205     if (AM.HasBaseReg)
4206       return false;
4207     break;
4208   default:  // Other stuff never works.
4209     return false;
4210   }
4211   
4212   return true;
4213 }
4214
4215
4216 /// isShuffleMaskLegal - Targets can use this to indicate that they only
4217 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
4218 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
4219 /// are assumed to be legal.
4220 bool
4221 X86TargetLowering::isShuffleMaskLegal(SDOperand Mask, MVT::ValueType VT) const {
4222   // Only do shuffles on 128-bit vector types for now.
4223   if (MVT::getSizeInBits(VT) == 64) return false;
4224   return (Mask.Val->getNumOperands() <= 4 ||
4225           isSplatMask(Mask.Val)  ||
4226           isPSHUFHW_PSHUFLWMask(Mask.Val) ||
4227           X86::isUNPCKLMask(Mask.Val) ||
4228           X86::isUNPCKL_v_undef_Mask(Mask.Val) ||
4229           X86::isUNPCKHMask(Mask.Val));
4230 }
4231
4232 bool X86TargetLowering::isVectorClearMaskLegal(std::vector<SDOperand> &BVOps,
4233                                                MVT::ValueType EVT,
4234                                                SelectionDAG &DAG) const {
4235   unsigned NumElts = BVOps.size();
4236   // Only do shuffles on 128-bit vector types for now.
4237   if (MVT::getSizeInBits(EVT) * NumElts == 64) return false;
4238   if (NumElts == 2) return true;
4239   if (NumElts == 4) {
4240     return (isMOVLMask(&BVOps[0], 4)  ||
4241             isCommutedMOVL(&BVOps[0], 4, true) ||
4242             isSHUFPMask(&BVOps[0], 4) || 
4243             isCommutedSHUFP(&BVOps[0], 4));
4244   }
4245   return false;
4246 }
4247
4248 //===----------------------------------------------------------------------===//
4249 //                           X86 Scheduler Hooks
4250 //===----------------------------------------------------------------------===//
4251
4252 MachineBasicBlock *
4253 X86TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
4254                                            MachineBasicBlock *BB) {
4255   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
4256   switch (MI->getOpcode()) {
4257   default: assert(false && "Unexpected instr type to insert");
4258   case X86::CMOV_FR32:
4259   case X86::CMOV_FR64:
4260   case X86::CMOV_V4F32:
4261   case X86::CMOV_V2F64:
4262   case X86::CMOV_V2I64: {
4263     // To "insert" a SELECT_CC instruction, we actually have to insert the
4264     // diamond control-flow pattern.  The incoming instruction knows the
4265     // destination vreg to set, the condition code register to branch on, the
4266     // true/false values to select between, and a branch opcode to use.
4267     const BasicBlock *LLVM_BB = BB->getBasicBlock();
4268     ilist<MachineBasicBlock>::iterator It = BB;
4269     ++It;
4270
4271     //  thisMBB:
4272     //  ...
4273     //   TrueVal = ...
4274     //   cmpTY ccX, r1, r2
4275     //   bCC copy1MBB
4276     //   fallthrough --> copy0MBB
4277     MachineBasicBlock *thisMBB = BB;
4278     MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
4279     MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
4280     unsigned Opc =
4281       X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
4282     BuildMI(BB, TII->get(Opc)).addMBB(sinkMBB);
4283     MachineFunction *F = BB->getParent();
4284     F->getBasicBlockList().insert(It, copy0MBB);
4285     F->getBasicBlockList().insert(It, sinkMBB);
4286     // Update machine-CFG edges by first adding all successors of the current
4287     // block to the new block which will contain the Phi node for the select.
4288     for(MachineBasicBlock::succ_iterator i = BB->succ_begin(),
4289         e = BB->succ_end(); i != e; ++i)
4290       sinkMBB->addSuccessor(*i);
4291     // Next, remove all successors of the current block, and add the true
4292     // and fallthrough blocks as its successors.
4293     while(!BB->succ_empty())
4294       BB->removeSuccessor(BB->succ_begin());
4295     BB->addSuccessor(copy0MBB);
4296     BB->addSuccessor(sinkMBB);
4297
4298     //  copy0MBB:
4299     //   %FalseValue = ...
4300     //   # fallthrough to sinkMBB
4301     BB = copy0MBB;
4302
4303     // Update machine-CFG edges
4304     BB->addSuccessor(sinkMBB);
4305
4306     //  sinkMBB:
4307     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
4308     //  ...
4309     BB = sinkMBB;
4310     BuildMI(BB, TII->get(X86::PHI), MI->getOperand(0).getReg())
4311       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
4312       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
4313
4314     delete MI;   // The pseudo instruction is gone now.
4315     return BB;
4316   }
4317
4318   case X86::FP_TO_INT16_IN_MEM:
4319   case X86::FP_TO_INT32_IN_MEM:
4320   case X86::FP_TO_INT64_IN_MEM: {
4321     // Change the floating point control register to use "round towards zero"
4322     // mode when truncating to an integer value.
4323     MachineFunction *F = BB->getParent();
4324     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
4325     addFrameReference(BuildMI(BB, TII->get(X86::FNSTCW16m)), CWFrameIdx);
4326
4327     // Load the old value of the high byte of the control word...
4328     unsigned OldCW =
4329       F->getSSARegMap()->createVirtualRegister(X86::GR16RegisterClass);
4330     addFrameReference(BuildMI(BB, TII->get(X86::MOV16rm), OldCW), CWFrameIdx);
4331
4332     // Set the high part to be round to zero...
4333     addFrameReference(BuildMI(BB, TII->get(X86::MOV16mi)), CWFrameIdx)
4334       .addImm(0xC7F);
4335
4336     // Reload the modified control word now...
4337     addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
4338
4339     // Restore the memory image of control word to original value
4340     addFrameReference(BuildMI(BB, TII->get(X86::MOV16mr)), CWFrameIdx)
4341       .addReg(OldCW);
4342
4343     // Get the X86 opcode to use.
4344     unsigned Opc;
4345     switch (MI->getOpcode()) {
4346     default: assert(0 && "illegal opcode!");
4347     case X86::FP_TO_INT16_IN_MEM: Opc = X86::FpIST16m; break;
4348     case X86::FP_TO_INT32_IN_MEM: Opc = X86::FpIST32m; break;
4349     case X86::FP_TO_INT64_IN_MEM: Opc = X86::FpIST64m; break;
4350     }
4351
4352     X86AddressMode AM;
4353     MachineOperand &Op = MI->getOperand(0);
4354     if (Op.isRegister()) {
4355       AM.BaseType = X86AddressMode::RegBase;
4356       AM.Base.Reg = Op.getReg();
4357     } else {
4358       AM.BaseType = X86AddressMode::FrameIndexBase;
4359       AM.Base.FrameIndex = Op.getFrameIndex();
4360     }
4361     Op = MI->getOperand(1);
4362     if (Op.isImmediate())
4363       AM.Scale = Op.getImm();
4364     Op = MI->getOperand(2);
4365     if (Op.isImmediate())
4366       AM.IndexReg = Op.getImm();
4367     Op = MI->getOperand(3);
4368     if (Op.isGlobalAddress()) {
4369       AM.GV = Op.getGlobal();
4370     } else {
4371       AM.Disp = Op.getImm();
4372     }
4373     addFullAddress(BuildMI(BB, TII->get(Opc)), AM)
4374                       .addReg(MI->getOperand(4).getReg());
4375
4376     // Reload the original control word now.
4377     addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
4378
4379     delete MI;   // The pseudo instruction is gone now.
4380     return BB;
4381   }
4382   }
4383 }
4384
4385 //===----------------------------------------------------------------------===//
4386 //                           X86 Optimization Hooks
4387 //===----------------------------------------------------------------------===//
4388
4389 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDOperand Op,
4390                                                        uint64_t Mask,
4391                                                        uint64_t &KnownZero,
4392                                                        uint64_t &KnownOne,
4393                                                        unsigned Depth) const {
4394   unsigned Opc = Op.getOpcode();
4395   assert((Opc >= ISD::BUILTIN_OP_END ||
4396           Opc == ISD::INTRINSIC_WO_CHAIN ||
4397           Opc == ISD::INTRINSIC_W_CHAIN ||
4398           Opc == ISD::INTRINSIC_VOID) &&
4399          "Should use MaskedValueIsZero if you don't know whether Op"
4400          " is a target node!");
4401
4402   KnownZero = KnownOne = 0;   // Don't know anything.
4403   switch (Opc) {
4404   default: break;
4405   case X86ISD::SETCC:
4406     KnownZero |= (MVT::getIntVTBitMask(Op.getValueType()) ^ 1ULL);
4407     break;
4408   }
4409 }
4410
4411 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4412 /// element of the result of the vector shuffle.
4413 static SDOperand getShuffleScalarElt(SDNode *N, unsigned i, SelectionDAG &DAG) {
4414   MVT::ValueType VT = N->getValueType(0);
4415   SDOperand PermMask = N->getOperand(2);
4416   unsigned NumElems = PermMask.getNumOperands();
4417   SDOperand V = (i < NumElems) ? N->getOperand(0) : N->getOperand(1);
4418   i %= NumElems;
4419   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4420     return (i == 0)
4421       ? V.getOperand(0) : DAG.getNode(ISD::UNDEF, MVT::getVectorBaseType(VT));
4422   } else if (V.getOpcode() == ISD::VECTOR_SHUFFLE) {
4423     SDOperand Idx = PermMask.getOperand(i);
4424     if (Idx.getOpcode() == ISD::UNDEF)
4425       return DAG.getNode(ISD::UNDEF, MVT::getVectorBaseType(VT));
4426     return getShuffleScalarElt(V.Val,cast<ConstantSDNode>(Idx)->getValue(),DAG);
4427   }
4428   return SDOperand();
4429 }
4430
4431 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
4432 /// node is a GlobalAddress + an offset.
4433 static bool isGAPlusOffset(SDNode *N, GlobalValue* &GA, int64_t &Offset) {
4434   unsigned Opc = N->getOpcode();
4435   if (Opc == X86ISD::Wrapper) {
4436     if (dyn_cast<GlobalAddressSDNode>(N->getOperand(0))) {
4437       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
4438       return true;
4439     }
4440   } else if (Opc == ISD::ADD) {
4441     SDOperand N1 = N->getOperand(0);
4442     SDOperand N2 = N->getOperand(1);
4443     if (isGAPlusOffset(N1.Val, GA, Offset)) {
4444       ConstantSDNode *V = dyn_cast<ConstantSDNode>(N2);
4445       if (V) {
4446         Offset += V->getSignExtended();
4447         return true;
4448       }
4449     } else if (isGAPlusOffset(N2.Val, GA, Offset)) {
4450       ConstantSDNode *V = dyn_cast<ConstantSDNode>(N1);
4451       if (V) {
4452         Offset += V->getSignExtended();
4453         return true;
4454       }
4455     }
4456   }
4457   return false;
4458 }
4459
4460 /// isConsecutiveLoad - Returns true if N is loading from an address of Base
4461 /// + Dist * Size.
4462 static bool isConsecutiveLoad(SDNode *N, SDNode *Base, int Dist, int Size,
4463                               MachineFrameInfo *MFI) {
4464   if (N->getOperand(0).Val != Base->getOperand(0).Val)
4465     return false;
4466
4467   SDOperand Loc = N->getOperand(1);
4468   SDOperand BaseLoc = Base->getOperand(1);
4469   if (Loc.getOpcode() == ISD::FrameIndex) {
4470     if (BaseLoc.getOpcode() != ISD::FrameIndex)
4471       return false;
4472     int FI  = dyn_cast<FrameIndexSDNode>(Loc)->getIndex();
4473     int BFI = dyn_cast<FrameIndexSDNode>(BaseLoc)->getIndex();
4474     int FS  = MFI->getObjectSize(FI);
4475     int BFS = MFI->getObjectSize(BFI);
4476     if (FS != BFS || FS != Size) return false;
4477     return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Size);
4478   } else {
4479     GlobalValue *GV1 = NULL;
4480     GlobalValue *GV2 = NULL;
4481     int64_t Offset1 = 0;
4482     int64_t Offset2 = 0;
4483     bool isGA1 = isGAPlusOffset(Loc.Val, GV1, Offset1);
4484     bool isGA2 = isGAPlusOffset(BaseLoc.Val, GV2, Offset2);
4485     if (isGA1 && isGA2 && GV1 == GV2)
4486       return Offset1 == (Offset2 + Dist*Size);
4487   }
4488
4489   return false;
4490 }
4491
4492 static bool isBaseAlignment16(SDNode *Base, MachineFrameInfo *MFI,
4493                               const X86Subtarget *Subtarget) {
4494   GlobalValue *GV;
4495   int64_t Offset;
4496   if (isGAPlusOffset(Base, GV, Offset))
4497     return (GV->getAlignment() >= 16 && (Offset % 16) == 0);
4498   else {
4499     assert(Base->getOpcode() == ISD::FrameIndex && "Unexpected base node!");
4500     int BFI = dyn_cast<FrameIndexSDNode>(Base)->getIndex();
4501     if (BFI < 0)
4502       // Fixed objects do not specify alignment, however the offsets are known.
4503       return ((Subtarget->getStackAlignment() % 16) == 0 &&
4504               (MFI->getObjectOffset(BFI) % 16) == 0);
4505     else
4506       return MFI->getObjectAlignment(BFI) >= 16;
4507   }
4508   return false;
4509 }
4510
4511
4512 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
4513 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
4514 /// if the load addresses are consecutive, non-overlapping, and in the right
4515 /// order.
4516 static SDOperand PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
4517                                        const X86Subtarget *Subtarget) {
4518   MachineFunction &MF = DAG.getMachineFunction();
4519   MachineFrameInfo *MFI = MF.getFrameInfo();
4520   MVT::ValueType VT = N->getValueType(0);
4521   MVT::ValueType EVT = MVT::getVectorBaseType(VT);
4522   SDOperand PermMask = N->getOperand(2);
4523   int NumElems = (int)PermMask.getNumOperands();
4524   SDNode *Base = NULL;
4525   for (int i = 0; i < NumElems; ++i) {
4526     SDOperand Idx = PermMask.getOperand(i);
4527     if (Idx.getOpcode() == ISD::UNDEF) {
4528       if (!Base) return SDOperand();
4529     } else {
4530       SDOperand Arg =
4531         getShuffleScalarElt(N, cast<ConstantSDNode>(Idx)->getValue(), DAG);
4532       if (!Arg.Val || !ISD::isNON_EXTLoad(Arg.Val))
4533         return SDOperand();
4534       if (!Base)
4535         Base = Arg.Val;
4536       else if (!isConsecutiveLoad(Arg.Val, Base,
4537                                   i, MVT::getSizeInBits(EVT)/8,MFI))
4538         return SDOperand();
4539     }
4540   }
4541
4542   bool isAlign16 = isBaseAlignment16(Base->getOperand(1).Val, MFI, Subtarget);
4543   if (isAlign16) {
4544     LoadSDNode *LD = cast<LoadSDNode>(Base);
4545     return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
4546                        LD->getSrcValueOffset());
4547   } else {
4548     // Just use movups, it's shorter.
4549     SDVTList Tys = DAG.getVTList(MVT::v4f32, MVT::Other);
4550     SmallVector<SDOperand, 3> Ops;
4551     Ops.push_back(Base->getOperand(0));
4552     Ops.push_back(Base->getOperand(1));
4553     Ops.push_back(Base->getOperand(2));
4554     return DAG.getNode(ISD::BIT_CONVERT, VT,
4555                        DAG.getNode(X86ISD::LOAD_UA, Tys, &Ops[0], Ops.size()));
4556   }
4557 }
4558
4559 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
4560 static SDOperand PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
4561                                       const X86Subtarget *Subtarget) {
4562   SDOperand Cond = N->getOperand(0);
4563
4564   // If we have SSE[12] support, try to form min/max nodes.
4565   if (Subtarget->hasSSE2() &&
4566       (N->getValueType(0) == MVT::f32 || N->getValueType(0) == MVT::f64)) {
4567     if (Cond.getOpcode() == ISD::SETCC) {
4568       // Get the LHS/RHS of the select.
4569       SDOperand LHS = N->getOperand(1);
4570       SDOperand RHS = N->getOperand(2);
4571       ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
4572
4573       unsigned Opcode = 0;
4574       if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
4575         switch (CC) {
4576         default: break;
4577         case ISD::SETOLE: // (X <= Y) ? X : Y -> min
4578         case ISD::SETULE:
4579         case ISD::SETLE:
4580           if (!UnsafeFPMath) break;
4581           // FALL THROUGH.
4582         case ISD::SETOLT:  // (X olt/lt Y) ? X : Y -> min
4583         case ISD::SETLT:
4584           Opcode = X86ISD::FMIN;
4585           break;
4586
4587         case ISD::SETOGT: // (X > Y) ? X : Y -> max
4588         case ISD::SETUGT:
4589         case ISD::SETGT:
4590           if (!UnsafeFPMath) break;
4591           // FALL THROUGH.
4592         case ISD::SETUGE:  // (X uge/ge Y) ? X : Y -> max
4593         case ISD::SETGE:
4594           Opcode = X86ISD::FMAX;
4595           break;
4596         }
4597       } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
4598         switch (CC) {
4599         default: break;
4600         case ISD::SETOGT: // (X > Y) ? Y : X -> min
4601         case ISD::SETUGT:
4602         case ISD::SETGT:
4603           if (!UnsafeFPMath) break;
4604           // FALL THROUGH.
4605         case ISD::SETUGE:  // (X uge/ge Y) ? Y : X -> min
4606         case ISD::SETGE:
4607           Opcode = X86ISD::FMIN;
4608           break;
4609
4610         case ISD::SETOLE:   // (X <= Y) ? Y : X -> max
4611         case ISD::SETULE:
4612         case ISD::SETLE:
4613           if (!UnsafeFPMath) break;
4614           // FALL THROUGH.
4615         case ISD::SETOLT:   // (X olt/lt Y) ? Y : X -> max
4616         case ISD::SETLT:
4617           Opcode = X86ISD::FMAX;
4618           break;
4619         }
4620       }
4621
4622       if (Opcode)
4623         return DAG.getNode(Opcode, N->getValueType(0), LHS, RHS);
4624     }
4625
4626   }
4627
4628   return SDOperand();
4629 }
4630
4631
4632 SDOperand X86TargetLowering::PerformDAGCombine(SDNode *N,
4633                                                DAGCombinerInfo &DCI) const {
4634   SelectionDAG &DAG = DCI.DAG;
4635   switch (N->getOpcode()) {
4636   default: break;
4637   case ISD::VECTOR_SHUFFLE:
4638     return PerformShuffleCombine(N, DAG, Subtarget);
4639   case ISD::SELECT:
4640     return PerformSELECTCombine(N, DAG, Subtarget);
4641   }
4642
4643   return SDOperand();
4644 }
4645
4646 //===----------------------------------------------------------------------===//
4647 //                           X86 Inline Assembly Support
4648 //===----------------------------------------------------------------------===//
4649
4650 /// getConstraintType - Given a constraint letter, return the type of
4651 /// constraint it is for this target.
4652 X86TargetLowering::ConstraintType
4653 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
4654   if (Constraint.size() == 1) {
4655     switch (Constraint[0]) {
4656     case 'A':
4657     case 'r':
4658     case 'R':
4659     case 'l':
4660     case 'q':
4661     case 'Q':
4662     case 'x':
4663     case 'Y':
4664       return C_RegisterClass;
4665     default:
4666       break;
4667     }
4668   }
4669   return TargetLowering::getConstraintType(Constraint);
4670 }
4671
4672 /// isOperandValidForConstraint - Return the specified operand (possibly
4673 /// modified) if the specified SDOperand is valid for the specified target
4674 /// constraint letter, otherwise return null.
4675 SDOperand X86TargetLowering::
4676 isOperandValidForConstraint(SDOperand Op, char Constraint, SelectionDAG &DAG) {
4677   switch (Constraint) {
4678   default: break;
4679   case 'I':
4680     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
4681       if (C->getValue() <= 31)
4682         return Op;
4683     }
4684     return SDOperand(0,0);
4685   case 'N':
4686     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
4687       if (C->getValue() <= 255)
4688         return Op;
4689     }
4690     return SDOperand(0,0);
4691   case 'i':
4692     // Literal immediates are always ok.
4693     if (isa<ConstantSDNode>(Op)) return Op;
4694
4695     // If we are in non-pic codegen mode, we allow the address of a global to
4696     // be used with 'i'.
4697     if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
4698       if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
4699         return SDOperand(0, 0);
4700
4701       if (GA->getOpcode() != ISD::TargetGlobalAddress)
4702         Op = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
4703                                         GA->getOffset());
4704       return Op;
4705     }
4706
4707     // Otherwise, not valid for this mode.
4708     return SDOperand(0, 0);
4709   }
4710   return TargetLowering::isOperandValidForConstraint(Op, Constraint, DAG);
4711 }
4712
4713 std::vector<unsigned> X86TargetLowering::
4714 getRegClassForInlineAsmConstraint(const std::string &Constraint,
4715                                   MVT::ValueType VT) const {
4716   if (Constraint.size() == 1) {
4717     // FIXME: not handling fp-stack yet!
4718     switch (Constraint[0]) {      // GCC X86 Constraint Letters
4719     default: break;  // Unknown constraint letter
4720     case 'A':   // EAX/EDX
4721       if (VT == MVT::i32 || VT == MVT::i64)
4722         return make_vector<unsigned>(X86::EAX, X86::EDX, 0);
4723       break;
4724     case 'q':   // Q_REGS (GENERAL_REGS in 64-bit mode)
4725     case 'Q':   // Q_REGS
4726       if (VT == MVT::i32)
4727         return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
4728       else if (VT == MVT::i16)
4729         return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
4730       else if (VT == MVT::i8)
4731         return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::DL, 0);
4732         break;
4733     }
4734   }
4735
4736   return std::vector<unsigned>();
4737 }
4738
4739 std::pair<unsigned, const TargetRegisterClass*>
4740 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
4741                                                 MVT::ValueType VT) const {
4742   // First, see if this is a constraint that directly corresponds to an LLVM
4743   // register class.
4744   if (Constraint.size() == 1) {
4745     // GCC Constraint Letters
4746     switch (Constraint[0]) {
4747     default: break;
4748     case 'r':   // GENERAL_REGS
4749     case 'R':   // LEGACY_REGS
4750     case 'l':   // INDEX_REGS
4751       if (VT == MVT::i64 && Subtarget->is64Bit())
4752         return std::make_pair(0U, X86::GR64RegisterClass);
4753       if (VT == MVT::i32)
4754         return std::make_pair(0U, X86::GR32RegisterClass);
4755       else if (VT == MVT::i16)
4756         return std::make_pair(0U, X86::GR16RegisterClass);
4757       else if (VT == MVT::i8)
4758         return std::make_pair(0U, X86::GR8RegisterClass);
4759       break;
4760     case 'y':   // MMX_REGS if MMX allowed.
4761       if (!Subtarget->hasMMX()) break;
4762       return std::make_pair(0U, X86::VR64RegisterClass);
4763       break;
4764     case 'Y':   // SSE_REGS if SSE2 allowed
4765       if (!Subtarget->hasSSE2()) break;
4766       // FALL THROUGH.
4767     case 'x':   // SSE_REGS if SSE1 allowed
4768       if (!Subtarget->hasSSE1()) break;
4769       
4770       switch (VT) {
4771       default: break;
4772       // Scalar SSE types.
4773       case MVT::f32:
4774       case MVT::i32:
4775         return std::make_pair(0U, X86::FR32RegisterClass);
4776       case MVT::f64:
4777       case MVT::i64:
4778         return std::make_pair(0U, X86::FR64RegisterClass);
4779       // Vector types.
4780       case MVT::Vector:
4781       case MVT::v16i8:
4782       case MVT::v8i16:
4783       case MVT::v4i32:
4784       case MVT::v2i64:
4785       case MVT::v4f32:
4786       case MVT::v2f64:
4787         return std::make_pair(0U, X86::VR128RegisterClass);
4788       }
4789       break;
4790     }
4791   }
4792   
4793   // Use the default implementation in TargetLowering to convert the register
4794   // constraint into a member of a register class.
4795   std::pair<unsigned, const TargetRegisterClass*> Res;
4796   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
4797
4798   // Not found as a standard register?
4799   if (Res.second == 0) {
4800     // GCC calls "st(0)" just plain "st".
4801     if (StringsEqualNoCase("{st}", Constraint)) {
4802       Res.first = X86::ST0;
4803       Res.second = X86::RSTRegisterClass;
4804     }
4805
4806     return Res;
4807   }
4808
4809   // Otherwise, check to see if this is a register class of the wrong value
4810   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
4811   // turn into {ax},{dx}.
4812   if (Res.second->hasType(VT))
4813     return Res;   // Correct type already, nothing to do.
4814
4815   // All of the single-register GCC register classes map their values onto
4816   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
4817   // really want an 8-bit or 32-bit register, map to the appropriate register
4818   // class and return the appropriate register.
4819   if (Res.second != X86::GR16RegisterClass)
4820     return Res;
4821
4822   if (VT == MVT::i8) {
4823     unsigned DestReg = 0;
4824     switch (Res.first) {
4825     default: break;
4826     case X86::AX: DestReg = X86::AL; break;
4827     case X86::DX: DestReg = X86::DL; break;
4828     case X86::CX: DestReg = X86::CL; break;
4829     case X86::BX: DestReg = X86::BL; break;
4830     }
4831     if (DestReg) {
4832       Res.first = DestReg;
4833       Res.second = Res.second = X86::GR8RegisterClass;
4834     }
4835   } else if (VT == MVT::i32) {
4836     unsigned DestReg = 0;
4837     switch (Res.first) {
4838     default: break;
4839     case X86::AX: DestReg = X86::EAX; break;
4840     case X86::DX: DestReg = X86::EDX; break;
4841     case X86::CX: DestReg = X86::ECX; break;
4842     case X86::BX: DestReg = X86::EBX; break;
4843     case X86::SI: DestReg = X86::ESI; break;
4844     case X86::DI: DestReg = X86::EDI; break;
4845     case X86::BP: DestReg = X86::EBP; break;
4846     case X86::SP: DestReg = X86::ESP; break;
4847     }
4848     if (DestReg) {
4849       Res.first = DestReg;
4850       Res.second = Res.second = X86::GR32RegisterClass;
4851     }
4852   } else if (VT == MVT::i64) {
4853     unsigned DestReg = 0;
4854     switch (Res.first) {
4855     default: break;
4856     case X86::AX: DestReg = X86::RAX; break;
4857     case X86::DX: DestReg = X86::RDX; break;
4858     case X86::CX: DestReg = X86::RCX; break;
4859     case X86::BX: DestReg = X86::RBX; break;
4860     case X86::SI: DestReg = X86::RSI; break;
4861     case X86::DI: DestReg = X86::RDI; break;
4862     case X86::BP: DestReg = X86::RBP; break;
4863     case X86::SP: DestReg = X86::RSP; break;
4864     }
4865     if (DestReg) {
4866       Res.first = DestReg;
4867       Res.second = Res.second = X86::GR64RegisterClass;
4868     }
4869   }
4870
4871   return Res;
4872 }