Rename "HasCalls" in MachineFrameInfo to "AdjustsStack" to better describe what
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "x86-isel"
16 #include "X86.h"
17 #include "X86InstrBuilder.h"
18 #include "X86ISelLowering.h"
19 #include "X86TargetMachine.h"
20 #include "X86TargetObjectFile.h"
21 #include "llvm/CallingConv.h"
22 #include "llvm/Constants.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/GlobalAlias.h"
25 #include "llvm/GlobalVariable.h"
26 #include "llvm/Function.h"
27 #include "llvm/Instructions.h"
28 #include "llvm/Intrinsics.h"
29 #include "llvm/LLVMContext.h"
30 #include "llvm/CodeGen/MachineFrameInfo.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineJumpTableInfo.h"
34 #include "llvm/CodeGen/MachineModuleInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/PseudoSourceValue.h"
37 #include "llvm/MC/MCAsmInfo.h"
38 #include "llvm/MC/MCContext.h"
39 #include "llvm/MC/MCExpr.h"
40 #include "llvm/MC/MCSymbol.h"
41 #include "llvm/ADT/BitVector.h"
42 #include "llvm/ADT/SmallSet.h"
43 #include "llvm/ADT/Statistic.h"
44 #include "llvm/ADT/StringExtras.h"
45 #include "llvm/ADT/VectorExtras.h"
46 #include "llvm/Support/CommandLine.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/Dwarf.h"
49 #include "llvm/Support/ErrorHandling.h"
50 #include "llvm/Support/MathExtras.h"
51 #include "llvm/Support/raw_ostream.h"
52 using namespace llvm;
53 using namespace dwarf;
54
55 STATISTIC(NumTailCalls, "Number of tail calls");
56
57 static cl::opt<bool>
58 DisableMMX("disable-mmx", cl::Hidden, cl::desc("Disable use of MMX"));
59
60 // Forward declarations.
61 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
62                        SDValue V2);
63
64 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
65   switch (TM.getSubtarget<X86Subtarget>().TargetType) {
66   default: llvm_unreachable("unknown subtarget type");
67   case X86Subtarget::isDarwin:
68     if (TM.getSubtarget<X86Subtarget>().is64Bit())
69       return new X8664_MachoTargetObjectFile();
70     return new TargetLoweringObjectFileMachO();
71   case X86Subtarget::isELF:
72    if (TM.getSubtarget<X86Subtarget>().is64Bit())
73      return new X8664_ELFTargetObjectFile(TM);
74     return new X8632_ELFTargetObjectFile(TM);
75   case X86Subtarget::isMingw:
76   case X86Subtarget::isCygwin:
77   case X86Subtarget::isWindows:
78     return new TargetLoweringObjectFileCOFF();
79   }
80 }
81
82 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
83   : TargetLowering(TM, createTLOF(TM)) {
84   Subtarget = &TM.getSubtarget<X86Subtarget>();
85   X86ScalarSSEf64 = Subtarget->hasSSE2();
86   X86ScalarSSEf32 = Subtarget->hasSSE1();
87   X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
88
89   RegInfo = TM.getRegisterInfo();
90   TD = getTargetData();
91
92   // Set up the TargetLowering object.
93
94   // X86 is weird, it always uses i8 for shift amounts and setcc results.
95   setShiftAmountType(MVT::i8);
96   setBooleanContents(ZeroOrOneBooleanContent);
97   setSchedulingPreference(SchedulingForRegPressure);
98   setStackPointerRegisterToSaveRestore(X86StackPtr);
99
100   if (Subtarget->isTargetDarwin()) {
101     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
102     setUseUnderscoreSetJmp(false);
103     setUseUnderscoreLongJmp(false);
104   } else if (Subtarget->isTargetMingw()) {
105     // MS runtime is weird: it exports _setjmp, but longjmp!
106     setUseUnderscoreSetJmp(true);
107     setUseUnderscoreLongJmp(false);
108   } else {
109     setUseUnderscoreSetJmp(true);
110     setUseUnderscoreLongJmp(true);
111   }
112
113   // Set up the register classes.
114   addRegisterClass(MVT::i8, X86::GR8RegisterClass);
115   addRegisterClass(MVT::i16, X86::GR16RegisterClass);
116   addRegisterClass(MVT::i32, X86::GR32RegisterClass);
117   if (Subtarget->is64Bit())
118     addRegisterClass(MVT::i64, X86::GR64RegisterClass);
119
120   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
121
122   // We don't accept any truncstore of integer registers.
123   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
124   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
125   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
126   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
127   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
128   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
129
130   // SETOEQ and SETUNE require checking two conditions.
131   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
132   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
133   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
134   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
135   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
136   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
137
138   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
139   // operation.
140   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
141   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
142   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
143
144   if (Subtarget->is64Bit()) {
145     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
146     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Expand);
147   } else if (!UseSoftFloat) {
148     if (X86ScalarSSEf64) {
149       // We have an impenetrably clever algorithm for ui64->double only.
150       setOperationAction(ISD::UINT_TO_FP   , MVT::i64  , Custom);
151     }
152     // We have an algorithm for SSE2, and we turn this into a 64-bit
153     // FILD for other targets.
154     setOperationAction(ISD::UINT_TO_FP   , MVT::i32  , Custom);
155   }
156
157   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
158   // this operation.
159   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
160   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
161
162   if (!UseSoftFloat) {
163     // SSE has no i16 to fp conversion, only i32
164     if (X86ScalarSSEf32) {
165       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
166       // f32 and f64 cases are Legal, f80 case is not
167       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
168     } else {
169       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
170       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
171     }
172   } else {
173     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
174     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
175   }
176
177   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
178   // are Legal, f80 is custom lowered.
179   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
180   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
181
182   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
183   // this operation.
184   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
185   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
186
187   if (X86ScalarSSEf32) {
188     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
189     // f32 and f64 cases are Legal, f80 case is not
190     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
191   } else {
192     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
193     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
194   }
195
196   // Handle FP_TO_UINT by promoting the destination to a larger signed
197   // conversion.
198   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
199   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
200   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
201
202   if (Subtarget->is64Bit()) {
203     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
204     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
205   } else if (!UseSoftFloat) {
206     if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
207       // Expand FP_TO_UINT into a select.
208       // FIXME: We would like to use a Custom expander here eventually to do
209       // the optimal thing for SSE vs. the default expansion in the legalizer.
210       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
211     else
212       // With SSE3 we can use fisttpll to convert to a signed i64; without
213       // SSE, we're stuck with a fistpll.
214       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
215   }
216
217   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
218   if (!X86ScalarSSEf64) {
219     setOperationAction(ISD::BIT_CONVERT      , MVT::f32  , Expand);
220     setOperationAction(ISD::BIT_CONVERT      , MVT::i32  , Expand);
221   }
222
223   // Scalar integer divide and remainder are lowered to use operations that
224   // produce two results, to match the available instructions. This exposes
225   // the two-result form to trivial CSE, which is able to combine x/y and x%y
226   // into a single instruction.
227   //
228   // Scalar integer multiply-high is also lowered to use two-result
229   // operations, to match the available instructions. However, plain multiply
230   // (low) operations are left as Legal, as there are single-result
231   // instructions for this in x86. Using the two-result multiply instructions
232   // when both high and low results are needed must be arranged by dagcombine.
233   setOperationAction(ISD::MULHS           , MVT::i8    , Expand);
234   setOperationAction(ISD::MULHU           , MVT::i8    , Expand);
235   setOperationAction(ISD::SDIV            , MVT::i8    , Expand);
236   setOperationAction(ISD::UDIV            , MVT::i8    , Expand);
237   setOperationAction(ISD::SREM            , MVT::i8    , Expand);
238   setOperationAction(ISD::UREM            , MVT::i8    , Expand);
239   setOperationAction(ISD::MULHS           , MVT::i16   , Expand);
240   setOperationAction(ISD::MULHU           , MVT::i16   , Expand);
241   setOperationAction(ISD::SDIV            , MVT::i16   , Expand);
242   setOperationAction(ISD::UDIV            , MVT::i16   , Expand);
243   setOperationAction(ISD::SREM            , MVT::i16   , Expand);
244   setOperationAction(ISD::UREM            , MVT::i16   , Expand);
245   setOperationAction(ISD::MULHS           , MVT::i32   , Expand);
246   setOperationAction(ISD::MULHU           , MVT::i32   , Expand);
247   setOperationAction(ISD::SDIV            , MVT::i32   , Expand);
248   setOperationAction(ISD::UDIV            , MVT::i32   , Expand);
249   setOperationAction(ISD::SREM            , MVT::i32   , Expand);
250   setOperationAction(ISD::UREM            , MVT::i32   , Expand);
251   setOperationAction(ISD::MULHS           , MVT::i64   , Expand);
252   setOperationAction(ISD::MULHU           , MVT::i64   , Expand);
253   setOperationAction(ISD::SDIV            , MVT::i64   , Expand);
254   setOperationAction(ISD::UDIV            , MVT::i64   , Expand);
255   setOperationAction(ISD::SREM            , MVT::i64   , Expand);
256   setOperationAction(ISD::UREM            , MVT::i64   , Expand);
257
258   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
259   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
260   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
261   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
262   if (Subtarget->is64Bit())
263     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
264   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
265   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
266   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
267   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
268   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
269   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
270   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
271   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
272
273   setOperationAction(ISD::CTPOP            , MVT::i8   , Expand);
274   setOperationAction(ISD::CTTZ             , MVT::i8   , Custom);
275   setOperationAction(ISD::CTLZ             , MVT::i8   , Custom);
276   setOperationAction(ISD::CTPOP            , MVT::i16  , Expand);
277   setOperationAction(ISD::CTTZ             , MVT::i16  , Custom);
278   setOperationAction(ISD::CTLZ             , MVT::i16  , Custom);
279   setOperationAction(ISD::CTPOP            , MVT::i32  , Expand);
280   setOperationAction(ISD::CTTZ             , MVT::i32  , Custom);
281   setOperationAction(ISD::CTLZ             , MVT::i32  , Custom);
282   if (Subtarget->is64Bit()) {
283     setOperationAction(ISD::CTPOP          , MVT::i64  , Expand);
284     setOperationAction(ISD::CTTZ           , MVT::i64  , Custom);
285     setOperationAction(ISD::CTLZ           , MVT::i64  , Custom);
286   }
287
288   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
289   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
290
291   // These should be promoted to a larger select which is supported.
292   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
293   // X86 wants to expand cmov itself.
294   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
295   setOperationAction(ISD::SELECT        , MVT::i16  , Custom);
296   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
297   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
298   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
299   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
300   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
301   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
302   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
303   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
304   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
305   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
306   if (Subtarget->is64Bit()) {
307     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
308     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
309   }
310   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
311
312   // Darwin ABI issue.
313   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
314   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
315   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
316   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
317   if (Subtarget->is64Bit())
318     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
319   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
320   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
321   if (Subtarget->is64Bit()) {
322     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
323     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
324     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
325     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
326     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
327   }
328   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
329   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
330   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
331   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
332   if (Subtarget->is64Bit()) {
333     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
334     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
335     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
336   }
337
338   if (Subtarget->hasSSE1())
339     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
340
341   if (!Subtarget->hasSSE2())
342     setOperationAction(ISD::MEMBARRIER    , MVT::Other, Expand);
343
344   // Expand certain atomics
345   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i8, Custom);
346   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i16, Custom);
347   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
348   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
349
350   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i8, Custom);
351   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i16, Custom);
352   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
353   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
354
355   if (!Subtarget->is64Bit()) {
356     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
357     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
358     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
359     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
360     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
361     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
362     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
363   }
364
365   // FIXME - use subtarget debug flags
366   if (!Subtarget->isTargetDarwin() &&
367       !Subtarget->isTargetELF() &&
368       !Subtarget->isTargetCygMing()) {
369     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
370   }
371
372   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
373   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
374   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
375   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
376   if (Subtarget->is64Bit()) {
377     setExceptionPointerRegister(X86::RAX);
378     setExceptionSelectorRegister(X86::RDX);
379   } else {
380     setExceptionPointerRegister(X86::EAX);
381     setExceptionSelectorRegister(X86::EDX);
382   }
383   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
384   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
385
386   setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
387
388   setOperationAction(ISD::TRAP, MVT::Other, Legal);
389
390   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
391   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
392   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
393   if (Subtarget->is64Bit()) {
394     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
395     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
396   } else {
397     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
398     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
399   }
400
401   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
402   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
403   if (Subtarget->is64Bit())
404     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
405   if (Subtarget->isTargetCygMing())
406     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
407   else
408     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
409
410   if (!UseSoftFloat && X86ScalarSSEf64) {
411     // f32 and f64 use SSE.
412     // Set up the FP register classes.
413     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
414     addRegisterClass(MVT::f64, X86::FR64RegisterClass);
415
416     // Use ANDPD to simulate FABS.
417     setOperationAction(ISD::FABS , MVT::f64, Custom);
418     setOperationAction(ISD::FABS , MVT::f32, Custom);
419
420     // Use XORP to simulate FNEG.
421     setOperationAction(ISD::FNEG , MVT::f64, Custom);
422     setOperationAction(ISD::FNEG , MVT::f32, Custom);
423
424     // Use ANDPD and ORPD to simulate FCOPYSIGN.
425     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
426     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
427
428     // We don't support sin/cos/fmod
429     setOperationAction(ISD::FSIN , MVT::f64, Expand);
430     setOperationAction(ISD::FCOS , MVT::f64, Expand);
431     setOperationAction(ISD::FSIN , MVT::f32, Expand);
432     setOperationAction(ISD::FCOS , MVT::f32, Expand);
433
434     // Expand FP immediates into loads from the stack, except for the special
435     // cases we handle.
436     addLegalFPImmediate(APFloat(+0.0)); // xorpd
437     addLegalFPImmediate(APFloat(+0.0f)); // xorps
438   } else if (!UseSoftFloat && X86ScalarSSEf32) {
439     // Use SSE for f32, x87 for f64.
440     // Set up the FP register classes.
441     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
442     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
443
444     // Use ANDPS to simulate FABS.
445     setOperationAction(ISD::FABS , MVT::f32, Custom);
446
447     // Use XORP to simulate FNEG.
448     setOperationAction(ISD::FNEG , MVT::f32, Custom);
449
450     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
451
452     // Use ANDPS and ORPS to simulate FCOPYSIGN.
453     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
454     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
455
456     // We don't support sin/cos/fmod
457     setOperationAction(ISD::FSIN , MVT::f32, Expand);
458     setOperationAction(ISD::FCOS , MVT::f32, Expand);
459
460     // Special cases we handle for FP constants.
461     addLegalFPImmediate(APFloat(+0.0f)); // xorps
462     addLegalFPImmediate(APFloat(+0.0)); // FLD0
463     addLegalFPImmediate(APFloat(+1.0)); // FLD1
464     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
465     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
466
467     if (!UnsafeFPMath) {
468       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
469       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
470     }
471   } else if (!UseSoftFloat) {
472     // f32 and f64 in x87.
473     // Set up the FP register classes.
474     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
475     addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
476
477     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
478     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
479     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
480     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
481
482     if (!UnsafeFPMath) {
483       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
484       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
485     }
486     addLegalFPImmediate(APFloat(+0.0)); // FLD0
487     addLegalFPImmediate(APFloat(+1.0)); // FLD1
488     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
489     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
490     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
491     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
492     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
493     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
494   }
495
496   // Long double always uses X87.
497   if (!UseSoftFloat) {
498     addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
499     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
500     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
501     {
502       bool ignored;
503       APFloat TmpFlt(+0.0);
504       TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
505                      &ignored);
506       addLegalFPImmediate(TmpFlt);  // FLD0
507       TmpFlt.changeSign();
508       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
509       APFloat TmpFlt2(+1.0);
510       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
511                       &ignored);
512       addLegalFPImmediate(TmpFlt2);  // FLD1
513       TmpFlt2.changeSign();
514       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
515     }
516
517     if (!UnsafeFPMath) {
518       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
519       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
520     }
521   }
522
523   // Always use a library call for pow.
524   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
525   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
526   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
527
528   setOperationAction(ISD::FLOG, MVT::f80, Expand);
529   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
530   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
531   setOperationAction(ISD::FEXP, MVT::f80, Expand);
532   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
533
534   // First set operation action for all vector types to either promote
535   // (for widening) or expand (for scalarization). Then we will selectively
536   // turn on ones that can be effectively codegen'd.
537   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
538        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
539     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
540     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
541     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
542     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
543     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
544     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
545     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
546     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
547     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
548     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
549     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
550     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
551     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
552     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
553     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
554     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
555     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
556     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
557     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
558     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
559     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
560     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
561     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
562     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
563     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
564     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
565     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
566     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
567     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
568     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
569     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
570     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
571     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
572     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
573     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
574     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
575     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
576     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
577     setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
578     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
579     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
580     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
581     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
582     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
583     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
584     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
585     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
586     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
587     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
588     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
589     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
590     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
591     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
592     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
593          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
594       setTruncStoreAction((MVT::SimpleValueType)VT,
595                           (MVT::SimpleValueType)InnerVT, Expand);
596     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
597     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
598     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
599   }
600
601   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
602   // with -msoft-float, disable use of MMX as well.
603   if (!UseSoftFloat && !DisableMMX && Subtarget->hasMMX()) {
604     addRegisterClass(MVT::v8i8,  X86::VR64RegisterClass, false);
605     addRegisterClass(MVT::v4i16, X86::VR64RegisterClass, false);
606     addRegisterClass(MVT::v2i32, X86::VR64RegisterClass, false);
607     addRegisterClass(MVT::v2f32, X86::VR64RegisterClass, false);
608     addRegisterClass(MVT::v1i64, X86::VR64RegisterClass, false);
609
610     setOperationAction(ISD::ADD,                MVT::v8i8,  Legal);
611     setOperationAction(ISD::ADD,                MVT::v4i16, Legal);
612     setOperationAction(ISD::ADD,                MVT::v2i32, Legal);
613     setOperationAction(ISD::ADD,                MVT::v1i64, Legal);
614
615     setOperationAction(ISD::SUB,                MVT::v8i8,  Legal);
616     setOperationAction(ISD::SUB,                MVT::v4i16, Legal);
617     setOperationAction(ISD::SUB,                MVT::v2i32, Legal);
618     setOperationAction(ISD::SUB,                MVT::v1i64, Legal);
619
620     setOperationAction(ISD::MULHS,              MVT::v4i16, Legal);
621     setOperationAction(ISD::MUL,                MVT::v4i16, Legal);
622
623     setOperationAction(ISD::AND,                MVT::v8i8,  Promote);
624     AddPromotedToType (ISD::AND,                MVT::v8i8,  MVT::v1i64);
625     setOperationAction(ISD::AND,                MVT::v4i16, Promote);
626     AddPromotedToType (ISD::AND,                MVT::v4i16, MVT::v1i64);
627     setOperationAction(ISD::AND,                MVT::v2i32, Promote);
628     AddPromotedToType (ISD::AND,                MVT::v2i32, MVT::v1i64);
629     setOperationAction(ISD::AND,                MVT::v1i64, Legal);
630
631     setOperationAction(ISD::OR,                 MVT::v8i8,  Promote);
632     AddPromotedToType (ISD::OR,                 MVT::v8i8,  MVT::v1i64);
633     setOperationAction(ISD::OR,                 MVT::v4i16, Promote);
634     AddPromotedToType (ISD::OR,                 MVT::v4i16, MVT::v1i64);
635     setOperationAction(ISD::OR,                 MVT::v2i32, Promote);
636     AddPromotedToType (ISD::OR,                 MVT::v2i32, MVT::v1i64);
637     setOperationAction(ISD::OR,                 MVT::v1i64, Legal);
638
639     setOperationAction(ISD::XOR,                MVT::v8i8,  Promote);
640     AddPromotedToType (ISD::XOR,                MVT::v8i8,  MVT::v1i64);
641     setOperationAction(ISD::XOR,                MVT::v4i16, Promote);
642     AddPromotedToType (ISD::XOR,                MVT::v4i16, MVT::v1i64);
643     setOperationAction(ISD::XOR,                MVT::v2i32, Promote);
644     AddPromotedToType (ISD::XOR,                MVT::v2i32, MVT::v1i64);
645     setOperationAction(ISD::XOR,                MVT::v1i64, Legal);
646
647     setOperationAction(ISD::LOAD,               MVT::v8i8,  Promote);
648     AddPromotedToType (ISD::LOAD,               MVT::v8i8,  MVT::v1i64);
649     setOperationAction(ISD::LOAD,               MVT::v4i16, Promote);
650     AddPromotedToType (ISD::LOAD,               MVT::v4i16, MVT::v1i64);
651     setOperationAction(ISD::LOAD,               MVT::v2i32, Promote);
652     AddPromotedToType (ISD::LOAD,               MVT::v2i32, MVT::v1i64);
653     setOperationAction(ISD::LOAD,               MVT::v2f32, Promote);
654     AddPromotedToType (ISD::LOAD,               MVT::v2f32, MVT::v1i64);
655     setOperationAction(ISD::LOAD,               MVT::v1i64, Legal);
656
657     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i8,  Custom);
658     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i16, Custom);
659     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i32, Custom);
660     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f32, Custom);
661     setOperationAction(ISD::BUILD_VECTOR,       MVT::v1i64, Custom);
662
663     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8i8,  Custom);
664     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i16, Custom);
665     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i32, Custom);
666     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v1i64, Custom);
667
668     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2f32, Custom);
669     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Custom);
670     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Custom);
671     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Custom);
672
673     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i16, Custom);
674
675     setOperationAction(ISD::SELECT,             MVT::v8i8, Promote);
676     setOperationAction(ISD::SELECT,             MVT::v4i16, Promote);
677     setOperationAction(ISD::SELECT,             MVT::v2i32, Promote);
678     setOperationAction(ISD::SELECT,             MVT::v1i64, Custom);
679     setOperationAction(ISD::VSETCC,             MVT::v8i8, Custom);
680     setOperationAction(ISD::VSETCC,             MVT::v4i16, Custom);
681     setOperationAction(ISD::VSETCC,             MVT::v2i32, Custom);
682   }
683
684   if (!UseSoftFloat && Subtarget->hasSSE1()) {
685     addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
686
687     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
688     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
689     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
690     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
691     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
692     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
693     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
694     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
695     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
696     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
697     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
698     setOperationAction(ISD::VSETCC,             MVT::v4f32, Custom);
699   }
700
701   if (!UseSoftFloat && Subtarget->hasSSE2()) {
702     addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
703
704     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
705     // registers cannot be used even for integer operations.
706     addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
707     addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
708     addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
709     addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
710
711     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
712     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
713     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
714     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
715     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
716     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
717     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
718     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
719     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
720     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
721     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
722     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
723     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
724     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
725     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
726     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
727
728     setOperationAction(ISD::VSETCC,             MVT::v2f64, Custom);
729     setOperationAction(ISD::VSETCC,             MVT::v16i8, Custom);
730     setOperationAction(ISD::VSETCC,             MVT::v8i16, Custom);
731     setOperationAction(ISD::VSETCC,             MVT::v4i32, Custom);
732
733     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
734     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
735     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
736     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
737     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
738
739     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2f64, Custom);
740     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2i64, Custom);
741     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i8, Custom);
742     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i16, Custom);
743     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i32, Custom);
744
745     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
746     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
747       EVT VT = (MVT::SimpleValueType)i;
748       // Do not attempt to custom lower non-power-of-2 vectors
749       if (!isPowerOf2_32(VT.getVectorNumElements()))
750         continue;
751       // Do not attempt to custom lower non-128-bit vectors
752       if (!VT.is128BitVector())
753         continue;
754       setOperationAction(ISD::BUILD_VECTOR,
755                          VT.getSimpleVT().SimpleTy, Custom);
756       setOperationAction(ISD::VECTOR_SHUFFLE,
757                          VT.getSimpleVT().SimpleTy, Custom);
758       setOperationAction(ISD::EXTRACT_VECTOR_ELT,
759                          VT.getSimpleVT().SimpleTy, Custom);
760     }
761
762     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
763     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
764     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
765     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
766     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
767     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
768
769     if (Subtarget->is64Bit()) {
770       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
771       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
772     }
773
774     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
775     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
776       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
777       EVT VT = SVT;
778
779       // Do not attempt to promote non-128-bit vectors
780       if (!VT.is128BitVector()) {
781         continue;
782       }
783       
784       setOperationAction(ISD::AND,    SVT, Promote);
785       AddPromotedToType (ISD::AND,    SVT, MVT::v2i64);
786       setOperationAction(ISD::OR,     SVT, Promote);
787       AddPromotedToType (ISD::OR,     SVT, MVT::v2i64);
788       setOperationAction(ISD::XOR,    SVT, Promote);
789       AddPromotedToType (ISD::XOR,    SVT, MVT::v2i64);
790       setOperationAction(ISD::LOAD,   SVT, Promote);
791       AddPromotedToType (ISD::LOAD,   SVT, MVT::v2i64);
792       setOperationAction(ISD::SELECT, SVT, Promote);
793       AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
794     }
795
796     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
797
798     // Custom lower v2i64 and v2f64 selects.
799     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
800     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
801     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
802     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
803
804     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
805     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
806     if (!DisableMMX && Subtarget->hasMMX()) {
807       setOperationAction(ISD::FP_TO_SINT,         MVT::v2i32, Custom);
808       setOperationAction(ISD::SINT_TO_FP,         MVT::v2i32, Custom);
809     }
810   }
811
812   if (Subtarget->hasSSE41()) {
813     // FIXME: Do we need to handle scalar-to-vector here?
814     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
815
816     // i8 and i16 vectors are custom , because the source register and source
817     // source memory operand types are not the same width.  f32 vectors are
818     // custom since the immediate controlling the insert encodes additional
819     // information.
820     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
821     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
822     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
823     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
824
825     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
826     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
827     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
828     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
829
830     if (Subtarget->is64Bit()) {
831       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Legal);
832       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
833     }
834   }
835
836   if (Subtarget->hasSSE42()) {
837     setOperationAction(ISD::VSETCC,             MVT::v2i64, Custom);
838   }
839
840   if (!UseSoftFloat && Subtarget->hasAVX()) {
841     addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
842     addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
843     addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
844     addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
845
846     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
847     setOperationAction(ISD::LOAD,               MVT::v8i32, Legal);
848     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
849     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
850     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
851     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
852     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
853     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
854     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
855     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
856     //setOperationAction(ISD::BUILD_VECTOR,       MVT::v8f32, Custom);
857     //setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8f32, Custom);
858     //setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8f32, Custom);
859     //setOperationAction(ISD::SELECT,             MVT::v8f32, Custom);
860     //setOperationAction(ISD::VSETCC,             MVT::v8f32, Custom);
861
862     // Operations to consider commented out -v16i16 v32i8
863     //setOperationAction(ISD::ADD,                MVT::v16i16, Legal);
864     setOperationAction(ISD::ADD,                MVT::v8i32, Custom);
865     setOperationAction(ISD::ADD,                MVT::v4i64, Custom);
866     //setOperationAction(ISD::SUB,                MVT::v32i8, Legal);
867     //setOperationAction(ISD::SUB,                MVT::v16i16, Legal);
868     setOperationAction(ISD::SUB,                MVT::v8i32, Custom);
869     setOperationAction(ISD::SUB,                MVT::v4i64, Custom);
870     //setOperationAction(ISD::MUL,                MVT::v16i16, Legal);
871     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
872     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
873     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
874     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
875     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
876     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
877
878     setOperationAction(ISD::VSETCC,             MVT::v4f64, Custom);
879     // setOperationAction(ISD::VSETCC,             MVT::v32i8, Custom);
880     // setOperationAction(ISD::VSETCC,             MVT::v16i16, Custom);
881     setOperationAction(ISD::VSETCC,             MVT::v8i32, Custom);
882
883     // setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v32i8, Custom);
884     // setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i16, Custom);
885     // setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i16, Custom);
886     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i32, Custom);
887     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8f32, Custom);
888
889     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f64, Custom);
890     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i64, Custom);
891     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f64, Custom);
892     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i64, Custom);
893     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f64, Custom);
894     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f64, Custom);
895
896 #if 0
897     // Not sure we want to do this since there are no 256-bit integer
898     // operations in AVX
899
900     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
901     // This includes 256-bit vectors
902     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; ++i) {
903       EVT VT = (MVT::SimpleValueType)i;
904
905       // Do not attempt to custom lower non-power-of-2 vectors
906       if (!isPowerOf2_32(VT.getVectorNumElements()))
907         continue;
908
909       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
910       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
911       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
912     }
913
914     if (Subtarget->is64Bit()) {
915       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i64, Custom);
916       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i64, Custom);
917     }
918 #endif
919
920 #if 0
921     // Not sure we want to do this since there are no 256-bit integer
922     // operations in AVX
923
924     // Promote v32i8, v16i16, v8i32 load, select, and, or, xor to v4i64.
925     // Including 256-bit vectors
926     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; i++) {
927       EVT VT = (MVT::SimpleValueType)i;
928
929       if (!VT.is256BitVector()) {
930         continue;
931       }
932       setOperationAction(ISD::AND,    VT, Promote);
933       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
934       setOperationAction(ISD::OR,     VT, Promote);
935       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
936       setOperationAction(ISD::XOR,    VT, Promote);
937       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
938       setOperationAction(ISD::LOAD,   VT, Promote);
939       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
940       setOperationAction(ISD::SELECT, VT, Promote);
941       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
942     }
943
944     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
945 #endif
946   }
947
948   // We want to custom lower some of our intrinsics.
949   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
950
951   // Add/Sub/Mul with overflow operations are custom lowered.
952   setOperationAction(ISD::SADDO, MVT::i32, Custom);
953   setOperationAction(ISD::SADDO, MVT::i64, Custom);
954   setOperationAction(ISD::UADDO, MVT::i32, Custom);
955   setOperationAction(ISD::UADDO, MVT::i64, Custom);
956   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
957   setOperationAction(ISD::SSUBO, MVT::i64, Custom);
958   setOperationAction(ISD::USUBO, MVT::i32, Custom);
959   setOperationAction(ISD::USUBO, MVT::i64, Custom);
960   setOperationAction(ISD::SMULO, MVT::i32, Custom);
961   setOperationAction(ISD::SMULO, MVT::i64, Custom);
962
963   if (!Subtarget->is64Bit()) {
964     // These libcalls are not available in 32-bit.
965     setLibcallName(RTLIB::SHL_I128, 0);
966     setLibcallName(RTLIB::SRL_I128, 0);
967     setLibcallName(RTLIB::SRA_I128, 0);
968   }
969
970   // We have target-specific dag combine patterns for the following nodes:
971   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
972   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
973   setTargetDAGCombine(ISD::BUILD_VECTOR);
974   setTargetDAGCombine(ISD::SELECT);
975   setTargetDAGCombine(ISD::SHL);
976   setTargetDAGCombine(ISD::SRA);
977   setTargetDAGCombine(ISD::SRL);
978   setTargetDAGCombine(ISD::OR);
979   setTargetDAGCombine(ISD::STORE);
980   setTargetDAGCombine(ISD::MEMBARRIER);
981   setTargetDAGCombine(ISD::ZERO_EXTEND);
982   if (Subtarget->is64Bit())
983     setTargetDAGCombine(ISD::MUL);
984
985   computeRegisterProperties();
986
987   // FIXME: These should be based on subtarget info. Plus, the values should
988   // be smaller when we are in optimizing for size mode.
989   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
990   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
991   maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
992   setPrefLoopAlignment(16);
993   benefitFromCodePlacementOpt = true;
994 }
995
996
997 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
998   return MVT::i8;
999 }
1000
1001
1002 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1003 /// the desired ByVal argument alignment.
1004 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
1005   if (MaxAlign == 16)
1006     return;
1007   if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1008     if (VTy->getBitWidth() == 128)
1009       MaxAlign = 16;
1010   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1011     unsigned EltAlign = 0;
1012     getMaxByValAlign(ATy->getElementType(), EltAlign);
1013     if (EltAlign > MaxAlign)
1014       MaxAlign = EltAlign;
1015   } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1016     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1017       unsigned EltAlign = 0;
1018       getMaxByValAlign(STy->getElementType(i), EltAlign);
1019       if (EltAlign > MaxAlign)
1020         MaxAlign = EltAlign;
1021       if (MaxAlign == 16)
1022         break;
1023     }
1024   }
1025   return;
1026 }
1027
1028 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1029 /// function arguments in the caller parameter area. For X86, aggregates
1030 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1031 /// are at 4-byte boundaries.
1032 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1033   if (Subtarget->is64Bit()) {
1034     // Max of 8 and alignment of type.
1035     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1036     if (TyAlign > 8)
1037       return TyAlign;
1038     return 8;
1039   }
1040
1041   unsigned Align = 4;
1042   if (Subtarget->hasSSE1())
1043     getMaxByValAlign(Ty, Align);
1044   return Align;
1045 }
1046
1047 /// getOptimalMemOpType - Returns the target specific optimal type for load
1048 /// and store operations as a result of memset, memcpy, and memmove
1049 /// lowering. If DstAlign is zero that means it's safe to destination
1050 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1051 /// means there isn't a need to check it against alignment requirement,
1052 /// probably because the source does not need to be loaded. If
1053 /// 'NonScalarIntSafe' is true, that means it's safe to return a
1054 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1055 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1056 /// constant so it does not need to be loaded.
1057 /// It returns EVT::Other if the type should be determined using generic
1058 /// target-independent logic.
1059 EVT
1060 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1061                                        unsigned DstAlign, unsigned SrcAlign,
1062                                        bool NonScalarIntSafe,
1063                                        bool MemcpyStrSrc,
1064                                        MachineFunction &MF) const {
1065   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1066   // linux.  This is because the stack realignment code can't handle certain
1067   // cases like PR2962.  This should be removed when PR2962 is fixed.
1068   const Function *F = MF.getFunction();
1069   if (NonScalarIntSafe &&
1070       !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1071     if (Size >= 16 &&
1072         (Subtarget->isUnalignedMemAccessFast() ||
1073          ((DstAlign == 0 || DstAlign >= 16) &&
1074           (SrcAlign == 0 || SrcAlign >= 16))) &&
1075         Subtarget->getStackAlignment() >= 16) {
1076       if (Subtarget->hasSSE2())
1077         return MVT::v4i32;
1078       if (Subtarget->hasSSE1())
1079         return MVT::v4f32;
1080     } else if (!MemcpyStrSrc && Size >= 8 &&
1081                !Subtarget->is64Bit() &&
1082                Subtarget->getStackAlignment() >= 8 &&
1083                Subtarget->hasSSE2()) {
1084       // Do not use f64 to lower memcpy if source is string constant. It's
1085       // better to use i32 to avoid the loads.
1086       return MVT::f64;
1087     }
1088   }
1089   if (Subtarget->is64Bit() && Size >= 8)
1090     return MVT::i64;
1091   return MVT::i32;
1092 }
1093
1094 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1095 /// current function.  The returned value is a member of the
1096 /// MachineJumpTableInfo::JTEntryKind enum.
1097 unsigned X86TargetLowering::getJumpTableEncoding() const {
1098   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1099   // symbol.
1100   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1101       Subtarget->isPICStyleGOT())
1102     return MachineJumpTableInfo::EK_Custom32;
1103   
1104   // Otherwise, use the normal jump table encoding heuristics.
1105   return TargetLowering::getJumpTableEncoding();
1106 }
1107
1108 /// getPICBaseSymbol - Return the X86-32 PIC base.
1109 MCSymbol *
1110 X86TargetLowering::getPICBaseSymbol(const MachineFunction *MF,
1111                                     MCContext &Ctx) const {
1112   const MCAsmInfo &MAI = *getTargetMachine().getMCAsmInfo();
1113   return Ctx.GetOrCreateSymbol(Twine(MAI.getPrivateGlobalPrefix())+
1114                                Twine(MF->getFunctionNumber())+"$pb");
1115 }
1116
1117
1118 const MCExpr *
1119 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1120                                              const MachineBasicBlock *MBB,
1121                                              unsigned uid,MCContext &Ctx) const{
1122   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1123          Subtarget->isPICStyleGOT());
1124   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1125   // entries.
1126   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1127                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1128 }
1129
1130 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1131 /// jumptable.
1132 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1133                                                     SelectionDAG &DAG) const {
1134   if (!Subtarget->is64Bit())
1135     // This doesn't have DebugLoc associated with it, but is not really the
1136     // same as a Register.
1137     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1138   return Table;
1139 }
1140
1141 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1142 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1143 /// MCExpr.
1144 const MCExpr *X86TargetLowering::
1145 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1146                              MCContext &Ctx) const {
1147   // X86-64 uses RIP relative addressing based on the jump table label.
1148   if (Subtarget->isPICStyleRIPRel())
1149     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1150
1151   // Otherwise, the reference is relative to the PIC base.
1152   return MCSymbolRefExpr::Create(getPICBaseSymbol(MF, Ctx), Ctx);
1153 }
1154
1155 /// getFunctionAlignment - Return the Log2 alignment of this function.
1156 unsigned X86TargetLowering::getFunctionAlignment(const Function *F) const {
1157   return F->hasFnAttr(Attribute::OptimizeForSize) ? 0 : 4;
1158 }
1159
1160 //===----------------------------------------------------------------------===//
1161 //               Return Value Calling Convention Implementation
1162 //===----------------------------------------------------------------------===//
1163
1164 #include "X86GenCallingConv.inc"
1165
1166 bool 
1167 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv, bool isVarArg,
1168                         const SmallVectorImpl<EVT> &OutTys,
1169                         const SmallVectorImpl<ISD::ArgFlagsTy> &ArgsFlags,
1170                         SelectionDAG &DAG) const {
1171   SmallVector<CCValAssign, 16> RVLocs;
1172   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1173                  RVLocs, *DAG.getContext());
1174   return CCInfo.CheckReturn(OutTys, ArgsFlags, RetCC_X86);
1175 }
1176
1177 SDValue
1178 X86TargetLowering::LowerReturn(SDValue Chain,
1179                                CallingConv::ID CallConv, bool isVarArg,
1180                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1181                                DebugLoc dl, SelectionDAG &DAG) const {
1182   MachineFunction &MF = DAG.getMachineFunction();
1183   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1184
1185   SmallVector<CCValAssign, 16> RVLocs;
1186   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1187                  RVLocs, *DAG.getContext());
1188   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1189
1190   // Add the regs to the liveout set for the function.
1191   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1192   for (unsigned i = 0; i != RVLocs.size(); ++i)
1193     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1194       MRI.addLiveOut(RVLocs[i].getLocReg());
1195
1196   SDValue Flag;
1197
1198   SmallVector<SDValue, 6> RetOps;
1199   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1200   // Operand #1 = Bytes To Pop
1201   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1202                    MVT::i16));
1203
1204   // Copy the result values into the output registers.
1205   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1206     CCValAssign &VA = RVLocs[i];
1207     assert(VA.isRegLoc() && "Can only return in registers!");
1208     SDValue ValToCopy = Outs[i].Val;
1209
1210     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1211     // the RET instruction and handled by the FP Stackifier.
1212     if (VA.getLocReg() == X86::ST0 ||
1213         VA.getLocReg() == X86::ST1) {
1214       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1215       // change the value to the FP stack register class.
1216       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1217         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1218       RetOps.push_back(ValToCopy);
1219       // Don't emit a copytoreg.
1220       continue;
1221     }
1222
1223     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1224     // which is returned in RAX / RDX.
1225     if (Subtarget->is64Bit()) {
1226       EVT ValVT = ValToCopy.getValueType();
1227       if (ValVT.isVector() && ValVT.getSizeInBits() == 64) {
1228         ValToCopy = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, ValToCopy);
1229         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1)
1230           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, ValToCopy);
1231       }
1232     }
1233
1234     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1235     Flag = Chain.getValue(1);
1236   }
1237
1238   // The x86-64 ABI for returning structs by value requires that we copy
1239   // the sret argument into %rax for the return. We saved the argument into
1240   // a virtual register in the entry block, so now we copy the value out
1241   // and into %rax.
1242   if (Subtarget->is64Bit() &&
1243       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1244     MachineFunction &MF = DAG.getMachineFunction();
1245     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1246     unsigned Reg = FuncInfo->getSRetReturnReg();
1247     if (!Reg) {
1248       Reg = MRI.createVirtualRegister(getRegClassFor(MVT::i64));
1249       FuncInfo->setSRetReturnReg(Reg);
1250     }
1251     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1252
1253     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1254     Flag = Chain.getValue(1);
1255
1256     // RAX now acts like a return value.
1257     MRI.addLiveOut(X86::RAX);
1258   }
1259
1260   RetOps[0] = Chain;  // Update chain.
1261
1262   // Add the flag if we have it.
1263   if (Flag.getNode())
1264     RetOps.push_back(Flag);
1265
1266   return DAG.getNode(X86ISD::RET_FLAG, dl,
1267                      MVT::Other, &RetOps[0], RetOps.size());
1268 }
1269
1270 /// LowerCallResult - Lower the result values of a call into the
1271 /// appropriate copies out of appropriate physical registers.
1272 ///
1273 SDValue
1274 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1275                                    CallingConv::ID CallConv, bool isVarArg,
1276                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1277                                    DebugLoc dl, SelectionDAG &DAG,
1278                                    SmallVectorImpl<SDValue> &InVals) const {
1279
1280   // Assign locations to each value returned by this call.
1281   SmallVector<CCValAssign, 16> RVLocs;
1282   bool Is64Bit = Subtarget->is64Bit();
1283   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1284                  RVLocs, *DAG.getContext());
1285   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1286
1287   // Copy all of the result registers out of their specified physreg.
1288   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1289     CCValAssign &VA = RVLocs[i];
1290     EVT CopyVT = VA.getValVT();
1291
1292     // If this is x86-64, and we disabled SSE, we can't return FP values
1293     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1294         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1295       report_fatal_error("SSE register return with SSE disabled");
1296     }
1297
1298     // If this is a call to a function that returns an fp value on the floating
1299     // point stack, but where we prefer to use the value in xmm registers, copy
1300     // it out as F80 and use a truncate to move it from fp stack reg to xmm reg.
1301     if ((VA.getLocReg() == X86::ST0 ||
1302          VA.getLocReg() == X86::ST1) &&
1303         isScalarFPTypeInSSEReg(VA.getValVT())) {
1304       CopyVT = MVT::f80;
1305     }
1306
1307     SDValue Val;
1308     if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1309       // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1310       if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1311         Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1312                                    MVT::v2i64, InFlag).getValue(1);
1313         Val = Chain.getValue(0);
1314         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1315                           Val, DAG.getConstant(0, MVT::i64));
1316       } else {
1317         Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1318                                    MVT::i64, InFlag).getValue(1);
1319         Val = Chain.getValue(0);
1320       }
1321       Val = DAG.getNode(ISD::BIT_CONVERT, dl, CopyVT, Val);
1322     } else {
1323       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1324                                  CopyVT, InFlag).getValue(1);
1325       Val = Chain.getValue(0);
1326     }
1327     InFlag = Chain.getValue(2);
1328
1329     if (CopyVT != VA.getValVT()) {
1330       // Round the F80 the right size, which also moves to the appropriate xmm
1331       // register.
1332       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1333                         // This truncation won't change the value.
1334                         DAG.getIntPtrConstant(1));
1335     }
1336
1337     InVals.push_back(Val);
1338   }
1339
1340   return Chain;
1341 }
1342
1343
1344 //===----------------------------------------------------------------------===//
1345 //                C & StdCall & Fast Calling Convention implementation
1346 //===----------------------------------------------------------------------===//
1347 //  StdCall calling convention seems to be standard for many Windows' API
1348 //  routines and around. It differs from C calling convention just a little:
1349 //  callee should clean up the stack, not caller. Symbols should be also
1350 //  decorated in some fancy way :) It doesn't support any vector arguments.
1351 //  For info on fast calling convention see Fast Calling Convention (tail call)
1352 //  implementation LowerX86_32FastCCCallTo.
1353
1354 /// CallIsStructReturn - Determines whether a call uses struct return
1355 /// semantics.
1356 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1357   if (Outs.empty())
1358     return false;
1359
1360   return Outs[0].Flags.isSRet();
1361 }
1362
1363 /// ArgsAreStructReturn - Determines whether a function uses struct
1364 /// return semantics.
1365 static bool
1366 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1367   if (Ins.empty())
1368     return false;
1369
1370   return Ins[0].Flags.isSRet();
1371 }
1372
1373 /// IsCalleePop - Determines whether the callee is required to pop its
1374 /// own arguments. Callee pop is necessary to support tail calls.
1375 bool X86TargetLowering::IsCalleePop(bool IsVarArg,
1376                                     CallingConv::ID CallingConv) const {
1377   if (IsVarArg)
1378     return false;
1379
1380   switch (CallingConv) {
1381   default:
1382     return false;
1383   case CallingConv::X86_StdCall:
1384     return !Subtarget->is64Bit();
1385   case CallingConv::X86_FastCall:
1386     return !Subtarget->is64Bit();
1387   case CallingConv::Fast:
1388     return GuaranteedTailCallOpt;
1389   case CallingConv::GHC:
1390     return GuaranteedTailCallOpt;
1391   }
1392 }
1393
1394 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1395 /// given CallingConvention value.
1396 CCAssignFn *X86TargetLowering::CCAssignFnForNode(CallingConv::ID CC) const {
1397   if (Subtarget->is64Bit()) {
1398     if (CC == CallingConv::GHC)
1399       return CC_X86_64_GHC;
1400     else if (Subtarget->isTargetWin64())
1401       return CC_X86_Win64_C;
1402     else
1403       return CC_X86_64_C;
1404   }
1405
1406   if (CC == CallingConv::X86_FastCall)
1407     return CC_X86_32_FastCall;
1408   else if (CC == CallingConv::Fast)
1409     return CC_X86_32_FastCC;
1410   else if (CC == CallingConv::GHC)
1411     return CC_X86_32_GHC;
1412   else
1413     return CC_X86_32_C;
1414 }
1415
1416 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1417 /// by "Src" to address "Dst" with size and alignment information specified by
1418 /// the specific parameter attribute. The copy will be passed as a byval
1419 /// function parameter.
1420 static SDValue
1421 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1422                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1423                           DebugLoc dl) {
1424   SDValue SizeNode     = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1425   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1426                        /*isVolatile*/false, /*AlwaysInline=*/true,
1427                        NULL, 0, NULL, 0);
1428 }
1429
1430 /// IsTailCallConvention - Return true if the calling convention is one that
1431 /// supports tail call optimization.
1432 static bool IsTailCallConvention(CallingConv::ID CC) {
1433   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1434 }
1435
1436 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1437 /// a tailcall target by changing its ABI.
1438 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1439   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1440 }
1441
1442 SDValue
1443 X86TargetLowering::LowerMemArgument(SDValue Chain,
1444                                     CallingConv::ID CallConv,
1445                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1446                                     DebugLoc dl, SelectionDAG &DAG,
1447                                     const CCValAssign &VA,
1448                                     MachineFrameInfo *MFI,
1449                                     unsigned i) const {
1450   // Create the nodes corresponding to a load from this parameter slot.
1451   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1452   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1453   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1454   EVT ValVT;
1455
1456   // If value is passed by pointer we have address passed instead of the value
1457   // itself.
1458   if (VA.getLocInfo() == CCValAssign::Indirect)
1459     ValVT = VA.getLocVT();
1460   else
1461     ValVT = VA.getValVT();
1462
1463   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1464   // changed with more analysis.
1465   // In case of tail call optimization mark all arguments mutable. Since they
1466   // could be overwritten by lowering of arguments in case of a tail call.
1467   if (Flags.isByVal()) {
1468     int FI = MFI->CreateFixedObject(Flags.getByValSize(),
1469                                     VA.getLocMemOffset(), isImmutable, false);
1470     return DAG.getFrameIndex(FI, getPointerTy());
1471   } else {
1472     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1473                                     VA.getLocMemOffset(), isImmutable, false);
1474     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1475     return DAG.getLoad(ValVT, dl, Chain, FIN,
1476                        PseudoSourceValue::getFixedStack(FI), 0,
1477                        false, false, 0);
1478   }
1479 }
1480
1481 SDValue
1482 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1483                                         CallingConv::ID CallConv,
1484                                         bool isVarArg,
1485                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1486                                         DebugLoc dl,
1487                                         SelectionDAG &DAG,
1488                                         SmallVectorImpl<SDValue> &InVals)
1489                                           const {
1490   MachineFunction &MF = DAG.getMachineFunction();
1491   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1492
1493   const Function* Fn = MF.getFunction();
1494   if (Fn->hasExternalLinkage() &&
1495       Subtarget->isTargetCygMing() &&
1496       Fn->getName() == "main")
1497     FuncInfo->setForceFramePointer(true);
1498
1499   MachineFrameInfo *MFI = MF.getFrameInfo();
1500   bool Is64Bit = Subtarget->is64Bit();
1501   bool IsWin64 = Subtarget->isTargetWin64();
1502
1503   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1504          "Var args not supported with calling convention fastcc or ghc");
1505
1506   // Assign locations to all of the incoming arguments.
1507   SmallVector<CCValAssign, 16> ArgLocs;
1508   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1509                  ArgLocs, *DAG.getContext());
1510   CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForNode(CallConv));
1511
1512   unsigned LastVal = ~0U;
1513   SDValue ArgValue;
1514   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1515     CCValAssign &VA = ArgLocs[i];
1516     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1517     // places.
1518     assert(VA.getValNo() != LastVal &&
1519            "Don't support value assigned to multiple locs yet");
1520     LastVal = VA.getValNo();
1521
1522     if (VA.isRegLoc()) {
1523       EVT RegVT = VA.getLocVT();
1524       TargetRegisterClass *RC = NULL;
1525       if (RegVT == MVT::i32)
1526         RC = X86::GR32RegisterClass;
1527       else if (Is64Bit && RegVT == MVT::i64)
1528         RC = X86::GR64RegisterClass;
1529       else if (RegVT == MVT::f32)
1530         RC = X86::FR32RegisterClass;
1531       else if (RegVT == MVT::f64)
1532         RC = X86::FR64RegisterClass;
1533       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1534         RC = X86::VR128RegisterClass;
1535       else if (RegVT.isVector() && RegVT.getSizeInBits() == 64)
1536         RC = X86::VR64RegisterClass;
1537       else
1538         llvm_unreachable("Unknown argument type!");
1539
1540       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1541       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1542
1543       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1544       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1545       // right size.
1546       if (VA.getLocInfo() == CCValAssign::SExt)
1547         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1548                                DAG.getValueType(VA.getValVT()));
1549       else if (VA.getLocInfo() == CCValAssign::ZExt)
1550         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1551                                DAG.getValueType(VA.getValVT()));
1552       else if (VA.getLocInfo() == CCValAssign::BCvt)
1553         ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1554
1555       if (VA.isExtInLoc()) {
1556         // Handle MMX values passed in XMM regs.
1557         if (RegVT.isVector()) {
1558           ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1559                                  ArgValue, DAG.getConstant(0, MVT::i64));
1560           ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1561         } else
1562           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1563       }
1564     } else {
1565       assert(VA.isMemLoc());
1566       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1567     }
1568
1569     // If value is passed via pointer - do a load.
1570     if (VA.getLocInfo() == CCValAssign::Indirect)
1571       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue, NULL, 0,
1572                              false, false, 0);
1573
1574     InVals.push_back(ArgValue);
1575   }
1576
1577   // The x86-64 ABI for returning structs by value requires that we copy
1578   // the sret argument into %rax for the return. Save the argument into
1579   // a virtual register so that we can access it from the return points.
1580   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1581     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1582     unsigned Reg = FuncInfo->getSRetReturnReg();
1583     if (!Reg) {
1584       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1585       FuncInfo->setSRetReturnReg(Reg);
1586     }
1587     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1588     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1589   }
1590
1591   unsigned StackSize = CCInfo.getNextStackOffset();
1592   // Align stack specially for tail calls.
1593   if (FuncIsMadeTailCallSafe(CallConv))
1594     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1595
1596   // If the function takes variable number of arguments, make a frame index for
1597   // the start of the first vararg value... for expansion of llvm.va_start.
1598   if (isVarArg) {
1599     if (Is64Bit || CallConv != CallingConv::X86_FastCall) {
1600       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,
1601                                                             true, false));
1602     }
1603     if (Is64Bit) {
1604       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1605
1606       // FIXME: We should really autogenerate these arrays
1607       static const unsigned GPR64ArgRegsWin64[] = {
1608         X86::RCX, X86::RDX, X86::R8,  X86::R9
1609       };
1610       static const unsigned XMMArgRegsWin64[] = {
1611         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1612       };
1613       static const unsigned GPR64ArgRegs64Bit[] = {
1614         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1615       };
1616       static const unsigned XMMArgRegs64Bit[] = {
1617         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1618         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1619       };
1620       const unsigned *GPR64ArgRegs, *XMMArgRegs;
1621
1622       if (IsWin64) {
1623         TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1624         GPR64ArgRegs = GPR64ArgRegsWin64;
1625         XMMArgRegs = XMMArgRegsWin64;
1626       } else {
1627         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1628         GPR64ArgRegs = GPR64ArgRegs64Bit;
1629         XMMArgRegs = XMMArgRegs64Bit;
1630       }
1631       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1632                                                        TotalNumIntRegs);
1633       unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1634                                                        TotalNumXMMRegs);
1635
1636       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1637       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1638              "SSE register cannot be used when SSE is disabled!");
1639       assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1640              "SSE register cannot be used when SSE is disabled!");
1641       if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
1642         // Kernel mode asks for SSE to be disabled, so don't push them
1643         // on the stack.
1644         TotalNumXMMRegs = 0;
1645
1646       // For X86-64, if there are vararg parameters that are passed via
1647       // registers, then we must store them to their spots on the stack so they
1648       // may be loaded by deferencing the result of va_next.
1649       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1650       FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1651       FuncInfo->setRegSaveFrameIndex(
1652         MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1653                                false));
1654
1655       // Store the integer parameter registers.
1656       SmallVector<SDValue, 8> MemOps;
1657       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1658                                         getPointerTy());
1659       unsigned Offset = FuncInfo->getVarArgsGPOffset();
1660       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1661         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1662                                   DAG.getIntPtrConstant(Offset));
1663         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1664                                      X86::GR64RegisterClass);
1665         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1666         SDValue Store =
1667           DAG.getStore(Val.getValue(1), dl, Val, FIN,
1668                        PseudoSourceValue::getFixedStack(
1669                          FuncInfo->getRegSaveFrameIndex()),
1670                        Offset, false, false, 0);
1671         MemOps.push_back(Store);
1672         Offset += 8;
1673       }
1674
1675       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1676         // Now store the XMM (fp + vector) parameter registers.
1677         SmallVector<SDValue, 11> SaveXMMOps;
1678         SaveXMMOps.push_back(Chain);
1679
1680         unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1681         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1682         SaveXMMOps.push_back(ALVal);
1683
1684         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1685                                FuncInfo->getRegSaveFrameIndex()));
1686         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1687                                FuncInfo->getVarArgsFPOffset()));
1688
1689         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1690           unsigned VReg = MF.addLiveIn(XMMArgRegs[NumXMMRegs],
1691                                        X86::VR128RegisterClass);
1692           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1693           SaveXMMOps.push_back(Val);
1694         }
1695         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1696                                      MVT::Other,
1697                                      &SaveXMMOps[0], SaveXMMOps.size()));
1698       }
1699
1700       if (!MemOps.empty())
1701         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1702                             &MemOps[0], MemOps.size());
1703     }
1704   }
1705
1706   // Some CCs need callee pop.
1707   if (IsCalleePop(isVarArg, CallConv)) {
1708     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1709   } else {
1710     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1711     // If this is an sret function, the return should pop the hidden pointer.
1712     if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1713       FuncInfo->setBytesToPopOnReturn(4);
1714   }
1715
1716   if (!Is64Bit) {
1717     // RegSaveFrameIndex is X86-64 only.
1718     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1719     if (CallConv == CallingConv::X86_FastCall)
1720       // fastcc functions can't have varargs.
1721       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1722   }
1723
1724   return Chain;
1725 }
1726
1727 SDValue
1728 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1729                                     SDValue StackPtr, SDValue Arg,
1730                                     DebugLoc dl, SelectionDAG &DAG,
1731                                     const CCValAssign &VA,
1732                                     ISD::ArgFlagsTy Flags) const {
1733   const unsigned FirstStackArgOffset = (Subtarget->isTargetWin64() ? 32 : 0);
1734   unsigned LocMemOffset = FirstStackArgOffset + VA.getLocMemOffset();
1735   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1736   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1737   if (Flags.isByVal()) {
1738     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1739   }
1740   return DAG.getStore(Chain, dl, Arg, PtrOff,
1741                       PseudoSourceValue::getStack(), LocMemOffset,
1742                       false, false, 0);
1743 }
1744
1745 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1746 /// optimization is performed and it is required.
1747 SDValue
1748 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1749                                            SDValue &OutRetAddr, SDValue Chain,
1750                                            bool IsTailCall, bool Is64Bit,
1751                                            int FPDiff, DebugLoc dl) const {
1752   // Adjust the Return address stack slot.
1753   EVT VT = getPointerTy();
1754   OutRetAddr = getReturnAddressFrameIndex(DAG);
1755
1756   // Load the "old" Return address.
1757   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, NULL, 0, false, false, 0);
1758   return SDValue(OutRetAddr.getNode(), 1);
1759 }
1760
1761 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1762 /// optimization is performed and it is required (FPDiff!=0).
1763 static SDValue
1764 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1765                          SDValue Chain, SDValue RetAddrFrIdx,
1766                          bool Is64Bit, int FPDiff, DebugLoc dl) {
1767   // Store the return address to the appropriate stack slot.
1768   if (!FPDiff) return Chain;
1769   // Calculate the new stack slot for the return address.
1770   int SlotSize = Is64Bit ? 8 : 4;
1771   int NewReturnAddrFI =
1772     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false, false);
1773   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1774   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1775   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1776                        PseudoSourceValue::getFixedStack(NewReturnAddrFI), 0,
1777                        false, false, 0);
1778   return Chain;
1779 }
1780
1781 SDValue
1782 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1783                              CallingConv::ID CallConv, bool isVarArg,
1784                              bool &isTailCall,
1785                              const SmallVectorImpl<ISD::OutputArg> &Outs,
1786                              const SmallVectorImpl<ISD::InputArg> &Ins,
1787                              DebugLoc dl, SelectionDAG &DAG,
1788                              SmallVectorImpl<SDValue> &InVals) const {
1789   MachineFunction &MF = DAG.getMachineFunction();
1790   bool Is64Bit        = Subtarget->is64Bit();
1791   bool IsStructRet    = CallIsStructReturn(Outs);
1792   bool IsSibcall      = false;
1793
1794   if (isTailCall) {
1795     // Check if it's really possible to do a tail call.
1796     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1797                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1798                                                    Outs, Ins, DAG);
1799
1800     // Sibcalls are automatically detected tailcalls which do not require
1801     // ABI changes.
1802     if (!GuaranteedTailCallOpt && isTailCall)
1803       IsSibcall = true;
1804
1805     if (isTailCall)
1806       ++NumTailCalls;
1807   }
1808
1809   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1810          "Var args not supported with calling convention fastcc or ghc");
1811
1812   // Analyze operands of the call, assigning locations to each operand.
1813   SmallVector<CCValAssign, 16> ArgLocs;
1814   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1815                  ArgLocs, *DAG.getContext());
1816   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CallConv));
1817
1818   // Get a count of how many bytes are to be pushed on the stack.
1819   unsigned NumBytes = CCInfo.getNextStackOffset();
1820   if (IsSibcall)
1821     // This is a sibcall. The memory operands are available in caller's
1822     // own caller's stack.
1823     NumBytes = 0;
1824   else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
1825     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1826
1827   int FPDiff = 0;
1828   if (isTailCall && !IsSibcall) {
1829     // Lower arguments at fp - stackoffset + fpdiff.
1830     unsigned NumBytesCallerPushed =
1831       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1832     FPDiff = NumBytesCallerPushed - NumBytes;
1833
1834     // Set the delta of movement of the returnaddr stackslot.
1835     // But only set if delta is greater than previous delta.
1836     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1837       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1838   }
1839
1840   if (!IsSibcall)
1841     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1842
1843   SDValue RetAddrFrIdx;
1844   // Load return adress for tail calls.
1845   if (isTailCall && FPDiff)
1846     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
1847                                     Is64Bit, FPDiff, dl);
1848
1849   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1850   SmallVector<SDValue, 8> MemOpChains;
1851   SDValue StackPtr;
1852
1853   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1854   // of tail call optimization arguments are handle later.
1855   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1856     CCValAssign &VA = ArgLocs[i];
1857     EVT RegVT = VA.getLocVT();
1858     SDValue Arg = Outs[i].Val;
1859     ISD::ArgFlagsTy Flags = Outs[i].Flags;
1860     bool isByVal = Flags.isByVal();
1861
1862     // Promote the value if needed.
1863     switch (VA.getLocInfo()) {
1864     default: llvm_unreachable("Unknown loc info!");
1865     case CCValAssign::Full: break;
1866     case CCValAssign::SExt:
1867       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
1868       break;
1869     case CCValAssign::ZExt:
1870       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
1871       break;
1872     case CCValAssign::AExt:
1873       if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
1874         // Special case: passing MMX values in XMM registers.
1875         Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1876         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
1877         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
1878       } else
1879         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
1880       break;
1881     case CCValAssign::BCvt:
1882       Arg = DAG.getNode(ISD::BIT_CONVERT, dl, RegVT, Arg);
1883       break;
1884     case CCValAssign::Indirect: {
1885       // Store the argument.
1886       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
1887       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1888       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
1889                            PseudoSourceValue::getFixedStack(FI), 0,
1890                            false, false, 0);
1891       Arg = SpillSlot;
1892       break;
1893     }
1894     }
1895
1896     if (VA.isRegLoc()) {
1897       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1898     } else if (!IsSibcall && (!isTailCall || isByVal)) {
1899       assert(VA.isMemLoc());
1900       if (StackPtr.getNode() == 0)
1901         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
1902       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1903                                              dl, DAG, VA, Flags));
1904     }
1905   }
1906
1907   if (!MemOpChains.empty())
1908     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1909                         &MemOpChains[0], MemOpChains.size());
1910
1911   // Build a sequence of copy-to-reg nodes chained together with token chain
1912   // and flag operands which copy the outgoing args into registers.
1913   SDValue InFlag;
1914   // Tail call byval lowering might overwrite argument registers so in case of
1915   // tail call optimization the copies to registers are lowered later.
1916   if (!isTailCall)
1917     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1918       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1919                                RegsToPass[i].second, InFlag);
1920       InFlag = Chain.getValue(1);
1921     }
1922
1923   if (Subtarget->isPICStyleGOT()) {
1924     // ELF / PIC requires GOT in the EBX register before function calls via PLT
1925     // GOT pointer.
1926     if (!isTailCall) {
1927       Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
1928                                DAG.getNode(X86ISD::GlobalBaseReg,
1929                                            DebugLoc(), getPointerTy()),
1930                                InFlag);
1931       InFlag = Chain.getValue(1);
1932     } else {
1933       // If we are tail calling and generating PIC/GOT style code load the
1934       // address of the callee into ECX. The value in ecx is used as target of
1935       // the tail jump. This is done to circumvent the ebx/callee-saved problem
1936       // for tail calls on PIC/GOT architectures. Normally we would just put the
1937       // address of GOT into ebx and then call target@PLT. But for tail calls
1938       // ebx would be restored (since ebx is callee saved) before jumping to the
1939       // target@PLT.
1940
1941       // Note: The actual moving to ECX is done further down.
1942       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1943       if (G && !G->getGlobal()->hasHiddenVisibility() &&
1944           !G->getGlobal()->hasProtectedVisibility())
1945         Callee = LowerGlobalAddress(Callee, DAG);
1946       else if (isa<ExternalSymbolSDNode>(Callee))
1947         Callee = LowerExternalSymbol(Callee, DAG);
1948     }
1949   }
1950
1951   if (Is64Bit && isVarArg) {
1952     // From AMD64 ABI document:
1953     // For calls that may call functions that use varargs or stdargs
1954     // (prototype-less calls or calls to functions containing ellipsis (...) in
1955     // the declaration) %al is used as hidden argument to specify the number
1956     // of SSE registers used. The contents of %al do not need to match exactly
1957     // the number of registers, but must be an ubound on the number of SSE
1958     // registers used and is in the range 0 - 8 inclusive.
1959
1960     // FIXME: Verify this on Win64
1961     // Count the number of XMM registers allocated.
1962     static const unsigned XMMArgRegs[] = {
1963       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1964       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1965     };
1966     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1967     assert((Subtarget->hasSSE1() || !NumXMMRegs)
1968            && "SSE registers cannot be used when SSE is disabled");
1969
1970     Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
1971                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1972     InFlag = Chain.getValue(1);
1973   }
1974
1975
1976   // For tail calls lower the arguments to the 'real' stack slot.
1977   if (isTailCall) {
1978     // Force all the incoming stack arguments to be loaded from the stack
1979     // before any new outgoing arguments are stored to the stack, because the
1980     // outgoing stack slots may alias the incoming argument stack slots, and
1981     // the alias isn't otherwise explicit. This is slightly more conservative
1982     // than necessary, because it means that each store effectively depends
1983     // on every argument instead of just those arguments it would clobber.
1984     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
1985
1986     SmallVector<SDValue, 8> MemOpChains2;
1987     SDValue FIN;
1988     int FI = 0;
1989     // Do not flag preceeding copytoreg stuff together with the following stuff.
1990     InFlag = SDValue();
1991     if (GuaranteedTailCallOpt) {
1992       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1993         CCValAssign &VA = ArgLocs[i];
1994         if (VA.isRegLoc())
1995           continue;
1996         assert(VA.isMemLoc());
1997         SDValue Arg = Outs[i].Val;
1998         ISD::ArgFlagsTy Flags = Outs[i].Flags;
1999         // Create frame index.
2000         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2001         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2002         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true, false);
2003         FIN = DAG.getFrameIndex(FI, getPointerTy());
2004
2005         if (Flags.isByVal()) {
2006           // Copy relative to framepointer.
2007           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2008           if (StackPtr.getNode() == 0)
2009             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2010                                           getPointerTy());
2011           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2012
2013           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2014                                                            ArgChain,
2015                                                            Flags, DAG, dl));
2016         } else {
2017           // Store relative to framepointer.
2018           MemOpChains2.push_back(
2019             DAG.getStore(ArgChain, dl, Arg, FIN,
2020                          PseudoSourceValue::getFixedStack(FI), 0,
2021                          false, false, 0));
2022         }
2023       }
2024     }
2025
2026     if (!MemOpChains2.empty())
2027       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2028                           &MemOpChains2[0], MemOpChains2.size());
2029
2030     // Copy arguments to their registers.
2031     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2032       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2033                                RegsToPass[i].second, InFlag);
2034       InFlag = Chain.getValue(1);
2035     }
2036     InFlag =SDValue();
2037
2038     // Store the return address to the appropriate stack slot.
2039     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2040                                      FPDiff, dl);
2041   }
2042
2043   bool WasGlobalOrExternal = false;
2044   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2045     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2046     // In the 64-bit large code model, we have to make all calls
2047     // through a register, since the call instruction's 32-bit
2048     // pc-relative offset may not be large enough to hold the whole
2049     // address.
2050   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2051     WasGlobalOrExternal = true;
2052     // If the callee is a GlobalAddress node (quite common, every direct call
2053     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2054     // it.
2055
2056     // We should use extra load for direct calls to dllimported functions in
2057     // non-JIT mode.
2058     const GlobalValue *GV = G->getGlobal();
2059     if (!GV->hasDLLImportLinkage()) {
2060       unsigned char OpFlags = 0;
2061
2062       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2063       // external symbols most go through the PLT in PIC mode.  If the symbol
2064       // has hidden or protected visibility, or if it is static or local, then
2065       // we don't need to use the PLT - we can directly call it.
2066       if (Subtarget->isTargetELF() &&
2067           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2068           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2069         OpFlags = X86II::MO_PLT;
2070       } else if (Subtarget->isPICStyleStubAny() &&
2071                (GV->isDeclaration() || GV->isWeakForLinker()) &&
2072                Subtarget->getDarwinVers() < 9) {
2073         // PC-relative references to external symbols should go through $stub,
2074         // unless we're building with the leopard linker or later, which
2075         // automatically synthesizes these stubs.
2076         OpFlags = X86II::MO_DARWIN_STUB;
2077       }
2078
2079       Callee = DAG.getTargetGlobalAddress(GV, getPointerTy(),
2080                                           G->getOffset(), OpFlags);
2081     }
2082   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2083     WasGlobalOrExternal = true;
2084     unsigned char OpFlags = 0;
2085
2086     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to external
2087     // symbols should go through the PLT.
2088     if (Subtarget->isTargetELF() &&
2089         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2090       OpFlags = X86II::MO_PLT;
2091     } else if (Subtarget->isPICStyleStubAny() &&
2092              Subtarget->getDarwinVers() < 9) {
2093       // PC-relative references to external symbols should go through $stub,
2094       // unless we're building with the leopard linker or later, which
2095       // automatically synthesizes these stubs.
2096       OpFlags = X86II::MO_DARWIN_STUB;
2097     }
2098
2099     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2100                                          OpFlags);
2101   }
2102
2103   // Returns a chain & a flag for retval copy to use.
2104   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
2105   SmallVector<SDValue, 8> Ops;
2106
2107   if (!IsSibcall && isTailCall) {
2108     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2109                            DAG.getIntPtrConstant(0, true), InFlag);
2110     InFlag = Chain.getValue(1);
2111   }
2112
2113   Ops.push_back(Chain);
2114   Ops.push_back(Callee);
2115
2116   if (isTailCall)
2117     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2118
2119   // Add argument registers to the end of the list so that they are known live
2120   // into the call.
2121   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2122     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2123                                   RegsToPass[i].second.getValueType()));
2124
2125   // Add an implicit use GOT pointer in EBX.
2126   if (!isTailCall && Subtarget->isPICStyleGOT())
2127     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2128
2129   // Add an implicit use of AL for x86 vararg functions.
2130   if (Is64Bit && isVarArg)
2131     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2132
2133   if (InFlag.getNode())
2134     Ops.push_back(InFlag);
2135
2136   if (isTailCall) {
2137     // If this is the first return lowered for this function, add the regs
2138     // to the liveout set for the function.
2139     if (MF.getRegInfo().liveout_empty()) {
2140       SmallVector<CCValAssign, 16> RVLocs;
2141       CCState CCInfo(CallConv, isVarArg, getTargetMachine(), RVLocs,
2142                      *DAG.getContext());
2143       CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2144       for (unsigned i = 0; i != RVLocs.size(); ++i)
2145         if (RVLocs[i].isRegLoc())
2146           MF.getRegInfo().addLiveOut(RVLocs[i].getLocReg());
2147     }
2148     return DAG.getNode(X86ISD::TC_RETURN, dl,
2149                        NodeTys, &Ops[0], Ops.size());
2150   }
2151
2152   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2153   InFlag = Chain.getValue(1);
2154
2155   // Create the CALLSEQ_END node.
2156   unsigned NumBytesForCalleeToPush;
2157   if (IsCalleePop(isVarArg, CallConv))
2158     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2159   else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2160     // If this is a call to a struct-return function, the callee
2161     // pops the hidden struct pointer, so we have to push it back.
2162     // This is common for Darwin/X86, Linux & Mingw32 targets.
2163     NumBytesForCalleeToPush = 4;
2164   else
2165     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2166
2167   // Returns a flag for retval copy to use.
2168   if (!IsSibcall) {
2169     Chain = DAG.getCALLSEQ_END(Chain,
2170                                DAG.getIntPtrConstant(NumBytes, true),
2171                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2172                                                      true),
2173                                InFlag);
2174     InFlag = Chain.getValue(1);
2175   }
2176
2177   // Handle result values, copying them out of physregs into vregs that we
2178   // return.
2179   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2180                          Ins, dl, DAG, InVals);
2181 }
2182
2183
2184 //===----------------------------------------------------------------------===//
2185 //                Fast Calling Convention (tail call) implementation
2186 //===----------------------------------------------------------------------===//
2187
2188 //  Like std call, callee cleans arguments, convention except that ECX is
2189 //  reserved for storing the tail called function address. Only 2 registers are
2190 //  free for argument passing (inreg). Tail call optimization is performed
2191 //  provided:
2192 //                * tailcallopt is enabled
2193 //                * caller/callee are fastcc
2194 //  On X86_64 architecture with GOT-style position independent code only local
2195 //  (within module) calls are supported at the moment.
2196 //  To keep the stack aligned according to platform abi the function
2197 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2198 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2199 //  If a tail called function callee has more arguments than the caller the
2200 //  caller needs to make sure that there is room to move the RETADDR to. This is
2201 //  achieved by reserving an area the size of the argument delta right after the
2202 //  original REtADDR, but before the saved framepointer or the spilled registers
2203 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2204 //  stack layout:
2205 //    arg1
2206 //    arg2
2207 //    RETADDR
2208 //    [ new RETADDR
2209 //      move area ]
2210 //    (possible EBP)
2211 //    ESI
2212 //    EDI
2213 //    local1 ..
2214
2215 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2216 /// for a 16 byte align requirement.
2217 unsigned
2218 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2219                                                SelectionDAG& DAG) const {
2220   MachineFunction &MF = DAG.getMachineFunction();
2221   const TargetMachine &TM = MF.getTarget();
2222   const TargetFrameInfo &TFI = *TM.getFrameInfo();
2223   unsigned StackAlignment = TFI.getStackAlignment();
2224   uint64_t AlignMask = StackAlignment - 1;
2225   int64_t Offset = StackSize;
2226   uint64_t SlotSize = TD->getPointerSize();
2227   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2228     // Number smaller than 12 so just add the difference.
2229     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2230   } else {
2231     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2232     Offset = ((~AlignMask) & Offset) + StackAlignment +
2233       (StackAlignment-SlotSize);
2234   }
2235   return Offset;
2236 }
2237
2238 /// MatchingStackOffset - Return true if the given stack call argument is
2239 /// already available in the same position (relatively) of the caller's
2240 /// incoming argument stack.
2241 static
2242 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2243                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2244                          const X86InstrInfo *TII) {
2245   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2246   int FI = INT_MAX;
2247   if (Arg.getOpcode() == ISD::CopyFromReg) {
2248     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2249     if (!VR || TargetRegisterInfo::isPhysicalRegister(VR))
2250       return false;
2251     MachineInstr *Def = MRI->getVRegDef(VR);
2252     if (!Def)
2253       return false;
2254     if (!Flags.isByVal()) {
2255       if (!TII->isLoadFromStackSlot(Def, FI))
2256         return false;
2257     } else {
2258       unsigned Opcode = Def->getOpcode();
2259       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2260           Def->getOperand(1).isFI()) {
2261         FI = Def->getOperand(1).getIndex();
2262         Bytes = Flags.getByValSize();
2263       } else
2264         return false;
2265     }
2266   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2267     if (Flags.isByVal())
2268       // ByVal argument is passed in as a pointer but it's now being
2269       // dereferenced. e.g.
2270       // define @foo(%struct.X* %A) {
2271       //   tail call @bar(%struct.X* byval %A)
2272       // }
2273       return false;
2274     SDValue Ptr = Ld->getBasePtr();
2275     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2276     if (!FINode)
2277       return false;
2278     FI = FINode->getIndex();
2279   } else
2280     return false;
2281
2282   assert(FI != INT_MAX);
2283   if (!MFI->isFixedObjectIndex(FI))
2284     return false;
2285   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2286 }
2287
2288 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2289 /// for tail call optimization. Targets which want to do tail call
2290 /// optimization should implement this function.
2291 bool
2292 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2293                                                      CallingConv::ID CalleeCC,
2294                                                      bool isVarArg,
2295                                                      bool isCalleeStructRet,
2296                                                      bool isCallerStructRet,
2297                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2298                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2299                                                      SelectionDAG& DAG) const {
2300   if (!IsTailCallConvention(CalleeCC) &&
2301       CalleeCC != CallingConv::C)
2302     return false;
2303
2304   // If -tailcallopt is specified, make fastcc functions tail-callable.
2305   const MachineFunction &MF = DAG.getMachineFunction();
2306   const Function *CallerF = DAG.getMachineFunction().getFunction();
2307   CallingConv::ID CallerCC = CallerF->getCallingConv();
2308   bool CCMatch = CallerCC == CalleeCC;
2309
2310   if (GuaranteedTailCallOpt) {
2311     if (IsTailCallConvention(CalleeCC) && CCMatch)
2312       return true;
2313     return false;
2314   }
2315
2316   // Look for obvious safe cases to perform tail call optimization that does not
2317   // requite ABI changes. This is what gcc calls sibcall.
2318
2319   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2320   // emit a special epilogue.
2321   if (RegInfo->needsStackRealignment(MF))
2322     return false;
2323
2324   // Do not sibcall optimize vararg calls unless the call site is not passing any
2325   // arguments.
2326   if (isVarArg && !Outs.empty())
2327     return false;
2328
2329   // Also avoid sibcall optimization if either caller or callee uses struct
2330   // return semantics.
2331   if (isCalleeStructRet || isCallerStructRet)
2332     return false;
2333
2334   // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2335   // Therefore if it's not used by the call it is not safe to optimize this into
2336   // a sibcall.
2337   bool Unused = false;
2338   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2339     if (!Ins[i].Used) {
2340       Unused = true;
2341       break;
2342     }
2343   }
2344   if (Unused) {
2345     SmallVector<CCValAssign, 16> RVLocs;
2346     CCState CCInfo(CalleeCC, false, getTargetMachine(),
2347                    RVLocs, *DAG.getContext());
2348     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2349     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2350       CCValAssign &VA = RVLocs[i];
2351       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2352         return false;
2353     }
2354   }
2355
2356   // If the calling conventions do not match, then we'd better make sure the
2357   // results are returned in the same way as what the caller expects.
2358   if (!CCMatch) {
2359     SmallVector<CCValAssign, 16> RVLocs1;
2360     CCState CCInfo1(CalleeCC, false, getTargetMachine(),
2361                     RVLocs1, *DAG.getContext());
2362     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2363
2364     SmallVector<CCValAssign, 16> RVLocs2;
2365     CCState CCInfo2(CallerCC, false, getTargetMachine(),
2366                     RVLocs2, *DAG.getContext());
2367     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2368
2369     if (RVLocs1.size() != RVLocs2.size())
2370       return false;
2371     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2372       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2373         return false;
2374       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2375         return false;
2376       if (RVLocs1[i].isRegLoc()) {
2377         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2378           return false;
2379       } else {
2380         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2381           return false;
2382       }
2383     }
2384   }
2385
2386   // If the callee takes no arguments then go on to check the results of the
2387   // call.
2388   if (!Outs.empty()) {
2389     // Check if stack adjustment is needed. For now, do not do this if any
2390     // argument is passed on the stack.
2391     SmallVector<CCValAssign, 16> ArgLocs;
2392     CCState CCInfo(CalleeCC, isVarArg, getTargetMachine(),
2393                    ArgLocs, *DAG.getContext());
2394     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CalleeCC));
2395     if (CCInfo.getNextStackOffset()) {
2396       MachineFunction &MF = DAG.getMachineFunction();
2397       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2398         return false;
2399       if (Subtarget->isTargetWin64())
2400         // Win64 ABI has additional complications.
2401         return false;
2402
2403       // Check if the arguments are already laid out in the right way as
2404       // the caller's fixed stack objects.
2405       MachineFrameInfo *MFI = MF.getFrameInfo();
2406       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2407       const X86InstrInfo *TII =
2408         ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2409       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2410         CCValAssign &VA = ArgLocs[i];
2411         EVT RegVT = VA.getLocVT();
2412         SDValue Arg = Outs[i].Val;
2413         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2414         if (VA.getLocInfo() == CCValAssign::Indirect)
2415           return false;
2416         if (!VA.isRegLoc()) {
2417           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2418                                    MFI, MRI, TII))
2419             return false;
2420         }
2421       }
2422     }
2423   }
2424
2425   return true;
2426 }
2427
2428 FastISel *
2429 X86TargetLowering::createFastISel(MachineFunction &mf,
2430                             DenseMap<const Value *, unsigned> &vm,
2431                             DenseMap<const BasicBlock*, MachineBasicBlock*> &bm,
2432                             DenseMap<const AllocaInst *, int> &am,
2433                             std::vector<std::pair<MachineInstr*, unsigned> > &pn
2434 #ifndef NDEBUG
2435                           , SmallSet<const Instruction *, 8> &cil
2436 #endif
2437                                   ) const {
2438   return X86::createFastISel(mf, vm, bm, am, pn
2439 #ifndef NDEBUG
2440                              , cil
2441 #endif
2442                              );
2443 }
2444
2445
2446 //===----------------------------------------------------------------------===//
2447 //                           Other Lowering Hooks
2448 //===----------------------------------------------------------------------===//
2449
2450
2451 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2452   MachineFunction &MF = DAG.getMachineFunction();
2453   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2454   int ReturnAddrIndex = FuncInfo->getRAIndex();
2455
2456   if (ReturnAddrIndex == 0) {
2457     // Set up a frame object for the return address.
2458     uint64_t SlotSize = TD->getPointerSize();
2459     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2460                                                            false, false);
2461     FuncInfo->setRAIndex(ReturnAddrIndex);
2462   }
2463
2464   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2465 }
2466
2467
2468 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2469                                        bool hasSymbolicDisplacement) {
2470   // Offset should fit into 32 bit immediate field.
2471   if (!isInt<32>(Offset))
2472     return false;
2473
2474   // If we don't have a symbolic displacement - we don't have any extra
2475   // restrictions.
2476   if (!hasSymbolicDisplacement)
2477     return true;
2478
2479   // FIXME: Some tweaks might be needed for medium code model.
2480   if (M != CodeModel::Small && M != CodeModel::Kernel)
2481     return false;
2482
2483   // For small code model we assume that latest object is 16MB before end of 31
2484   // bits boundary. We may also accept pretty large negative constants knowing
2485   // that all objects are in the positive half of address space.
2486   if (M == CodeModel::Small && Offset < 16*1024*1024)
2487     return true;
2488
2489   // For kernel code model we know that all object resist in the negative half
2490   // of 32bits address space. We may not accept negative offsets, since they may
2491   // be just off and we may accept pretty large positive ones.
2492   if (M == CodeModel::Kernel && Offset > 0)
2493     return true;
2494
2495   return false;
2496 }
2497
2498 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2499 /// specific condition code, returning the condition code and the LHS/RHS of the
2500 /// comparison to make.
2501 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2502                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2503   if (!isFP) {
2504     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2505       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2506         // X > -1   -> X == 0, jump !sign.
2507         RHS = DAG.getConstant(0, RHS.getValueType());
2508         return X86::COND_NS;
2509       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2510         // X < 0   -> X == 0, jump on sign.
2511         return X86::COND_S;
2512       } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2513         // X < 1   -> X <= 0
2514         RHS = DAG.getConstant(0, RHS.getValueType());
2515         return X86::COND_LE;
2516       }
2517     }
2518
2519     switch (SetCCOpcode) {
2520     default: llvm_unreachable("Invalid integer condition!");
2521     case ISD::SETEQ:  return X86::COND_E;
2522     case ISD::SETGT:  return X86::COND_G;
2523     case ISD::SETGE:  return X86::COND_GE;
2524     case ISD::SETLT:  return X86::COND_L;
2525     case ISD::SETLE:  return X86::COND_LE;
2526     case ISD::SETNE:  return X86::COND_NE;
2527     case ISD::SETULT: return X86::COND_B;
2528     case ISD::SETUGT: return X86::COND_A;
2529     case ISD::SETULE: return X86::COND_BE;
2530     case ISD::SETUGE: return X86::COND_AE;
2531     }
2532   }
2533
2534   // First determine if it is required or is profitable to flip the operands.
2535
2536   // If LHS is a foldable load, but RHS is not, flip the condition.
2537   if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2538       !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2539     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2540     std::swap(LHS, RHS);
2541   }
2542
2543   switch (SetCCOpcode) {
2544   default: break;
2545   case ISD::SETOLT:
2546   case ISD::SETOLE:
2547   case ISD::SETUGT:
2548   case ISD::SETUGE:
2549     std::swap(LHS, RHS);
2550     break;
2551   }
2552
2553   // On a floating point condition, the flags are set as follows:
2554   // ZF  PF  CF   op
2555   //  0 | 0 | 0 | X > Y
2556   //  0 | 0 | 1 | X < Y
2557   //  1 | 0 | 0 | X == Y
2558   //  1 | 1 | 1 | unordered
2559   switch (SetCCOpcode) {
2560   default: llvm_unreachable("Condcode should be pre-legalized away");
2561   case ISD::SETUEQ:
2562   case ISD::SETEQ:   return X86::COND_E;
2563   case ISD::SETOLT:              // flipped
2564   case ISD::SETOGT:
2565   case ISD::SETGT:   return X86::COND_A;
2566   case ISD::SETOLE:              // flipped
2567   case ISD::SETOGE:
2568   case ISD::SETGE:   return X86::COND_AE;
2569   case ISD::SETUGT:              // flipped
2570   case ISD::SETULT:
2571   case ISD::SETLT:   return X86::COND_B;
2572   case ISD::SETUGE:              // flipped
2573   case ISD::SETULE:
2574   case ISD::SETLE:   return X86::COND_BE;
2575   case ISD::SETONE:
2576   case ISD::SETNE:   return X86::COND_NE;
2577   case ISD::SETUO:   return X86::COND_P;
2578   case ISD::SETO:    return X86::COND_NP;
2579   case ISD::SETOEQ:
2580   case ISD::SETUNE:  return X86::COND_INVALID;
2581   }
2582 }
2583
2584 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2585 /// code. Current x86 isa includes the following FP cmov instructions:
2586 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2587 static bool hasFPCMov(unsigned X86CC) {
2588   switch (X86CC) {
2589   default:
2590     return false;
2591   case X86::COND_B:
2592   case X86::COND_BE:
2593   case X86::COND_E:
2594   case X86::COND_P:
2595   case X86::COND_A:
2596   case X86::COND_AE:
2597   case X86::COND_NE:
2598   case X86::COND_NP:
2599     return true;
2600   }
2601 }
2602
2603 /// isFPImmLegal - Returns true if the target can instruction select the
2604 /// specified FP immediate natively. If false, the legalizer will
2605 /// materialize the FP immediate as a load from a constant pool.
2606 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2607   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
2608     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
2609       return true;
2610   }
2611   return false;
2612 }
2613
2614 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2615 /// the specified range (L, H].
2616 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2617   return (Val < 0) || (Val >= Low && Val < Hi);
2618 }
2619
2620 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2621 /// specified value.
2622 static bool isUndefOrEqual(int Val, int CmpVal) {
2623   if (Val < 0 || Val == CmpVal)
2624     return true;
2625   return false;
2626 }
2627
2628 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2629 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
2630 /// the second operand.
2631 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2632   if (VT == MVT::v4f32 || VT == MVT::v4i32 || VT == MVT::v4i16)
2633     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2634   if (VT == MVT::v2f64 || VT == MVT::v2i64)
2635     return (Mask[0] < 2 && Mask[1] < 2);
2636   return false;
2637 }
2638
2639 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2640   SmallVector<int, 8> M;
2641   N->getMask(M);
2642   return ::isPSHUFDMask(M, N->getValueType(0));
2643 }
2644
2645 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2646 /// is suitable for input to PSHUFHW.
2647 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2648   if (VT != MVT::v8i16)
2649     return false;
2650
2651   // Lower quadword copied in order or undef.
2652   for (int i = 0; i != 4; ++i)
2653     if (Mask[i] >= 0 && Mask[i] != i)
2654       return false;
2655
2656   // Upper quadword shuffled.
2657   for (int i = 4; i != 8; ++i)
2658     if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2659       return false;
2660
2661   return true;
2662 }
2663
2664 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2665   SmallVector<int, 8> M;
2666   N->getMask(M);
2667   return ::isPSHUFHWMask(M, N->getValueType(0));
2668 }
2669
2670 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
2671 /// is suitable for input to PSHUFLW.
2672 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2673   if (VT != MVT::v8i16)
2674     return false;
2675
2676   // Upper quadword copied in order.
2677   for (int i = 4; i != 8; ++i)
2678     if (Mask[i] >= 0 && Mask[i] != i)
2679       return false;
2680
2681   // Lower quadword shuffled.
2682   for (int i = 0; i != 4; ++i)
2683     if (Mask[i] >= 4)
2684       return false;
2685
2686   return true;
2687 }
2688
2689 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
2690   SmallVector<int, 8> M;
2691   N->getMask(M);
2692   return ::isPSHUFLWMask(M, N->getValueType(0));
2693 }
2694
2695 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
2696 /// is suitable for input to PALIGNR.
2697 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
2698                           bool hasSSSE3) {
2699   int i, e = VT.getVectorNumElements();
2700   
2701   // Do not handle v2i64 / v2f64 shuffles with palignr.
2702   if (e < 4 || !hasSSSE3)
2703     return false;
2704   
2705   for (i = 0; i != e; ++i)
2706     if (Mask[i] >= 0)
2707       break;
2708   
2709   // All undef, not a palignr.
2710   if (i == e)
2711     return false;
2712
2713   // Determine if it's ok to perform a palignr with only the LHS, since we
2714   // don't have access to the actual shuffle elements to see if RHS is undef.
2715   bool Unary = Mask[i] < (int)e;
2716   bool NeedsUnary = false;
2717
2718   int s = Mask[i] - i;
2719   
2720   // Check the rest of the elements to see if they are consecutive.
2721   for (++i; i != e; ++i) {
2722     int m = Mask[i];
2723     if (m < 0) 
2724       continue;
2725     
2726     Unary = Unary && (m < (int)e);
2727     NeedsUnary = NeedsUnary || (m < s);
2728
2729     if (NeedsUnary && !Unary)
2730       return false;
2731     if (Unary && m != ((s+i) & (e-1)))
2732       return false;
2733     if (!Unary && m != (s+i))
2734       return false;
2735   }
2736   return true;
2737 }
2738
2739 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
2740   SmallVector<int, 8> M;
2741   N->getMask(M);
2742   return ::isPALIGNRMask(M, N->getValueType(0), true);
2743 }
2744
2745 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2746 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2747 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2748   int NumElems = VT.getVectorNumElements();
2749   if (NumElems != 2 && NumElems != 4)
2750     return false;
2751
2752   int Half = NumElems / 2;
2753   for (int i = 0; i < Half; ++i)
2754     if (!isUndefOrInRange(Mask[i], 0, NumElems))
2755       return false;
2756   for (int i = Half; i < NumElems; ++i)
2757     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2758       return false;
2759
2760   return true;
2761 }
2762
2763 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
2764   SmallVector<int, 8> M;
2765   N->getMask(M);
2766   return ::isSHUFPMask(M, N->getValueType(0));
2767 }
2768
2769 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2770 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2771 /// half elements to come from vector 1 (which would equal the dest.) and
2772 /// the upper half to come from vector 2.
2773 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2774   int NumElems = VT.getVectorNumElements();
2775
2776   if (NumElems != 2 && NumElems != 4)
2777     return false;
2778
2779   int Half = NumElems / 2;
2780   for (int i = 0; i < Half; ++i)
2781     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2782       return false;
2783   for (int i = Half; i < NumElems; ++i)
2784     if (!isUndefOrInRange(Mask[i], 0, NumElems))
2785       return false;
2786   return true;
2787 }
2788
2789 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
2790   SmallVector<int, 8> M;
2791   N->getMask(M);
2792   return isCommutedSHUFPMask(M, N->getValueType(0));
2793 }
2794
2795 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2796 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2797 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
2798   if (N->getValueType(0).getVectorNumElements() != 4)
2799     return false;
2800
2801   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2802   return isUndefOrEqual(N->getMaskElt(0), 6) &&
2803          isUndefOrEqual(N->getMaskElt(1), 7) &&
2804          isUndefOrEqual(N->getMaskElt(2), 2) &&
2805          isUndefOrEqual(N->getMaskElt(3), 3);
2806 }
2807
2808 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2809 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2810 /// <2, 3, 2, 3>
2811 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
2812   unsigned NumElems = N->getValueType(0).getVectorNumElements();
2813   
2814   if (NumElems != 4)
2815     return false;
2816   
2817   return isUndefOrEqual(N->getMaskElt(0), 2) &&
2818   isUndefOrEqual(N->getMaskElt(1), 3) &&
2819   isUndefOrEqual(N->getMaskElt(2), 2) &&
2820   isUndefOrEqual(N->getMaskElt(3), 3);
2821 }
2822
2823 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2824 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2825 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
2826   unsigned NumElems = N->getValueType(0).getVectorNumElements();
2827
2828   if (NumElems != 2 && NumElems != 4)
2829     return false;
2830
2831   for (unsigned i = 0; i < NumElems/2; ++i)
2832     if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
2833       return false;
2834
2835   for (unsigned i = NumElems/2; i < NumElems; ++i)
2836     if (!isUndefOrEqual(N->getMaskElt(i), i))
2837       return false;
2838
2839   return true;
2840 }
2841
2842 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
2843 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
2844 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
2845   unsigned NumElems = N->getValueType(0).getVectorNumElements();
2846
2847   if (NumElems != 2 && NumElems != 4)
2848     return false;
2849
2850   for (unsigned i = 0; i < NumElems/2; ++i)
2851     if (!isUndefOrEqual(N->getMaskElt(i), i))
2852       return false;
2853
2854   for (unsigned i = 0; i < NumElems/2; ++i)
2855     if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
2856       return false;
2857
2858   return true;
2859 }
2860
2861 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2862 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2863 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
2864                          bool V2IsSplat = false) {
2865   int NumElts = VT.getVectorNumElements();
2866   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2867     return false;
2868
2869   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2870     int BitI  = Mask[i];
2871     int BitI1 = Mask[i+1];
2872     if (!isUndefOrEqual(BitI, j))
2873       return false;
2874     if (V2IsSplat) {
2875       if (!isUndefOrEqual(BitI1, NumElts))
2876         return false;
2877     } else {
2878       if (!isUndefOrEqual(BitI1, j + NumElts))
2879         return false;
2880     }
2881   }
2882   return true;
2883 }
2884
2885 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2886   SmallVector<int, 8> M;
2887   N->getMask(M);
2888   return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
2889 }
2890
2891 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2892 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2893 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
2894                          bool V2IsSplat = false) {
2895   int NumElts = VT.getVectorNumElements();
2896   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2897     return false;
2898
2899   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2900     int BitI  = Mask[i];
2901     int BitI1 = Mask[i+1];
2902     if (!isUndefOrEqual(BitI, j + NumElts/2))
2903       return false;
2904     if (V2IsSplat) {
2905       if (isUndefOrEqual(BitI1, NumElts))
2906         return false;
2907     } else {
2908       if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2909         return false;
2910     }
2911   }
2912   return true;
2913 }
2914
2915 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2916   SmallVector<int, 8> M;
2917   N->getMask(M);
2918   return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
2919 }
2920
2921 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2922 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2923 /// <0, 0, 1, 1>
2924 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
2925   int NumElems = VT.getVectorNumElements();
2926   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2927     return false;
2928
2929   for (int i = 0, j = 0; i != NumElems; i += 2, ++j) {
2930     int BitI  = Mask[i];
2931     int BitI1 = Mask[i+1];
2932     if (!isUndefOrEqual(BitI, j))
2933       return false;
2934     if (!isUndefOrEqual(BitI1, j))
2935       return false;
2936   }
2937   return true;
2938 }
2939
2940 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
2941   SmallVector<int, 8> M;
2942   N->getMask(M);
2943   return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
2944 }
2945
2946 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2947 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2948 /// <2, 2, 3, 3>
2949 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
2950   int NumElems = VT.getVectorNumElements();
2951   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2952     return false;
2953
2954   for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2955     int BitI  = Mask[i];
2956     int BitI1 = Mask[i+1];
2957     if (!isUndefOrEqual(BitI, j))
2958       return false;
2959     if (!isUndefOrEqual(BitI1, j))
2960       return false;
2961   }
2962   return true;
2963 }
2964
2965 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
2966   SmallVector<int, 8> M;
2967   N->getMask(M);
2968   return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
2969 }
2970
2971 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2972 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2973 /// MOVSD, and MOVD, i.e. setting the lowest element.
2974 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2975   if (VT.getVectorElementType().getSizeInBits() < 32)
2976     return false;
2977
2978   int NumElts = VT.getVectorNumElements();
2979
2980   if (!isUndefOrEqual(Mask[0], NumElts))
2981     return false;
2982
2983   for (int i = 1; i < NumElts; ++i)
2984     if (!isUndefOrEqual(Mask[i], i))
2985       return false;
2986
2987   return true;
2988 }
2989
2990 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
2991   SmallVector<int, 8> M;
2992   N->getMask(M);
2993   return ::isMOVLMask(M, N->getValueType(0));
2994 }
2995
2996 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2997 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
2998 /// element of vector 2 and the other elements to come from vector 1 in order.
2999 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3000                                bool V2IsSplat = false, bool V2IsUndef = false) {
3001   int NumOps = VT.getVectorNumElements();
3002   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3003     return false;
3004
3005   if (!isUndefOrEqual(Mask[0], 0))
3006     return false;
3007
3008   for (int i = 1; i < NumOps; ++i)
3009     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3010           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3011           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3012       return false;
3013
3014   return true;
3015 }
3016
3017 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3018                            bool V2IsUndef = false) {
3019   SmallVector<int, 8> M;
3020   N->getMask(M);
3021   return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3022 }
3023
3024 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3025 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3026 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
3027   if (N->getValueType(0).getVectorNumElements() != 4)
3028     return false;
3029
3030   // Expect 1, 1, 3, 3
3031   for (unsigned i = 0; i < 2; ++i) {
3032     int Elt = N->getMaskElt(i);
3033     if (Elt >= 0 && Elt != 1)
3034       return false;
3035   }
3036
3037   bool HasHi = false;
3038   for (unsigned i = 2; i < 4; ++i) {
3039     int Elt = N->getMaskElt(i);
3040     if (Elt >= 0 && Elt != 3)
3041       return false;
3042     if (Elt == 3)
3043       HasHi = true;
3044   }
3045   // Don't use movshdup if it can be done with a shufps.
3046   // FIXME: verify that matching u, u, 3, 3 is what we want.
3047   return HasHi;
3048 }
3049
3050 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3051 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3052 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
3053   if (N->getValueType(0).getVectorNumElements() != 4)
3054     return false;
3055
3056   // Expect 0, 0, 2, 2
3057   for (unsigned i = 0; i < 2; ++i)
3058     if (N->getMaskElt(i) > 0)
3059       return false;
3060
3061   bool HasHi = false;
3062   for (unsigned i = 2; i < 4; ++i) {
3063     int Elt = N->getMaskElt(i);
3064     if (Elt >= 0 && Elt != 2)
3065       return false;
3066     if (Elt == 2)
3067       HasHi = true;
3068   }
3069   // Don't use movsldup if it can be done with a shufps.
3070   return HasHi;
3071 }
3072
3073 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3074 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3075 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3076   int e = N->getValueType(0).getVectorNumElements() / 2;
3077
3078   for (int i = 0; i < e; ++i)
3079     if (!isUndefOrEqual(N->getMaskElt(i), i))
3080       return false;
3081   for (int i = 0; i < e; ++i)
3082     if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3083       return false;
3084   return true;
3085 }
3086
3087 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3088 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3089 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3090   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3091   int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3092
3093   unsigned Shift = (NumOperands == 4) ? 2 : 1;
3094   unsigned Mask = 0;
3095   for (int i = 0; i < NumOperands; ++i) {
3096     int Val = SVOp->getMaskElt(NumOperands-i-1);
3097     if (Val < 0) Val = 0;
3098     if (Val >= NumOperands) Val -= NumOperands;
3099     Mask |= Val;
3100     if (i != NumOperands - 1)
3101       Mask <<= Shift;
3102   }
3103   return Mask;
3104 }
3105
3106 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3107 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3108 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3109   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3110   unsigned Mask = 0;
3111   // 8 nodes, but we only care about the last 4.
3112   for (unsigned i = 7; i >= 4; --i) {
3113     int Val = SVOp->getMaskElt(i);
3114     if (Val >= 0)
3115       Mask |= (Val - 4);
3116     if (i != 4)
3117       Mask <<= 2;
3118   }
3119   return Mask;
3120 }
3121
3122 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3123 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3124 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3125   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3126   unsigned Mask = 0;
3127   // 8 nodes, but we only care about the first 4.
3128   for (int i = 3; i >= 0; --i) {
3129     int Val = SVOp->getMaskElt(i);
3130     if (Val >= 0)
3131       Mask |= Val;
3132     if (i != 0)
3133       Mask <<= 2;
3134   }
3135   return Mask;
3136 }
3137
3138 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3139 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3140 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3141   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3142   EVT VVT = N->getValueType(0);
3143   unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3144   int Val = 0;
3145
3146   unsigned i, e;
3147   for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3148     Val = SVOp->getMaskElt(i);
3149     if (Val >= 0)
3150       break;
3151   }
3152   return (Val - i) * EltSize;
3153 }
3154
3155 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3156 /// constant +0.0.
3157 bool X86::isZeroNode(SDValue Elt) {
3158   return ((isa<ConstantSDNode>(Elt) &&
3159            cast<ConstantSDNode>(Elt)->getZExtValue() == 0) ||
3160           (isa<ConstantFPSDNode>(Elt) &&
3161            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3162 }
3163
3164 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3165 /// their permute mask.
3166 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3167                                     SelectionDAG &DAG) {
3168   EVT VT = SVOp->getValueType(0);
3169   unsigned NumElems = VT.getVectorNumElements();
3170   SmallVector<int, 8> MaskVec;
3171
3172   for (unsigned i = 0; i != NumElems; ++i) {
3173     int idx = SVOp->getMaskElt(i);
3174     if (idx < 0)
3175       MaskVec.push_back(idx);
3176     else if (idx < (int)NumElems)
3177       MaskVec.push_back(idx + NumElems);
3178     else
3179       MaskVec.push_back(idx - NumElems);
3180   }
3181   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3182                               SVOp->getOperand(0), &MaskVec[0]);
3183 }
3184
3185 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3186 /// the two vector operands have swapped position.
3187 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3188   unsigned NumElems = VT.getVectorNumElements();
3189   for (unsigned i = 0; i != NumElems; ++i) {
3190     int idx = Mask[i];
3191     if (idx < 0)
3192       continue;
3193     else if (idx < (int)NumElems)
3194       Mask[i] = idx + NumElems;
3195     else
3196       Mask[i] = idx - NumElems;
3197   }
3198 }
3199
3200 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3201 /// match movhlps. The lower half elements should come from upper half of
3202 /// V1 (and in order), and the upper half elements should come from the upper
3203 /// half of V2 (and in order).
3204 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3205   if (Op->getValueType(0).getVectorNumElements() != 4)
3206     return false;
3207   for (unsigned i = 0, e = 2; i != e; ++i)
3208     if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3209       return false;
3210   for (unsigned i = 2; i != 4; ++i)
3211     if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3212       return false;
3213   return true;
3214 }
3215
3216 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3217 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3218 /// required.
3219 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3220   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3221     return false;
3222   N = N->getOperand(0).getNode();
3223   if (!ISD::isNON_EXTLoad(N))
3224     return false;
3225   if (LD)
3226     *LD = cast<LoadSDNode>(N);
3227   return true;
3228 }
3229
3230 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3231 /// match movlp{s|d}. The lower half elements should come from lower half of
3232 /// V1 (and in order), and the upper half elements should come from the upper
3233 /// half of V2 (and in order). And since V1 will become the source of the
3234 /// MOVLP, it must be either a vector load or a scalar load to vector.
3235 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3236                                ShuffleVectorSDNode *Op) {
3237   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3238     return false;
3239   // Is V2 is a vector load, don't do this transformation. We will try to use
3240   // load folding shufps op.
3241   if (ISD::isNON_EXTLoad(V2))
3242     return false;
3243
3244   unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3245
3246   if (NumElems != 2 && NumElems != 4)
3247     return false;
3248   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3249     if (!isUndefOrEqual(Op->getMaskElt(i), i))
3250       return false;
3251   for (unsigned i = NumElems/2; i != NumElems; ++i)
3252     if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3253       return false;
3254   return true;
3255 }
3256
3257 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3258 /// all the same.
3259 static bool isSplatVector(SDNode *N) {
3260   if (N->getOpcode() != ISD::BUILD_VECTOR)
3261     return false;
3262
3263   SDValue SplatValue = N->getOperand(0);
3264   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3265     if (N->getOperand(i) != SplatValue)
3266       return false;
3267   return true;
3268 }
3269
3270 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3271 /// to an zero vector.
3272 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3273 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3274   SDValue V1 = N->getOperand(0);
3275   SDValue V2 = N->getOperand(1);
3276   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3277   for (unsigned i = 0; i != NumElems; ++i) {
3278     int Idx = N->getMaskElt(i);
3279     if (Idx >= (int)NumElems) {
3280       unsigned Opc = V2.getOpcode();
3281       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3282         continue;
3283       if (Opc != ISD::BUILD_VECTOR ||
3284           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3285         return false;
3286     } else if (Idx >= 0) {
3287       unsigned Opc = V1.getOpcode();
3288       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3289         continue;
3290       if (Opc != ISD::BUILD_VECTOR ||
3291           !X86::isZeroNode(V1.getOperand(Idx)))
3292         return false;
3293     }
3294   }
3295   return true;
3296 }
3297
3298 /// getZeroVector - Returns a vector of specified type with all zero elements.
3299 ///
3300 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3301                              DebugLoc dl) {
3302   assert(VT.isVector() && "Expected a vector type");
3303
3304   // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3305   // type.  This ensures they get CSE'd.
3306   SDValue Vec;
3307   if (VT.getSizeInBits() == 64) { // MMX
3308     SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3309     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3310   } else if (HasSSE2) {  // SSE2
3311     SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3312     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3313   } else { // SSE1
3314     SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3315     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3316   }
3317   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3318 }
3319
3320 /// getOnesVector - Returns a vector of specified type with all bits set.
3321 ///
3322 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3323   assert(VT.isVector() && "Expected a vector type");
3324
3325   // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3326   // type.  This ensures they get CSE'd.
3327   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3328   SDValue Vec;
3329   if (VT.getSizeInBits() == 64)  // MMX
3330     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3331   else                                              // SSE
3332     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3333   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3334 }
3335
3336
3337 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3338 /// that point to V2 points to its first element.
3339 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3340   EVT VT = SVOp->getValueType(0);
3341   unsigned NumElems = VT.getVectorNumElements();
3342
3343   bool Changed = false;
3344   SmallVector<int, 8> MaskVec;
3345   SVOp->getMask(MaskVec);
3346
3347   for (unsigned i = 0; i != NumElems; ++i) {
3348     if (MaskVec[i] > (int)NumElems) {
3349       MaskVec[i] = NumElems;
3350       Changed = true;
3351     }
3352   }
3353   if (Changed)
3354     return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3355                                 SVOp->getOperand(1), &MaskVec[0]);
3356   return SDValue(SVOp, 0);
3357 }
3358
3359 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3360 /// operation of specified width.
3361 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3362                        SDValue V2) {
3363   unsigned NumElems = VT.getVectorNumElements();
3364   SmallVector<int, 8> Mask;
3365   Mask.push_back(NumElems);
3366   for (unsigned i = 1; i != NumElems; ++i)
3367     Mask.push_back(i);
3368   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3369 }
3370
3371 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3372 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3373                           SDValue V2) {
3374   unsigned NumElems = VT.getVectorNumElements();
3375   SmallVector<int, 8> Mask;
3376   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3377     Mask.push_back(i);
3378     Mask.push_back(i + NumElems);
3379   }
3380   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3381 }
3382
3383 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3384 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3385                           SDValue V2) {
3386   unsigned NumElems = VT.getVectorNumElements();
3387   unsigned Half = NumElems/2;
3388   SmallVector<int, 8> Mask;
3389   for (unsigned i = 0; i != Half; ++i) {
3390     Mask.push_back(i + Half);
3391     Mask.push_back(i + NumElems + Half);
3392   }
3393   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3394 }
3395
3396 /// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
3397 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG,
3398                             bool HasSSE2) {
3399   if (SV->getValueType(0).getVectorNumElements() <= 4)
3400     return SDValue(SV, 0);
3401
3402   EVT PVT = MVT::v4f32;
3403   EVT VT = SV->getValueType(0);
3404   DebugLoc dl = SV->getDebugLoc();
3405   SDValue V1 = SV->getOperand(0);
3406   int NumElems = VT.getVectorNumElements();
3407   int EltNo = SV->getSplatIndex();
3408
3409   // unpack elements to the correct location
3410   while (NumElems > 4) {
3411     if (EltNo < NumElems/2) {
3412       V1 = getUnpackl(DAG, dl, VT, V1, V1);
3413     } else {
3414       V1 = getUnpackh(DAG, dl, VT, V1, V1);
3415       EltNo -= NumElems/2;
3416     }
3417     NumElems >>= 1;
3418   }
3419
3420   // Perform the splat.
3421   int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3422   V1 = DAG.getNode(ISD::BIT_CONVERT, dl, PVT, V1);
3423   V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3424   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, V1);
3425 }
3426
3427 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3428 /// vector of zero or undef vector.  This produces a shuffle where the low
3429 /// element of V2 is swizzled into the zero/undef vector, landing at element
3430 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
3431 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3432                                              bool isZero, bool HasSSE2,
3433                                              SelectionDAG &DAG) {
3434   EVT VT = V2.getValueType();
3435   SDValue V1 = isZero
3436     ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3437   unsigned NumElems = VT.getVectorNumElements();
3438   SmallVector<int, 16> MaskVec;
3439   for (unsigned i = 0; i != NumElems; ++i)
3440     // If this is the insertion idx, put the low elt of V2 here.
3441     MaskVec.push_back(i == Idx ? NumElems : i);
3442   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3443 }
3444
3445 /// getNumOfConsecutiveZeros - Return the number of elements in a result of
3446 /// a shuffle that is zero.
3447 static
3448 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, int NumElems,
3449                                   bool Low, SelectionDAG &DAG) {
3450   unsigned NumZeros = 0;
3451   for (int i = 0; i < NumElems; ++i) {
3452     unsigned Index = Low ? i : NumElems-i-1;
3453     int Idx = SVOp->getMaskElt(Index);
3454     if (Idx < 0) {
3455       ++NumZeros;
3456       continue;
3457     }
3458     SDValue Elt = DAG.getShuffleScalarElt(SVOp, Index);
3459     if (Elt.getNode() && X86::isZeroNode(Elt))
3460       ++NumZeros;
3461     else
3462       break;
3463   }
3464   return NumZeros;
3465 }
3466
3467 /// isVectorShift - Returns true if the shuffle can be implemented as a
3468 /// logical left or right shift of a vector.
3469 /// FIXME: split into pslldqi, psrldqi, palignr variants.
3470 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3471                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3472   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
3473
3474   isLeft = true;
3475   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, true, DAG);
3476   if (!NumZeros) {
3477     isLeft = false;
3478     NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, false, DAG);
3479     if (!NumZeros)
3480       return false;
3481   }
3482   bool SeenV1 = false;
3483   bool SeenV2 = false;
3484   for (unsigned i = NumZeros; i < NumElems; ++i) {
3485     unsigned Val = isLeft ? (i - NumZeros) : i;
3486     int Idx_ = SVOp->getMaskElt(isLeft ? i : (i - NumZeros));
3487     if (Idx_ < 0)
3488       continue;
3489     unsigned Idx = (unsigned) Idx_;
3490     if (Idx < NumElems)
3491       SeenV1 = true;
3492     else {
3493       Idx -= NumElems;
3494       SeenV2 = true;
3495     }
3496     if (Idx != Val)
3497       return false;
3498   }
3499   if (SeenV1 && SeenV2)
3500     return false;
3501
3502   ShVal = SeenV1 ? SVOp->getOperand(0) : SVOp->getOperand(1);
3503   ShAmt = NumZeros;
3504   return true;
3505 }
3506
3507
3508 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3509 ///
3510 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3511                                        unsigned NumNonZero, unsigned NumZero,
3512                                        SelectionDAG &DAG,
3513                                        const TargetLowering &TLI) {
3514   if (NumNonZero > 8)
3515     return SDValue();
3516
3517   DebugLoc dl = Op.getDebugLoc();
3518   SDValue V(0, 0);
3519   bool First = true;
3520   for (unsigned i = 0; i < 16; ++i) {
3521     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3522     if (ThisIsNonZero && First) {
3523       if (NumZero)
3524         V = getZeroVector(MVT::v8i16, true, DAG, dl);
3525       else
3526         V = DAG.getUNDEF(MVT::v8i16);
3527       First = false;
3528     }
3529
3530     if ((i & 1) != 0) {
3531       SDValue ThisElt(0, 0), LastElt(0, 0);
3532       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3533       if (LastIsNonZero) {
3534         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
3535                               MVT::i16, Op.getOperand(i-1));
3536       }
3537       if (ThisIsNonZero) {
3538         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
3539         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
3540                               ThisElt, DAG.getConstant(8, MVT::i8));
3541         if (LastIsNonZero)
3542           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
3543       } else
3544         ThisElt = LastElt;
3545
3546       if (ThisElt.getNode())
3547         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
3548                         DAG.getIntPtrConstant(i/2));
3549     }
3550   }
3551
3552   return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V);
3553 }
3554
3555 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3556 ///
3557 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3558                                      unsigned NumNonZero, unsigned NumZero,
3559                                      SelectionDAG &DAG,
3560                                      const TargetLowering &TLI) {
3561   if (NumNonZero > 4)
3562     return SDValue();
3563
3564   DebugLoc dl = Op.getDebugLoc();
3565   SDValue V(0, 0);
3566   bool First = true;
3567   for (unsigned i = 0; i < 8; ++i) {
3568     bool isNonZero = (NonZeros & (1 << i)) != 0;
3569     if (isNonZero) {
3570       if (First) {
3571         if (NumZero)
3572           V = getZeroVector(MVT::v8i16, true, DAG, dl);
3573         else
3574           V = DAG.getUNDEF(MVT::v8i16);
3575         First = false;
3576       }
3577       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
3578                       MVT::v8i16, V, Op.getOperand(i),
3579                       DAG.getIntPtrConstant(i));
3580     }
3581   }
3582
3583   return V;
3584 }
3585
3586 /// getVShift - Return a vector logical shift node.
3587 ///
3588 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
3589                          unsigned NumBits, SelectionDAG &DAG,
3590                          const TargetLowering &TLI, DebugLoc dl) {
3591   bool isMMX = VT.getSizeInBits() == 64;
3592   EVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
3593   unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3594   SrcOp = DAG.getNode(ISD::BIT_CONVERT, dl, ShVT, SrcOp);
3595   return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3596                      DAG.getNode(Opc, dl, ShVT, SrcOp,
3597                              DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3598 }
3599
3600 SDValue
3601 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
3602                                           SelectionDAG &DAG) const {
3603   
3604   // Check if the scalar load can be widened into a vector load. And if
3605   // the address is "base + cst" see if the cst can be "absorbed" into
3606   // the shuffle mask.
3607   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
3608     SDValue Ptr = LD->getBasePtr();
3609     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
3610       return SDValue();
3611     EVT PVT = LD->getValueType(0);
3612     if (PVT != MVT::i32 && PVT != MVT::f32)
3613       return SDValue();
3614
3615     int FI = -1;
3616     int64_t Offset = 0;
3617     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
3618       FI = FINode->getIndex();
3619       Offset = 0;
3620     } else if (Ptr.getOpcode() == ISD::ADD &&
3621                isa<ConstantSDNode>(Ptr.getOperand(1)) &&
3622                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
3623       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
3624       Offset = Ptr.getConstantOperandVal(1);
3625       Ptr = Ptr.getOperand(0);
3626     } else {
3627       return SDValue();
3628     }
3629
3630     SDValue Chain = LD->getChain();
3631     // Make sure the stack object alignment is at least 16.
3632     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3633     if (DAG.InferPtrAlignment(Ptr) < 16) {
3634       if (MFI->isFixedObjectIndex(FI)) {
3635         // Can't change the alignment. FIXME: It's possible to compute
3636         // the exact stack offset and reference FI + adjust offset instead.
3637         // If someone *really* cares about this. That's the way to implement it.
3638         return SDValue();
3639       } else {
3640         MFI->setObjectAlignment(FI, 16);
3641       }
3642     }
3643
3644     // (Offset % 16) must be multiple of 4. Then address is then
3645     // Ptr + (Offset & ~15).
3646     if (Offset < 0)
3647       return SDValue();
3648     if ((Offset % 16) & 3)
3649       return SDValue();
3650     int64_t StartOffset = Offset & ~15;
3651     if (StartOffset)
3652       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
3653                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
3654
3655     int EltNo = (Offset - StartOffset) >> 2;
3656     int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
3657     EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
3658     SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,LD->getSrcValue(),0,
3659                              false, false, 0);
3660     // Canonicalize it to a v4i32 shuffle.
3661     V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32, V1);
3662     return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3663                        DAG.getVectorShuffle(MVT::v4i32, dl, V1,
3664                                             DAG.getUNDEF(MVT::v4i32), &Mask[0]));
3665   }
3666
3667   return SDValue();
3668 }
3669
3670 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a 
3671 /// vector of type 'VT', see if the elements can be replaced by a single large 
3672 /// load which has the same value as a build_vector whose operands are 'elts'.
3673 ///
3674 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
3675 /// 
3676 /// FIXME: we'd also like to handle the case where the last elements are zero
3677 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
3678 /// There's even a handy isZeroNode for that purpose.
3679 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
3680                                         DebugLoc &dl, SelectionDAG &DAG) {
3681   EVT EltVT = VT.getVectorElementType();
3682   unsigned NumElems = Elts.size();
3683   
3684   LoadSDNode *LDBase = NULL;
3685   unsigned LastLoadedElt = -1U;
3686   
3687   // For each element in the initializer, see if we've found a load or an undef.
3688   // If we don't find an initial load element, or later load elements are 
3689   // non-consecutive, bail out.
3690   for (unsigned i = 0; i < NumElems; ++i) {
3691     SDValue Elt = Elts[i];
3692     
3693     if (!Elt.getNode() ||
3694         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
3695       return SDValue();
3696     if (!LDBase) {
3697       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
3698         return SDValue();
3699       LDBase = cast<LoadSDNode>(Elt.getNode());
3700       LastLoadedElt = i;
3701       continue;
3702     }
3703     if (Elt.getOpcode() == ISD::UNDEF)
3704       continue;
3705
3706     LoadSDNode *LD = cast<LoadSDNode>(Elt);
3707     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
3708       return SDValue();
3709     LastLoadedElt = i;
3710   }
3711
3712   // If we have found an entire vector of loads and undefs, then return a large
3713   // load of the entire vector width starting at the base pointer.  If we found
3714   // consecutive loads for the low half, generate a vzext_load node.
3715   if (LastLoadedElt == NumElems - 1) {
3716     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
3717       return DAG.getLoad(VT, dl, LDBase->getChain(), LDBase->getBasePtr(),
3718                          LDBase->getSrcValue(), LDBase->getSrcValueOffset(),
3719                          LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
3720     return DAG.getLoad(VT, dl, LDBase->getChain(), LDBase->getBasePtr(),
3721                        LDBase->getSrcValue(), LDBase->getSrcValueOffset(),
3722                        LDBase->isVolatile(), LDBase->isNonTemporal(),
3723                        LDBase->getAlignment());
3724   } else if (NumElems == 4 && LastLoadedElt == 1) {
3725     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
3726     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
3727     SDValue ResNode = DAG.getNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2);
3728     return DAG.getNode(ISD::BIT_CONVERT, dl, VT, ResNode);
3729   }
3730   return SDValue();
3731 }
3732
3733 SDValue
3734 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
3735   DebugLoc dl = Op.getDebugLoc();
3736   // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3737   if (ISD::isBuildVectorAllZeros(Op.getNode())
3738       || ISD::isBuildVectorAllOnes(Op.getNode())) {
3739     // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3740     // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3741     // eliminated on x86-32 hosts.
3742     if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3743       return Op;
3744
3745     if (ISD::isBuildVectorAllOnes(Op.getNode()))
3746       return getOnesVector(Op.getValueType(), DAG, dl);
3747     return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
3748   }
3749
3750   EVT VT = Op.getValueType();
3751   EVT ExtVT = VT.getVectorElementType();
3752   unsigned EVTBits = ExtVT.getSizeInBits();
3753
3754   unsigned NumElems = Op.getNumOperands();
3755   unsigned NumZero  = 0;
3756   unsigned NumNonZero = 0;
3757   unsigned NonZeros = 0;
3758   bool IsAllConstants = true;
3759   SmallSet<SDValue, 8> Values;
3760   for (unsigned i = 0; i < NumElems; ++i) {
3761     SDValue Elt = Op.getOperand(i);
3762     if (Elt.getOpcode() == ISD::UNDEF)
3763       continue;
3764     Values.insert(Elt);
3765     if (Elt.getOpcode() != ISD::Constant &&
3766         Elt.getOpcode() != ISD::ConstantFP)
3767       IsAllConstants = false;
3768     if (X86::isZeroNode(Elt))
3769       NumZero++;
3770     else {
3771       NonZeros |= (1 << i);
3772       NumNonZero++;
3773     }
3774   }
3775
3776   if (NumNonZero == 0) {
3777     // All undef vector. Return an UNDEF.  All zero vectors were handled above.
3778     return DAG.getUNDEF(VT);
3779   }
3780
3781   // Special case for single non-zero, non-undef, element.
3782   if (NumNonZero == 1) {
3783     unsigned Idx = CountTrailingZeros_32(NonZeros);
3784     SDValue Item = Op.getOperand(Idx);
3785
3786     // If this is an insertion of an i64 value on x86-32, and if the top bits of
3787     // the value are obviously zero, truncate the value to i32 and do the
3788     // insertion that way.  Only do this if the value is non-constant or if the
3789     // value is a constant being inserted into element 0.  It is cheaper to do
3790     // a constant pool load than it is to do a movd + shuffle.
3791     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
3792         (!IsAllConstants || Idx == 0)) {
3793       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3794         // Handle MMX and SSE both.
3795         EVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3796         unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
3797
3798         // Truncate the value (which may itself be a constant) to i32, and
3799         // convert it to a vector with movd (S2V+shuffle to zero extend).
3800         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
3801         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
3802         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3803                                            Subtarget->hasSSE2(), DAG);
3804
3805         // Now we have our 32-bit value zero extended in the low element of
3806         // a vector.  If Idx != 0, swizzle it into place.
3807         if (Idx != 0) {
3808           SmallVector<int, 4> Mask;
3809           Mask.push_back(Idx);
3810           for (unsigned i = 1; i != VecElts; ++i)
3811             Mask.push_back(i);
3812           Item = DAG.getVectorShuffle(VecVT, dl, Item,
3813                                       DAG.getUNDEF(Item.getValueType()),
3814                                       &Mask[0]);
3815         }
3816         return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Item);
3817       }
3818     }
3819
3820     // If we have a constant or non-constant insertion into the low element of
3821     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3822     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
3823     // depending on what the source datatype is.
3824     if (Idx == 0) {
3825       if (NumZero == 0) {
3826         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3827       } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
3828           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
3829         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3830         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3831         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
3832                                            DAG);
3833       } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
3834         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
3835         EVT MiddleVT = VT.getSizeInBits() == 64 ? MVT::v2i32 : MVT::v4i32;
3836         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
3837         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3838                                            Subtarget->hasSSE2(), DAG);
3839         return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Item);
3840       }
3841     }
3842
3843     // Is it a vector logical left shift?
3844     if (NumElems == 2 && Idx == 1 &&
3845         X86::isZeroNode(Op.getOperand(0)) &&
3846         !X86::isZeroNode(Op.getOperand(1))) {
3847       unsigned NumBits = VT.getSizeInBits();
3848       return getVShift(true, VT,
3849                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
3850                                    VT, Op.getOperand(1)),
3851                        NumBits/2, DAG, *this, dl);
3852     }
3853
3854     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3855       return SDValue();
3856
3857     // Otherwise, if this is a vector with i32 or f32 elements, and the element
3858     // is a non-constant being inserted into an element other than the low one,
3859     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
3860     // movd/movss) to move this into the low element, then shuffle it into
3861     // place.
3862     if (EVTBits == 32) {
3863       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3864
3865       // Turn it into a shuffle of zero and zero-extended scalar to vector.
3866       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3867                                          Subtarget->hasSSE2(), DAG);
3868       SmallVector<int, 8> MaskVec;
3869       for (unsigned i = 0; i < NumElems; i++)
3870         MaskVec.push_back(i == Idx ? 0 : 1);
3871       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
3872     }
3873   }
3874
3875   // Splat is obviously ok. Let legalizer expand it to a shuffle.
3876   if (Values.size() == 1) {
3877     if (EVTBits == 32) {
3878       // Instead of a shuffle like this:
3879       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
3880       // Check if it's possible to issue this instead.
3881       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
3882       unsigned Idx = CountTrailingZeros_32(NonZeros);
3883       SDValue Item = Op.getOperand(Idx);
3884       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
3885         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
3886     }
3887     return SDValue();
3888   }
3889
3890   // A vector full of immediates; various special cases are already
3891   // handled, so this is best done with a single constant-pool load.
3892   if (IsAllConstants)
3893     return SDValue();
3894
3895   // Let legalizer expand 2-wide build_vectors.
3896   if (EVTBits == 64) {
3897     if (NumNonZero == 1) {
3898       // One half is zero or undef.
3899       unsigned Idx = CountTrailingZeros_32(NonZeros);
3900       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
3901                                  Op.getOperand(Idx));
3902       return getShuffleVectorZeroOrUndef(V2, Idx, true,
3903                                          Subtarget->hasSSE2(), DAG);
3904     }
3905     return SDValue();
3906   }
3907
3908   // If element VT is < 32 bits, convert it to inserts into a zero vector.
3909   if (EVTBits == 8 && NumElems == 16) {
3910     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3911                                         *this);
3912     if (V.getNode()) return V;
3913   }
3914
3915   if (EVTBits == 16 && NumElems == 8) {
3916     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3917                                         *this);
3918     if (V.getNode()) return V;
3919   }
3920
3921   // If element VT is == 32 bits, turn it into a number of shuffles.
3922   SmallVector<SDValue, 8> V;
3923   V.resize(NumElems);
3924   if (NumElems == 4 && NumZero > 0) {
3925     for (unsigned i = 0; i < 4; ++i) {
3926       bool isZero = !(NonZeros & (1 << i));
3927       if (isZero)
3928         V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
3929       else
3930         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3931     }
3932
3933     for (unsigned i = 0; i < 2; ++i) {
3934       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3935         default: break;
3936         case 0:
3937           V[i] = V[i*2];  // Must be a zero vector.
3938           break;
3939         case 1:
3940           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
3941           break;
3942         case 2:
3943           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
3944           break;
3945         case 3:
3946           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
3947           break;
3948       }
3949     }
3950
3951     SmallVector<int, 8> MaskVec;
3952     bool Reverse = (NonZeros & 0x3) == 2;
3953     for (unsigned i = 0; i < 2; ++i)
3954       MaskVec.push_back(Reverse ? 1-i : i);
3955     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3956     for (unsigned i = 0; i < 2; ++i)
3957       MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
3958     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
3959   }
3960
3961   if (Values.size() > 1 && VT.getSizeInBits() == 128) {
3962     // Check for a build vector of consecutive loads.
3963     for (unsigned i = 0; i < NumElems; ++i)
3964       V[i] = Op.getOperand(i);
3965     
3966     // Check for elements which are consecutive loads.
3967     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
3968     if (LD.getNode())
3969       return LD;
3970     
3971     // For SSE 4.1, use inserts into undef.  
3972     if (getSubtarget()->hasSSE41()) {
3973       V[0] = DAG.getUNDEF(VT);
3974       for (unsigned i = 0; i < NumElems; ++i)
3975         if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
3976           V[0] = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, V[0],
3977                              Op.getOperand(i), DAG.getIntPtrConstant(i));
3978       return V[0];
3979     }
3980     
3981     // Otherwise, expand into a number of unpckl*
3982     // e.g. for v4f32
3983     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3984     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3985     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
3986     for (unsigned i = 0; i < NumElems; ++i)
3987       V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3988     NumElems >>= 1;
3989     while (NumElems != 0) {
3990       for (unsigned i = 0; i < NumElems; ++i)
3991         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + NumElems]);
3992       NumElems >>= 1;
3993     }
3994     return V[0];
3995   }
3996   return SDValue();
3997 }
3998
3999 SDValue
4000 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
4001   // We support concatenate two MMX registers and place them in a MMX
4002   // register.  This is better than doing a stack convert.
4003   DebugLoc dl = Op.getDebugLoc();
4004   EVT ResVT = Op.getValueType();
4005   assert(Op.getNumOperands() == 2);
4006   assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
4007          ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
4008   int Mask[2];
4009   SDValue InVec = DAG.getNode(ISD::BIT_CONVERT,dl, MVT::v1i64, Op.getOperand(0));
4010   SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4011   InVec = Op.getOperand(1);
4012   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4013     unsigned NumElts = ResVT.getVectorNumElements();
4014     VecOp = DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
4015     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
4016                        InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
4017   } else {
4018     InVec = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v1i64, InVec);
4019     SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4020     Mask[0] = 0; Mask[1] = 2;
4021     VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
4022   }
4023   return DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
4024 }
4025
4026 // v8i16 shuffles - Prefer shuffles in the following order:
4027 // 1. [all]   pshuflw, pshufhw, optional move
4028 // 2. [ssse3] 1 x pshufb
4029 // 3. [ssse3] 2 x pshufb + 1 x por
4030 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
4031 static
4032 SDValue LowerVECTOR_SHUFFLEv8i16(ShuffleVectorSDNode *SVOp,
4033                                  SelectionDAG &DAG,
4034                                  const X86TargetLowering &TLI) {
4035   SDValue V1 = SVOp->getOperand(0);
4036   SDValue V2 = SVOp->getOperand(1);
4037   DebugLoc dl = SVOp->getDebugLoc();
4038   SmallVector<int, 8> MaskVals;
4039
4040   // Determine if more than 1 of the words in each of the low and high quadwords
4041   // of the result come from the same quadword of one of the two inputs.  Undef
4042   // mask values count as coming from any quadword, for better codegen.
4043   SmallVector<unsigned, 4> LoQuad(4);
4044   SmallVector<unsigned, 4> HiQuad(4);
4045   BitVector InputQuads(4);
4046   for (unsigned i = 0; i < 8; ++i) {
4047     SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
4048     int EltIdx = SVOp->getMaskElt(i);
4049     MaskVals.push_back(EltIdx);
4050     if (EltIdx < 0) {
4051       ++Quad[0];
4052       ++Quad[1];
4053       ++Quad[2];
4054       ++Quad[3];
4055       continue;
4056     }
4057     ++Quad[EltIdx / 4];
4058     InputQuads.set(EltIdx / 4);
4059   }
4060
4061   int BestLoQuad = -1;
4062   unsigned MaxQuad = 1;
4063   for (unsigned i = 0; i < 4; ++i) {
4064     if (LoQuad[i] > MaxQuad) {
4065       BestLoQuad = i;
4066       MaxQuad = LoQuad[i];
4067     }
4068   }
4069
4070   int BestHiQuad = -1;
4071   MaxQuad = 1;
4072   for (unsigned i = 0; i < 4; ++i) {
4073     if (HiQuad[i] > MaxQuad) {
4074       BestHiQuad = i;
4075       MaxQuad = HiQuad[i];
4076     }
4077   }
4078
4079   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
4080   // of the two input vectors, shuffle them into one input vector so only a
4081   // single pshufb instruction is necessary. If There are more than 2 input
4082   // quads, disable the next transformation since it does not help SSSE3.
4083   bool V1Used = InputQuads[0] || InputQuads[1];
4084   bool V2Used = InputQuads[2] || InputQuads[3];
4085   if (TLI.getSubtarget()->hasSSSE3()) {
4086     if (InputQuads.count() == 2 && V1Used && V2Used) {
4087       BestLoQuad = InputQuads.find_first();
4088       BestHiQuad = InputQuads.find_next(BestLoQuad);
4089     }
4090     if (InputQuads.count() > 2) {
4091       BestLoQuad = -1;
4092       BestHiQuad = -1;
4093     }
4094   }
4095
4096   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
4097   // the shuffle mask.  If a quad is scored as -1, that means that it contains
4098   // words from all 4 input quadwords.
4099   SDValue NewV;
4100   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
4101     SmallVector<int, 8> MaskV;
4102     MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
4103     MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
4104     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
4105                   DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V1),
4106                   DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V2), &MaskV[0]);
4107     NewV = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, NewV);
4108
4109     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
4110     // source words for the shuffle, to aid later transformations.
4111     bool AllWordsInNewV = true;
4112     bool InOrder[2] = { true, true };
4113     for (unsigned i = 0; i != 8; ++i) {
4114       int idx = MaskVals[i];
4115       if (idx != (int)i)
4116         InOrder[i/4] = false;
4117       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
4118         continue;
4119       AllWordsInNewV = false;
4120       break;
4121     }
4122
4123     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
4124     if (AllWordsInNewV) {
4125       for (int i = 0; i != 8; ++i) {
4126         int idx = MaskVals[i];
4127         if (idx < 0)
4128           continue;
4129         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
4130         if ((idx != i) && idx < 4)
4131           pshufhw = false;
4132         if ((idx != i) && idx > 3)
4133           pshuflw = false;
4134       }
4135       V1 = NewV;
4136       V2Used = false;
4137       BestLoQuad = 0;
4138       BestHiQuad = 1;
4139     }
4140
4141     // If we've eliminated the use of V2, and the new mask is a pshuflw or
4142     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
4143     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
4144       return DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
4145                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
4146     }
4147   }
4148
4149   // If we have SSSE3, and all words of the result are from 1 input vector,
4150   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
4151   // is present, fall back to case 4.
4152   if (TLI.getSubtarget()->hasSSSE3()) {
4153     SmallVector<SDValue,16> pshufbMask;
4154
4155     // If we have elements from both input vectors, set the high bit of the
4156     // shuffle mask element to zero out elements that come from V2 in the V1
4157     // mask, and elements that come from V1 in the V2 mask, so that the two
4158     // results can be OR'd together.
4159     bool TwoInputs = V1Used && V2Used;
4160     for (unsigned i = 0; i != 8; ++i) {
4161       int EltIdx = MaskVals[i] * 2;
4162       if (TwoInputs && (EltIdx >= 16)) {
4163         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4164         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4165         continue;
4166       }
4167       pshufbMask.push_back(DAG.getConstant(EltIdx,   MVT::i8));
4168       pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
4169     }
4170     V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V1);
4171     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4172                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4173                                  MVT::v16i8, &pshufbMask[0], 16));
4174     if (!TwoInputs)
4175       return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4176
4177     // Calculate the shuffle mask for the second input, shuffle it, and
4178     // OR it with the first shuffled input.
4179     pshufbMask.clear();
4180     for (unsigned i = 0; i != 8; ++i) {
4181       int EltIdx = MaskVals[i] * 2;
4182       if (EltIdx < 16) {
4183         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4184         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4185         continue;
4186       }
4187       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4188       pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
4189     }
4190     V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V2);
4191     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4192                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4193                                  MVT::v16i8, &pshufbMask[0], 16));
4194     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4195     return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4196   }
4197
4198   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
4199   // and update MaskVals with new element order.
4200   BitVector InOrder(8);
4201   if (BestLoQuad >= 0) {
4202     SmallVector<int, 8> MaskV;
4203     for (int i = 0; i != 4; ++i) {
4204       int idx = MaskVals[i];
4205       if (idx < 0) {
4206         MaskV.push_back(-1);
4207         InOrder.set(i);
4208       } else if ((idx / 4) == BestLoQuad) {
4209         MaskV.push_back(idx & 3);
4210         InOrder.set(i);
4211       } else {
4212         MaskV.push_back(-1);
4213       }
4214     }
4215     for (unsigned i = 4; i != 8; ++i)
4216       MaskV.push_back(i);
4217     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4218                                 &MaskV[0]);
4219   }
4220
4221   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
4222   // and update MaskVals with the new element order.
4223   if (BestHiQuad >= 0) {
4224     SmallVector<int, 8> MaskV;
4225     for (unsigned i = 0; i != 4; ++i)
4226       MaskV.push_back(i);
4227     for (unsigned i = 4; i != 8; ++i) {
4228       int idx = MaskVals[i];
4229       if (idx < 0) {
4230         MaskV.push_back(-1);
4231         InOrder.set(i);
4232       } else if ((idx / 4) == BestHiQuad) {
4233         MaskV.push_back((idx & 3) + 4);
4234         InOrder.set(i);
4235       } else {
4236         MaskV.push_back(-1);
4237       }
4238     }
4239     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4240                                 &MaskV[0]);
4241   }
4242
4243   // In case BestHi & BestLo were both -1, which means each quadword has a word
4244   // from each of the four input quadwords, calculate the InOrder bitvector now
4245   // before falling through to the insert/extract cleanup.
4246   if (BestLoQuad == -1 && BestHiQuad == -1) {
4247     NewV = V1;
4248     for (int i = 0; i != 8; ++i)
4249       if (MaskVals[i] < 0 || MaskVals[i] == i)
4250         InOrder.set(i);
4251   }
4252
4253   // The other elements are put in the right place using pextrw and pinsrw.
4254   for (unsigned i = 0; i != 8; ++i) {
4255     if (InOrder[i])
4256       continue;
4257     int EltIdx = MaskVals[i];
4258     if (EltIdx < 0)
4259       continue;
4260     SDValue ExtOp = (EltIdx < 8)
4261     ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
4262                   DAG.getIntPtrConstant(EltIdx))
4263     : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
4264                   DAG.getIntPtrConstant(EltIdx - 8));
4265     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
4266                        DAG.getIntPtrConstant(i));
4267   }
4268   return NewV;
4269 }
4270
4271 // v16i8 shuffles - Prefer shuffles in the following order:
4272 // 1. [ssse3] 1 x pshufb
4273 // 2. [ssse3] 2 x pshufb + 1 x por
4274 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
4275 static
4276 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
4277                                  SelectionDAG &DAG,
4278                                  const X86TargetLowering &TLI) {
4279   SDValue V1 = SVOp->getOperand(0);
4280   SDValue V2 = SVOp->getOperand(1);
4281   DebugLoc dl = SVOp->getDebugLoc();
4282   SmallVector<int, 16> MaskVals;
4283   SVOp->getMask(MaskVals);
4284
4285   // If we have SSSE3, case 1 is generated when all result bytes come from
4286   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
4287   // present, fall back to case 3.
4288   // FIXME: kill V2Only once shuffles are canonizalized by getNode.
4289   bool V1Only = true;
4290   bool V2Only = true;
4291   for (unsigned i = 0; i < 16; ++i) {
4292     int EltIdx = MaskVals[i];
4293     if (EltIdx < 0)
4294       continue;
4295     if (EltIdx < 16)
4296       V2Only = false;
4297     else
4298       V1Only = false;
4299   }
4300
4301   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
4302   if (TLI.getSubtarget()->hasSSSE3()) {
4303     SmallVector<SDValue,16> pshufbMask;
4304
4305     // If all result elements are from one input vector, then only translate
4306     // undef mask values to 0x80 (zero out result) in the pshufb mask.
4307     //
4308     // Otherwise, we have elements from both input vectors, and must zero out
4309     // elements that come from V2 in the first mask, and V1 in the second mask
4310     // so that we can OR them together.
4311     bool TwoInputs = !(V1Only || V2Only);
4312     for (unsigned i = 0; i != 16; ++i) {
4313       int EltIdx = MaskVals[i];
4314       if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
4315         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4316         continue;
4317       }
4318       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4319     }
4320     // If all the elements are from V2, assign it to V1 and return after
4321     // building the first pshufb.
4322     if (V2Only)
4323       V1 = V2;
4324     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4325                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4326                                  MVT::v16i8, &pshufbMask[0], 16));
4327     if (!TwoInputs)
4328       return V1;
4329
4330     // Calculate the shuffle mask for the second input, shuffle it, and
4331     // OR it with the first shuffled input.
4332     pshufbMask.clear();
4333     for (unsigned i = 0; i != 16; ++i) {
4334       int EltIdx = MaskVals[i];
4335       if (EltIdx < 16) {
4336         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4337         continue;
4338       }
4339       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4340     }
4341     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4342                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4343                                  MVT::v16i8, &pshufbMask[0], 16));
4344     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4345   }
4346
4347   // No SSSE3 - Calculate in place words and then fix all out of place words
4348   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
4349   // the 16 different words that comprise the two doublequadword input vectors.
4350   V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4351   V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V2);
4352   SDValue NewV = V2Only ? V2 : V1;
4353   for (int i = 0; i != 8; ++i) {
4354     int Elt0 = MaskVals[i*2];
4355     int Elt1 = MaskVals[i*2+1];
4356
4357     // This word of the result is all undef, skip it.
4358     if (Elt0 < 0 && Elt1 < 0)
4359       continue;
4360
4361     // This word of the result is already in the correct place, skip it.
4362     if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
4363       continue;
4364     if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
4365       continue;
4366
4367     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
4368     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
4369     SDValue InsElt;
4370
4371     // If Elt0 and Elt1 are defined, are consecutive, and can be load
4372     // using a single extract together, load it and store it.
4373     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
4374       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4375                            DAG.getIntPtrConstant(Elt1 / 2));
4376       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4377                         DAG.getIntPtrConstant(i));
4378       continue;
4379     }
4380
4381     // If Elt1 is defined, extract it from the appropriate source.  If the
4382     // source byte is not also odd, shift the extracted word left 8 bits
4383     // otherwise clear the bottom 8 bits if we need to do an or.
4384     if (Elt1 >= 0) {
4385       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4386                            DAG.getIntPtrConstant(Elt1 / 2));
4387       if ((Elt1 & 1) == 0)
4388         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
4389                              DAG.getConstant(8, TLI.getShiftAmountTy()));
4390       else if (Elt0 >= 0)
4391         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
4392                              DAG.getConstant(0xFF00, MVT::i16));
4393     }
4394     // If Elt0 is defined, extract it from the appropriate source.  If the
4395     // source byte is not also even, shift the extracted word right 8 bits. If
4396     // Elt1 was also defined, OR the extracted values together before
4397     // inserting them in the result.
4398     if (Elt0 >= 0) {
4399       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
4400                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
4401       if ((Elt0 & 1) != 0)
4402         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
4403                               DAG.getConstant(8, TLI.getShiftAmountTy()));
4404       else if (Elt1 >= 0)
4405         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
4406                              DAG.getConstant(0x00FF, MVT::i16));
4407       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
4408                          : InsElt0;
4409     }
4410     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4411                        DAG.getIntPtrConstant(i));
4412   }
4413   return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, NewV);
4414 }
4415
4416 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
4417 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
4418 /// done when every pair / quad of shuffle mask elements point to elements in
4419 /// the right sequence. e.g.
4420 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
4421 static
4422 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
4423                                  SelectionDAG &DAG,
4424                                  const TargetLowering &TLI, DebugLoc dl) {
4425   EVT VT = SVOp->getValueType(0);
4426   SDValue V1 = SVOp->getOperand(0);
4427   SDValue V2 = SVOp->getOperand(1);
4428   unsigned NumElems = VT.getVectorNumElements();
4429   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
4430   EVT MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
4431   EVT MaskEltVT = MaskVT.getVectorElementType();
4432   EVT NewVT = MaskVT;
4433   switch (VT.getSimpleVT().SimpleTy) {
4434   default: assert(false && "Unexpected!");
4435   case MVT::v4f32: NewVT = MVT::v2f64; break;
4436   case MVT::v4i32: NewVT = MVT::v2i64; break;
4437   case MVT::v8i16: NewVT = MVT::v4i32; break;
4438   case MVT::v16i8: NewVT = MVT::v4i32; break;
4439   }
4440
4441   if (NewWidth == 2) {
4442     if (VT.isInteger())
4443       NewVT = MVT::v2i64;
4444     else
4445       NewVT = MVT::v2f64;
4446   }
4447   int Scale = NumElems / NewWidth;
4448   SmallVector<int, 8> MaskVec;
4449   for (unsigned i = 0; i < NumElems; i += Scale) {
4450     int StartIdx = -1;
4451     for (int j = 0; j < Scale; ++j) {
4452       int EltIdx = SVOp->getMaskElt(i+j);
4453       if (EltIdx < 0)
4454         continue;
4455       if (StartIdx == -1)
4456         StartIdx = EltIdx - (EltIdx % Scale);
4457       if (EltIdx != StartIdx + j)
4458         return SDValue();
4459     }
4460     if (StartIdx == -1)
4461       MaskVec.push_back(-1);
4462     else
4463       MaskVec.push_back(StartIdx / Scale);
4464   }
4465
4466   V1 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V1);
4467   V2 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V2);
4468   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
4469 }
4470
4471 /// getVZextMovL - Return a zero-extending vector move low node.
4472 ///
4473 static SDValue getVZextMovL(EVT VT, EVT OpVT,
4474                             SDValue SrcOp, SelectionDAG &DAG,
4475                             const X86Subtarget *Subtarget, DebugLoc dl) {
4476   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
4477     LoadSDNode *LD = NULL;
4478     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
4479       LD = dyn_cast<LoadSDNode>(SrcOp);
4480     if (!LD) {
4481       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
4482       // instead.
4483       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
4484       if ((ExtVT.SimpleTy != MVT::i64 || Subtarget->is64Bit()) &&
4485           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
4486           SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
4487           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
4488         // PR2108
4489         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
4490         return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4491                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4492                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4493                                                    OpVT,
4494                                                    SrcOp.getOperand(0)
4495                                                           .getOperand(0))));
4496       }
4497     }
4498   }
4499
4500   return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4501                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4502                                  DAG.getNode(ISD::BIT_CONVERT, dl,
4503                                              OpVT, SrcOp)));
4504 }
4505
4506 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
4507 /// shuffles.
4508 static SDValue
4509 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4510   SDValue V1 = SVOp->getOperand(0);
4511   SDValue V2 = SVOp->getOperand(1);
4512   DebugLoc dl = SVOp->getDebugLoc();
4513   EVT VT = SVOp->getValueType(0);
4514
4515   SmallVector<std::pair<int, int>, 8> Locs;
4516   Locs.resize(4);
4517   SmallVector<int, 8> Mask1(4U, -1);
4518   SmallVector<int, 8> PermMask;
4519   SVOp->getMask(PermMask);
4520
4521   unsigned NumHi = 0;
4522   unsigned NumLo = 0;
4523   for (unsigned i = 0; i != 4; ++i) {
4524     int Idx = PermMask[i];
4525     if (Idx < 0) {
4526       Locs[i] = std::make_pair(-1, -1);
4527     } else {
4528       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
4529       if (Idx < 4) {
4530         Locs[i] = std::make_pair(0, NumLo);
4531         Mask1[NumLo] = Idx;
4532         NumLo++;
4533       } else {
4534         Locs[i] = std::make_pair(1, NumHi);
4535         if (2+NumHi < 4)
4536           Mask1[2+NumHi] = Idx;
4537         NumHi++;
4538       }
4539     }
4540   }
4541
4542   if (NumLo <= 2 && NumHi <= 2) {
4543     // If no more than two elements come from either vector. This can be
4544     // implemented with two shuffles. First shuffle gather the elements.
4545     // The second shuffle, which takes the first shuffle as both of its
4546     // vector operands, put the elements into the right order.
4547     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4548
4549     SmallVector<int, 8> Mask2(4U, -1);
4550
4551     for (unsigned i = 0; i != 4; ++i) {
4552       if (Locs[i].first == -1)
4553         continue;
4554       else {
4555         unsigned Idx = (i < 2) ? 0 : 4;
4556         Idx += Locs[i].first * 2 + Locs[i].second;
4557         Mask2[i] = Idx;
4558       }
4559     }
4560
4561     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
4562   } else if (NumLo == 3 || NumHi == 3) {
4563     // Otherwise, we must have three elements from one vector, call it X, and
4564     // one element from the other, call it Y.  First, use a shufps to build an
4565     // intermediate vector with the one element from Y and the element from X
4566     // that will be in the same half in the final destination (the indexes don't
4567     // matter). Then, use a shufps to build the final vector, taking the half
4568     // containing the element from Y from the intermediate, and the other half
4569     // from X.
4570     if (NumHi == 3) {
4571       // Normalize it so the 3 elements come from V1.
4572       CommuteVectorShuffleMask(PermMask, VT);
4573       std::swap(V1, V2);
4574     }
4575
4576     // Find the element from V2.
4577     unsigned HiIndex;
4578     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
4579       int Val = PermMask[HiIndex];
4580       if (Val < 0)
4581         continue;
4582       if (Val >= 4)
4583         break;
4584     }
4585
4586     Mask1[0] = PermMask[HiIndex];
4587     Mask1[1] = -1;
4588     Mask1[2] = PermMask[HiIndex^1];
4589     Mask1[3] = -1;
4590     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4591
4592     if (HiIndex >= 2) {
4593       Mask1[0] = PermMask[0];
4594       Mask1[1] = PermMask[1];
4595       Mask1[2] = HiIndex & 1 ? 6 : 4;
4596       Mask1[3] = HiIndex & 1 ? 4 : 6;
4597       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4598     } else {
4599       Mask1[0] = HiIndex & 1 ? 2 : 0;
4600       Mask1[1] = HiIndex & 1 ? 0 : 2;
4601       Mask1[2] = PermMask[2];
4602       Mask1[3] = PermMask[3];
4603       if (Mask1[2] >= 0)
4604         Mask1[2] += 4;
4605       if (Mask1[3] >= 0)
4606         Mask1[3] += 4;
4607       return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
4608     }
4609   }
4610
4611   // Break it into (shuffle shuffle_hi, shuffle_lo).
4612   Locs.clear();
4613   SmallVector<int,8> LoMask(4U, -1);
4614   SmallVector<int,8> HiMask(4U, -1);
4615
4616   SmallVector<int,8> *MaskPtr = &LoMask;
4617   unsigned MaskIdx = 0;
4618   unsigned LoIdx = 0;
4619   unsigned HiIdx = 2;
4620   for (unsigned i = 0; i != 4; ++i) {
4621     if (i == 2) {
4622       MaskPtr = &HiMask;
4623       MaskIdx = 1;
4624       LoIdx = 0;
4625       HiIdx = 2;
4626     }
4627     int Idx = PermMask[i];
4628     if (Idx < 0) {
4629       Locs[i] = std::make_pair(-1, -1);
4630     } else if (Idx < 4) {
4631       Locs[i] = std::make_pair(MaskIdx, LoIdx);
4632       (*MaskPtr)[LoIdx] = Idx;
4633       LoIdx++;
4634     } else {
4635       Locs[i] = std::make_pair(MaskIdx, HiIdx);
4636       (*MaskPtr)[HiIdx] = Idx;
4637       HiIdx++;
4638     }
4639   }
4640
4641   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
4642   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
4643   SmallVector<int, 8> MaskOps;
4644   for (unsigned i = 0; i != 4; ++i) {
4645     if (Locs[i].first == -1) {
4646       MaskOps.push_back(-1);
4647     } else {
4648       unsigned Idx = Locs[i].first * 4 + Locs[i].second;
4649       MaskOps.push_back(Idx);
4650     }
4651   }
4652   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
4653 }
4654
4655 SDValue
4656 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
4657   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4658   SDValue V1 = Op.getOperand(0);
4659   SDValue V2 = Op.getOperand(1);
4660   EVT VT = Op.getValueType();
4661   DebugLoc dl = Op.getDebugLoc();
4662   unsigned NumElems = VT.getVectorNumElements();
4663   bool isMMX = VT.getSizeInBits() == 64;
4664   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
4665   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
4666   bool V1IsSplat = false;
4667   bool V2IsSplat = false;
4668
4669   if (isZeroShuffle(SVOp))
4670     return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4671
4672   // Promote splats to v4f32.
4673   if (SVOp->isSplat()) {
4674     if (isMMX || NumElems < 4)
4675       return Op;
4676     return PromoteSplat(SVOp, DAG, Subtarget->hasSSE2());
4677   }
4678
4679   // If the shuffle can be profitably rewritten as a narrower shuffle, then
4680   // do it!
4681   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
4682     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4683     if (NewOp.getNode())
4684       return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4685                          LowerVECTOR_SHUFFLE(NewOp, DAG));
4686   } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
4687     // FIXME: Figure out a cleaner way to do this.
4688     // Try to make use of movq to zero out the top part.
4689     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
4690       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4691       if (NewOp.getNode()) {
4692         if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
4693           return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
4694                               DAG, Subtarget, dl);
4695       }
4696     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
4697       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4698       if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
4699         return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
4700                             DAG, Subtarget, dl);
4701     }
4702   }
4703
4704   if (X86::isPSHUFDMask(SVOp))
4705     return Op;
4706
4707   // Check if this can be converted into a logical shift.
4708   bool isLeft = false;
4709   unsigned ShAmt = 0;
4710   SDValue ShVal;
4711   bool isShift = getSubtarget()->hasSSE2() &&
4712     isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
4713   if (isShift && ShVal.hasOneUse()) {
4714     // If the shifted value has multiple uses, it may be cheaper to use
4715     // v_set0 + movlhps or movhlps, etc.
4716     EVT EltVT = VT.getVectorElementType();
4717     ShAmt *= EltVT.getSizeInBits();
4718     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4719   }
4720
4721   if (X86::isMOVLMask(SVOp)) {
4722     if (V1IsUndef)
4723       return V2;
4724     if (ISD::isBuildVectorAllZeros(V1.getNode()))
4725       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
4726     if (!isMMX)
4727       return Op;
4728   }
4729
4730   // FIXME: fold these into legal mask.
4731   if (!isMMX && (X86::isMOVSHDUPMask(SVOp) ||
4732                  X86::isMOVSLDUPMask(SVOp) ||
4733                  X86::isMOVHLPSMask(SVOp) ||
4734                  X86::isMOVLHPSMask(SVOp) ||
4735                  X86::isMOVLPMask(SVOp)))
4736     return Op;
4737
4738   if (ShouldXformToMOVHLPS(SVOp) ||
4739       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
4740     return CommuteVectorShuffle(SVOp, DAG);
4741
4742   if (isShift) {
4743     // No better options. Use a vshl / vsrl.
4744     EVT EltVT = VT.getVectorElementType();
4745     ShAmt *= EltVT.getSizeInBits();
4746     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4747   }
4748
4749   bool Commuted = false;
4750   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
4751   // 1,1,1,1 -> v8i16 though.
4752   V1IsSplat = isSplatVector(V1.getNode());
4753   V2IsSplat = isSplatVector(V2.getNode());
4754
4755   // Canonicalize the splat or undef, if present, to be on the RHS.
4756   if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
4757     Op = CommuteVectorShuffle(SVOp, DAG);
4758     SVOp = cast<ShuffleVectorSDNode>(Op);
4759     V1 = SVOp->getOperand(0);
4760     V2 = SVOp->getOperand(1);
4761     std::swap(V1IsSplat, V2IsSplat);
4762     std::swap(V1IsUndef, V2IsUndef);
4763     Commuted = true;
4764   }
4765
4766   if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
4767     // Shuffling low element of v1 into undef, just return v1.
4768     if (V2IsUndef)
4769       return V1;
4770     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
4771     // the instruction selector will not match, so get a canonical MOVL with
4772     // swapped operands to undo the commute.
4773     return getMOVL(DAG, dl, VT, V2, V1);
4774   }
4775
4776   if (X86::isUNPCKL_v_undef_Mask(SVOp) ||
4777       X86::isUNPCKH_v_undef_Mask(SVOp) ||
4778       X86::isUNPCKLMask(SVOp) ||
4779       X86::isUNPCKHMask(SVOp))
4780     return Op;
4781
4782   if (V2IsSplat) {
4783     // Normalize mask so all entries that point to V2 points to its first
4784     // element then try to match unpck{h|l} again. If match, return a
4785     // new vector_shuffle with the corrected mask.
4786     SDValue NewMask = NormalizeMask(SVOp, DAG);
4787     ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
4788     if (NSVOp != SVOp) {
4789       if (X86::isUNPCKLMask(NSVOp, true)) {
4790         return NewMask;
4791       } else if (X86::isUNPCKHMask(NSVOp, true)) {
4792         return NewMask;
4793       }
4794     }
4795   }
4796
4797   if (Commuted) {
4798     // Commute is back and try unpck* again.
4799     // FIXME: this seems wrong.
4800     SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
4801     ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
4802     if (X86::isUNPCKL_v_undef_Mask(NewSVOp) ||
4803         X86::isUNPCKH_v_undef_Mask(NewSVOp) ||
4804         X86::isUNPCKLMask(NewSVOp) ||
4805         X86::isUNPCKHMask(NewSVOp))
4806       return NewOp;
4807   }
4808
4809   // FIXME: for mmx, bitcast v2i32 to v4i16 for shuffle.
4810
4811   // Normalize the node to match x86 shuffle ops if needed
4812   if (!isMMX && V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
4813     return CommuteVectorShuffle(SVOp, DAG);
4814
4815   // Check for legal shuffle and return?
4816   SmallVector<int, 16> PermMask;
4817   SVOp->getMask(PermMask);
4818   if (isShuffleMaskLegal(PermMask, VT))
4819     return Op;
4820
4821   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
4822   if (VT == MVT::v8i16) {
4823     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(SVOp, DAG, *this);
4824     if (NewOp.getNode())
4825       return NewOp;
4826   }
4827
4828   if (VT == MVT::v16i8) {
4829     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
4830     if (NewOp.getNode())
4831       return NewOp;
4832   }
4833
4834   // Handle all 4 wide cases with a number of shuffles except for MMX.
4835   if (NumElems == 4 && !isMMX)
4836     return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
4837
4838   return SDValue();
4839 }
4840
4841 SDValue
4842 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
4843                                                 SelectionDAG &DAG) const {
4844   EVT VT = Op.getValueType();
4845   DebugLoc dl = Op.getDebugLoc();
4846   if (VT.getSizeInBits() == 8) {
4847     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
4848                                     Op.getOperand(0), Op.getOperand(1));
4849     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4850                                     DAG.getValueType(VT));
4851     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4852   } else if (VT.getSizeInBits() == 16) {
4853     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4854     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
4855     if (Idx == 0)
4856       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4857                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4858                                      DAG.getNode(ISD::BIT_CONVERT, dl,
4859                                                  MVT::v4i32,
4860                                                  Op.getOperand(0)),
4861                                      Op.getOperand(1)));
4862     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
4863                                     Op.getOperand(0), Op.getOperand(1));
4864     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4865                                     DAG.getValueType(VT));
4866     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4867   } else if (VT == MVT::f32) {
4868     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
4869     // the result back to FR32 register. It's only worth matching if the
4870     // result has a single use which is a store or a bitcast to i32.  And in
4871     // the case of a store, it's not worth it if the index is a constant 0,
4872     // because a MOVSSmr can be used instead, which is smaller and faster.
4873     if (!Op.hasOneUse())
4874       return SDValue();
4875     SDNode *User = *Op.getNode()->use_begin();
4876     if ((User->getOpcode() != ISD::STORE ||
4877          (isa<ConstantSDNode>(Op.getOperand(1)) &&
4878           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
4879         (User->getOpcode() != ISD::BIT_CONVERT ||
4880          User->getValueType(0) != MVT::i32))
4881       return SDValue();
4882     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4883                                   DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32,
4884                                               Op.getOperand(0)),
4885                                               Op.getOperand(1));
4886     return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Extract);
4887   } else if (VT == MVT::i32) {
4888     // ExtractPS works with constant index.
4889     if (isa<ConstantSDNode>(Op.getOperand(1)))
4890       return Op;
4891   }
4892   return SDValue();
4893 }
4894
4895
4896 SDValue
4897 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
4898                                            SelectionDAG &DAG) const {
4899   if (!isa<ConstantSDNode>(Op.getOperand(1)))
4900     return SDValue();
4901
4902   if (Subtarget->hasSSE41()) {
4903     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
4904     if (Res.getNode())
4905       return Res;
4906   }
4907
4908   EVT VT = Op.getValueType();
4909   DebugLoc dl = Op.getDebugLoc();
4910   // TODO: handle v16i8.
4911   if (VT.getSizeInBits() == 16) {
4912     SDValue Vec = Op.getOperand(0);
4913     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4914     if (Idx == 0)
4915       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4916                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4917                                      DAG.getNode(ISD::BIT_CONVERT, dl,
4918                                                  MVT::v4i32, Vec),
4919                                      Op.getOperand(1)));
4920     // Transform it so it match pextrw which produces a 32-bit result.
4921     EVT EltVT = MVT::i32;
4922     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
4923                                     Op.getOperand(0), Op.getOperand(1));
4924     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
4925                                     DAG.getValueType(VT));
4926     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4927   } else if (VT.getSizeInBits() == 32) {
4928     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4929     if (Idx == 0)
4930       return Op;
4931
4932     // SHUFPS the element to the lowest double word, then movss.
4933     int Mask[4] = { Idx, -1, -1, -1 };
4934     EVT VVT = Op.getOperand(0).getValueType();
4935     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4936                                        DAG.getUNDEF(VVT), Mask);
4937     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4938                        DAG.getIntPtrConstant(0));
4939   } else if (VT.getSizeInBits() == 64) {
4940     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
4941     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
4942     //        to match extract_elt for f64.
4943     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4944     if (Idx == 0)
4945       return Op;
4946
4947     // UNPCKHPD the element to the lowest double word, then movsd.
4948     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
4949     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
4950     int Mask[2] = { 1, -1 };
4951     EVT VVT = Op.getOperand(0).getValueType();
4952     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4953                                        DAG.getUNDEF(VVT), Mask);
4954     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4955                        DAG.getIntPtrConstant(0));
4956   }
4957
4958   return SDValue();
4959 }
4960
4961 SDValue
4962 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
4963                                                SelectionDAG &DAG) const {
4964   EVT VT = Op.getValueType();
4965   EVT EltVT = VT.getVectorElementType();
4966   DebugLoc dl = Op.getDebugLoc();
4967
4968   SDValue N0 = Op.getOperand(0);
4969   SDValue N1 = Op.getOperand(1);
4970   SDValue N2 = Op.getOperand(2);
4971
4972   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
4973       isa<ConstantSDNode>(N2)) {
4974     unsigned Opc;
4975     if (VT == MVT::v8i16)
4976       Opc = X86ISD::PINSRW;
4977     else if (VT == MVT::v4i16)
4978       Opc = X86ISD::MMX_PINSRW;
4979     else if (VT == MVT::v16i8)
4980       Opc = X86ISD::PINSRB;
4981     else
4982       Opc = X86ISD::PINSRB;
4983
4984     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
4985     // argument.
4986     if (N1.getValueType() != MVT::i32)
4987       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4988     if (N2.getValueType() != MVT::i32)
4989       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4990     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
4991   } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
4992     // Bits [7:6] of the constant are the source select.  This will always be
4993     //  zero here.  The DAG Combiner may combine an extract_elt index into these
4994     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
4995     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
4996     // Bits [5:4] of the constant are the destination select.  This is the
4997     //  value of the incoming immediate.
4998     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
4999     //   combine either bitwise AND or insert of float 0.0 to set these bits.
5000     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
5001     // Create this as a scalar to vector..
5002     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
5003     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
5004   } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
5005     // PINSR* works with constant index.
5006     return Op;
5007   }
5008   return SDValue();
5009 }
5010
5011 SDValue
5012 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
5013   EVT VT = Op.getValueType();
5014   EVT EltVT = VT.getVectorElementType();
5015
5016   if (Subtarget->hasSSE41())
5017     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
5018
5019   if (EltVT == MVT::i8)
5020     return SDValue();
5021
5022   DebugLoc dl = Op.getDebugLoc();
5023   SDValue N0 = Op.getOperand(0);
5024   SDValue N1 = Op.getOperand(1);
5025   SDValue N2 = Op.getOperand(2);
5026
5027   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
5028     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
5029     // as its second argument.
5030     if (N1.getValueType() != MVT::i32)
5031       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
5032     if (N2.getValueType() != MVT::i32)
5033       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
5034     return DAG.getNode(VT == MVT::v8i16 ? X86ISD::PINSRW : X86ISD::MMX_PINSRW,
5035                        dl, VT, N0, N1, N2);
5036   }
5037   return SDValue();
5038 }
5039
5040 SDValue
5041 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5042   DebugLoc dl = Op.getDebugLoc();
5043   if (Op.getValueType() == MVT::v2f32)
5044     return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f32,
5045                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i32,
5046                                    DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32,
5047                                                Op.getOperand(0))));
5048
5049   if (Op.getValueType() == MVT::v1i64 && Op.getOperand(0).getValueType() == MVT::i64)
5050     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
5051
5052   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
5053   EVT VT = MVT::v2i32;
5054   switch (Op.getValueType().getSimpleVT().SimpleTy) {
5055   default: break;
5056   case MVT::v16i8:
5057   case MVT::v8i16:
5058     VT = MVT::v4i32;
5059     break;
5060   }
5061   return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(),
5062                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, AnyExt));
5063 }
5064
5065 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
5066 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
5067 // one of the above mentioned nodes. It has to be wrapped because otherwise
5068 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
5069 // be used to form addressing mode. These wrapped nodes will be selected
5070 // into MOV32ri.
5071 SDValue
5072 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
5073   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
5074
5075   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5076   // global base reg.
5077   unsigned char OpFlag = 0;
5078   unsigned WrapperKind = X86ISD::Wrapper;
5079   CodeModel::Model M = getTargetMachine().getCodeModel();
5080
5081   if (Subtarget->isPICStyleRIPRel() &&
5082       (M == CodeModel::Small || M == CodeModel::Kernel))
5083     WrapperKind = X86ISD::WrapperRIP;
5084   else if (Subtarget->isPICStyleGOT())
5085     OpFlag = X86II::MO_GOTOFF;
5086   else if (Subtarget->isPICStyleStubPIC())
5087     OpFlag = X86II::MO_PIC_BASE_OFFSET;
5088
5089   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
5090                                              CP->getAlignment(),
5091                                              CP->getOffset(), OpFlag);
5092   DebugLoc DL = CP->getDebugLoc();
5093   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5094   // With PIC, the address is actually $g + Offset.
5095   if (OpFlag) {
5096     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5097                          DAG.getNode(X86ISD::GlobalBaseReg,
5098                                      DebugLoc(), getPointerTy()),
5099                          Result);
5100   }
5101
5102   return Result;
5103 }
5104
5105 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
5106   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
5107
5108   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5109   // global base reg.
5110   unsigned char OpFlag = 0;
5111   unsigned WrapperKind = X86ISD::Wrapper;
5112   CodeModel::Model M = getTargetMachine().getCodeModel();
5113
5114   if (Subtarget->isPICStyleRIPRel() &&
5115       (M == CodeModel::Small || M == CodeModel::Kernel))
5116     WrapperKind = X86ISD::WrapperRIP;
5117   else if (Subtarget->isPICStyleGOT())
5118     OpFlag = X86II::MO_GOTOFF;
5119   else if (Subtarget->isPICStyleStubPIC())
5120     OpFlag = X86II::MO_PIC_BASE_OFFSET;
5121
5122   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
5123                                           OpFlag);
5124   DebugLoc DL = JT->getDebugLoc();
5125   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5126
5127   // With PIC, the address is actually $g + Offset.
5128   if (OpFlag) {
5129     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5130                          DAG.getNode(X86ISD::GlobalBaseReg,
5131                                      DebugLoc(), getPointerTy()),
5132                          Result);
5133   }
5134
5135   return Result;
5136 }
5137
5138 SDValue
5139 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
5140   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
5141
5142   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5143   // global base reg.
5144   unsigned char OpFlag = 0;
5145   unsigned WrapperKind = X86ISD::Wrapper;
5146   CodeModel::Model M = getTargetMachine().getCodeModel();
5147
5148   if (Subtarget->isPICStyleRIPRel() &&
5149       (M == CodeModel::Small || M == CodeModel::Kernel))
5150     WrapperKind = X86ISD::WrapperRIP;
5151   else if (Subtarget->isPICStyleGOT())
5152     OpFlag = X86II::MO_GOTOFF;
5153   else if (Subtarget->isPICStyleStubPIC())
5154     OpFlag = X86II::MO_PIC_BASE_OFFSET;
5155
5156   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
5157
5158   DebugLoc DL = Op.getDebugLoc();
5159   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5160
5161
5162   // With PIC, the address is actually $g + Offset.
5163   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
5164       !Subtarget->is64Bit()) {
5165     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5166                          DAG.getNode(X86ISD::GlobalBaseReg,
5167                                      DebugLoc(), getPointerTy()),
5168                          Result);
5169   }
5170
5171   return Result;
5172 }
5173
5174 SDValue
5175 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
5176   // Create the TargetBlockAddressAddress node.
5177   unsigned char OpFlags =
5178     Subtarget->ClassifyBlockAddressReference();
5179   CodeModel::Model M = getTargetMachine().getCodeModel();
5180   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
5181   DebugLoc dl = Op.getDebugLoc();
5182   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
5183                                        /*isTarget=*/true, OpFlags);
5184
5185   if (Subtarget->isPICStyleRIPRel() &&
5186       (M == CodeModel::Small || M == CodeModel::Kernel))
5187     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
5188   else
5189     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
5190
5191   // With PIC, the address is actually $g + Offset.
5192   if (isGlobalRelativeToPICBase(OpFlags)) {
5193     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5194                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
5195                          Result);
5196   }
5197
5198   return Result;
5199 }
5200
5201 SDValue
5202 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
5203                                       int64_t Offset,
5204                                       SelectionDAG &DAG) const {
5205   // Create the TargetGlobalAddress node, folding in the constant
5206   // offset if it is legal.
5207   unsigned char OpFlags =
5208     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
5209   CodeModel::Model M = getTargetMachine().getCodeModel();
5210   SDValue Result;
5211   if (OpFlags == X86II::MO_NO_FLAG &&
5212       X86::isOffsetSuitableForCodeModel(Offset, M)) {
5213     // A direct static reference to a global.
5214     Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), Offset);
5215     Offset = 0;
5216   } else {
5217     Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), 0, OpFlags);
5218   }
5219
5220   if (Subtarget->isPICStyleRIPRel() &&
5221       (M == CodeModel::Small || M == CodeModel::Kernel))
5222     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
5223   else
5224     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
5225
5226   // With PIC, the address is actually $g + Offset.
5227   if (isGlobalRelativeToPICBase(OpFlags)) {
5228     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5229                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
5230                          Result);
5231   }
5232
5233   // For globals that require a load from a stub to get the address, emit the
5234   // load.
5235   if (isGlobalStubReference(OpFlags))
5236     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
5237                          PseudoSourceValue::getGOT(), 0, false, false, 0);
5238
5239   // If there was a non-zero offset that we didn't fold, create an explicit
5240   // addition for it.
5241   if (Offset != 0)
5242     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
5243                          DAG.getConstant(Offset, getPointerTy()));
5244
5245   return Result;
5246 }
5247
5248 SDValue
5249 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
5250   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
5251   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
5252   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
5253 }
5254
5255 static SDValue
5256 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
5257            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
5258            unsigned char OperandFlags) {
5259   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5260   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
5261   DebugLoc dl = GA->getDebugLoc();
5262   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
5263                                            GA->getValueType(0),
5264                                            GA->getOffset(),
5265                                            OperandFlags);
5266   if (InFlag) {
5267     SDValue Ops[] = { Chain,  TGA, *InFlag };
5268     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
5269   } else {
5270     SDValue Ops[]  = { Chain, TGA };
5271     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
5272   }
5273
5274   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
5275   MFI->setAdjustsStack(true);
5276
5277   SDValue Flag = Chain.getValue(1);
5278   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
5279 }
5280
5281 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
5282 static SDValue
5283 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5284                                 const EVT PtrVT) {
5285   SDValue InFlag;
5286   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
5287   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
5288                                      DAG.getNode(X86ISD::GlobalBaseReg,
5289                                                  DebugLoc(), PtrVT), InFlag);
5290   InFlag = Chain.getValue(1);
5291
5292   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
5293 }
5294
5295 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
5296 static SDValue
5297 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5298                                 const EVT PtrVT) {
5299   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
5300                     X86::RAX, X86II::MO_TLSGD);
5301 }
5302
5303 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
5304 // "local exec" model.
5305 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5306                                    const EVT PtrVT, TLSModel::Model model,
5307                                    bool is64Bit) {
5308   DebugLoc dl = GA->getDebugLoc();
5309   // Get the Thread Pointer
5310   SDValue Base = DAG.getNode(X86ISD::SegmentBaseAddress,
5311                              DebugLoc(), PtrVT,
5312                              DAG.getRegister(is64Bit? X86::FS : X86::GS,
5313                                              MVT::i32));
5314
5315   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Base,
5316                                       NULL, 0, false, false, 0);
5317
5318   unsigned char OperandFlags = 0;
5319   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
5320   // initialexec.
5321   unsigned WrapperKind = X86ISD::Wrapper;
5322   if (model == TLSModel::LocalExec) {
5323     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
5324   } else if (is64Bit) {
5325     assert(model == TLSModel::InitialExec);
5326     OperandFlags = X86II::MO_GOTTPOFF;
5327     WrapperKind = X86ISD::WrapperRIP;
5328   } else {
5329     assert(model == TLSModel::InitialExec);
5330     OperandFlags = X86II::MO_INDNTPOFF;
5331   }
5332
5333   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
5334   // exec)
5335   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
5336                                            GA->getOffset(), OperandFlags);
5337   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
5338
5339   if (model == TLSModel::InitialExec)
5340     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
5341                          PseudoSourceValue::getGOT(), 0, false, false, 0);
5342
5343   // The address of the thread local variable is the add of the thread
5344   // pointer with the offset of the variable.
5345   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
5346 }
5347
5348 SDValue
5349 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
5350   // TODO: implement the "local dynamic" model
5351   // TODO: implement the "initial exec"model for pic executables
5352   assert(Subtarget->isTargetELF() &&
5353          "TLS not implemented for non-ELF targets");
5354   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
5355   const GlobalValue *GV = GA->getGlobal();
5356
5357   // If GV is an alias then use the aliasee for determining
5358   // thread-localness.
5359   if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
5360     GV = GA->resolveAliasedGlobal(false);
5361
5362   TLSModel::Model model = getTLSModel(GV,
5363                                       getTargetMachine().getRelocationModel());
5364
5365   switch (model) {
5366   case TLSModel::GeneralDynamic:
5367   case TLSModel::LocalDynamic: // not implemented
5368     if (Subtarget->is64Bit())
5369       return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
5370     return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
5371
5372   case TLSModel::InitialExec:
5373   case TLSModel::LocalExec:
5374     return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
5375                                Subtarget->is64Bit());
5376   }
5377
5378   llvm_unreachable("Unreachable");
5379   return SDValue();
5380 }
5381
5382
5383 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
5384 /// take a 2 x i32 value to shift plus a shift amount.
5385 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
5386   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5387   EVT VT = Op.getValueType();
5388   unsigned VTBits = VT.getSizeInBits();
5389   DebugLoc dl = Op.getDebugLoc();
5390   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
5391   SDValue ShOpLo = Op.getOperand(0);
5392   SDValue ShOpHi = Op.getOperand(1);
5393   SDValue ShAmt  = Op.getOperand(2);
5394   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
5395                                      DAG.getConstant(VTBits - 1, MVT::i8))
5396                        : DAG.getConstant(0, VT);
5397
5398   SDValue Tmp2, Tmp3;
5399   if (Op.getOpcode() == ISD::SHL_PARTS) {
5400     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
5401     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5402   } else {
5403     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
5404     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
5405   }
5406
5407   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
5408                                 DAG.getConstant(VTBits, MVT::i8));
5409   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
5410                              AndNode, DAG.getConstant(0, MVT::i8));
5411
5412   SDValue Hi, Lo;
5413   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5414   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
5415   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
5416
5417   if (Op.getOpcode() == ISD::SHL_PARTS) {
5418     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
5419     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
5420   } else {
5421     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
5422     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
5423   }
5424
5425   SDValue Ops[2] = { Lo, Hi };
5426   return DAG.getMergeValues(Ops, 2, dl);
5427 }
5428
5429 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
5430                                            SelectionDAG &DAG) const {
5431   EVT SrcVT = Op.getOperand(0).getValueType();
5432
5433   if (SrcVT.isVector()) {
5434     if (SrcVT == MVT::v2i32 && Op.getValueType() == MVT::v2f64) {
5435       return Op;
5436     }
5437     return SDValue();
5438   }
5439
5440   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
5441          "Unknown SINT_TO_FP to lower!");
5442
5443   // These are really Legal; return the operand so the caller accepts it as
5444   // Legal.
5445   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
5446     return Op;
5447   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
5448       Subtarget->is64Bit()) {
5449     return Op;
5450   }
5451
5452   DebugLoc dl = Op.getDebugLoc();
5453   unsigned Size = SrcVT.getSizeInBits()/8;
5454   MachineFunction &MF = DAG.getMachineFunction();
5455   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
5456   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5457   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5458                                StackSlot,
5459                                PseudoSourceValue::getFixedStack(SSFI), 0,
5460                                false, false, 0);
5461   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
5462 }
5463
5464 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
5465                                      SDValue StackSlot,
5466                                      SelectionDAG &DAG) const {
5467   // Build the FILD
5468   DebugLoc dl = Op.getDebugLoc();
5469   SDVTList Tys;
5470   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
5471   if (useSSE)
5472     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
5473   else
5474     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
5475   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
5476   SDValue Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD, dl,
5477                                Tys, Ops, array_lengthof(Ops));
5478
5479   if (useSSE) {
5480     Chain = Result.getValue(1);
5481     SDValue InFlag = Result.getValue(2);
5482
5483     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
5484     // shouldn't be necessary except that RFP cannot be live across
5485     // multiple blocks. When stackifier is fixed, they can be uncoupled.
5486     MachineFunction &MF = DAG.getMachineFunction();
5487     int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
5488     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5489     Tys = DAG.getVTList(MVT::Other);
5490     SDValue Ops[] = {
5491       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
5492     };
5493     Chain = DAG.getNode(X86ISD::FST, dl, Tys, Ops, array_lengthof(Ops));
5494     Result = DAG.getLoad(Op.getValueType(), dl, Chain, StackSlot,
5495                          PseudoSourceValue::getFixedStack(SSFI), 0,
5496                          false, false, 0);
5497   }
5498
5499   return Result;
5500 }
5501
5502 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
5503 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
5504                                                SelectionDAG &DAG) const {
5505   // This algorithm is not obvious. Here it is in C code, more or less:
5506   /*
5507     double uint64_to_double( uint32_t hi, uint32_t lo ) {
5508       static const __m128i exp = { 0x4330000045300000ULL, 0 };
5509       static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
5510
5511       // Copy ints to xmm registers.
5512       __m128i xh = _mm_cvtsi32_si128( hi );
5513       __m128i xl = _mm_cvtsi32_si128( lo );
5514
5515       // Combine into low half of a single xmm register.
5516       __m128i x = _mm_unpacklo_epi32( xh, xl );
5517       __m128d d;
5518       double sd;
5519
5520       // Merge in appropriate exponents to give the integer bits the right
5521       // magnitude.
5522       x = _mm_unpacklo_epi32( x, exp );
5523
5524       // Subtract away the biases to deal with the IEEE-754 double precision
5525       // implicit 1.
5526       d = _mm_sub_pd( (__m128d) x, bias );
5527
5528       // All conversions up to here are exact. The correctly rounded result is
5529       // calculated using the current rounding mode using the following
5530       // horizontal add.
5531       d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
5532       _mm_store_sd( &sd, d );   // Because we are returning doubles in XMM, this
5533                                 // store doesn't really need to be here (except
5534                                 // maybe to zero the other double)
5535       return sd;
5536     }
5537   */
5538
5539   DebugLoc dl = Op.getDebugLoc();
5540   LLVMContext *Context = DAG.getContext();
5541
5542   // Build some magic constants.
5543   std::vector<Constant*> CV0;
5544   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
5545   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
5546   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
5547   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
5548   Constant *C0 = ConstantVector::get(CV0);
5549   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
5550
5551   std::vector<Constant*> CV1;
5552   CV1.push_back(
5553     ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
5554   CV1.push_back(
5555     ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
5556   Constant *C1 = ConstantVector::get(CV1);
5557   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
5558
5559   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5560                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5561                                         Op.getOperand(0),
5562                                         DAG.getIntPtrConstant(1)));
5563   SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5564                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5565                                         Op.getOperand(0),
5566                                         DAG.getIntPtrConstant(0)));
5567   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
5568   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
5569                               PseudoSourceValue::getConstantPool(), 0,
5570                               false, false, 16);
5571   SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
5572   SDValue XR2F = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Unpck2);
5573   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
5574                               PseudoSourceValue::getConstantPool(), 0,
5575                               false, false, 16);
5576   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
5577
5578   // Add the halves; easiest way is to swap them into another reg first.
5579   int ShufMask[2] = { 1, -1 };
5580   SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
5581                                       DAG.getUNDEF(MVT::v2f64), ShufMask);
5582   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
5583   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
5584                      DAG.getIntPtrConstant(0));
5585 }
5586
5587 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
5588 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
5589                                                SelectionDAG &DAG) const {
5590   DebugLoc dl = Op.getDebugLoc();
5591   // FP constant to bias correct the final result.
5592   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
5593                                    MVT::f64);
5594
5595   // Load the 32-bit value into an XMM register.
5596   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5597                              DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5598                                          Op.getOperand(0),
5599                                          DAG.getIntPtrConstant(0)));
5600
5601   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5602                      DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Load),
5603                      DAG.getIntPtrConstant(0));
5604
5605   // Or the load with the bias.
5606   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
5607                            DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5608                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5609                                                    MVT::v2f64, Load)),
5610                            DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5611                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5612                                                    MVT::v2f64, Bias)));
5613   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5614                    DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Or),
5615                    DAG.getIntPtrConstant(0));
5616
5617   // Subtract the bias.
5618   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
5619
5620   // Handle final rounding.
5621   EVT DestVT = Op.getValueType();
5622
5623   if (DestVT.bitsLT(MVT::f64)) {
5624     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
5625                        DAG.getIntPtrConstant(0));
5626   } else if (DestVT.bitsGT(MVT::f64)) {
5627     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
5628   }
5629
5630   // Handle final rounding.
5631   return Sub;
5632 }
5633
5634 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
5635                                            SelectionDAG &DAG) const {
5636   SDValue N0 = Op.getOperand(0);
5637   DebugLoc dl = Op.getDebugLoc();
5638
5639   // Now not UINT_TO_FP is legal (it's marked custom), dag combiner won't
5640   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
5641   // the optimization here.
5642   if (DAG.SignBitIsZero(N0))
5643     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
5644
5645   EVT SrcVT = N0.getValueType();
5646   if (SrcVT == MVT::i64) {
5647     // We only handle SSE2 f64 target here; caller can expand the rest.
5648     if (Op.getValueType() != MVT::f64 || !X86ScalarSSEf64)
5649       return SDValue();
5650
5651     return LowerUINT_TO_FP_i64(Op, DAG);
5652   } else if (SrcVT == MVT::i32 && X86ScalarSSEf64) {
5653     return LowerUINT_TO_FP_i32(Op, DAG);
5654   }
5655
5656   assert(SrcVT == MVT::i32 && "Unknown UINT_TO_FP to lower!");
5657
5658   // Make a 64-bit buffer, and use it to build an FILD.
5659   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
5660   SDValue WordOff = DAG.getConstant(4, getPointerTy());
5661   SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
5662                                    getPointerTy(), StackSlot, WordOff);
5663   SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5664                                 StackSlot, NULL, 0, false, false, 0);
5665   SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
5666                                 OffsetSlot, NULL, 0, false, false, 0);
5667   return BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
5668 }
5669
5670 std::pair<SDValue,SDValue> X86TargetLowering::
5671 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
5672   DebugLoc dl = Op.getDebugLoc();
5673
5674   EVT DstTy = Op.getValueType();
5675
5676   if (!IsSigned) {
5677     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
5678     DstTy = MVT::i64;
5679   }
5680
5681   assert(DstTy.getSimpleVT() <= MVT::i64 &&
5682          DstTy.getSimpleVT() >= MVT::i16 &&
5683          "Unknown FP_TO_SINT to lower!");
5684
5685   // These are really Legal.
5686   if (DstTy == MVT::i32 &&
5687       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5688     return std::make_pair(SDValue(), SDValue());
5689   if (Subtarget->is64Bit() &&
5690       DstTy == MVT::i64 &&
5691       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5692     return std::make_pair(SDValue(), SDValue());
5693
5694   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
5695   // stack slot.
5696   MachineFunction &MF = DAG.getMachineFunction();
5697   unsigned MemSize = DstTy.getSizeInBits()/8;
5698   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
5699   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5700
5701   unsigned Opc;
5702   switch (DstTy.getSimpleVT().SimpleTy) {
5703   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
5704   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
5705   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
5706   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
5707   }
5708
5709   SDValue Chain = DAG.getEntryNode();
5710   SDValue Value = Op.getOperand(0);
5711   if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
5712     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
5713     Chain = DAG.getStore(Chain, dl, Value, StackSlot,
5714                          PseudoSourceValue::getFixedStack(SSFI), 0,
5715                          false, false, 0);
5716     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
5717     SDValue Ops[] = {
5718       Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
5719     };
5720     Value = DAG.getNode(X86ISD::FLD, dl, Tys, Ops, 3);
5721     Chain = Value.getValue(1);
5722     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
5723     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5724   }
5725
5726   // Build the FP_TO_INT*_IN_MEM
5727   SDValue Ops[] = { Chain, Value, StackSlot };
5728   SDValue FIST = DAG.getNode(Opc, dl, MVT::Other, Ops, 3);
5729
5730   return std::make_pair(FIST, StackSlot);
5731 }
5732
5733 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
5734                                            SelectionDAG &DAG) const {
5735   if (Op.getValueType().isVector()) {
5736     if (Op.getValueType() == MVT::v2i32 &&
5737         Op.getOperand(0).getValueType() == MVT::v2f64) {
5738       return Op;
5739     }
5740     return SDValue();
5741   }
5742
5743   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
5744   SDValue FIST = Vals.first, StackSlot = Vals.second;
5745   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
5746   if (FIST.getNode() == 0) return Op;
5747
5748   // Load the result.
5749   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5750                      FIST, StackSlot, NULL, 0, false, false, 0);
5751 }
5752
5753 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
5754                                            SelectionDAG &DAG) const {
5755   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
5756   SDValue FIST = Vals.first, StackSlot = Vals.second;
5757   assert(FIST.getNode() && "Unexpected failure");
5758
5759   // Load the result.
5760   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5761                      FIST, StackSlot, NULL, 0, false, false, 0);
5762 }
5763
5764 SDValue X86TargetLowering::LowerFABS(SDValue Op,
5765                                      SelectionDAG &DAG) const {
5766   LLVMContext *Context = DAG.getContext();
5767   DebugLoc dl = Op.getDebugLoc();
5768   EVT VT = Op.getValueType();
5769   EVT EltVT = VT;
5770   if (VT.isVector())
5771     EltVT = VT.getVectorElementType();
5772   std::vector<Constant*> CV;
5773   if (EltVT == MVT::f64) {
5774     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
5775     CV.push_back(C);
5776     CV.push_back(C);
5777   } else {
5778     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
5779     CV.push_back(C);
5780     CV.push_back(C);
5781     CV.push_back(C);
5782     CV.push_back(C);
5783   }
5784   Constant *C = ConstantVector::get(CV);
5785   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5786   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5787                              PseudoSourceValue::getConstantPool(), 0,
5788                              false, false, 16);
5789   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
5790 }
5791
5792 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
5793   LLVMContext *Context = DAG.getContext();
5794   DebugLoc dl = Op.getDebugLoc();
5795   EVT VT = Op.getValueType();
5796   EVT EltVT = VT;
5797   if (VT.isVector())
5798     EltVT = VT.getVectorElementType();
5799   std::vector<Constant*> CV;
5800   if (EltVT == MVT::f64) {
5801     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
5802     CV.push_back(C);
5803     CV.push_back(C);
5804   } else {
5805     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
5806     CV.push_back(C);
5807     CV.push_back(C);
5808     CV.push_back(C);
5809     CV.push_back(C);
5810   }
5811   Constant *C = ConstantVector::get(CV);
5812   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5813   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5814                              PseudoSourceValue::getConstantPool(), 0,
5815                              false, false, 16);
5816   if (VT.isVector()) {
5817     return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
5818                        DAG.getNode(ISD::XOR, dl, MVT::v2i64,
5819                     DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5820                                 Op.getOperand(0)),
5821                     DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, Mask)));
5822   } else {
5823     return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
5824   }
5825 }
5826
5827 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
5828   LLVMContext *Context = DAG.getContext();
5829   SDValue Op0 = Op.getOperand(0);
5830   SDValue Op1 = Op.getOperand(1);
5831   DebugLoc dl = Op.getDebugLoc();
5832   EVT VT = Op.getValueType();
5833   EVT SrcVT = Op1.getValueType();
5834
5835   // If second operand is smaller, extend it first.
5836   if (SrcVT.bitsLT(VT)) {
5837     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
5838     SrcVT = VT;
5839   }
5840   // And if it is bigger, shrink it first.
5841   if (SrcVT.bitsGT(VT)) {
5842     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
5843     SrcVT = VT;
5844   }
5845
5846   // At this point the operands and the result should have the same
5847   // type, and that won't be f80 since that is not custom lowered.
5848
5849   // First get the sign bit of second operand.
5850   std::vector<Constant*> CV;
5851   if (SrcVT == MVT::f64) {
5852     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
5853     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
5854   } else {
5855     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
5856     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5857     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5858     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5859   }
5860   Constant *C = ConstantVector::get(CV);
5861   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5862   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
5863                               PseudoSourceValue::getConstantPool(), 0,
5864                               false, false, 16);
5865   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
5866
5867   // Shift sign bit right or left if the two operands have different types.
5868   if (SrcVT.bitsGT(VT)) {
5869     // Op0 is MVT::f32, Op1 is MVT::f64.
5870     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
5871     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
5872                           DAG.getConstant(32, MVT::i32));
5873     SignBit = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, SignBit);
5874     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
5875                           DAG.getIntPtrConstant(0));
5876   }
5877
5878   // Clear first operand sign bit.
5879   CV.clear();
5880   if (VT == MVT::f64) {
5881     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
5882     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
5883   } else {
5884     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
5885     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5886     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5887     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5888   }
5889   C = ConstantVector::get(CV);
5890   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5891   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5892                               PseudoSourceValue::getConstantPool(), 0,
5893                               false, false, 16);
5894   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
5895
5896   // Or the value with the sign bit.
5897   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
5898 }
5899
5900 /// Emit nodes that will be selected as "test Op0,Op0", or something
5901 /// equivalent.
5902 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
5903                                     SelectionDAG &DAG) const {
5904   DebugLoc dl = Op.getDebugLoc();
5905
5906   // CF and OF aren't always set the way we want. Determine which
5907   // of these we need.
5908   bool NeedCF = false;
5909   bool NeedOF = false;
5910   switch (X86CC) {
5911   case X86::COND_A: case X86::COND_AE:
5912   case X86::COND_B: case X86::COND_BE:
5913     NeedCF = true;
5914     break;
5915   case X86::COND_G: case X86::COND_GE:
5916   case X86::COND_L: case X86::COND_LE:
5917   case X86::COND_O: case X86::COND_NO:
5918     NeedOF = true;
5919     break;
5920   default: break;
5921   }
5922
5923   // See if we can use the EFLAGS value from the operand instead of
5924   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
5925   // we prove that the arithmetic won't overflow, we can't use OF or CF.
5926   if (Op.getResNo() == 0 && !NeedOF && !NeedCF) {
5927     unsigned Opcode = 0;
5928     unsigned NumOperands = 0;
5929     switch (Op.getNode()->getOpcode()) {
5930     case ISD::ADD:
5931       // Due to an isel shortcoming, be conservative if this add is
5932       // likely to be selected as part of a load-modify-store
5933       // instruction. When the root node in a match is a store, isel
5934       // doesn't know how to remap non-chain non-flag uses of other
5935       // nodes in the match, such as the ADD in this case. This leads
5936       // to the ADD being left around and reselected, with the result
5937       // being two adds in the output.  Alas, even if none our users
5938       // are stores, that doesn't prove we're O.K.  Ergo, if we have
5939       // any parents that aren't CopyToReg or SETCC, eschew INC/DEC.
5940       // A better fix seems to require climbing the DAG back to the
5941       // root, and it doesn't seem to be worth the effort.
5942       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5943              UE = Op.getNode()->use_end(); UI != UE; ++UI)
5944         if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
5945           goto default_case;
5946       if (ConstantSDNode *C =
5947             dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
5948         // An add of one will be selected as an INC.
5949         if (C->getAPIntValue() == 1) {
5950           Opcode = X86ISD::INC;
5951           NumOperands = 1;
5952           break;
5953         }
5954         // An add of negative one (subtract of one) will be selected as a DEC.
5955         if (C->getAPIntValue().isAllOnesValue()) {
5956           Opcode = X86ISD::DEC;
5957           NumOperands = 1;
5958           break;
5959         }
5960       }
5961       // Otherwise use a regular EFLAGS-setting add.
5962       Opcode = X86ISD::ADD;
5963       NumOperands = 2;
5964       break;
5965     case ISD::AND: {
5966       // If the primary and result isn't used, don't bother using X86ISD::AND,
5967       // because a TEST instruction will be better.
5968       bool NonFlagUse = false;
5969       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5970              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
5971         SDNode *User = *UI;
5972         unsigned UOpNo = UI.getOperandNo();
5973         if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
5974           // Look pass truncate.
5975           UOpNo = User->use_begin().getOperandNo();
5976           User = *User->use_begin();
5977         }
5978         if (User->getOpcode() != ISD::BRCOND &&
5979             User->getOpcode() != ISD::SETCC &&
5980             (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
5981           NonFlagUse = true;
5982           break;
5983         }
5984       }
5985       if (!NonFlagUse)
5986         break;
5987     }
5988     // FALL THROUGH
5989     case ISD::SUB:
5990     case ISD::OR:
5991     case ISD::XOR:
5992       // Due to the ISEL shortcoming noted above, be conservative if this op is
5993       // likely to be selected as part of a load-modify-store instruction.
5994       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5995            UE = Op.getNode()->use_end(); UI != UE; ++UI)
5996         if (UI->getOpcode() == ISD::STORE)
5997           goto default_case;
5998       // Otherwise use a regular EFLAGS-setting instruction.
5999       switch (Op.getNode()->getOpcode()) {
6000       case ISD::SUB: Opcode = X86ISD::SUB; break;
6001       case ISD::OR:  Opcode = X86ISD::OR;  break;
6002       case ISD::XOR: Opcode = X86ISD::XOR; break;
6003       case ISD::AND: Opcode = X86ISD::AND; break;
6004       default: llvm_unreachable("unexpected operator!");
6005       }
6006       NumOperands = 2;
6007       break;
6008     case X86ISD::ADD:
6009     case X86ISD::SUB:
6010     case X86ISD::INC:
6011     case X86ISD::DEC:
6012     case X86ISD::OR:
6013     case X86ISD::XOR:
6014     case X86ISD::AND:
6015       return SDValue(Op.getNode(), 1);
6016     default:
6017     default_case:
6018       break;
6019     }
6020     if (Opcode != 0) {
6021       SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
6022       SmallVector<SDValue, 4> Ops;
6023       for (unsigned i = 0; i != NumOperands; ++i)
6024         Ops.push_back(Op.getOperand(i));
6025       SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
6026       DAG.ReplaceAllUsesWith(Op, New);
6027       return SDValue(New.getNode(), 1);
6028     }
6029   }
6030
6031   // Otherwise just emit a CMP with 0, which is the TEST pattern.
6032   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
6033                      DAG.getConstant(0, Op.getValueType()));
6034 }
6035
6036 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
6037 /// equivalent.
6038 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
6039                                    SelectionDAG &DAG) const {
6040   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
6041     if (C->getAPIntValue() == 0)
6042       return EmitTest(Op0, X86CC, DAG);
6043
6044   DebugLoc dl = Op0.getDebugLoc();
6045   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
6046 }
6047
6048 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
6049 /// if it's possible.
6050 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
6051                                      DebugLoc dl, SelectionDAG &DAG) const {
6052   SDValue Op0 = And.getOperand(0);
6053   SDValue Op1 = And.getOperand(1);
6054   if (Op0.getOpcode() == ISD::TRUNCATE)
6055     Op0 = Op0.getOperand(0);
6056   if (Op1.getOpcode() == ISD::TRUNCATE)
6057     Op1 = Op1.getOperand(0);
6058
6059   SDValue LHS, RHS;
6060   if (Op1.getOpcode() == ISD::SHL) {
6061     if (ConstantSDNode *And10C = dyn_cast<ConstantSDNode>(Op1.getOperand(0)))
6062       if (And10C->getZExtValue() == 1) {
6063         LHS = Op0;
6064         RHS = Op1.getOperand(1);
6065       }
6066   } else if (Op0.getOpcode() == ISD::SHL) {
6067     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
6068       if (And00C->getZExtValue() == 1) {
6069         LHS = Op1;
6070         RHS = Op0.getOperand(1);
6071       }
6072   } else if (Op1.getOpcode() == ISD::Constant) {
6073     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
6074     SDValue AndLHS = Op0;
6075     if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
6076       LHS = AndLHS.getOperand(0);
6077       RHS = AndLHS.getOperand(1);
6078     }
6079   }
6080
6081   if (LHS.getNode()) {
6082     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
6083     // instruction.  Since the shift amount is in-range-or-undefined, we know
6084     // that doing a bittest on the i32 value is ok.  We extend to i32 because
6085     // the encoding for the i16 version is larger than the i32 version.
6086     // Also promote i16 to i32 for performance / code size reason.
6087     if (LHS.getValueType() == MVT::i8 ||
6088         LHS.getValueType() == MVT::i16)
6089       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
6090
6091     // If the operand types disagree, extend the shift amount to match.  Since
6092     // BT ignores high bits (like shifts) we can use anyextend.
6093     if (LHS.getValueType() != RHS.getValueType())
6094       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
6095
6096     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
6097     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
6098     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6099                        DAG.getConstant(Cond, MVT::i8), BT);
6100   }
6101
6102   return SDValue();
6103 }
6104
6105 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
6106   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
6107   SDValue Op0 = Op.getOperand(0);
6108   SDValue Op1 = Op.getOperand(1);
6109   DebugLoc dl = Op.getDebugLoc();
6110   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6111
6112   // Optimize to BT if possible.
6113   // Lower (X & (1 << N)) == 0 to BT(X, N).
6114   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
6115   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
6116   if (Op0.getOpcode() == ISD::AND &&
6117       Op0.hasOneUse() &&
6118       Op1.getOpcode() == ISD::Constant &&
6119       cast<ConstantSDNode>(Op1)->getZExtValue() == 0 &&
6120       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
6121     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
6122     if (NewSetCC.getNode())
6123       return NewSetCC;
6124   }
6125
6126   // Look for "(setcc) == / != 1" to avoid unncessary setcc.
6127   if (Op0.getOpcode() == X86ISD::SETCC &&
6128       Op1.getOpcode() == ISD::Constant &&
6129       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
6130        cast<ConstantSDNode>(Op1)->isNullValue()) &&
6131       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
6132     X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
6133     bool Invert = (CC == ISD::SETNE) ^
6134       cast<ConstantSDNode>(Op1)->isNullValue();
6135     if (Invert)
6136       CCode = X86::GetOppositeBranchCondition(CCode);
6137     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6138                        DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
6139   }
6140
6141   bool isFP = Op1.getValueType().isFloatingPoint();
6142   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
6143   if (X86CC == X86::COND_INVALID)
6144     return SDValue();
6145
6146   SDValue Cond = EmitCmp(Op0, Op1, X86CC, DAG);
6147
6148   // Use sbb x, x to materialize carry bit into a GPR.
6149   if (X86CC == X86::COND_B)
6150     return DAG.getNode(ISD::AND, dl, MVT::i8,
6151                        DAG.getNode(X86ISD::SETCC_CARRY, dl, MVT::i8,
6152                                    DAG.getConstant(X86CC, MVT::i8), Cond),
6153                        DAG.getConstant(1, MVT::i8));
6154
6155   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6156                      DAG.getConstant(X86CC, MVT::i8), Cond);
6157 }
6158
6159 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
6160   SDValue Cond;
6161   SDValue Op0 = Op.getOperand(0);
6162   SDValue Op1 = Op.getOperand(1);
6163   SDValue CC = Op.getOperand(2);
6164   EVT VT = Op.getValueType();
6165   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
6166   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
6167   DebugLoc dl = Op.getDebugLoc();
6168
6169   if (isFP) {
6170     unsigned SSECC = 8;
6171     EVT VT0 = Op0.getValueType();
6172     assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
6173     unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
6174     bool Swap = false;
6175
6176     switch (SetCCOpcode) {
6177     default: break;
6178     case ISD::SETOEQ:
6179     case ISD::SETEQ:  SSECC = 0; break;
6180     case ISD::SETOGT:
6181     case ISD::SETGT: Swap = true; // Fallthrough
6182     case ISD::SETLT:
6183     case ISD::SETOLT: SSECC = 1; break;
6184     case ISD::SETOGE:
6185     case ISD::SETGE: Swap = true; // Fallthrough
6186     case ISD::SETLE:
6187     case ISD::SETOLE: SSECC = 2; break;
6188     case ISD::SETUO:  SSECC = 3; break;
6189     case ISD::SETUNE:
6190     case ISD::SETNE:  SSECC = 4; break;
6191     case ISD::SETULE: Swap = true;
6192     case ISD::SETUGE: SSECC = 5; break;
6193     case ISD::SETULT: Swap = true;
6194     case ISD::SETUGT: SSECC = 6; break;
6195     case ISD::SETO:   SSECC = 7; break;
6196     }
6197     if (Swap)
6198       std::swap(Op0, Op1);
6199
6200     // In the two special cases we can't handle, emit two comparisons.
6201     if (SSECC == 8) {
6202       if (SetCCOpcode == ISD::SETUEQ) {
6203         SDValue UNORD, EQ;
6204         UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
6205         EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
6206         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
6207       }
6208       else if (SetCCOpcode == ISD::SETONE) {
6209         SDValue ORD, NEQ;
6210         ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
6211         NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
6212         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
6213       }
6214       llvm_unreachable("Illegal FP comparison");
6215     }
6216     // Handle all other FP comparisons here.
6217     return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
6218   }
6219
6220   // We are handling one of the integer comparisons here.  Since SSE only has
6221   // GT and EQ comparisons for integer, swapping operands and multiple
6222   // operations may be required for some comparisons.
6223   unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
6224   bool Swap = false, Invert = false, FlipSigns = false;
6225
6226   switch (VT.getSimpleVT().SimpleTy) {
6227   default: break;
6228   case MVT::v8i8:
6229   case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
6230   case MVT::v4i16:
6231   case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
6232   case MVT::v2i32:
6233   case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
6234   case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
6235   }
6236
6237   switch (SetCCOpcode) {
6238   default: break;
6239   case ISD::SETNE:  Invert = true;
6240   case ISD::SETEQ:  Opc = EQOpc; break;
6241   case ISD::SETLT:  Swap = true;
6242   case ISD::SETGT:  Opc = GTOpc; break;
6243   case ISD::SETGE:  Swap = true;
6244   case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
6245   case ISD::SETULT: Swap = true;
6246   case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
6247   case ISD::SETUGE: Swap = true;
6248   case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
6249   }
6250   if (Swap)
6251     std::swap(Op0, Op1);
6252
6253   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
6254   // bits of the inputs before performing those operations.
6255   if (FlipSigns) {
6256     EVT EltVT = VT.getVectorElementType();
6257     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
6258                                       EltVT);
6259     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
6260     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
6261                                     SignBits.size());
6262     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
6263     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
6264   }
6265
6266   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
6267
6268   // If the logical-not of the result is required, perform that now.
6269   if (Invert)
6270     Result = DAG.getNOT(dl, Result, VT);
6271
6272   return Result;
6273 }
6274
6275 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
6276 static bool isX86LogicalCmp(SDValue Op) {
6277   unsigned Opc = Op.getNode()->getOpcode();
6278   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
6279     return true;
6280   if (Op.getResNo() == 1 &&
6281       (Opc == X86ISD::ADD ||
6282        Opc == X86ISD::SUB ||
6283        Opc == X86ISD::SMUL ||
6284        Opc == X86ISD::UMUL ||
6285        Opc == X86ISD::INC ||
6286        Opc == X86ISD::DEC ||
6287        Opc == X86ISD::OR ||
6288        Opc == X86ISD::XOR ||
6289        Opc == X86ISD::AND))
6290     return true;
6291
6292   return false;
6293 }
6294
6295 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
6296   bool addTest = true;
6297   SDValue Cond  = Op.getOperand(0);
6298   DebugLoc dl = Op.getDebugLoc();
6299   SDValue CC;
6300
6301   if (Cond.getOpcode() == ISD::SETCC) {
6302     SDValue NewCond = LowerSETCC(Cond, DAG);
6303     if (NewCond.getNode())
6304       Cond = NewCond;
6305   }
6306
6307   // (select (x == 0), -1, 0) -> (sign_bit (x - 1))
6308   SDValue Op1 = Op.getOperand(1);
6309   SDValue Op2 = Op.getOperand(2);
6310   if (Cond.getOpcode() == X86ISD::SETCC &&
6311       cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue() == X86::COND_E) {
6312     SDValue Cmp = Cond.getOperand(1);
6313     if (Cmp.getOpcode() == X86ISD::CMP) {
6314       ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op1);
6315       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
6316       ConstantSDNode *RHSC =
6317         dyn_cast<ConstantSDNode>(Cmp.getOperand(1).getNode());
6318       if (N1C && N1C->isAllOnesValue() &&
6319           N2C && N2C->isNullValue() &&
6320           RHSC && RHSC->isNullValue()) {
6321         SDValue CmpOp0 = Cmp.getOperand(0);
6322         Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
6323                           CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
6324         return DAG.getNode(X86ISD::SETCC_CARRY, dl, Op.getValueType(),
6325                            DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
6326       }
6327     }
6328   }
6329
6330   // Look pass (and (setcc_carry (cmp ...)), 1).
6331   if (Cond.getOpcode() == ISD::AND &&
6332       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
6333     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
6334     if (C && C->getAPIntValue() == 1) 
6335       Cond = Cond.getOperand(0);
6336   }
6337
6338   // If condition flag is set by a X86ISD::CMP, then use it as the condition
6339   // setting operand in place of the X86ISD::SETCC.
6340   if (Cond.getOpcode() == X86ISD::SETCC ||
6341       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
6342     CC = Cond.getOperand(0);
6343
6344     SDValue Cmp = Cond.getOperand(1);
6345     unsigned Opc = Cmp.getOpcode();
6346     EVT VT = Op.getValueType();
6347
6348     bool IllegalFPCMov = false;
6349     if (VT.isFloatingPoint() && !VT.isVector() &&
6350         !isScalarFPTypeInSSEReg(VT))  // FPStack?
6351       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
6352
6353     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
6354         Opc == X86ISD::BT) { // FIXME
6355       Cond = Cmp;
6356       addTest = false;
6357     }
6358   }
6359
6360   if (addTest) {
6361     // Look pass the truncate.
6362     if (Cond.getOpcode() == ISD::TRUNCATE)
6363       Cond = Cond.getOperand(0);
6364
6365     // We know the result of AND is compared against zero. Try to match
6366     // it to BT.
6367     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) { 
6368       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
6369       if (NewSetCC.getNode()) {
6370         CC = NewSetCC.getOperand(0);
6371         Cond = NewSetCC.getOperand(1);
6372         addTest = false;
6373       }
6374     }
6375   }
6376
6377   if (addTest) {
6378     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6379     Cond = EmitTest(Cond, X86::COND_NE, DAG);
6380   }
6381
6382   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
6383   // condition is true.
6384   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Flag);
6385   SDValue Ops[] = { Op2, Op1, CC, Cond };
6386   return DAG.getNode(X86ISD::CMOV, dl, VTs, Ops, array_lengthof(Ops));
6387 }
6388
6389 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
6390 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
6391 // from the AND / OR.
6392 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
6393   Opc = Op.getOpcode();
6394   if (Opc != ISD::OR && Opc != ISD::AND)
6395     return false;
6396   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
6397           Op.getOperand(0).hasOneUse() &&
6398           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
6399           Op.getOperand(1).hasOneUse());
6400 }
6401
6402 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
6403 // 1 and that the SETCC node has a single use.
6404 static bool isXor1OfSetCC(SDValue Op) {
6405   if (Op.getOpcode() != ISD::XOR)
6406     return false;
6407   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6408   if (N1C && N1C->getAPIntValue() == 1) {
6409     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
6410       Op.getOperand(0).hasOneUse();
6411   }
6412   return false;
6413 }
6414
6415 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
6416   bool addTest = true;
6417   SDValue Chain = Op.getOperand(0);
6418   SDValue Cond  = Op.getOperand(1);
6419   SDValue Dest  = Op.getOperand(2);
6420   DebugLoc dl = Op.getDebugLoc();
6421   SDValue CC;
6422
6423   if (Cond.getOpcode() == ISD::SETCC) {
6424     SDValue NewCond = LowerSETCC(Cond, DAG);
6425     if (NewCond.getNode())
6426       Cond = NewCond;
6427   }
6428 #if 0
6429   // FIXME: LowerXALUO doesn't handle these!!
6430   else if (Cond.getOpcode() == X86ISD::ADD  ||
6431            Cond.getOpcode() == X86ISD::SUB  ||
6432            Cond.getOpcode() == X86ISD::SMUL ||
6433            Cond.getOpcode() == X86ISD::UMUL)
6434     Cond = LowerXALUO(Cond, DAG);
6435 #endif
6436
6437   // Look pass (and (setcc_carry (cmp ...)), 1).
6438   if (Cond.getOpcode() == ISD::AND &&
6439       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
6440     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
6441     if (C && C->getAPIntValue() == 1) 
6442       Cond = Cond.getOperand(0);
6443   }
6444
6445   // If condition flag is set by a X86ISD::CMP, then use it as the condition
6446   // setting operand in place of the X86ISD::SETCC.
6447   if (Cond.getOpcode() == X86ISD::SETCC ||
6448       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
6449     CC = Cond.getOperand(0);
6450
6451     SDValue Cmp = Cond.getOperand(1);
6452     unsigned Opc = Cmp.getOpcode();
6453     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
6454     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
6455       Cond = Cmp;
6456       addTest = false;
6457     } else {
6458       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
6459       default: break;
6460       case X86::COND_O:
6461       case X86::COND_B:
6462         // These can only come from an arithmetic instruction with overflow,
6463         // e.g. SADDO, UADDO.
6464         Cond = Cond.getNode()->getOperand(1);
6465         addTest = false;
6466         break;
6467       }
6468     }
6469   } else {
6470     unsigned CondOpc;
6471     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
6472       SDValue Cmp = Cond.getOperand(0).getOperand(1);
6473       if (CondOpc == ISD::OR) {
6474         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
6475         // two branches instead of an explicit OR instruction with a
6476         // separate test.
6477         if (Cmp == Cond.getOperand(1).getOperand(1) &&
6478             isX86LogicalCmp(Cmp)) {
6479           CC = Cond.getOperand(0).getOperand(0);
6480           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6481                               Chain, Dest, CC, Cmp);
6482           CC = Cond.getOperand(1).getOperand(0);
6483           Cond = Cmp;
6484           addTest = false;
6485         }
6486       } else { // ISD::AND
6487         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
6488         // two branches instead of an explicit AND instruction with a
6489         // separate test. However, we only do this if this block doesn't
6490         // have a fall-through edge, because this requires an explicit
6491         // jmp when the condition is false.
6492         if (Cmp == Cond.getOperand(1).getOperand(1) &&
6493             isX86LogicalCmp(Cmp) &&
6494             Op.getNode()->hasOneUse()) {
6495           X86::CondCode CCode =
6496             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
6497           CCode = X86::GetOppositeBranchCondition(CCode);
6498           CC = DAG.getConstant(CCode, MVT::i8);
6499           SDValue User = SDValue(*Op.getNode()->use_begin(), 0);
6500           // Look for an unconditional branch following this conditional branch.
6501           // We need this because we need to reverse the successors in order
6502           // to implement FCMP_OEQ.
6503           if (User.getOpcode() == ISD::BR) {
6504             SDValue FalseBB = User.getOperand(1);
6505             SDValue NewBR =
6506               DAG.UpdateNodeOperands(User, User.getOperand(0), Dest);
6507             assert(NewBR == User);
6508             Dest = FalseBB;
6509
6510             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6511                                 Chain, Dest, CC, Cmp);
6512             X86::CondCode CCode =
6513               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
6514             CCode = X86::GetOppositeBranchCondition(CCode);
6515             CC = DAG.getConstant(CCode, MVT::i8);
6516             Cond = Cmp;
6517             addTest = false;
6518           }
6519         }
6520       }
6521     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
6522       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
6523       // It should be transformed during dag combiner except when the condition
6524       // is set by a arithmetics with overflow node.
6525       X86::CondCode CCode =
6526         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
6527       CCode = X86::GetOppositeBranchCondition(CCode);
6528       CC = DAG.getConstant(CCode, MVT::i8);
6529       Cond = Cond.getOperand(0).getOperand(1);
6530       addTest = false;
6531     }
6532   }
6533
6534   if (addTest) {
6535     // Look pass the truncate.
6536     if (Cond.getOpcode() == ISD::TRUNCATE)
6537       Cond = Cond.getOperand(0);
6538
6539     // We know the result of AND is compared against zero. Try to match
6540     // it to BT.
6541     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) { 
6542       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
6543       if (NewSetCC.getNode()) {
6544         CC = NewSetCC.getOperand(0);
6545         Cond = NewSetCC.getOperand(1);
6546         addTest = false;
6547       }
6548     }
6549   }
6550
6551   if (addTest) {
6552     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6553     Cond = EmitTest(Cond, X86::COND_NE, DAG);
6554   }
6555   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6556                      Chain, Dest, CC, Cond);
6557 }
6558
6559
6560 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
6561 // Calls to _alloca is needed to probe the stack when allocating more than 4k
6562 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
6563 // that the guard pages used by the OS virtual memory manager are allocated in
6564 // correct sequence.
6565 SDValue
6566 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
6567                                            SelectionDAG &DAG) const {
6568   assert(Subtarget->isTargetCygMing() &&
6569          "This should be used only on Cygwin/Mingw targets");
6570   DebugLoc dl = Op.getDebugLoc();
6571
6572   // Get the inputs.
6573   SDValue Chain = Op.getOperand(0);
6574   SDValue Size  = Op.getOperand(1);
6575   // FIXME: Ensure alignment here
6576
6577   SDValue Flag;
6578
6579   EVT IntPtr = getPointerTy();
6580   EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
6581
6582   Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
6583   Flag = Chain.getValue(1);
6584
6585   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
6586
6587   Chain = DAG.getNode(X86ISD::MINGW_ALLOCA, dl, NodeTys, Chain, Flag);
6588   Flag = Chain.getValue(1);
6589
6590   Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
6591
6592   SDValue Ops1[2] = { Chain.getValue(0), Chain };
6593   return DAG.getMergeValues(Ops1, 2, dl);
6594 }
6595
6596 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
6597   MachineFunction &MF = DAG.getMachineFunction();
6598   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
6599
6600   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
6601   DebugLoc dl = Op.getDebugLoc();
6602
6603   if (!Subtarget->is64Bit()) {
6604     // vastart just stores the address of the VarArgsFrameIndex slot into the
6605     // memory location argument.
6606     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
6607                                    getPointerTy());
6608     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), SV, 0,
6609                         false, false, 0);
6610   }
6611
6612   // __va_list_tag:
6613   //   gp_offset         (0 - 6 * 8)
6614   //   fp_offset         (48 - 48 + 8 * 16)
6615   //   overflow_arg_area (point to parameters coming in memory).
6616   //   reg_save_area
6617   SmallVector<SDValue, 8> MemOps;
6618   SDValue FIN = Op.getOperand(1);
6619   // Store gp_offset
6620   SDValue Store = DAG.getStore(Op.getOperand(0), dl,
6621                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
6622                                                MVT::i32),
6623                                FIN, SV, 0, false, false, 0);
6624   MemOps.push_back(Store);
6625
6626   // Store fp_offset
6627   FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6628                     FIN, DAG.getIntPtrConstant(4));
6629   Store = DAG.getStore(Op.getOperand(0), dl,
6630                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
6631                                        MVT::i32),
6632                        FIN, SV, 0, false, false, 0);
6633   MemOps.push_back(Store);
6634
6635   // Store ptr to overflow_arg_area
6636   FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6637                     FIN, DAG.getIntPtrConstant(4));
6638   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
6639                                     getPointerTy());
6640   Store = DAG.getStore(Op.getOperand(0), dl, OVFIN, FIN, SV, 0,
6641                        false, false, 0);
6642   MemOps.push_back(Store);
6643
6644   // Store ptr to reg_save_area.
6645   FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6646                     FIN, DAG.getIntPtrConstant(8));
6647   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
6648                                     getPointerTy());
6649   Store = DAG.getStore(Op.getOperand(0), dl, RSFIN, FIN, SV, 0,
6650                        false, false, 0);
6651   MemOps.push_back(Store);
6652   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6653                      &MemOps[0], MemOps.size());
6654 }
6655
6656 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
6657   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6658   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
6659   SDValue Chain = Op.getOperand(0);
6660   SDValue SrcPtr = Op.getOperand(1);
6661   SDValue SrcSV = Op.getOperand(2);
6662
6663   report_fatal_error("VAArgInst is not yet implemented for x86-64!");
6664   return SDValue();
6665 }
6666
6667 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
6668   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6669   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
6670   SDValue Chain = Op.getOperand(0);
6671   SDValue DstPtr = Op.getOperand(1);
6672   SDValue SrcPtr = Op.getOperand(2);
6673   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
6674   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6675   DebugLoc dl = Op.getDebugLoc();
6676
6677   return DAG.getMemcpy(Chain, dl, DstPtr, SrcPtr,
6678                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
6679                        false, DstSV, 0, SrcSV, 0);
6680 }
6681
6682 SDValue
6683 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
6684   DebugLoc dl = Op.getDebugLoc();
6685   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6686   switch (IntNo) {
6687   default: return SDValue();    // Don't custom lower most intrinsics.
6688   // Comparison intrinsics.
6689   case Intrinsic::x86_sse_comieq_ss:
6690   case Intrinsic::x86_sse_comilt_ss:
6691   case Intrinsic::x86_sse_comile_ss:
6692   case Intrinsic::x86_sse_comigt_ss:
6693   case Intrinsic::x86_sse_comige_ss:
6694   case Intrinsic::x86_sse_comineq_ss:
6695   case Intrinsic::x86_sse_ucomieq_ss:
6696   case Intrinsic::x86_sse_ucomilt_ss:
6697   case Intrinsic::x86_sse_ucomile_ss:
6698   case Intrinsic::x86_sse_ucomigt_ss:
6699   case Intrinsic::x86_sse_ucomige_ss:
6700   case Intrinsic::x86_sse_ucomineq_ss:
6701   case Intrinsic::x86_sse2_comieq_sd:
6702   case Intrinsic::x86_sse2_comilt_sd:
6703   case Intrinsic::x86_sse2_comile_sd:
6704   case Intrinsic::x86_sse2_comigt_sd:
6705   case Intrinsic::x86_sse2_comige_sd:
6706   case Intrinsic::x86_sse2_comineq_sd:
6707   case Intrinsic::x86_sse2_ucomieq_sd:
6708   case Intrinsic::x86_sse2_ucomilt_sd:
6709   case Intrinsic::x86_sse2_ucomile_sd:
6710   case Intrinsic::x86_sse2_ucomigt_sd:
6711   case Intrinsic::x86_sse2_ucomige_sd:
6712   case Intrinsic::x86_sse2_ucomineq_sd: {
6713     unsigned Opc = 0;
6714     ISD::CondCode CC = ISD::SETCC_INVALID;
6715     switch (IntNo) {
6716     default: break;
6717     case Intrinsic::x86_sse_comieq_ss:
6718     case Intrinsic::x86_sse2_comieq_sd:
6719       Opc = X86ISD::COMI;
6720       CC = ISD::SETEQ;
6721       break;
6722     case Intrinsic::x86_sse_comilt_ss:
6723     case Intrinsic::x86_sse2_comilt_sd:
6724       Opc = X86ISD::COMI;
6725       CC = ISD::SETLT;
6726       break;
6727     case Intrinsic::x86_sse_comile_ss:
6728     case Intrinsic::x86_sse2_comile_sd:
6729       Opc = X86ISD::COMI;
6730       CC = ISD::SETLE;
6731       break;
6732     case Intrinsic::x86_sse_comigt_ss:
6733     case Intrinsic::x86_sse2_comigt_sd:
6734       Opc = X86ISD::COMI;
6735       CC = ISD::SETGT;
6736       break;
6737     case Intrinsic::x86_sse_comige_ss:
6738     case Intrinsic::x86_sse2_comige_sd:
6739       Opc = X86ISD::COMI;
6740       CC = ISD::SETGE;
6741       break;
6742     case Intrinsic::x86_sse_comineq_ss:
6743     case Intrinsic::x86_sse2_comineq_sd:
6744       Opc = X86ISD::COMI;
6745       CC = ISD::SETNE;
6746       break;
6747     case Intrinsic::x86_sse_ucomieq_ss:
6748     case Intrinsic::x86_sse2_ucomieq_sd:
6749       Opc = X86ISD::UCOMI;
6750       CC = ISD::SETEQ;
6751       break;
6752     case Intrinsic::x86_sse_ucomilt_ss:
6753     case Intrinsic::x86_sse2_ucomilt_sd:
6754       Opc = X86ISD::UCOMI;
6755       CC = ISD::SETLT;
6756       break;
6757     case Intrinsic::x86_sse_ucomile_ss:
6758     case Intrinsic::x86_sse2_ucomile_sd:
6759       Opc = X86ISD::UCOMI;
6760       CC = ISD::SETLE;
6761       break;
6762     case Intrinsic::x86_sse_ucomigt_ss:
6763     case Intrinsic::x86_sse2_ucomigt_sd:
6764       Opc = X86ISD::UCOMI;
6765       CC = ISD::SETGT;
6766       break;
6767     case Intrinsic::x86_sse_ucomige_ss:
6768     case Intrinsic::x86_sse2_ucomige_sd:
6769       Opc = X86ISD::UCOMI;
6770       CC = ISD::SETGE;
6771       break;
6772     case Intrinsic::x86_sse_ucomineq_ss:
6773     case Intrinsic::x86_sse2_ucomineq_sd:
6774       Opc = X86ISD::UCOMI;
6775       CC = ISD::SETNE;
6776       break;
6777     }
6778
6779     SDValue LHS = Op.getOperand(1);
6780     SDValue RHS = Op.getOperand(2);
6781     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
6782     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
6783     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
6784     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6785                                 DAG.getConstant(X86CC, MVT::i8), Cond);
6786     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6787   }
6788   // ptest intrinsics. The intrinsic these come from are designed to return
6789   // an integer value, not just an instruction so lower it to the ptest
6790   // pattern and a setcc for the result.
6791   case Intrinsic::x86_sse41_ptestz:
6792   case Intrinsic::x86_sse41_ptestc:
6793   case Intrinsic::x86_sse41_ptestnzc:{
6794     unsigned X86CC = 0;
6795     switch (IntNo) {
6796     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
6797     case Intrinsic::x86_sse41_ptestz:
6798       // ZF = 1
6799       X86CC = X86::COND_E;
6800       break;
6801     case Intrinsic::x86_sse41_ptestc:
6802       // CF = 1
6803       X86CC = X86::COND_B;
6804       break;
6805     case Intrinsic::x86_sse41_ptestnzc:
6806       // ZF and CF = 0
6807       X86CC = X86::COND_A;
6808       break;
6809     }
6810
6811     SDValue LHS = Op.getOperand(1);
6812     SDValue RHS = Op.getOperand(2);
6813     SDValue Test = DAG.getNode(X86ISD::PTEST, dl, MVT::i32, LHS, RHS);
6814     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
6815     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
6816     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6817   }
6818
6819   // Fix vector shift instructions where the last operand is a non-immediate
6820   // i32 value.
6821   case Intrinsic::x86_sse2_pslli_w:
6822   case Intrinsic::x86_sse2_pslli_d:
6823   case Intrinsic::x86_sse2_pslli_q:
6824   case Intrinsic::x86_sse2_psrli_w:
6825   case Intrinsic::x86_sse2_psrli_d:
6826   case Intrinsic::x86_sse2_psrli_q:
6827   case Intrinsic::x86_sse2_psrai_w:
6828   case Intrinsic::x86_sse2_psrai_d:
6829   case Intrinsic::x86_mmx_pslli_w:
6830   case Intrinsic::x86_mmx_pslli_d:
6831   case Intrinsic::x86_mmx_pslli_q:
6832   case Intrinsic::x86_mmx_psrli_w:
6833   case Intrinsic::x86_mmx_psrli_d:
6834   case Intrinsic::x86_mmx_psrli_q:
6835   case Intrinsic::x86_mmx_psrai_w:
6836   case Intrinsic::x86_mmx_psrai_d: {
6837     SDValue ShAmt = Op.getOperand(2);
6838     if (isa<ConstantSDNode>(ShAmt))
6839       return SDValue();
6840
6841     unsigned NewIntNo = 0;
6842     EVT ShAmtVT = MVT::v4i32;
6843     switch (IntNo) {
6844     case Intrinsic::x86_sse2_pslli_w:
6845       NewIntNo = Intrinsic::x86_sse2_psll_w;
6846       break;
6847     case Intrinsic::x86_sse2_pslli_d:
6848       NewIntNo = Intrinsic::x86_sse2_psll_d;
6849       break;
6850     case Intrinsic::x86_sse2_pslli_q:
6851       NewIntNo = Intrinsic::x86_sse2_psll_q;
6852       break;
6853     case Intrinsic::x86_sse2_psrli_w:
6854       NewIntNo = Intrinsic::x86_sse2_psrl_w;
6855       break;
6856     case Intrinsic::x86_sse2_psrli_d:
6857       NewIntNo = Intrinsic::x86_sse2_psrl_d;
6858       break;
6859     case Intrinsic::x86_sse2_psrli_q:
6860       NewIntNo = Intrinsic::x86_sse2_psrl_q;
6861       break;
6862     case Intrinsic::x86_sse2_psrai_w:
6863       NewIntNo = Intrinsic::x86_sse2_psra_w;
6864       break;
6865     case Intrinsic::x86_sse2_psrai_d:
6866       NewIntNo = Intrinsic::x86_sse2_psra_d;
6867       break;
6868     default: {
6869       ShAmtVT = MVT::v2i32;
6870       switch (IntNo) {
6871       case Intrinsic::x86_mmx_pslli_w:
6872         NewIntNo = Intrinsic::x86_mmx_psll_w;
6873         break;
6874       case Intrinsic::x86_mmx_pslli_d:
6875         NewIntNo = Intrinsic::x86_mmx_psll_d;
6876         break;
6877       case Intrinsic::x86_mmx_pslli_q:
6878         NewIntNo = Intrinsic::x86_mmx_psll_q;
6879         break;
6880       case Intrinsic::x86_mmx_psrli_w:
6881         NewIntNo = Intrinsic::x86_mmx_psrl_w;
6882         break;
6883       case Intrinsic::x86_mmx_psrli_d:
6884         NewIntNo = Intrinsic::x86_mmx_psrl_d;
6885         break;
6886       case Intrinsic::x86_mmx_psrli_q:
6887         NewIntNo = Intrinsic::x86_mmx_psrl_q;
6888         break;
6889       case Intrinsic::x86_mmx_psrai_w:
6890         NewIntNo = Intrinsic::x86_mmx_psra_w;
6891         break;
6892       case Intrinsic::x86_mmx_psrai_d:
6893         NewIntNo = Intrinsic::x86_mmx_psra_d;
6894         break;
6895       default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6896       }
6897       break;
6898     }
6899     }
6900
6901     // The vector shift intrinsics with scalars uses 32b shift amounts but
6902     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
6903     // to be zero.
6904     SDValue ShOps[4];
6905     ShOps[0] = ShAmt;
6906     ShOps[1] = DAG.getConstant(0, MVT::i32);
6907     if (ShAmtVT == MVT::v4i32) {
6908       ShOps[2] = DAG.getUNDEF(MVT::i32);
6909       ShOps[3] = DAG.getUNDEF(MVT::i32);
6910       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
6911     } else {
6912       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
6913     }
6914
6915     EVT VT = Op.getValueType();
6916     ShAmt = DAG.getNode(ISD::BIT_CONVERT, dl, VT, ShAmt);
6917     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6918                        DAG.getConstant(NewIntNo, MVT::i32),
6919                        Op.getOperand(1), ShAmt);
6920   }
6921   }
6922 }
6923
6924 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
6925                                            SelectionDAG &DAG) const {
6926   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6927   DebugLoc dl = Op.getDebugLoc();
6928
6929   if (Depth > 0) {
6930     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
6931     SDValue Offset =
6932       DAG.getConstant(TD->getPointerSize(),
6933                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
6934     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6935                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
6936                                    FrameAddr, Offset),
6937                        NULL, 0, false, false, 0);
6938   }
6939
6940   // Just load the return address.
6941   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
6942   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6943                      RetAddrFI, NULL, 0, false, false, 0);
6944 }
6945
6946 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
6947   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6948   MFI->setFrameAddressIsTaken(true);
6949   EVT VT = Op.getValueType();
6950   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
6951   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6952   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
6953   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
6954   while (Depth--)
6955     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, NULL, 0,
6956                             false, false, 0);
6957   return FrameAddr;
6958 }
6959
6960 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
6961                                                      SelectionDAG &DAG) const {
6962   return DAG.getIntPtrConstant(2*TD->getPointerSize());
6963 }
6964
6965 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
6966   MachineFunction &MF = DAG.getMachineFunction();
6967   SDValue Chain     = Op.getOperand(0);
6968   SDValue Offset    = Op.getOperand(1);
6969   SDValue Handler   = Op.getOperand(2);
6970   DebugLoc dl       = Op.getDebugLoc();
6971
6972   SDValue Frame = DAG.getRegister(Subtarget->is64Bit() ? X86::RBP : X86::EBP,
6973                                   getPointerTy());
6974   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
6975
6976   SDValue StoreAddr = DAG.getNode(ISD::SUB, dl, getPointerTy(), Frame,
6977                                   DAG.getIntPtrConstant(-TD->getPointerSize()));
6978   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
6979   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, NULL, 0, false, false, 0);
6980   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
6981   MF.getRegInfo().addLiveOut(StoreAddrReg);
6982
6983   return DAG.getNode(X86ISD::EH_RETURN, dl,
6984                      MVT::Other,
6985                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
6986 }
6987
6988 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
6989                                              SelectionDAG &DAG) const {
6990   SDValue Root = Op.getOperand(0);
6991   SDValue Trmp = Op.getOperand(1); // trampoline
6992   SDValue FPtr = Op.getOperand(2); // nested function
6993   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
6994   DebugLoc dl  = Op.getDebugLoc();
6995
6996   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6997
6998   if (Subtarget->is64Bit()) {
6999     SDValue OutChains[6];
7000
7001     // Large code-model.
7002     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
7003     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
7004
7005     const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
7006     const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
7007
7008     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
7009
7010     // Load the pointer to the nested function into R11.
7011     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
7012     SDValue Addr = Trmp;
7013     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7014                                 Addr, TrmpAddr, 0, false, false, 0);
7015
7016     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7017                        DAG.getConstant(2, MVT::i64));
7018     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr, TrmpAddr, 2,
7019                                 false, false, 2);
7020
7021     // Load the 'nest' parameter value into R10.
7022     // R10 is specified in X86CallingConv.td
7023     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
7024     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7025                        DAG.getConstant(10, MVT::i64));
7026     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7027                                 Addr, TrmpAddr, 10, false, false, 0);
7028
7029     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7030                        DAG.getConstant(12, MVT::i64));
7031     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 12,
7032                                 false, false, 2);
7033
7034     // Jump to the nested function.
7035     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
7036     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7037                        DAG.getConstant(20, MVT::i64));
7038     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7039                                 Addr, TrmpAddr, 20, false, false, 0);
7040
7041     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
7042     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7043                        DAG.getConstant(22, MVT::i64));
7044     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
7045                                 TrmpAddr, 22, false, false, 0);
7046
7047     SDValue Ops[] =
7048       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
7049     return DAG.getMergeValues(Ops, 2, dl);
7050   } else {
7051     const Function *Func =
7052       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
7053     CallingConv::ID CC = Func->getCallingConv();
7054     unsigned NestReg;
7055
7056     switch (CC) {
7057     default:
7058       llvm_unreachable("Unsupported calling convention");
7059     case CallingConv::C:
7060     case CallingConv::X86_StdCall: {
7061       // Pass 'nest' parameter in ECX.
7062       // Must be kept in sync with X86CallingConv.td
7063       NestReg = X86::ECX;
7064
7065       // Check that ECX wasn't needed by an 'inreg' parameter.
7066       const FunctionType *FTy = Func->getFunctionType();
7067       const AttrListPtr &Attrs = Func->getAttributes();
7068
7069       if (!Attrs.isEmpty() && !Func->isVarArg()) {
7070         unsigned InRegCount = 0;
7071         unsigned Idx = 1;
7072
7073         for (FunctionType::param_iterator I = FTy->param_begin(),
7074              E = FTy->param_end(); I != E; ++I, ++Idx)
7075           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
7076             // FIXME: should only count parameters that are lowered to integers.
7077             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
7078
7079         if (InRegCount > 2) {
7080           report_fatal_error("Nest register in use - reduce number of inreg parameters!");
7081         }
7082       }
7083       break;
7084     }
7085     case CallingConv::X86_FastCall:
7086     case CallingConv::Fast:
7087       // Pass 'nest' parameter in EAX.
7088       // Must be kept in sync with X86CallingConv.td
7089       NestReg = X86::EAX;
7090       break;
7091     }
7092
7093     SDValue OutChains[4];
7094     SDValue Addr, Disp;
7095
7096     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7097                        DAG.getConstant(10, MVT::i32));
7098     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
7099
7100     // This is storing the opcode for MOV32ri.
7101     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
7102     const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
7103     OutChains[0] = DAG.getStore(Root, dl,
7104                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
7105                                 Trmp, TrmpAddr, 0, false, false, 0);
7106
7107     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7108                        DAG.getConstant(1, MVT::i32));
7109     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 1,
7110                                 false, false, 1);
7111
7112     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
7113     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7114                        DAG.getConstant(5, MVT::i32));
7115     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
7116                                 TrmpAddr, 5, false, false, 1);
7117
7118     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7119                        DAG.getConstant(6, MVT::i32));
7120     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr, TrmpAddr, 6,
7121                                 false, false, 1);
7122
7123     SDValue Ops[] =
7124       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
7125     return DAG.getMergeValues(Ops, 2, dl);
7126   }
7127 }
7128
7129 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
7130                                             SelectionDAG &DAG) const {
7131   /*
7132    The rounding mode is in bits 11:10 of FPSR, and has the following
7133    settings:
7134      00 Round to nearest
7135      01 Round to -inf
7136      10 Round to +inf
7137      11 Round to 0
7138
7139   FLT_ROUNDS, on the other hand, expects the following:
7140     -1 Undefined
7141      0 Round to 0
7142      1 Round to nearest
7143      2 Round to +inf
7144      3 Round to -inf
7145
7146   To perform the conversion, we do:
7147     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
7148   */
7149
7150   MachineFunction &MF = DAG.getMachineFunction();
7151   const TargetMachine &TM = MF.getTarget();
7152   const TargetFrameInfo &TFI = *TM.getFrameInfo();
7153   unsigned StackAlignment = TFI.getStackAlignment();
7154   EVT VT = Op.getValueType();
7155   DebugLoc dl = Op.getDebugLoc();
7156
7157   // Save FP Control Word to stack slot
7158   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
7159   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7160
7161   SDValue Chain = DAG.getNode(X86ISD::FNSTCW16m, dl, MVT::Other,
7162                               DAG.getEntryNode(), StackSlot);
7163
7164   // Load FP Control Word from stack slot
7165   SDValue CWD = DAG.getLoad(MVT::i16, dl, Chain, StackSlot, NULL, 0,
7166                             false, false, 0);
7167
7168   // Transform as necessary
7169   SDValue CWD1 =
7170     DAG.getNode(ISD::SRL, dl, MVT::i16,
7171                 DAG.getNode(ISD::AND, dl, MVT::i16,
7172                             CWD, DAG.getConstant(0x800, MVT::i16)),
7173                 DAG.getConstant(11, MVT::i8));
7174   SDValue CWD2 =
7175     DAG.getNode(ISD::SRL, dl, MVT::i16,
7176                 DAG.getNode(ISD::AND, dl, MVT::i16,
7177                             CWD, DAG.getConstant(0x400, MVT::i16)),
7178                 DAG.getConstant(9, MVT::i8));
7179
7180   SDValue RetVal =
7181     DAG.getNode(ISD::AND, dl, MVT::i16,
7182                 DAG.getNode(ISD::ADD, dl, MVT::i16,
7183                             DAG.getNode(ISD::OR, dl, MVT::i16, CWD1, CWD2),
7184                             DAG.getConstant(1, MVT::i16)),
7185                 DAG.getConstant(3, MVT::i16));
7186
7187
7188   return DAG.getNode((VT.getSizeInBits() < 16 ?
7189                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
7190 }
7191
7192 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
7193   EVT VT = Op.getValueType();
7194   EVT OpVT = VT;
7195   unsigned NumBits = VT.getSizeInBits();
7196   DebugLoc dl = Op.getDebugLoc();
7197
7198   Op = Op.getOperand(0);
7199   if (VT == MVT::i8) {
7200     // Zero extend to i32 since there is not an i8 bsr.
7201     OpVT = MVT::i32;
7202     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
7203   }
7204
7205   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
7206   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
7207   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
7208
7209   // If src is zero (i.e. bsr sets ZF), returns NumBits.
7210   SDValue Ops[] = {
7211     Op,
7212     DAG.getConstant(NumBits+NumBits-1, OpVT),
7213     DAG.getConstant(X86::COND_E, MVT::i8),
7214     Op.getValue(1)
7215   };
7216   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
7217
7218   // Finally xor with NumBits-1.
7219   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
7220
7221   if (VT == MVT::i8)
7222     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
7223   return Op;
7224 }
7225
7226 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
7227   EVT VT = Op.getValueType();
7228   EVT OpVT = VT;
7229   unsigned NumBits = VT.getSizeInBits();
7230   DebugLoc dl = Op.getDebugLoc();
7231
7232   Op = Op.getOperand(0);
7233   if (VT == MVT::i8) {
7234     OpVT = MVT::i32;
7235     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
7236   }
7237
7238   // Issue a bsf (scan bits forward) which also sets EFLAGS.
7239   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
7240   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
7241
7242   // If src is zero (i.e. bsf sets ZF), returns NumBits.
7243   SDValue Ops[] = {
7244     Op,
7245     DAG.getConstant(NumBits, OpVT),
7246     DAG.getConstant(X86::COND_E, MVT::i8),
7247     Op.getValue(1)
7248   };
7249   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
7250
7251   if (VT == MVT::i8)
7252     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
7253   return Op;
7254 }
7255
7256 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) const {
7257   EVT VT = Op.getValueType();
7258   assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
7259   DebugLoc dl = Op.getDebugLoc();
7260
7261   //  ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
7262   //  ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
7263   //  ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
7264   //  ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
7265   //  ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
7266   //
7267   //  AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
7268   //  AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
7269   //  return AloBlo + AloBhi + AhiBlo;
7270
7271   SDValue A = Op.getOperand(0);
7272   SDValue B = Op.getOperand(1);
7273
7274   SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7275                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
7276                        A, DAG.getConstant(32, MVT::i32));
7277   SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7278                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
7279                        B, DAG.getConstant(32, MVT::i32));
7280   SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7281                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7282                        A, B);
7283   SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7284                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7285                        A, Bhi);
7286   SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7287                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7288                        Ahi, B);
7289   AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7290                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
7291                        AloBhi, DAG.getConstant(32, MVT::i32));
7292   AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7293                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
7294                        AhiBlo, DAG.getConstant(32, MVT::i32));
7295   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
7296   Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
7297   return Res;
7298 }
7299
7300
7301 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
7302   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
7303   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
7304   // looks for this combo and may remove the "setcc" instruction if the "setcc"
7305   // has only one use.
7306   SDNode *N = Op.getNode();
7307   SDValue LHS = N->getOperand(0);
7308   SDValue RHS = N->getOperand(1);
7309   unsigned BaseOp = 0;
7310   unsigned Cond = 0;
7311   DebugLoc dl = Op.getDebugLoc();
7312
7313   switch (Op.getOpcode()) {
7314   default: llvm_unreachable("Unknown ovf instruction!");
7315   case ISD::SADDO:
7316     // A subtract of one will be selected as a INC. Note that INC doesn't
7317     // set CF, so we can't do this for UADDO.
7318     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
7319       if (C->getAPIntValue() == 1) {
7320         BaseOp = X86ISD::INC;
7321         Cond = X86::COND_O;
7322         break;
7323       }
7324     BaseOp = X86ISD::ADD;
7325     Cond = X86::COND_O;
7326     break;
7327   case ISD::UADDO:
7328     BaseOp = X86ISD::ADD;
7329     Cond = X86::COND_B;
7330     break;
7331   case ISD::SSUBO:
7332     // A subtract of one will be selected as a DEC. Note that DEC doesn't
7333     // set CF, so we can't do this for USUBO.
7334     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
7335       if (C->getAPIntValue() == 1) {
7336         BaseOp = X86ISD::DEC;
7337         Cond = X86::COND_O;
7338         break;
7339       }
7340     BaseOp = X86ISD::SUB;
7341     Cond = X86::COND_O;
7342     break;
7343   case ISD::USUBO:
7344     BaseOp = X86ISD::SUB;
7345     Cond = X86::COND_B;
7346     break;
7347   case ISD::SMULO:
7348     BaseOp = X86ISD::SMUL;
7349     Cond = X86::COND_O;
7350     break;
7351   case ISD::UMULO:
7352     BaseOp = X86ISD::UMUL;
7353     Cond = X86::COND_B;
7354     break;
7355   }
7356
7357   // Also sets EFLAGS.
7358   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
7359   SDValue Sum = DAG.getNode(BaseOp, dl, VTs, LHS, RHS);
7360
7361   SDValue SetCC =
7362     DAG.getNode(X86ISD::SETCC, dl, N->getValueType(1),
7363                 DAG.getConstant(Cond, MVT::i32), SDValue(Sum.getNode(), 1));
7364
7365   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
7366   return Sum;
7367 }
7368
7369 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
7370   EVT T = Op.getValueType();
7371   DebugLoc dl = Op.getDebugLoc();
7372   unsigned Reg = 0;
7373   unsigned size = 0;
7374   switch(T.getSimpleVT().SimpleTy) {
7375   default:
7376     assert(false && "Invalid value type!");
7377   case MVT::i8:  Reg = X86::AL;  size = 1; break;
7378   case MVT::i16: Reg = X86::AX;  size = 2; break;
7379   case MVT::i32: Reg = X86::EAX; size = 4; break;
7380   case MVT::i64:
7381     assert(Subtarget->is64Bit() && "Node not type legal!");
7382     Reg = X86::RAX; size = 8;
7383     break;
7384   }
7385   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), dl, Reg,
7386                                     Op.getOperand(2), SDValue());
7387   SDValue Ops[] = { cpIn.getValue(0),
7388                     Op.getOperand(1),
7389                     Op.getOperand(3),
7390                     DAG.getTargetConstant(size, MVT::i8),
7391                     cpIn.getValue(1) };
7392   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7393   SDValue Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, dl, Tys, Ops, 5);
7394   SDValue cpOut =
7395     DAG.getCopyFromReg(Result.getValue(0), dl, Reg, T, Result.getValue(1));
7396   return cpOut;
7397 }
7398
7399 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
7400                                                  SelectionDAG &DAG) const {
7401   assert(Subtarget->is64Bit() && "Result not type legalized?");
7402   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7403   SDValue TheChain = Op.getOperand(0);
7404   DebugLoc dl = Op.getDebugLoc();
7405   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
7406   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
7407   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
7408                                    rax.getValue(2));
7409   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
7410                             DAG.getConstant(32, MVT::i8));
7411   SDValue Ops[] = {
7412     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
7413     rdx.getValue(1)
7414   };
7415   return DAG.getMergeValues(Ops, 2, dl);
7416 }
7417
7418 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
7419   SDNode *Node = Op.getNode();
7420   DebugLoc dl = Node->getDebugLoc();
7421   EVT T = Node->getValueType(0);
7422   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
7423                               DAG.getConstant(0, T), Node->getOperand(2));
7424   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
7425                        cast<AtomicSDNode>(Node)->getMemoryVT(),
7426                        Node->getOperand(0),
7427                        Node->getOperand(1), negOp,
7428                        cast<AtomicSDNode>(Node)->getSrcValue(),
7429                        cast<AtomicSDNode>(Node)->getAlignment());
7430 }
7431
7432 /// LowerOperation - Provide custom lowering hooks for some operations.
7433 ///
7434 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
7435   switch (Op.getOpcode()) {
7436   default: llvm_unreachable("Should not custom lower this!");
7437   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
7438   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
7439   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
7440   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
7441   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
7442   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
7443   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
7444   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
7445   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
7446   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
7447   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
7448   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
7449   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
7450   case ISD::SHL_PARTS:
7451   case ISD::SRA_PARTS:
7452   case ISD::SRL_PARTS:          return LowerShift(Op, DAG);
7453   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
7454   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
7455   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
7456   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
7457   case ISD::FABS:               return LowerFABS(Op, DAG);
7458   case ISD::FNEG:               return LowerFNEG(Op, DAG);
7459   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
7460   case ISD::SETCC:              return LowerSETCC(Op, DAG);
7461   case ISD::VSETCC:             return LowerVSETCC(Op, DAG);
7462   case ISD::SELECT:             return LowerSELECT(Op, DAG);
7463   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
7464   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
7465   case ISD::VASTART:            return LowerVASTART(Op, DAG);
7466   case ISD::VAARG:              return LowerVAARG(Op, DAG);
7467   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
7468   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
7469   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
7470   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
7471   case ISD::FRAME_TO_ARGS_OFFSET:
7472                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
7473   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
7474   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
7475   case ISD::TRAMPOLINE:         return LowerTRAMPOLINE(Op, DAG);
7476   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
7477   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
7478   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
7479   case ISD::MUL:                return LowerMUL_V2I64(Op, DAG);
7480   case ISD::SADDO:
7481   case ISD::UADDO:
7482   case ISD::SSUBO:
7483   case ISD::USUBO:
7484   case ISD::SMULO:
7485   case ISD::UMULO:              return LowerXALUO(Op, DAG);
7486   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
7487   }
7488 }
7489
7490 void X86TargetLowering::
7491 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
7492                         SelectionDAG &DAG, unsigned NewOp) const {
7493   EVT T = Node->getValueType(0);
7494   DebugLoc dl = Node->getDebugLoc();
7495   assert (T == MVT::i64 && "Only know how to expand i64 atomics");
7496
7497   SDValue Chain = Node->getOperand(0);
7498   SDValue In1 = Node->getOperand(1);
7499   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7500                              Node->getOperand(2), DAG.getIntPtrConstant(0));
7501   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7502                              Node->getOperand(2), DAG.getIntPtrConstant(1));
7503   SDValue Ops[] = { Chain, In1, In2L, In2H };
7504   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
7505   SDValue Result =
7506     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
7507                             cast<MemSDNode>(Node)->getMemOperand());
7508   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
7509   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
7510   Results.push_back(Result.getValue(2));
7511 }
7512
7513 /// ReplaceNodeResults - Replace a node with an illegal result type
7514 /// with a new node built out of custom code.
7515 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
7516                                            SmallVectorImpl<SDValue>&Results,
7517                                            SelectionDAG &DAG) const {
7518   DebugLoc dl = N->getDebugLoc();
7519   switch (N->getOpcode()) {
7520   default:
7521     assert(false && "Do not know how to custom type legalize this operation!");
7522     return;
7523   case ISD::FP_TO_SINT: {
7524     std::pair<SDValue,SDValue> Vals =
7525         FP_TO_INTHelper(SDValue(N, 0), DAG, true);
7526     SDValue FIST = Vals.first, StackSlot = Vals.second;
7527     if (FIST.getNode() != 0) {
7528       EVT VT = N->getValueType(0);
7529       // Return a load from the stack slot.
7530       Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot, NULL, 0,
7531                                     false, false, 0));
7532     }
7533     return;
7534   }
7535   case ISD::READCYCLECOUNTER: {
7536     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7537     SDValue TheChain = N->getOperand(0);
7538     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
7539     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
7540                                      rd.getValue(1));
7541     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
7542                                      eax.getValue(2));
7543     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
7544     SDValue Ops[] = { eax, edx };
7545     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
7546     Results.push_back(edx.getValue(1));
7547     return;
7548   }
7549   case ISD::ATOMIC_CMP_SWAP: {
7550     EVT T = N->getValueType(0);
7551     assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
7552     SDValue cpInL, cpInH;
7553     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7554                         DAG.getConstant(0, MVT::i32));
7555     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7556                         DAG.getConstant(1, MVT::i32));
7557     cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
7558     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
7559                              cpInL.getValue(1));
7560     SDValue swapInL, swapInH;
7561     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7562                           DAG.getConstant(0, MVT::i32));
7563     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7564                           DAG.getConstant(1, MVT::i32));
7565     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
7566                                cpInH.getValue(1));
7567     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
7568                                swapInL.getValue(1));
7569     SDValue Ops[] = { swapInH.getValue(0),
7570                       N->getOperand(1),
7571                       swapInH.getValue(1) };
7572     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7573     SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, dl, Tys, Ops, 3);
7574     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
7575                                         MVT::i32, Result.getValue(1));
7576     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
7577                                         MVT::i32, cpOutL.getValue(2));
7578     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
7579     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
7580     Results.push_back(cpOutH.getValue(1));
7581     return;
7582   }
7583   case ISD::ATOMIC_LOAD_ADD:
7584     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
7585     return;
7586   case ISD::ATOMIC_LOAD_AND:
7587     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
7588     return;
7589   case ISD::ATOMIC_LOAD_NAND:
7590     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
7591     return;
7592   case ISD::ATOMIC_LOAD_OR:
7593     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
7594     return;
7595   case ISD::ATOMIC_LOAD_SUB:
7596     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
7597     return;
7598   case ISD::ATOMIC_LOAD_XOR:
7599     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
7600     return;
7601   case ISD::ATOMIC_SWAP:
7602     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
7603     return;
7604   }
7605 }
7606
7607 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
7608   switch (Opcode) {
7609   default: return NULL;
7610   case X86ISD::BSF:                return "X86ISD::BSF";
7611   case X86ISD::BSR:                return "X86ISD::BSR";
7612   case X86ISD::SHLD:               return "X86ISD::SHLD";
7613   case X86ISD::SHRD:               return "X86ISD::SHRD";
7614   case X86ISD::FAND:               return "X86ISD::FAND";
7615   case X86ISD::FOR:                return "X86ISD::FOR";
7616   case X86ISD::FXOR:               return "X86ISD::FXOR";
7617   case X86ISD::FSRL:               return "X86ISD::FSRL";
7618   case X86ISD::FILD:               return "X86ISD::FILD";
7619   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
7620   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
7621   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
7622   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
7623   case X86ISD::FLD:                return "X86ISD::FLD";
7624   case X86ISD::FST:                return "X86ISD::FST";
7625   case X86ISD::CALL:               return "X86ISD::CALL";
7626   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
7627   case X86ISD::BT:                 return "X86ISD::BT";
7628   case X86ISD::CMP:                return "X86ISD::CMP";
7629   case X86ISD::COMI:               return "X86ISD::COMI";
7630   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
7631   case X86ISD::SETCC:              return "X86ISD::SETCC";
7632   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
7633   case X86ISD::CMOV:               return "X86ISD::CMOV";
7634   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
7635   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
7636   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
7637   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
7638   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
7639   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
7640   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
7641   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
7642   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
7643   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
7644   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
7645   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
7646   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
7647   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
7648   case X86ISD::FMAX:               return "X86ISD::FMAX";
7649   case X86ISD::FMIN:               return "X86ISD::FMIN";
7650   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
7651   case X86ISD::FRCP:               return "X86ISD::FRCP";
7652   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
7653   case X86ISD::SegmentBaseAddress: return "X86ISD::SegmentBaseAddress";
7654   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
7655   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
7656   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
7657   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
7658   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
7659   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
7660   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
7661   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
7662   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
7663   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
7664   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
7665   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
7666   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
7667   case X86ISD::VSHL:               return "X86ISD::VSHL";
7668   case X86ISD::VSRL:               return "X86ISD::VSRL";
7669   case X86ISD::CMPPD:              return "X86ISD::CMPPD";
7670   case X86ISD::CMPPS:              return "X86ISD::CMPPS";
7671   case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
7672   case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
7673   case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
7674   case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
7675   case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
7676   case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
7677   case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
7678   case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
7679   case X86ISD::ADD:                return "X86ISD::ADD";
7680   case X86ISD::SUB:                return "X86ISD::SUB";
7681   case X86ISD::SMUL:               return "X86ISD::SMUL";
7682   case X86ISD::UMUL:               return "X86ISD::UMUL";
7683   case X86ISD::INC:                return "X86ISD::INC";
7684   case X86ISD::DEC:                return "X86ISD::DEC";
7685   case X86ISD::OR:                 return "X86ISD::OR";
7686   case X86ISD::XOR:                return "X86ISD::XOR";
7687   case X86ISD::AND:                return "X86ISD::AND";
7688   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
7689   case X86ISD::PTEST:              return "X86ISD::PTEST";
7690   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
7691   case X86ISD::MINGW_ALLOCA:       return "X86ISD::MINGW_ALLOCA";
7692   }
7693 }
7694
7695 // isLegalAddressingMode - Return true if the addressing mode represented
7696 // by AM is legal for this target, for a load/store of the specified type.
7697 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
7698                                               const Type *Ty) const {
7699   // X86 supports extremely general addressing modes.
7700   CodeModel::Model M = getTargetMachine().getCodeModel();
7701
7702   // X86 allows a sign-extended 32-bit immediate field as a displacement.
7703   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
7704     return false;
7705
7706   if (AM.BaseGV) {
7707     unsigned GVFlags =
7708       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
7709
7710     // If a reference to this global requires an extra load, we can't fold it.
7711     if (isGlobalStubReference(GVFlags))
7712       return false;
7713
7714     // If BaseGV requires a register for the PIC base, we cannot also have a
7715     // BaseReg specified.
7716     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
7717       return false;
7718
7719     // If lower 4G is not available, then we must use rip-relative addressing.
7720     if (Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
7721       return false;
7722   }
7723
7724   switch (AM.Scale) {
7725   case 0:
7726   case 1:
7727   case 2:
7728   case 4:
7729   case 8:
7730     // These scales always work.
7731     break;
7732   case 3:
7733   case 5:
7734   case 9:
7735     // These scales are formed with basereg+scalereg.  Only accept if there is
7736     // no basereg yet.
7737     if (AM.HasBaseReg)
7738       return false;
7739     break;
7740   default:  // Other stuff never works.
7741     return false;
7742   }
7743
7744   return true;
7745 }
7746
7747
7748 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
7749   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
7750     return false;
7751   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7752   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
7753   if (NumBits1 <= NumBits2)
7754     return false;
7755   return true;
7756 }
7757
7758 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
7759   if (!VT1.isInteger() || !VT2.isInteger())
7760     return false;
7761   unsigned NumBits1 = VT1.getSizeInBits();
7762   unsigned NumBits2 = VT2.getSizeInBits();
7763   if (NumBits1 <= NumBits2)
7764     return false;
7765   return true;
7766 }
7767
7768 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
7769   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
7770   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
7771 }
7772
7773 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
7774   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
7775   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
7776 }
7777
7778 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
7779   // i16 instructions are longer (0x66 prefix) and potentially slower.
7780   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
7781 }
7782
7783 /// isShuffleMaskLegal - Targets can use this to indicate that they only
7784 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
7785 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
7786 /// are assumed to be legal.
7787 bool
7788 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
7789                                       EVT VT) const {
7790   // Very little shuffling can be done for 64-bit vectors right now.
7791   if (VT.getSizeInBits() == 64)
7792     return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
7793
7794   // FIXME: pshufb, blends, shifts.
7795   return (VT.getVectorNumElements() == 2 ||
7796           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
7797           isMOVLMask(M, VT) ||
7798           isSHUFPMask(M, VT) ||
7799           isPSHUFDMask(M, VT) ||
7800           isPSHUFHWMask(M, VT) ||
7801           isPSHUFLWMask(M, VT) ||
7802           isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
7803           isUNPCKLMask(M, VT) ||
7804           isUNPCKHMask(M, VT) ||
7805           isUNPCKL_v_undef_Mask(M, VT) ||
7806           isUNPCKH_v_undef_Mask(M, VT));
7807 }
7808
7809 bool
7810 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
7811                                           EVT VT) const {
7812   unsigned NumElts = VT.getVectorNumElements();
7813   // FIXME: This collection of masks seems suspect.
7814   if (NumElts == 2)
7815     return true;
7816   if (NumElts == 4 && VT.getSizeInBits() == 128) {
7817     return (isMOVLMask(Mask, VT)  ||
7818             isCommutedMOVLMask(Mask, VT, true) ||
7819             isSHUFPMask(Mask, VT) ||
7820             isCommutedSHUFPMask(Mask, VT));
7821   }
7822   return false;
7823 }
7824
7825 //===----------------------------------------------------------------------===//
7826 //                           X86 Scheduler Hooks
7827 //===----------------------------------------------------------------------===//
7828
7829 // private utility function
7830 MachineBasicBlock *
7831 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
7832                                                        MachineBasicBlock *MBB,
7833                                                        unsigned regOpc,
7834                                                        unsigned immOpc,
7835                                                        unsigned LoadOpc,
7836                                                        unsigned CXchgOpc,
7837                                                        unsigned copyOpc,
7838                                                        unsigned notOpc,
7839                                                        unsigned EAXreg,
7840                                                        TargetRegisterClass *RC,
7841                                                        bool invSrc) const {
7842   // For the atomic bitwise operator, we generate
7843   //   thisMBB:
7844   //   newMBB:
7845   //     ld  t1 = [bitinstr.addr]
7846   //     op  t2 = t1, [bitinstr.val]
7847   //     mov EAX = t1
7848   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
7849   //     bz  newMBB
7850   //     fallthrough -->nextMBB
7851   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7852   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7853   MachineFunction::iterator MBBIter = MBB;
7854   ++MBBIter;
7855
7856   /// First build the CFG
7857   MachineFunction *F = MBB->getParent();
7858   MachineBasicBlock *thisMBB = MBB;
7859   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7860   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7861   F->insert(MBBIter, newMBB);
7862   F->insert(MBBIter, nextMBB);
7863
7864   // Move all successors to thisMBB to nextMBB
7865   nextMBB->transferSuccessors(thisMBB);
7866
7867   // Update thisMBB to fall through to newMBB
7868   thisMBB->addSuccessor(newMBB);
7869
7870   // newMBB jumps to itself and fall through to nextMBB
7871   newMBB->addSuccessor(nextMBB);
7872   newMBB->addSuccessor(newMBB);
7873
7874   // Insert instructions into newMBB based on incoming instruction
7875   assert(bInstr->getNumOperands() < X86AddrNumOperands + 4 &&
7876          "unexpected number of operands");
7877   DebugLoc dl = bInstr->getDebugLoc();
7878   MachineOperand& destOper = bInstr->getOperand(0);
7879   MachineOperand* argOpers[2 + X86AddrNumOperands];
7880   int numArgs = bInstr->getNumOperands() - 1;
7881   for (int i=0; i < numArgs; ++i)
7882     argOpers[i] = &bInstr->getOperand(i+1);
7883
7884   // x86 address has 4 operands: base, index, scale, and displacement
7885   int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7886   int valArgIndx = lastAddrIndx + 1;
7887
7888   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
7889   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
7890   for (int i=0; i <= lastAddrIndx; ++i)
7891     (*MIB).addOperand(*argOpers[i]);
7892
7893   unsigned tt = F->getRegInfo().createVirtualRegister(RC);
7894   if (invSrc) {
7895     MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
7896   }
7897   else
7898     tt = t1;
7899
7900   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
7901   assert((argOpers[valArgIndx]->isReg() ||
7902           argOpers[valArgIndx]->isImm()) &&
7903          "invalid operand");
7904   if (argOpers[valArgIndx]->isReg())
7905     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
7906   else
7907     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
7908   MIB.addReg(tt);
7909   (*MIB).addOperand(*argOpers[valArgIndx]);
7910
7911   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), EAXreg);
7912   MIB.addReg(t1);
7913
7914   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
7915   for (int i=0; i <= lastAddrIndx; ++i)
7916     (*MIB).addOperand(*argOpers[i]);
7917   MIB.addReg(t2);
7918   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7919   (*MIB).setMemRefs(bInstr->memoperands_begin(),
7920                     bInstr->memoperands_end());
7921
7922   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), destOper.getReg());
7923   MIB.addReg(EAXreg);
7924
7925   // insert branch
7926   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
7927
7928   F->DeleteMachineInstr(bInstr);   // The pseudo instruction is gone now.
7929   return nextMBB;
7930 }
7931
7932 // private utility function:  64 bit atomics on 32 bit host.
7933 MachineBasicBlock *
7934 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
7935                                                        MachineBasicBlock *MBB,
7936                                                        unsigned regOpcL,
7937                                                        unsigned regOpcH,
7938                                                        unsigned immOpcL,
7939                                                        unsigned immOpcH,
7940                                                        bool invSrc) const {
7941   // For the atomic bitwise operator, we generate
7942   //   thisMBB (instructions are in pairs, except cmpxchg8b)
7943   //     ld t1,t2 = [bitinstr.addr]
7944   //   newMBB:
7945   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
7946   //     op  t5, t6 <- out1, out2, [bitinstr.val]
7947   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
7948   //     mov ECX, EBX <- t5, t6
7949   //     mov EAX, EDX <- t1, t2
7950   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
7951   //     mov t3, t4 <- EAX, EDX
7952   //     bz  newMBB
7953   //     result in out1, out2
7954   //     fallthrough -->nextMBB
7955
7956   const TargetRegisterClass *RC = X86::GR32RegisterClass;
7957   const unsigned LoadOpc = X86::MOV32rm;
7958   const unsigned copyOpc = X86::MOV32rr;
7959   const unsigned NotOpc = X86::NOT32r;
7960   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7961   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7962   MachineFunction::iterator MBBIter = MBB;
7963   ++MBBIter;
7964
7965   /// First build the CFG
7966   MachineFunction *F = MBB->getParent();
7967   MachineBasicBlock *thisMBB = MBB;
7968   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7969   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7970   F->insert(MBBIter, newMBB);
7971   F->insert(MBBIter, nextMBB);
7972
7973   // Move all successors to thisMBB to nextMBB
7974   nextMBB->transferSuccessors(thisMBB);
7975
7976   // Update thisMBB to fall through to newMBB
7977   thisMBB->addSuccessor(newMBB);
7978
7979   // newMBB jumps to itself and fall through to nextMBB
7980   newMBB->addSuccessor(nextMBB);
7981   newMBB->addSuccessor(newMBB);
7982
7983   DebugLoc dl = bInstr->getDebugLoc();
7984   // Insert instructions into newMBB based on incoming instruction
7985   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
7986   assert(bInstr->getNumOperands() < X86AddrNumOperands + 14 &&
7987          "unexpected number of operands");
7988   MachineOperand& dest1Oper = bInstr->getOperand(0);
7989   MachineOperand& dest2Oper = bInstr->getOperand(1);
7990   MachineOperand* argOpers[2 + X86AddrNumOperands];
7991   for (int i=0; i < 2 + X86AddrNumOperands; ++i) {
7992     argOpers[i] = &bInstr->getOperand(i+2);
7993
7994     // We use some of the operands multiple times, so conservatively just
7995     // clear any kill flags that might be present.
7996     if (argOpers[i]->isReg() && argOpers[i]->isUse())
7997       argOpers[i]->setIsKill(false);
7998   }
7999
8000   // x86 address has 5 operands: base, index, scale, displacement, and segment.
8001   int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
8002
8003   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
8004   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
8005   for (int i=0; i <= lastAddrIndx; ++i)
8006     (*MIB).addOperand(*argOpers[i]);
8007   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
8008   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
8009   // add 4 to displacement.
8010   for (int i=0; i <= lastAddrIndx-2; ++i)
8011     (*MIB).addOperand(*argOpers[i]);
8012   MachineOperand newOp3 = *(argOpers[3]);
8013   if (newOp3.isImm())
8014     newOp3.setImm(newOp3.getImm()+4);
8015   else
8016     newOp3.setOffset(newOp3.getOffset()+4);
8017   (*MIB).addOperand(newOp3);
8018   (*MIB).addOperand(*argOpers[lastAddrIndx]);
8019
8020   // t3/4 are defined later, at the bottom of the loop
8021   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
8022   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
8023   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
8024     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
8025   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
8026     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
8027
8028   // The subsequent operations should be using the destination registers of
8029   //the PHI instructions.
8030   if (invSrc) {
8031     t1 = F->getRegInfo().createVirtualRegister(RC);
8032     t2 = F->getRegInfo().createVirtualRegister(RC);
8033     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
8034     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
8035   } else {
8036     t1 = dest1Oper.getReg();
8037     t2 = dest2Oper.getReg();
8038   }
8039
8040   int valArgIndx = lastAddrIndx + 1;
8041   assert((argOpers[valArgIndx]->isReg() ||
8042           argOpers[valArgIndx]->isImm()) &&
8043          "invalid operand");
8044   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
8045   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
8046   if (argOpers[valArgIndx]->isReg())
8047     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
8048   else
8049     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
8050   if (regOpcL != X86::MOV32rr)
8051     MIB.addReg(t1);
8052   (*MIB).addOperand(*argOpers[valArgIndx]);
8053   assert(argOpers[valArgIndx + 1]->isReg() ==
8054          argOpers[valArgIndx]->isReg());
8055   assert(argOpers[valArgIndx + 1]->isImm() ==
8056          argOpers[valArgIndx]->isImm());
8057   if (argOpers[valArgIndx + 1]->isReg())
8058     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
8059   else
8060     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
8061   if (regOpcH != X86::MOV32rr)
8062     MIB.addReg(t2);
8063   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
8064
8065   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EAX);
8066   MIB.addReg(t1);
8067   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EDX);
8068   MIB.addReg(t2);
8069
8070   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EBX);
8071   MIB.addReg(t5);
8072   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::ECX);
8073   MIB.addReg(t6);
8074
8075   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
8076   for (int i=0; i <= lastAddrIndx; ++i)
8077     (*MIB).addOperand(*argOpers[i]);
8078
8079   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
8080   (*MIB).setMemRefs(bInstr->memoperands_begin(),
8081                     bInstr->memoperands_end());
8082
8083   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t3);
8084   MIB.addReg(X86::EAX);
8085   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t4);
8086   MIB.addReg(X86::EDX);
8087
8088   // insert branch
8089   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
8090
8091   F->DeleteMachineInstr(bInstr);   // The pseudo instruction is gone now.
8092   return nextMBB;
8093 }
8094
8095 // private utility function
8096 MachineBasicBlock *
8097 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
8098                                                       MachineBasicBlock *MBB,
8099                                                       unsigned cmovOpc) const {
8100   // For the atomic min/max operator, we generate
8101   //   thisMBB:
8102   //   newMBB:
8103   //     ld t1 = [min/max.addr]
8104   //     mov t2 = [min/max.val]
8105   //     cmp  t1, t2
8106   //     cmov[cond] t2 = t1
8107   //     mov EAX = t1
8108   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
8109   //     bz   newMBB
8110   //     fallthrough -->nextMBB
8111   //
8112   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8113   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8114   MachineFunction::iterator MBBIter = MBB;
8115   ++MBBIter;
8116
8117   /// First build the CFG
8118   MachineFunction *F = MBB->getParent();
8119   MachineBasicBlock *thisMBB = MBB;
8120   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
8121   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
8122   F->insert(MBBIter, newMBB);
8123   F->insert(MBBIter, nextMBB);
8124
8125   // Move all successors of thisMBB to nextMBB
8126   nextMBB->transferSuccessors(thisMBB);
8127
8128   // Update thisMBB to fall through to newMBB
8129   thisMBB->addSuccessor(newMBB);
8130
8131   // newMBB jumps to newMBB and fall through to nextMBB
8132   newMBB->addSuccessor(nextMBB);
8133   newMBB->addSuccessor(newMBB);
8134
8135   DebugLoc dl = mInstr->getDebugLoc();
8136   // Insert instructions into newMBB based on incoming instruction
8137   assert(mInstr->getNumOperands() < X86AddrNumOperands + 4 &&
8138          "unexpected number of operands");
8139   MachineOperand& destOper = mInstr->getOperand(0);
8140   MachineOperand* argOpers[2 + X86AddrNumOperands];
8141   int numArgs = mInstr->getNumOperands() - 1;
8142   for (int i=0; i < numArgs; ++i)
8143     argOpers[i] = &mInstr->getOperand(i+1);
8144
8145   // x86 address has 4 operands: base, index, scale, and displacement
8146   int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
8147   int valArgIndx = lastAddrIndx + 1;
8148
8149   unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8150   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
8151   for (int i=0; i <= lastAddrIndx; ++i)
8152     (*MIB).addOperand(*argOpers[i]);
8153
8154   // We only support register and immediate values
8155   assert((argOpers[valArgIndx]->isReg() ||
8156           argOpers[valArgIndx]->isImm()) &&
8157          "invalid operand");
8158
8159   unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8160   if (argOpers[valArgIndx]->isReg())
8161     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
8162   else
8163     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
8164   (*MIB).addOperand(*argOpers[valArgIndx]);
8165
8166   MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), X86::EAX);
8167   MIB.addReg(t1);
8168
8169   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
8170   MIB.addReg(t1);
8171   MIB.addReg(t2);
8172
8173   // Generate movc
8174   unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8175   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
8176   MIB.addReg(t2);
8177   MIB.addReg(t1);
8178
8179   // Cmp and exchange if none has modified the memory location
8180   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
8181   for (int i=0; i <= lastAddrIndx; ++i)
8182     (*MIB).addOperand(*argOpers[i]);
8183   MIB.addReg(t3);
8184   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
8185   (*MIB).setMemRefs(mInstr->memoperands_begin(),
8186                     mInstr->memoperands_end());
8187
8188   MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), destOper.getReg());
8189   MIB.addReg(X86::EAX);
8190
8191   // insert branch
8192   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
8193
8194   F->DeleteMachineInstr(mInstr);   // The pseudo instruction is gone now.
8195   return nextMBB;
8196 }
8197
8198 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
8199 // all of this code can be replaced with that in the .td file.
8200 MachineBasicBlock *
8201 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
8202                             unsigned numArgs, bool memArg) const {
8203
8204   MachineFunction *F = BB->getParent();
8205   DebugLoc dl = MI->getDebugLoc();
8206   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8207
8208   unsigned Opc;
8209   if (memArg)
8210     Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
8211   else
8212     Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
8213
8214   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(Opc));
8215
8216   for (unsigned i = 0; i < numArgs; ++i) {
8217     MachineOperand &Op = MI->getOperand(i+1);
8218
8219     if (!(Op.isReg() && Op.isImplicit()))
8220       MIB.addOperand(Op);
8221   }
8222
8223   BuildMI(BB, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
8224     .addReg(X86::XMM0);
8225
8226   F->DeleteMachineInstr(MI);
8227
8228   return BB;
8229 }
8230
8231 MachineBasicBlock *
8232 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
8233                                                  MachineInstr *MI,
8234                                                  MachineBasicBlock *MBB) const {
8235   // Emit code to save XMM registers to the stack. The ABI says that the
8236   // number of registers to save is given in %al, so it's theoretically
8237   // possible to do an indirect jump trick to avoid saving all of them,
8238   // however this code takes a simpler approach and just executes all
8239   // of the stores if %al is non-zero. It's less code, and it's probably
8240   // easier on the hardware branch predictor, and stores aren't all that
8241   // expensive anyway.
8242
8243   // Create the new basic blocks. One block contains all the XMM stores,
8244   // and one block is the final destination regardless of whether any
8245   // stores were performed.
8246   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8247   MachineFunction *F = MBB->getParent();
8248   MachineFunction::iterator MBBIter = MBB;
8249   ++MBBIter;
8250   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
8251   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
8252   F->insert(MBBIter, XMMSaveMBB);
8253   F->insert(MBBIter, EndMBB);
8254
8255   // Set up the CFG.
8256   // Move any original successors of MBB to the end block.
8257   EndMBB->transferSuccessors(MBB);
8258   // The original block will now fall through to the XMM save block.
8259   MBB->addSuccessor(XMMSaveMBB);
8260   // The XMMSaveMBB will fall through to the end block.
8261   XMMSaveMBB->addSuccessor(EndMBB);
8262
8263   // Now add the instructions.
8264   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8265   DebugLoc DL = MI->getDebugLoc();
8266
8267   unsigned CountReg = MI->getOperand(0).getReg();
8268   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
8269   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
8270
8271   if (!Subtarget->isTargetWin64()) {
8272     // If %al is 0, branch around the XMM save block.
8273     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
8274     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
8275     MBB->addSuccessor(EndMBB);
8276   }
8277
8278   // In the XMM save block, save all the XMM argument registers.
8279   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
8280     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
8281     MachineMemOperand *MMO =
8282       F->getMachineMemOperand(
8283         PseudoSourceValue::getFixedStack(RegSaveFrameIndex),
8284         MachineMemOperand::MOStore, Offset,
8285         /*Size=*/16, /*Align=*/16);
8286     BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
8287       .addFrameIndex(RegSaveFrameIndex)
8288       .addImm(/*Scale=*/1)
8289       .addReg(/*IndexReg=*/0)
8290       .addImm(/*Disp=*/Offset)
8291       .addReg(/*Segment=*/0)
8292       .addReg(MI->getOperand(i).getReg())
8293       .addMemOperand(MMO);
8294   }
8295
8296   F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
8297
8298   return EndMBB;
8299 }
8300
8301 MachineBasicBlock *
8302 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
8303                                      MachineBasicBlock *BB) const {
8304   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8305   DebugLoc DL = MI->getDebugLoc();
8306
8307   // To "insert" a SELECT_CC instruction, we actually have to insert the
8308   // diamond control-flow pattern.  The incoming instruction knows the
8309   // destination vreg to set, the condition code register to branch on, the
8310   // true/false values to select between, and a branch opcode to use.
8311   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8312   MachineFunction::iterator It = BB;
8313   ++It;
8314
8315   //  thisMBB:
8316   //  ...
8317   //   TrueVal = ...
8318   //   cmpTY ccX, r1, r2
8319   //   bCC copy1MBB
8320   //   fallthrough --> copy0MBB
8321   MachineBasicBlock *thisMBB = BB;
8322   MachineFunction *F = BB->getParent();
8323   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
8324   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8325   unsigned Opc =
8326     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
8327   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
8328   F->insert(It, copy0MBB);
8329   F->insert(It, sinkMBB);
8330   // Update machine-CFG edges by first adding all successors of the current
8331   // block to the new block which will contain the Phi node for the select.
8332   for (MachineBasicBlock::succ_iterator I = BB->succ_begin(),
8333          E = BB->succ_end(); I != E; ++I)
8334     sinkMBB->addSuccessor(*I);
8335   // Next, remove all successors of the current block, and add the true
8336   // and fallthrough blocks as its successors.
8337   while (!BB->succ_empty())
8338     BB->removeSuccessor(BB->succ_begin());
8339   // Add the true and fallthrough blocks as its successors.
8340   BB->addSuccessor(copy0MBB);
8341   BB->addSuccessor(sinkMBB);
8342
8343   //  copy0MBB:
8344   //   %FalseValue = ...
8345   //   # fallthrough to sinkMBB
8346   copy0MBB->addSuccessor(sinkMBB);
8347
8348   //  sinkMBB:
8349   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
8350   //  ...
8351   BuildMI(sinkMBB, DL, TII->get(X86::PHI), MI->getOperand(0).getReg())
8352     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
8353     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
8354
8355   F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
8356   return sinkMBB;
8357 }
8358
8359 MachineBasicBlock *
8360 X86TargetLowering::EmitLoweredMingwAlloca(MachineInstr *MI,
8361                                           MachineBasicBlock *BB) const {
8362   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8363   DebugLoc DL = MI->getDebugLoc();
8364   MachineFunction *F = BB->getParent();
8365
8366   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
8367   // non-trivial part is impdef of ESP.
8368   // FIXME: The code should be tweaked as soon as we'll try to do codegen for
8369   // mingw-w64.
8370
8371   BuildMI(BB, DL, TII->get(X86::CALLpcrel32))
8372     .addExternalSymbol("_alloca")
8373     .addReg(X86::EAX, RegState::Implicit)
8374     .addReg(X86::ESP, RegState::Implicit)
8375     .addReg(X86::EAX, RegState::Define | RegState::Implicit)
8376     .addReg(X86::ESP, RegState::Define | RegState::Implicit);
8377
8378   F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
8379   return BB;
8380 }
8381
8382 MachineBasicBlock *
8383 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
8384                                                MachineBasicBlock *BB) const {
8385   switch (MI->getOpcode()) {
8386   default: assert(false && "Unexpected instr type to insert");
8387   case X86::MINGW_ALLOCA:
8388     return EmitLoweredMingwAlloca(MI, BB);
8389   case X86::CMOV_GR8:
8390   case X86::CMOV_V1I64:
8391   case X86::CMOV_FR32:
8392   case X86::CMOV_FR64:
8393   case X86::CMOV_V4F32:
8394   case X86::CMOV_V2F64:
8395   case X86::CMOV_V2I64:
8396   case X86::CMOV_GR16:
8397   case X86::CMOV_GR32:
8398   case X86::CMOV_RFP32:
8399   case X86::CMOV_RFP64:
8400   case X86::CMOV_RFP80:
8401     return EmitLoweredSelect(MI, BB);
8402
8403   case X86::FP32_TO_INT16_IN_MEM:
8404   case X86::FP32_TO_INT32_IN_MEM:
8405   case X86::FP32_TO_INT64_IN_MEM:
8406   case X86::FP64_TO_INT16_IN_MEM:
8407   case X86::FP64_TO_INT32_IN_MEM:
8408   case X86::FP64_TO_INT64_IN_MEM:
8409   case X86::FP80_TO_INT16_IN_MEM:
8410   case X86::FP80_TO_INT32_IN_MEM:
8411   case X86::FP80_TO_INT64_IN_MEM: {
8412     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8413     DebugLoc DL = MI->getDebugLoc();
8414
8415     // Change the floating point control register to use "round towards zero"
8416     // mode when truncating to an integer value.
8417     MachineFunction *F = BB->getParent();
8418     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
8419     addFrameReference(BuildMI(BB, DL, TII->get(X86::FNSTCW16m)), CWFrameIdx);
8420
8421     // Load the old value of the high byte of the control word...
8422     unsigned OldCW =
8423       F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
8424     addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16rm), OldCW),
8425                       CWFrameIdx);
8426
8427     // Set the high part to be round to zero...
8428     addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
8429       .addImm(0xC7F);
8430
8431     // Reload the modified control word now...
8432     addFrameReference(BuildMI(BB, DL, TII->get(X86::FLDCW16m)), CWFrameIdx);
8433
8434     // Restore the memory image of control word to original value
8435     addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
8436       .addReg(OldCW);
8437
8438     // Get the X86 opcode to use.
8439     unsigned Opc;
8440     switch (MI->getOpcode()) {
8441     default: llvm_unreachable("illegal opcode!");
8442     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
8443     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
8444     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
8445     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
8446     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
8447     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
8448     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
8449     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
8450     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
8451     }
8452
8453     X86AddressMode AM;
8454     MachineOperand &Op = MI->getOperand(0);
8455     if (Op.isReg()) {
8456       AM.BaseType = X86AddressMode::RegBase;
8457       AM.Base.Reg = Op.getReg();
8458     } else {
8459       AM.BaseType = X86AddressMode::FrameIndexBase;
8460       AM.Base.FrameIndex = Op.getIndex();
8461     }
8462     Op = MI->getOperand(1);
8463     if (Op.isImm())
8464       AM.Scale = Op.getImm();
8465     Op = MI->getOperand(2);
8466     if (Op.isImm())
8467       AM.IndexReg = Op.getImm();
8468     Op = MI->getOperand(3);
8469     if (Op.isGlobal()) {
8470       AM.GV = Op.getGlobal();
8471     } else {
8472       AM.Disp = Op.getImm();
8473     }
8474     addFullAddress(BuildMI(BB, DL, TII->get(Opc)), AM)
8475                       .addReg(MI->getOperand(X86AddrNumOperands).getReg());
8476
8477     // Reload the original control word now.
8478     addFrameReference(BuildMI(BB, DL, TII->get(X86::FLDCW16m)), CWFrameIdx);
8479
8480     F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
8481     return BB;
8482   }
8483     // String/text processing lowering.
8484   case X86::PCMPISTRM128REG:
8485     return EmitPCMP(MI, BB, 3, false /* in-mem */);
8486   case X86::PCMPISTRM128MEM:
8487     return EmitPCMP(MI, BB, 3, true /* in-mem */);
8488   case X86::PCMPESTRM128REG:
8489     return EmitPCMP(MI, BB, 5, false /* in mem */);
8490   case X86::PCMPESTRM128MEM:
8491     return EmitPCMP(MI, BB, 5, true /* in mem */);
8492
8493     // Atomic Lowering.
8494   case X86::ATOMAND32:
8495     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
8496                                                X86::AND32ri, X86::MOV32rm,
8497                                                X86::LCMPXCHG32, X86::MOV32rr,
8498                                                X86::NOT32r, X86::EAX,
8499                                                X86::GR32RegisterClass);
8500   case X86::ATOMOR32:
8501     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
8502                                                X86::OR32ri, X86::MOV32rm,
8503                                                X86::LCMPXCHG32, X86::MOV32rr,
8504                                                X86::NOT32r, X86::EAX,
8505                                                X86::GR32RegisterClass);
8506   case X86::ATOMXOR32:
8507     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
8508                                                X86::XOR32ri, X86::MOV32rm,
8509                                                X86::LCMPXCHG32, X86::MOV32rr,
8510                                                X86::NOT32r, X86::EAX,
8511                                                X86::GR32RegisterClass);
8512   case X86::ATOMNAND32:
8513     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
8514                                                X86::AND32ri, X86::MOV32rm,
8515                                                X86::LCMPXCHG32, X86::MOV32rr,
8516                                                X86::NOT32r, X86::EAX,
8517                                                X86::GR32RegisterClass, true);
8518   case X86::ATOMMIN32:
8519     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
8520   case X86::ATOMMAX32:
8521     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
8522   case X86::ATOMUMIN32:
8523     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
8524   case X86::ATOMUMAX32:
8525     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
8526
8527   case X86::ATOMAND16:
8528     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
8529                                                X86::AND16ri, X86::MOV16rm,
8530                                                X86::LCMPXCHG16, X86::MOV16rr,
8531                                                X86::NOT16r, X86::AX,
8532                                                X86::GR16RegisterClass);
8533   case X86::ATOMOR16:
8534     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
8535                                                X86::OR16ri, X86::MOV16rm,
8536                                                X86::LCMPXCHG16, X86::MOV16rr,
8537                                                X86::NOT16r, X86::AX,
8538                                                X86::GR16RegisterClass);
8539   case X86::ATOMXOR16:
8540     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
8541                                                X86::XOR16ri, X86::MOV16rm,
8542                                                X86::LCMPXCHG16, X86::MOV16rr,
8543                                                X86::NOT16r, X86::AX,
8544                                                X86::GR16RegisterClass);
8545   case X86::ATOMNAND16:
8546     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
8547                                                X86::AND16ri, X86::MOV16rm,
8548                                                X86::LCMPXCHG16, X86::MOV16rr,
8549                                                X86::NOT16r, X86::AX,
8550                                                X86::GR16RegisterClass, true);
8551   case X86::ATOMMIN16:
8552     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
8553   case X86::ATOMMAX16:
8554     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
8555   case X86::ATOMUMIN16:
8556     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
8557   case X86::ATOMUMAX16:
8558     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
8559
8560   case X86::ATOMAND8:
8561     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
8562                                                X86::AND8ri, X86::MOV8rm,
8563                                                X86::LCMPXCHG8, X86::MOV8rr,
8564                                                X86::NOT8r, X86::AL,
8565                                                X86::GR8RegisterClass);
8566   case X86::ATOMOR8:
8567     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
8568                                                X86::OR8ri, X86::MOV8rm,
8569                                                X86::LCMPXCHG8, X86::MOV8rr,
8570                                                X86::NOT8r, X86::AL,
8571                                                X86::GR8RegisterClass);
8572   case X86::ATOMXOR8:
8573     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
8574                                                X86::XOR8ri, X86::MOV8rm,
8575                                                X86::LCMPXCHG8, X86::MOV8rr,
8576                                                X86::NOT8r, X86::AL,
8577                                                X86::GR8RegisterClass);
8578   case X86::ATOMNAND8:
8579     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
8580                                                X86::AND8ri, X86::MOV8rm,
8581                                                X86::LCMPXCHG8, X86::MOV8rr,
8582                                                X86::NOT8r, X86::AL,
8583                                                X86::GR8RegisterClass, true);
8584   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
8585   // This group is for 64-bit host.
8586   case X86::ATOMAND64:
8587     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
8588                                                X86::AND64ri32, X86::MOV64rm,
8589                                                X86::LCMPXCHG64, X86::MOV64rr,
8590                                                X86::NOT64r, X86::RAX,
8591                                                X86::GR64RegisterClass);
8592   case X86::ATOMOR64:
8593     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
8594                                                X86::OR64ri32, X86::MOV64rm,
8595                                                X86::LCMPXCHG64, X86::MOV64rr,
8596                                                X86::NOT64r, X86::RAX,
8597                                                X86::GR64RegisterClass);
8598   case X86::ATOMXOR64:
8599     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
8600                                                X86::XOR64ri32, X86::MOV64rm,
8601                                                X86::LCMPXCHG64, X86::MOV64rr,
8602                                                X86::NOT64r, X86::RAX,
8603                                                X86::GR64RegisterClass);
8604   case X86::ATOMNAND64:
8605     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
8606                                                X86::AND64ri32, X86::MOV64rm,
8607                                                X86::LCMPXCHG64, X86::MOV64rr,
8608                                                X86::NOT64r, X86::RAX,
8609                                                X86::GR64RegisterClass, true);
8610   case X86::ATOMMIN64:
8611     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
8612   case X86::ATOMMAX64:
8613     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
8614   case X86::ATOMUMIN64:
8615     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
8616   case X86::ATOMUMAX64:
8617     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
8618
8619   // This group does 64-bit operations on a 32-bit host.
8620   case X86::ATOMAND6432:
8621     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8622                                                X86::AND32rr, X86::AND32rr,
8623                                                X86::AND32ri, X86::AND32ri,
8624                                                false);
8625   case X86::ATOMOR6432:
8626     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8627                                                X86::OR32rr, X86::OR32rr,
8628                                                X86::OR32ri, X86::OR32ri,
8629                                                false);
8630   case X86::ATOMXOR6432:
8631     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8632                                                X86::XOR32rr, X86::XOR32rr,
8633                                                X86::XOR32ri, X86::XOR32ri,
8634                                                false);
8635   case X86::ATOMNAND6432:
8636     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8637                                                X86::AND32rr, X86::AND32rr,
8638                                                X86::AND32ri, X86::AND32ri,
8639                                                true);
8640   case X86::ATOMADD6432:
8641     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8642                                                X86::ADD32rr, X86::ADC32rr,
8643                                                X86::ADD32ri, X86::ADC32ri,
8644                                                false);
8645   case X86::ATOMSUB6432:
8646     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8647                                                X86::SUB32rr, X86::SBB32rr,
8648                                                X86::SUB32ri, X86::SBB32ri,
8649                                                false);
8650   case X86::ATOMSWAP6432:
8651     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8652                                                X86::MOV32rr, X86::MOV32rr,
8653                                                X86::MOV32ri, X86::MOV32ri,
8654                                                false);
8655   case X86::VASTART_SAVE_XMM_REGS:
8656     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
8657   }
8658 }
8659
8660 //===----------------------------------------------------------------------===//
8661 //                           X86 Optimization Hooks
8662 //===----------------------------------------------------------------------===//
8663
8664 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
8665                                                        const APInt &Mask,
8666                                                        APInt &KnownZero,
8667                                                        APInt &KnownOne,
8668                                                        const SelectionDAG &DAG,
8669                                                        unsigned Depth) const {
8670   unsigned Opc = Op.getOpcode();
8671   assert((Opc >= ISD::BUILTIN_OP_END ||
8672           Opc == ISD::INTRINSIC_WO_CHAIN ||
8673           Opc == ISD::INTRINSIC_W_CHAIN ||
8674           Opc == ISD::INTRINSIC_VOID) &&
8675          "Should use MaskedValueIsZero if you don't know whether Op"
8676          " is a target node!");
8677
8678   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
8679   switch (Opc) {
8680   default: break;
8681   case X86ISD::ADD:
8682   case X86ISD::SUB:
8683   case X86ISD::SMUL:
8684   case X86ISD::UMUL:
8685   case X86ISD::INC:
8686   case X86ISD::DEC:
8687   case X86ISD::OR:
8688   case X86ISD::XOR:
8689   case X86ISD::AND:
8690     // These nodes' second result is a boolean.
8691     if (Op.getResNo() == 0)
8692       break;
8693     // Fallthrough
8694   case X86ISD::SETCC:
8695     KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
8696                                        Mask.getBitWidth() - 1);
8697     break;
8698   }
8699 }
8700
8701 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
8702 /// node is a GlobalAddress + offset.
8703 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
8704                                        const GlobalValue* &GA,
8705                                        int64_t &Offset) const {
8706   if (N->getOpcode() == X86ISD::Wrapper) {
8707     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
8708       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
8709       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
8710       return true;
8711     }
8712   }
8713   return TargetLowering::isGAPlusOffset(N, GA, Offset);
8714 }
8715
8716 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
8717 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
8718 /// if the load addresses are consecutive, non-overlapping, and in the right
8719 /// order.
8720 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
8721                                      const TargetLowering &TLI) {
8722   DebugLoc dl = N->getDebugLoc();
8723   EVT VT = N->getValueType(0);
8724   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8725
8726   if (VT.getSizeInBits() != 128)
8727     return SDValue();
8728
8729   SmallVector<SDValue, 16> Elts;
8730   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
8731     Elts.push_back(DAG.getShuffleScalarElt(SVN, i));
8732   
8733   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
8734 }
8735
8736 /// PerformShuffleCombine - Detect vector gather/scatter index generation
8737 /// and convert it from being a bunch of shuffles and extracts to a simple
8738 /// store and scalar loads to extract the elements.
8739 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
8740                                                 const TargetLowering &TLI) {
8741   SDValue InputVector = N->getOperand(0);
8742
8743   // Only operate on vectors of 4 elements, where the alternative shuffling
8744   // gets to be more expensive.
8745   if (InputVector.getValueType() != MVT::v4i32)
8746     return SDValue();
8747
8748   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
8749   // single use which is a sign-extend or zero-extend, and all elements are
8750   // used.
8751   SmallVector<SDNode *, 4> Uses;
8752   unsigned ExtractedElements = 0;
8753   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
8754        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
8755     if (UI.getUse().getResNo() != InputVector.getResNo())
8756       return SDValue();
8757
8758     SDNode *Extract = *UI;
8759     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8760       return SDValue();
8761
8762     if (Extract->getValueType(0) != MVT::i32)
8763       return SDValue();
8764     if (!Extract->hasOneUse())
8765       return SDValue();
8766     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
8767         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
8768       return SDValue();
8769     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
8770       return SDValue();
8771
8772     // Record which element was extracted.
8773     ExtractedElements |=
8774       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
8775
8776     Uses.push_back(Extract);
8777   }
8778
8779   // If not all the elements were used, this may not be worthwhile.
8780   if (ExtractedElements != 15)
8781     return SDValue();
8782
8783   // Ok, we've now decided to do the transformation.
8784   DebugLoc dl = InputVector.getDebugLoc();
8785
8786   // Store the value to a temporary stack slot.
8787   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
8788   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr, NULL, 0,
8789                             false, false, 0);
8790
8791   // Replace each use (extract) with a load of the appropriate element.
8792   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
8793        UE = Uses.end(); UI != UE; ++UI) {
8794     SDNode *Extract = *UI;
8795
8796     // Compute the element's address.
8797     SDValue Idx = Extract->getOperand(1);
8798     unsigned EltSize =
8799         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
8800     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
8801     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
8802
8803     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(), OffsetVal, StackPtr);
8804
8805     // Load the scalar.
8806     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch, ScalarAddr,
8807                           NULL, 0, false, false, 0);
8808
8809     // Replace the exact with the load.
8810     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
8811   }
8812
8813   // The replacement was made in place; don't return anything.
8814   return SDValue();
8815 }
8816
8817 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
8818 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
8819                                     const X86Subtarget *Subtarget) {
8820   DebugLoc DL = N->getDebugLoc();
8821   SDValue Cond = N->getOperand(0);
8822   // Get the LHS/RHS of the select.
8823   SDValue LHS = N->getOperand(1);
8824   SDValue RHS = N->getOperand(2);
8825
8826   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
8827   // instructions match the semantics of the common C idiom x<y?x:y but not
8828   // x<=y?x:y, because of how they handle negative zero (which can be
8829   // ignored in unsafe-math mode).
8830   if (Subtarget->hasSSE2() &&
8831       (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
8832       Cond.getOpcode() == ISD::SETCC) {
8833     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
8834
8835     unsigned Opcode = 0;
8836     // Check for x CC y ? x : y.
8837     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
8838         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
8839       switch (CC) {
8840       default: break;
8841       case ISD::SETULT:
8842         // Converting this to a min would handle NaNs incorrectly, and swapping
8843         // the operands would cause it to handle comparisons between positive
8844         // and negative zero incorrectly.
8845         if (!FiniteOnlyFPMath() &&
8846             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))) {
8847           if (!UnsafeFPMath &&
8848               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
8849             break;
8850           std::swap(LHS, RHS);
8851         }
8852         Opcode = X86ISD::FMIN;
8853         break;
8854       case ISD::SETOLE:
8855         // Converting this to a min would handle comparisons between positive
8856         // and negative zero incorrectly.
8857         if (!UnsafeFPMath &&
8858             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
8859           break;
8860         Opcode = X86ISD::FMIN;
8861         break;
8862       case ISD::SETULE:
8863         // Converting this to a min would handle both negative zeros and NaNs
8864         // incorrectly, but we can swap the operands to fix both.
8865         std::swap(LHS, RHS);
8866       case ISD::SETOLT:
8867       case ISD::SETLT:
8868       case ISD::SETLE:
8869         Opcode = X86ISD::FMIN;
8870         break;
8871
8872       case ISD::SETOGE:
8873         // Converting this to a max would handle comparisons between positive
8874         // and negative zero incorrectly.
8875         if (!UnsafeFPMath &&
8876             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS))
8877           break;
8878         Opcode = X86ISD::FMAX;
8879         break;
8880       case ISD::SETUGT:
8881         // Converting this to a max would handle NaNs incorrectly, and swapping
8882         // the operands would cause it to handle comparisons between positive
8883         // and negative zero incorrectly.
8884         if (!FiniteOnlyFPMath() &&
8885             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))) {
8886           if (!UnsafeFPMath &&
8887               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
8888             break;
8889           std::swap(LHS, RHS);
8890         }
8891         Opcode = X86ISD::FMAX;
8892         break;
8893       case ISD::SETUGE:
8894         // Converting this to a max would handle both negative zeros and NaNs
8895         // incorrectly, but we can swap the operands to fix both.
8896         std::swap(LHS, RHS);
8897       case ISD::SETOGT:
8898       case ISD::SETGT:
8899       case ISD::SETGE:
8900         Opcode = X86ISD::FMAX;
8901         break;
8902       }
8903     // Check for x CC y ? y : x -- a min/max with reversed arms.
8904     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
8905                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
8906       switch (CC) {
8907       default: break;
8908       case ISD::SETOGE:
8909         // Converting this to a min would handle comparisons between positive
8910         // and negative zero incorrectly, and swapping the operands would
8911         // cause it to handle NaNs incorrectly.
8912         if (!UnsafeFPMath &&
8913             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
8914           if (!FiniteOnlyFPMath() &&
8915               (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
8916             break;
8917           std::swap(LHS, RHS);
8918         }
8919         Opcode = X86ISD::FMIN;
8920         break;
8921       case ISD::SETUGT:
8922         // Converting this to a min would handle NaNs incorrectly.
8923         if (!UnsafeFPMath &&
8924             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
8925           break;
8926         Opcode = X86ISD::FMIN;
8927         break;
8928       case ISD::SETUGE:
8929         // Converting this to a min would handle both negative zeros and NaNs
8930         // incorrectly, but we can swap the operands to fix both.
8931         std::swap(LHS, RHS);
8932       case ISD::SETOGT:
8933       case ISD::SETGT:
8934       case ISD::SETGE:
8935         Opcode = X86ISD::FMIN;
8936         break;
8937
8938       case ISD::SETULT:
8939         // Converting this to a max would handle NaNs incorrectly.
8940         if (!FiniteOnlyFPMath() &&
8941             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
8942           break;
8943         Opcode = X86ISD::FMAX;
8944         break;
8945       case ISD::SETOLE:
8946         // Converting this to a max would handle comparisons between positive
8947         // and negative zero incorrectly, and swapping the operands would
8948         // cause it to handle NaNs incorrectly.
8949         if (!UnsafeFPMath &&
8950             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
8951           if (!FiniteOnlyFPMath() &&
8952               (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
8953             break;
8954           std::swap(LHS, RHS);
8955         }
8956         Opcode = X86ISD::FMAX;
8957         break;
8958       case ISD::SETULE:
8959         // Converting this to a max would handle both negative zeros and NaNs
8960         // incorrectly, but we can swap the operands to fix both.
8961         std::swap(LHS, RHS);
8962       case ISD::SETOLT:
8963       case ISD::SETLT:
8964       case ISD::SETLE:
8965         Opcode = X86ISD::FMAX;
8966         break;
8967       }
8968     }
8969
8970     if (Opcode)
8971       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
8972   }
8973
8974   // If this is a select between two integer constants, try to do some
8975   // optimizations.
8976   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
8977     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
8978       // Don't do this for crazy integer types.
8979       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
8980         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
8981         // so that TrueC (the true value) is larger than FalseC.
8982         bool NeedsCondInvert = false;
8983
8984         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
8985             // Efficiently invertible.
8986             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
8987              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
8988               isa<ConstantSDNode>(Cond.getOperand(1))))) {
8989           NeedsCondInvert = true;
8990           std::swap(TrueC, FalseC);
8991         }
8992
8993         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
8994         if (FalseC->getAPIntValue() == 0 &&
8995             TrueC->getAPIntValue().isPowerOf2()) {
8996           if (NeedsCondInvert) // Invert the condition if needed.
8997             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
8998                                DAG.getConstant(1, Cond.getValueType()));
8999
9000           // Zero extend the condition if needed.
9001           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
9002
9003           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
9004           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
9005                              DAG.getConstant(ShAmt, MVT::i8));
9006         }
9007
9008         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
9009         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
9010           if (NeedsCondInvert) // Invert the condition if needed.
9011             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
9012                                DAG.getConstant(1, Cond.getValueType()));
9013
9014           // Zero extend the condition if needed.
9015           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
9016                              FalseC->getValueType(0), Cond);
9017           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9018                              SDValue(FalseC, 0));
9019         }
9020
9021         // Optimize cases that will turn into an LEA instruction.  This requires
9022         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
9023         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
9024           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
9025           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
9026
9027           bool isFastMultiplier = false;
9028           if (Diff < 10) {
9029             switch ((unsigned char)Diff) {
9030               default: break;
9031               case 1:  // result = add base, cond
9032               case 2:  // result = lea base(    , cond*2)
9033               case 3:  // result = lea base(cond, cond*2)
9034               case 4:  // result = lea base(    , cond*4)
9035               case 5:  // result = lea base(cond, cond*4)
9036               case 8:  // result = lea base(    , cond*8)
9037               case 9:  // result = lea base(cond, cond*8)
9038                 isFastMultiplier = true;
9039                 break;
9040             }
9041           }
9042
9043           if (isFastMultiplier) {
9044             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
9045             if (NeedsCondInvert) // Invert the condition if needed.
9046               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
9047                                  DAG.getConstant(1, Cond.getValueType()));
9048
9049             // Zero extend the condition if needed.
9050             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
9051                                Cond);
9052             // Scale the condition by the difference.
9053             if (Diff != 1)
9054               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
9055                                  DAG.getConstant(Diff, Cond.getValueType()));
9056
9057             // Add the base if non-zero.
9058             if (FalseC->getAPIntValue() != 0)
9059               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9060                                  SDValue(FalseC, 0));
9061             return Cond;
9062           }
9063         }
9064       }
9065   }
9066
9067   return SDValue();
9068 }
9069
9070 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
9071 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
9072                                   TargetLowering::DAGCombinerInfo &DCI) {
9073   DebugLoc DL = N->getDebugLoc();
9074
9075   // If the flag operand isn't dead, don't touch this CMOV.
9076   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
9077     return SDValue();
9078
9079   // If this is a select between two integer constants, try to do some
9080   // optimizations.  Note that the operands are ordered the opposite of SELECT
9081   // operands.
9082   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
9083     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9084       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
9085       // larger than FalseC (the false value).
9086       X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
9087
9088       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
9089         CC = X86::GetOppositeBranchCondition(CC);
9090         std::swap(TrueC, FalseC);
9091       }
9092
9093       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
9094       // This is efficient for any integer data type (including i8/i16) and
9095       // shift amount.
9096       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
9097         SDValue Cond = N->getOperand(3);
9098         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9099                            DAG.getConstant(CC, MVT::i8), Cond);
9100
9101         // Zero extend the condition if needed.
9102         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
9103
9104         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
9105         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
9106                            DAG.getConstant(ShAmt, MVT::i8));
9107         if (N->getNumValues() == 2)  // Dead flag value?
9108           return DCI.CombineTo(N, Cond, SDValue());
9109         return Cond;
9110       }
9111
9112       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
9113       // for any integer data type, including i8/i16.
9114       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
9115         SDValue Cond = N->getOperand(3);
9116         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9117                            DAG.getConstant(CC, MVT::i8), Cond);
9118
9119         // Zero extend the condition if needed.
9120         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
9121                            FalseC->getValueType(0), Cond);
9122         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9123                            SDValue(FalseC, 0));
9124
9125         if (N->getNumValues() == 2)  // Dead flag value?
9126           return DCI.CombineTo(N, Cond, SDValue());
9127         return Cond;
9128       }
9129
9130       // Optimize cases that will turn into an LEA instruction.  This requires
9131       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
9132       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
9133         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
9134         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
9135
9136         bool isFastMultiplier = false;
9137         if (Diff < 10) {
9138           switch ((unsigned char)Diff) {
9139           default: break;
9140           case 1:  // result = add base, cond
9141           case 2:  // result = lea base(    , cond*2)
9142           case 3:  // result = lea base(cond, cond*2)
9143           case 4:  // result = lea base(    , cond*4)
9144           case 5:  // result = lea base(cond, cond*4)
9145           case 8:  // result = lea base(    , cond*8)
9146           case 9:  // result = lea base(cond, cond*8)
9147             isFastMultiplier = true;
9148             break;
9149           }
9150         }
9151
9152         if (isFastMultiplier) {
9153           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
9154           SDValue Cond = N->getOperand(3);
9155           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9156                              DAG.getConstant(CC, MVT::i8), Cond);
9157           // Zero extend the condition if needed.
9158           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
9159                              Cond);
9160           // Scale the condition by the difference.
9161           if (Diff != 1)
9162             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
9163                                DAG.getConstant(Diff, Cond.getValueType()));
9164
9165           // Add the base if non-zero.
9166           if (FalseC->getAPIntValue() != 0)
9167             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9168                                SDValue(FalseC, 0));
9169           if (N->getNumValues() == 2)  // Dead flag value?
9170             return DCI.CombineTo(N, Cond, SDValue());
9171           return Cond;
9172         }
9173       }
9174     }
9175   }
9176   return SDValue();
9177 }
9178
9179
9180 /// PerformMulCombine - Optimize a single multiply with constant into two
9181 /// in order to implement it with two cheaper instructions, e.g.
9182 /// LEA + SHL, LEA + LEA.
9183 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
9184                                  TargetLowering::DAGCombinerInfo &DCI) {
9185   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9186     return SDValue();
9187
9188   EVT VT = N->getValueType(0);
9189   if (VT != MVT::i64)
9190     return SDValue();
9191
9192   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
9193   if (!C)
9194     return SDValue();
9195   uint64_t MulAmt = C->getZExtValue();
9196   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
9197     return SDValue();
9198
9199   uint64_t MulAmt1 = 0;
9200   uint64_t MulAmt2 = 0;
9201   if ((MulAmt % 9) == 0) {
9202     MulAmt1 = 9;
9203     MulAmt2 = MulAmt / 9;
9204   } else if ((MulAmt % 5) == 0) {
9205     MulAmt1 = 5;
9206     MulAmt2 = MulAmt / 5;
9207   } else if ((MulAmt % 3) == 0) {
9208     MulAmt1 = 3;
9209     MulAmt2 = MulAmt / 3;
9210   }
9211   if (MulAmt2 &&
9212       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
9213     DebugLoc DL = N->getDebugLoc();
9214
9215     if (isPowerOf2_64(MulAmt2) &&
9216         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
9217       // If second multiplifer is pow2, issue it first. We want the multiply by
9218       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
9219       // is an add.
9220       std::swap(MulAmt1, MulAmt2);
9221
9222     SDValue NewMul;
9223     if (isPowerOf2_64(MulAmt1))
9224       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
9225                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
9226     else
9227       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
9228                            DAG.getConstant(MulAmt1, VT));
9229
9230     if (isPowerOf2_64(MulAmt2))
9231       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
9232                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
9233     else
9234       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
9235                            DAG.getConstant(MulAmt2, VT));
9236
9237     // Do not add new nodes to DAG combiner worklist.
9238     DCI.CombineTo(N, NewMul, false);
9239   }
9240   return SDValue();
9241 }
9242
9243 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
9244   SDValue N0 = N->getOperand(0);
9245   SDValue N1 = N->getOperand(1);
9246   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
9247   EVT VT = N0.getValueType();
9248
9249   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
9250   // since the result of setcc_c is all zero's or all ones.
9251   if (N1C && N0.getOpcode() == ISD::AND &&
9252       N0.getOperand(1).getOpcode() == ISD::Constant) {
9253     SDValue N00 = N0.getOperand(0);
9254     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
9255         ((N00.getOpcode() == ISD::ANY_EXTEND ||
9256           N00.getOpcode() == ISD::ZERO_EXTEND) &&
9257          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
9258       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
9259       APInt ShAmt = N1C->getAPIntValue();
9260       Mask = Mask.shl(ShAmt);
9261       if (Mask != 0)
9262         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
9263                            N00, DAG.getConstant(Mask, VT));
9264     }
9265   }
9266
9267   return SDValue();
9268 }
9269
9270 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
9271 ///                       when possible.
9272 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
9273                                    const X86Subtarget *Subtarget) {
9274   EVT VT = N->getValueType(0);
9275   if (!VT.isVector() && VT.isInteger() &&
9276       N->getOpcode() == ISD::SHL)
9277     return PerformSHLCombine(N, DAG);
9278
9279   // On X86 with SSE2 support, we can transform this to a vector shift if
9280   // all elements are shifted by the same amount.  We can't do this in legalize
9281   // because the a constant vector is typically transformed to a constant pool
9282   // so we have no knowledge of the shift amount.
9283   if (!Subtarget->hasSSE2())
9284     return SDValue();
9285
9286   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
9287     return SDValue();
9288
9289   SDValue ShAmtOp = N->getOperand(1);
9290   EVT EltVT = VT.getVectorElementType();
9291   DebugLoc DL = N->getDebugLoc();
9292   SDValue BaseShAmt = SDValue();
9293   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
9294     unsigned NumElts = VT.getVectorNumElements();
9295     unsigned i = 0;
9296     for (; i != NumElts; ++i) {
9297       SDValue Arg = ShAmtOp.getOperand(i);
9298       if (Arg.getOpcode() == ISD::UNDEF) continue;
9299       BaseShAmt = Arg;
9300       break;
9301     }
9302     for (; i != NumElts; ++i) {
9303       SDValue Arg = ShAmtOp.getOperand(i);
9304       if (Arg.getOpcode() == ISD::UNDEF) continue;
9305       if (Arg != BaseShAmt) {
9306         return SDValue();
9307       }
9308     }
9309   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
9310              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
9311     SDValue InVec = ShAmtOp.getOperand(0);
9312     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
9313       unsigned NumElts = InVec.getValueType().getVectorNumElements();
9314       unsigned i = 0;
9315       for (; i != NumElts; ++i) {
9316         SDValue Arg = InVec.getOperand(i);
9317         if (Arg.getOpcode() == ISD::UNDEF) continue;
9318         BaseShAmt = Arg;
9319         break;
9320       }
9321     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
9322        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
9323          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
9324          if (C->getZExtValue() == SplatIdx)
9325            BaseShAmt = InVec.getOperand(1);
9326        }
9327     }
9328     if (BaseShAmt.getNode() == 0)
9329       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
9330                               DAG.getIntPtrConstant(0));
9331   } else
9332     return SDValue();
9333
9334   // The shift amount is an i32.
9335   if (EltVT.bitsGT(MVT::i32))
9336     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
9337   else if (EltVT.bitsLT(MVT::i32))
9338     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
9339
9340   // The shift amount is identical so we can do a vector shift.
9341   SDValue  ValOp = N->getOperand(0);
9342   switch (N->getOpcode()) {
9343   default:
9344     llvm_unreachable("Unknown shift opcode!");
9345     break;
9346   case ISD::SHL:
9347     if (VT == MVT::v2i64)
9348       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9349                          DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9350                          ValOp, BaseShAmt);
9351     if (VT == MVT::v4i32)
9352       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9353                          DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
9354                          ValOp, BaseShAmt);
9355     if (VT == MVT::v8i16)
9356       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9357                          DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
9358                          ValOp, BaseShAmt);
9359     break;
9360   case ISD::SRA:
9361     if (VT == MVT::v4i32)
9362       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9363                          DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
9364                          ValOp, BaseShAmt);
9365     if (VT == MVT::v8i16)
9366       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9367                          DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
9368                          ValOp, BaseShAmt);
9369     break;
9370   case ISD::SRL:
9371     if (VT == MVT::v2i64)
9372       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9373                          DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9374                          ValOp, BaseShAmt);
9375     if (VT == MVT::v4i32)
9376       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9377                          DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
9378                          ValOp, BaseShAmt);
9379     if (VT ==  MVT::v8i16)
9380       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9381                          DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
9382                          ValOp, BaseShAmt);
9383     break;
9384   }
9385   return SDValue();
9386 }
9387
9388 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
9389                                 TargetLowering::DAGCombinerInfo &DCI,
9390                                 const X86Subtarget *Subtarget) {
9391   if (DCI.isBeforeLegalizeOps())
9392     return SDValue();
9393
9394   EVT VT = N->getValueType(0);
9395   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
9396     return SDValue();
9397
9398   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
9399   SDValue N0 = N->getOperand(0);
9400   SDValue N1 = N->getOperand(1);
9401   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
9402     std::swap(N0, N1);
9403   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
9404     return SDValue();
9405   if (!N0.hasOneUse() || !N1.hasOneUse())
9406     return SDValue();
9407
9408   SDValue ShAmt0 = N0.getOperand(1);
9409   if (ShAmt0.getValueType() != MVT::i8)
9410     return SDValue();
9411   SDValue ShAmt1 = N1.getOperand(1);
9412   if (ShAmt1.getValueType() != MVT::i8)
9413     return SDValue();
9414   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
9415     ShAmt0 = ShAmt0.getOperand(0);
9416   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
9417     ShAmt1 = ShAmt1.getOperand(0);
9418
9419   DebugLoc DL = N->getDebugLoc();
9420   unsigned Opc = X86ISD::SHLD;
9421   SDValue Op0 = N0.getOperand(0);
9422   SDValue Op1 = N1.getOperand(0);
9423   if (ShAmt0.getOpcode() == ISD::SUB) {
9424     Opc = X86ISD::SHRD;
9425     std::swap(Op0, Op1);
9426     std::swap(ShAmt0, ShAmt1);
9427   }
9428
9429   unsigned Bits = VT.getSizeInBits();
9430   if (ShAmt1.getOpcode() == ISD::SUB) {
9431     SDValue Sum = ShAmt1.getOperand(0);
9432     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
9433       if (SumC->getSExtValue() == Bits &&
9434           ShAmt1.getOperand(1) == ShAmt0)
9435         return DAG.getNode(Opc, DL, VT,
9436                            Op0, Op1,
9437                            DAG.getNode(ISD::TRUNCATE, DL,
9438                                        MVT::i8, ShAmt0));
9439     }
9440   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
9441     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
9442     if (ShAmt0C &&
9443         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
9444       return DAG.getNode(Opc, DL, VT,
9445                          N0.getOperand(0), N1.getOperand(0),
9446                          DAG.getNode(ISD::TRUNCATE, DL,
9447                                        MVT::i8, ShAmt0));
9448   }
9449
9450   return SDValue();
9451 }
9452
9453 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
9454 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
9455                                    const X86Subtarget *Subtarget) {
9456   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
9457   // the FP state in cases where an emms may be missing.
9458   // A preferable solution to the general problem is to figure out the right
9459   // places to insert EMMS.  This qualifies as a quick hack.
9460
9461   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
9462   StoreSDNode *St = cast<StoreSDNode>(N);
9463   EVT VT = St->getValue().getValueType();
9464   if (VT.getSizeInBits() != 64)
9465     return SDValue();
9466
9467   const Function *F = DAG.getMachineFunction().getFunction();
9468   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
9469   bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
9470     && Subtarget->hasSSE2();
9471   if ((VT.isVector() ||
9472        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
9473       isa<LoadSDNode>(St->getValue()) &&
9474       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
9475       St->getChain().hasOneUse() && !St->isVolatile()) {
9476     SDNode* LdVal = St->getValue().getNode();
9477     LoadSDNode *Ld = 0;
9478     int TokenFactorIndex = -1;
9479     SmallVector<SDValue, 8> Ops;
9480     SDNode* ChainVal = St->getChain().getNode();
9481     // Must be a store of a load.  We currently handle two cases:  the load
9482     // is a direct child, and it's under an intervening TokenFactor.  It is
9483     // possible to dig deeper under nested TokenFactors.
9484     if (ChainVal == LdVal)
9485       Ld = cast<LoadSDNode>(St->getChain());
9486     else if (St->getValue().hasOneUse() &&
9487              ChainVal->getOpcode() == ISD::TokenFactor) {
9488       for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
9489         if (ChainVal->getOperand(i).getNode() == LdVal) {
9490           TokenFactorIndex = i;
9491           Ld = cast<LoadSDNode>(St->getValue());
9492         } else
9493           Ops.push_back(ChainVal->getOperand(i));
9494       }
9495     }
9496
9497     if (!Ld || !ISD::isNormalLoad(Ld))
9498       return SDValue();
9499
9500     // If this is not the MMX case, i.e. we are just turning i64 load/store
9501     // into f64 load/store, avoid the transformation if there are multiple
9502     // uses of the loaded value.
9503     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
9504       return SDValue();
9505
9506     DebugLoc LdDL = Ld->getDebugLoc();
9507     DebugLoc StDL = N->getDebugLoc();
9508     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
9509     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
9510     // pair instead.
9511     if (Subtarget->is64Bit() || F64IsLegal) {
9512       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
9513       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(),
9514                                   Ld->getBasePtr(), Ld->getSrcValue(),
9515                                   Ld->getSrcValueOffset(), Ld->isVolatile(),
9516                                   Ld->isNonTemporal(), Ld->getAlignment());
9517       SDValue NewChain = NewLd.getValue(1);
9518       if (TokenFactorIndex != -1) {
9519         Ops.push_back(NewChain);
9520         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
9521                                Ops.size());
9522       }
9523       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
9524                           St->getSrcValue(), St->getSrcValueOffset(),
9525                           St->isVolatile(), St->isNonTemporal(),
9526                           St->getAlignment());
9527     }
9528
9529     // Otherwise, lower to two pairs of 32-bit loads / stores.
9530     SDValue LoAddr = Ld->getBasePtr();
9531     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
9532                                  DAG.getConstant(4, MVT::i32));
9533
9534     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
9535                                Ld->getSrcValue(), Ld->getSrcValueOffset(),
9536                                Ld->isVolatile(), Ld->isNonTemporal(),
9537                                Ld->getAlignment());
9538     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
9539                                Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
9540                                Ld->isVolatile(), Ld->isNonTemporal(),
9541                                MinAlign(Ld->getAlignment(), 4));
9542
9543     SDValue NewChain = LoLd.getValue(1);
9544     if (TokenFactorIndex != -1) {
9545       Ops.push_back(LoLd);
9546       Ops.push_back(HiLd);
9547       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
9548                              Ops.size());
9549     }
9550
9551     LoAddr = St->getBasePtr();
9552     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
9553                          DAG.getConstant(4, MVT::i32));
9554
9555     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
9556                                 St->getSrcValue(), St->getSrcValueOffset(),
9557                                 St->isVolatile(), St->isNonTemporal(),
9558                                 St->getAlignment());
9559     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
9560                                 St->getSrcValue(),
9561                                 St->getSrcValueOffset() + 4,
9562                                 St->isVolatile(),
9563                                 St->isNonTemporal(),
9564                                 MinAlign(St->getAlignment(), 4));
9565     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
9566   }
9567   return SDValue();
9568 }
9569
9570 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
9571 /// X86ISD::FXOR nodes.
9572 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
9573   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
9574   // F[X]OR(0.0, x) -> x
9575   // F[X]OR(x, 0.0) -> x
9576   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
9577     if (C->getValueAPF().isPosZero())
9578       return N->getOperand(1);
9579   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
9580     if (C->getValueAPF().isPosZero())
9581       return N->getOperand(0);
9582   return SDValue();
9583 }
9584
9585 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
9586 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
9587   // FAND(0.0, x) -> 0.0
9588   // FAND(x, 0.0) -> 0.0
9589   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
9590     if (C->getValueAPF().isPosZero())
9591       return N->getOperand(0);
9592   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
9593     if (C->getValueAPF().isPosZero())
9594       return N->getOperand(1);
9595   return SDValue();
9596 }
9597
9598 static SDValue PerformBTCombine(SDNode *N,
9599                                 SelectionDAG &DAG,
9600                                 TargetLowering::DAGCombinerInfo &DCI) {
9601   // BT ignores high bits in the bit index operand.
9602   SDValue Op1 = N->getOperand(1);
9603   if (Op1.hasOneUse()) {
9604     unsigned BitWidth = Op1.getValueSizeInBits();
9605     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
9606     APInt KnownZero, KnownOne;
9607     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
9608                                           !DCI.isBeforeLegalizeOps());
9609     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9610     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
9611         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
9612       DCI.CommitTargetLoweringOpt(TLO);
9613   }
9614   return SDValue();
9615 }
9616
9617 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
9618   SDValue Op = N->getOperand(0);
9619   if (Op.getOpcode() == ISD::BIT_CONVERT)
9620     Op = Op.getOperand(0);
9621   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
9622   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
9623       VT.getVectorElementType().getSizeInBits() ==
9624       OpVT.getVectorElementType().getSizeInBits()) {
9625     return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT, Op);
9626   }
9627   return SDValue();
9628 }
9629
9630 // On X86 and X86-64, atomic operations are lowered to locked instructions.
9631 // Locked instructions, in turn, have implicit fence semantics (all memory
9632 // operations are flushed before issuing the locked instruction, and the
9633 // are not buffered), so we can fold away the common pattern of
9634 // fence-atomic-fence.
9635 static SDValue PerformMEMBARRIERCombine(SDNode* N, SelectionDAG &DAG) {
9636   SDValue atomic = N->getOperand(0);
9637   switch (atomic.getOpcode()) {
9638     case ISD::ATOMIC_CMP_SWAP:
9639     case ISD::ATOMIC_SWAP:
9640     case ISD::ATOMIC_LOAD_ADD:
9641     case ISD::ATOMIC_LOAD_SUB:
9642     case ISD::ATOMIC_LOAD_AND:
9643     case ISD::ATOMIC_LOAD_OR:
9644     case ISD::ATOMIC_LOAD_XOR:
9645     case ISD::ATOMIC_LOAD_NAND:
9646     case ISD::ATOMIC_LOAD_MIN:
9647     case ISD::ATOMIC_LOAD_MAX:
9648     case ISD::ATOMIC_LOAD_UMIN:
9649     case ISD::ATOMIC_LOAD_UMAX:
9650       break;
9651     default:
9652       return SDValue();
9653   }
9654
9655   SDValue fence = atomic.getOperand(0);
9656   if (fence.getOpcode() != ISD::MEMBARRIER)
9657     return SDValue();
9658
9659   switch (atomic.getOpcode()) {
9660     case ISD::ATOMIC_CMP_SWAP:
9661       return DAG.UpdateNodeOperands(atomic, fence.getOperand(0),
9662                                     atomic.getOperand(1), atomic.getOperand(2),
9663                                     atomic.getOperand(3));
9664     case ISD::ATOMIC_SWAP:
9665     case ISD::ATOMIC_LOAD_ADD:
9666     case ISD::ATOMIC_LOAD_SUB:
9667     case ISD::ATOMIC_LOAD_AND:
9668     case ISD::ATOMIC_LOAD_OR:
9669     case ISD::ATOMIC_LOAD_XOR:
9670     case ISD::ATOMIC_LOAD_NAND:
9671     case ISD::ATOMIC_LOAD_MIN:
9672     case ISD::ATOMIC_LOAD_MAX:
9673     case ISD::ATOMIC_LOAD_UMIN:
9674     case ISD::ATOMIC_LOAD_UMAX:
9675       return DAG.UpdateNodeOperands(atomic, fence.getOperand(0),
9676                                     atomic.getOperand(1), atomic.getOperand(2));
9677     default:
9678       return SDValue();
9679   }
9680 }
9681
9682 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
9683   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
9684   //           (and (i32 x86isd::setcc_carry), 1)
9685   // This eliminates the zext. This transformation is necessary because
9686   // ISD::SETCC is always legalized to i8.
9687   DebugLoc dl = N->getDebugLoc();
9688   SDValue N0 = N->getOperand(0);
9689   EVT VT = N->getValueType(0);
9690   if (N0.getOpcode() == ISD::AND &&
9691       N0.hasOneUse() &&
9692       N0.getOperand(0).hasOneUse()) {
9693     SDValue N00 = N0.getOperand(0);
9694     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
9695       return SDValue();
9696     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
9697     if (!C || C->getZExtValue() != 1)
9698       return SDValue();
9699     return DAG.getNode(ISD::AND, dl, VT,
9700                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
9701                                    N00.getOperand(0), N00.getOperand(1)),
9702                        DAG.getConstant(1, VT));
9703   }
9704
9705   return SDValue();
9706 }
9707
9708 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
9709                                              DAGCombinerInfo &DCI) const {
9710   SelectionDAG &DAG = DCI.DAG;
9711   switch (N->getOpcode()) {
9712   default: break;
9713   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
9714   case ISD::EXTRACT_VECTOR_ELT:
9715                         return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
9716   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
9717   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
9718   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
9719   case ISD::SHL:
9720   case ISD::SRA:
9721   case ISD::SRL:            return PerformShiftCombine(N, DAG, Subtarget);
9722   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
9723   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
9724   case X86ISD::FXOR:
9725   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
9726   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
9727   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
9728   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
9729   case ISD::MEMBARRIER:     return PerformMEMBARRIERCombine(N, DAG);
9730   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG);
9731   }
9732
9733   return SDValue();
9734 }
9735
9736 /// isTypeDesirableForOp - Return true if the target has native support for
9737 /// the specified value type and it is 'desirable' to use the type for the
9738 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
9739 /// instruction encodings are longer and some i16 instructions are slow.
9740 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
9741   if (!isTypeLegal(VT))
9742     return false;
9743   if (VT != MVT::i16)
9744     return true;
9745
9746   switch (Opc) {
9747   default:
9748     return true;
9749   case ISD::LOAD:
9750   case ISD::SIGN_EXTEND:
9751   case ISD::ZERO_EXTEND:
9752   case ISD::ANY_EXTEND:
9753   case ISD::SHL:
9754   case ISD::SRL:
9755   case ISD::SUB:
9756   case ISD::ADD:
9757   case ISD::MUL:
9758   case ISD::AND:
9759   case ISD::OR:
9760   case ISD::XOR:
9761     return false;
9762   }
9763 }
9764
9765 static bool MayFoldLoad(SDValue Op) {
9766   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
9767 }
9768
9769 static bool MayFoldIntoStore(SDValue Op) {
9770   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
9771 }
9772
9773 /// IsDesirableToPromoteOp - This method query the target whether it is
9774 /// beneficial for dag combiner to promote the specified node. If true, it
9775 /// should return the desired promotion type by reference.
9776 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
9777   EVT VT = Op.getValueType();
9778   if (VT != MVT::i16)
9779     return false;
9780
9781   bool Promote = false;
9782   bool Commute = false;
9783   switch (Op.getOpcode()) {
9784   default: break;
9785   case ISD::LOAD: {
9786     LoadSDNode *LD = cast<LoadSDNode>(Op);
9787     // If the non-extending load has a single use and it's not live out, then it
9788     // might be folded.
9789     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
9790                                                      Op.hasOneUse()*/) {
9791       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9792              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
9793         // The only case where we'd want to promote LOAD (rather then it being
9794         // promoted as an operand is when it's only use is liveout.
9795         if (UI->getOpcode() != ISD::CopyToReg)
9796           return false;
9797       }
9798     }
9799     Promote = true;
9800     break;
9801   }
9802   case ISD::SIGN_EXTEND:
9803   case ISD::ZERO_EXTEND:
9804   case ISD::ANY_EXTEND:
9805     Promote = true;
9806     break;
9807   case ISD::SHL:
9808   case ISD::SRL: {
9809     SDValue N0 = Op.getOperand(0);
9810     // Look out for (store (shl (load), x)).
9811     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
9812       return false;
9813     Promote = true;
9814     break;
9815   }
9816   case ISD::ADD:
9817   case ISD::MUL:
9818   case ISD::AND:
9819   case ISD::OR:
9820   case ISD::XOR:
9821     Commute = true;
9822     // fallthrough
9823   case ISD::SUB: {
9824     SDValue N0 = Op.getOperand(0);
9825     SDValue N1 = Op.getOperand(1);
9826     if (!Commute && MayFoldLoad(N1))
9827       return false;
9828     // Avoid disabling potential load folding opportunities.
9829     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
9830       return false;
9831     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
9832       return false;
9833     Promote = true;
9834   }
9835   }
9836
9837   PVT = MVT::i32;
9838   return Promote;
9839 }
9840
9841 //===----------------------------------------------------------------------===//
9842 //                           X86 Inline Assembly Support
9843 //===----------------------------------------------------------------------===//
9844
9845 static bool LowerToBSwap(CallInst *CI) {
9846   // FIXME: this should verify that we are targetting a 486 or better.  If not,
9847   // we will turn this bswap into something that will be lowered to logical ops
9848   // instead of emitting the bswap asm.  For now, we don't support 486 or lower
9849   // so don't worry about this.
9850
9851   // Verify this is a simple bswap.
9852   if (CI->getNumOperands() != 2 ||
9853       CI->getType() != CI->getOperand(1)->getType() ||
9854       !CI->getType()->isIntegerTy())
9855     return false;
9856
9857   const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
9858   if (!Ty || Ty->getBitWidth() % 16 != 0)
9859     return false;
9860
9861   // Okay, we can do this xform, do so now.
9862   const Type *Tys[] = { Ty };
9863   Module *M = CI->getParent()->getParent()->getParent();
9864   Constant *Int = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
9865
9866   Value *Op = CI->getOperand(1);
9867   Op = CallInst::Create(Int, Op, CI->getName(), CI);
9868
9869   CI->replaceAllUsesWith(Op);
9870   CI->eraseFromParent();
9871   return true;
9872 }
9873
9874 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
9875   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
9876   std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
9877
9878   std::string AsmStr = IA->getAsmString();
9879
9880   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
9881   SmallVector<StringRef, 4> AsmPieces;
9882   SplitString(AsmStr, AsmPieces, "\n");  // ; as separator?
9883
9884   switch (AsmPieces.size()) {
9885   default: return false;
9886   case 1:
9887     AsmStr = AsmPieces[0];
9888     AsmPieces.clear();
9889     SplitString(AsmStr, AsmPieces, " \t");  // Split with whitespace.
9890
9891     // bswap $0
9892     if (AsmPieces.size() == 2 &&
9893         (AsmPieces[0] == "bswap" ||
9894          AsmPieces[0] == "bswapq" ||
9895          AsmPieces[0] == "bswapl") &&
9896         (AsmPieces[1] == "$0" ||
9897          AsmPieces[1] == "${0:q}")) {
9898       // No need to check constraints, nothing other than the equivalent of
9899       // "=r,0" would be valid here.
9900       return LowerToBSwap(CI);
9901     }
9902     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
9903     if (CI->getType()->isIntegerTy(16) &&
9904         AsmPieces.size() == 3 &&
9905         (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
9906         AsmPieces[1] == "$$8," &&
9907         AsmPieces[2] == "${0:w}" &&
9908         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
9909       AsmPieces.clear();
9910       const std::string &Constraints = IA->getConstraintString();
9911       SplitString(StringRef(Constraints).substr(5), AsmPieces, ",");
9912       std::sort(AsmPieces.begin(), AsmPieces.end());
9913       if (AsmPieces.size() == 4 &&
9914           AsmPieces[0] == "~{cc}" &&
9915           AsmPieces[1] == "~{dirflag}" &&
9916           AsmPieces[2] == "~{flags}" &&
9917           AsmPieces[3] == "~{fpsr}") {
9918         return LowerToBSwap(CI);
9919       }
9920     }
9921     break;
9922   case 3:
9923     if (CI->getType()->isIntegerTy(64) &&
9924         Constraints.size() >= 2 &&
9925         Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
9926         Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
9927       // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
9928       SmallVector<StringRef, 4> Words;
9929       SplitString(AsmPieces[0], Words, " \t");
9930       if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
9931         Words.clear();
9932         SplitString(AsmPieces[1], Words, " \t");
9933         if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
9934           Words.clear();
9935           SplitString(AsmPieces[2], Words, " \t,");
9936           if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
9937               Words[2] == "%edx") {
9938             return LowerToBSwap(CI);
9939           }
9940         }
9941       }
9942     }
9943     break;
9944   }
9945   return false;
9946 }
9947
9948
9949
9950 /// getConstraintType - Given a constraint letter, return the type of
9951 /// constraint it is for this target.
9952 X86TargetLowering::ConstraintType
9953 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
9954   if (Constraint.size() == 1) {
9955     switch (Constraint[0]) {
9956     case 'A':
9957       return C_Register;
9958     case 'f':
9959     case 'r':
9960     case 'R':
9961     case 'l':
9962     case 'q':
9963     case 'Q':
9964     case 'x':
9965     case 'y':
9966     case 'Y':
9967       return C_RegisterClass;
9968     case 'e':
9969     case 'Z':
9970       return C_Other;
9971     default:
9972       break;
9973     }
9974   }
9975   return TargetLowering::getConstraintType(Constraint);
9976 }
9977
9978 /// LowerXConstraint - try to replace an X constraint, which matches anything,
9979 /// with another that has more specific requirements based on the type of the
9980 /// corresponding operand.
9981 const char *X86TargetLowering::
9982 LowerXConstraint(EVT ConstraintVT) const {
9983   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
9984   // 'f' like normal targets.
9985   if (ConstraintVT.isFloatingPoint()) {
9986     if (Subtarget->hasSSE2())
9987       return "Y";
9988     if (Subtarget->hasSSE1())
9989       return "x";
9990   }
9991
9992   return TargetLowering::LowerXConstraint(ConstraintVT);
9993 }
9994
9995 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
9996 /// vector.  If it is invalid, don't add anything to Ops.
9997 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
9998                                                      char Constraint,
9999                                                      bool hasMemory,
10000                                                      std::vector<SDValue>&Ops,
10001                                                      SelectionDAG &DAG) const {
10002   SDValue Result(0, 0);
10003
10004   switch (Constraint) {
10005   default: break;
10006   case 'I':
10007     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10008       if (C->getZExtValue() <= 31) {
10009         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10010         break;
10011       }
10012     }
10013     return;
10014   case 'J':
10015     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10016       if (C->getZExtValue() <= 63) {
10017         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10018         break;
10019       }
10020     }
10021     return;
10022   case 'K':
10023     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10024       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
10025         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10026         break;
10027       }
10028     }
10029     return;
10030   case 'N':
10031     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10032       if (C->getZExtValue() <= 255) {
10033         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10034         break;
10035       }
10036     }
10037     return;
10038   case 'e': {
10039     // 32-bit signed value
10040     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10041       const ConstantInt *CI = C->getConstantIntValue();
10042       if (CI->isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
10043                                   C->getSExtValue())) {
10044         // Widen to 64 bits here to get it sign extended.
10045         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
10046         break;
10047       }
10048     // FIXME gcc accepts some relocatable values here too, but only in certain
10049     // memory models; it's complicated.
10050     }
10051     return;
10052   }
10053   case 'Z': {
10054     // 32-bit unsigned value
10055     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10056       const ConstantInt *CI = C->getConstantIntValue();
10057       if (CI->isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
10058                                   C->getZExtValue())) {
10059         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10060         break;
10061       }
10062     }
10063     // FIXME gcc accepts some relocatable values here too, but only in certain
10064     // memory models; it's complicated.
10065     return;
10066   }
10067   case 'i': {
10068     // Literal immediates are always ok.
10069     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
10070       // Widen to 64 bits here to get it sign extended.
10071       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
10072       break;
10073     }
10074
10075     // If we are in non-pic codegen mode, we allow the address of a global (with
10076     // an optional displacement) to be used with 'i'.
10077     GlobalAddressSDNode *GA = 0;
10078     int64_t Offset = 0;
10079
10080     // Match either (GA), (GA+C), (GA+C1+C2), etc.
10081     while (1) {
10082       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
10083         Offset += GA->getOffset();
10084         break;
10085       } else if (Op.getOpcode() == ISD::ADD) {
10086         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
10087           Offset += C->getZExtValue();
10088           Op = Op.getOperand(0);
10089           continue;
10090         }
10091       } else if (Op.getOpcode() == ISD::SUB) {
10092         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
10093           Offset += -C->getZExtValue();
10094           Op = Op.getOperand(0);
10095           continue;
10096         }
10097       }
10098
10099       // Otherwise, this isn't something we can handle, reject it.
10100       return;
10101     }
10102
10103     const GlobalValue *GV = GA->getGlobal();
10104     // If we require an extra load to get this address, as in PIC mode, we
10105     // can't accept it.
10106     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
10107                                                         getTargetMachine())))
10108       return;
10109
10110     if (hasMemory)
10111       Op = LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
10112     else
10113       Op = DAG.getTargetGlobalAddress(GV, GA->getValueType(0), Offset);
10114     Result = Op;
10115     break;
10116   }
10117   }
10118
10119   if (Result.getNode()) {
10120     Ops.push_back(Result);
10121     return;
10122   }
10123   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, hasMemory,
10124                                                       Ops, DAG);
10125 }
10126
10127 std::vector<unsigned> X86TargetLowering::
10128 getRegClassForInlineAsmConstraint(const std::string &Constraint,
10129                                   EVT VT) const {
10130   if (Constraint.size() == 1) {
10131     // FIXME: not handling fp-stack yet!
10132     switch (Constraint[0]) {      // GCC X86 Constraint Letters
10133     default: break;  // Unknown constraint letter
10134     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
10135       if (Subtarget->is64Bit()) {
10136         if (VT == MVT::i32)
10137           return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
10138                                        X86::ESI, X86::EDI, X86::R8D, X86::R9D,
10139                                        X86::R10D,X86::R11D,X86::R12D,
10140                                        X86::R13D,X86::R14D,X86::R15D,
10141                                        X86::EBP, X86::ESP, 0);
10142         else if (VT == MVT::i16)
10143           return make_vector<unsigned>(X86::AX,  X86::DX,  X86::CX, X86::BX,
10144                                        X86::SI,  X86::DI,  X86::R8W,X86::R9W,
10145                                        X86::R10W,X86::R11W,X86::R12W,
10146                                        X86::R13W,X86::R14W,X86::R15W,
10147                                        X86::BP,  X86::SP, 0);
10148         else if (VT == MVT::i8)
10149           return make_vector<unsigned>(X86::AL,  X86::DL,  X86::CL, X86::BL,
10150                                        X86::SIL, X86::DIL, X86::R8B,X86::R9B,
10151                                        X86::R10B,X86::R11B,X86::R12B,
10152                                        X86::R13B,X86::R14B,X86::R15B,
10153                                        X86::BPL, X86::SPL, 0);
10154
10155         else if (VT == MVT::i64)
10156           return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
10157                                        X86::RSI, X86::RDI, X86::R8,  X86::R9,
10158                                        X86::R10, X86::R11, X86::R12,
10159                                        X86::R13, X86::R14, X86::R15,
10160                                        X86::RBP, X86::RSP, 0);
10161
10162         break;
10163       }
10164       // 32-bit fallthrough
10165     case 'Q':   // Q_REGS
10166       if (VT == MVT::i32)
10167         return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
10168       else if (VT == MVT::i16)
10169         return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
10170       else if (VT == MVT::i8)
10171         return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
10172       else if (VT == MVT::i64)
10173         return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
10174       break;
10175     }
10176   }
10177
10178   return std::vector<unsigned>();
10179 }
10180
10181 std::pair<unsigned, const TargetRegisterClass*>
10182 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10183                                                 EVT VT) const {
10184   // First, see if this is a constraint that directly corresponds to an LLVM
10185   // register class.
10186   if (Constraint.size() == 1) {
10187     // GCC Constraint Letters
10188     switch (Constraint[0]) {
10189     default: break;
10190     case 'r':   // GENERAL_REGS
10191     case 'l':   // INDEX_REGS
10192       if (VT == MVT::i8)
10193         return std::make_pair(0U, X86::GR8RegisterClass);
10194       if (VT == MVT::i16)
10195         return std::make_pair(0U, X86::GR16RegisterClass);
10196       if (VT == MVT::i32 || !Subtarget->is64Bit())
10197         return std::make_pair(0U, X86::GR32RegisterClass);
10198       return std::make_pair(0U, X86::GR64RegisterClass);
10199     case 'R':   // LEGACY_REGS
10200       if (VT == MVT::i8)
10201         return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
10202       if (VT == MVT::i16)
10203         return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
10204       if (VT == MVT::i32 || !Subtarget->is64Bit())
10205         return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
10206       return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
10207     case 'f':  // FP Stack registers.
10208       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
10209       // value to the correct fpstack register class.
10210       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
10211         return std::make_pair(0U, X86::RFP32RegisterClass);
10212       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
10213         return std::make_pair(0U, X86::RFP64RegisterClass);
10214       return std::make_pair(0U, X86::RFP80RegisterClass);
10215     case 'y':   // MMX_REGS if MMX allowed.
10216       if (!Subtarget->hasMMX()) break;
10217       return std::make_pair(0U, X86::VR64RegisterClass);
10218     case 'Y':   // SSE_REGS if SSE2 allowed
10219       if (!Subtarget->hasSSE2()) break;
10220       // FALL THROUGH.
10221     case 'x':   // SSE_REGS if SSE1 allowed
10222       if (!Subtarget->hasSSE1()) break;
10223
10224       switch (VT.getSimpleVT().SimpleTy) {
10225       default: break;
10226       // Scalar SSE types.
10227       case MVT::f32:
10228       case MVT::i32:
10229         return std::make_pair(0U, X86::FR32RegisterClass);
10230       case MVT::f64:
10231       case MVT::i64:
10232         return std::make_pair(0U, X86::FR64RegisterClass);
10233       // Vector types.
10234       case MVT::v16i8:
10235       case MVT::v8i16:
10236       case MVT::v4i32:
10237       case MVT::v2i64:
10238       case MVT::v4f32:
10239       case MVT::v2f64:
10240         return std::make_pair(0U, X86::VR128RegisterClass);
10241       }
10242       break;
10243     }
10244   }
10245
10246   // Use the default implementation in TargetLowering to convert the register
10247   // constraint into a member of a register class.
10248   std::pair<unsigned, const TargetRegisterClass*> Res;
10249   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10250
10251   // Not found as a standard register?
10252   if (Res.second == 0) {
10253     // Map st(0) -> st(7) -> ST0
10254     if (Constraint.size() == 7 && Constraint[0] == '{' &&
10255         tolower(Constraint[1]) == 's' &&
10256         tolower(Constraint[2]) == 't' &&
10257         Constraint[3] == '(' &&
10258         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
10259         Constraint[5] == ')' &&
10260         Constraint[6] == '}') {
10261
10262       Res.first = X86::ST0+Constraint[4]-'0';
10263       Res.second = X86::RFP80RegisterClass;
10264       return Res;
10265     }
10266
10267     // GCC allows "st(0)" to be called just plain "st".
10268     if (StringRef("{st}").equals_lower(Constraint)) {
10269       Res.first = X86::ST0;
10270       Res.second = X86::RFP80RegisterClass;
10271       return Res;
10272     }
10273
10274     // flags -> EFLAGS
10275     if (StringRef("{flags}").equals_lower(Constraint)) {
10276       Res.first = X86::EFLAGS;
10277       Res.second = X86::CCRRegisterClass;
10278       return Res;
10279     }
10280
10281     // 'A' means EAX + EDX.
10282     if (Constraint == "A") {
10283       Res.first = X86::EAX;
10284       Res.second = X86::GR32_ADRegisterClass;
10285       return Res;
10286     }
10287     return Res;
10288   }
10289
10290   // Otherwise, check to see if this is a register class of the wrong value
10291   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
10292   // turn into {ax},{dx}.
10293   if (Res.second->hasType(VT))
10294     return Res;   // Correct type already, nothing to do.
10295
10296   // All of the single-register GCC register classes map their values onto
10297   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
10298   // really want an 8-bit or 32-bit register, map to the appropriate register
10299   // class and return the appropriate register.
10300   if (Res.second == X86::GR16RegisterClass) {
10301     if (VT == MVT::i8) {
10302       unsigned DestReg = 0;
10303       switch (Res.first) {
10304       default: break;
10305       case X86::AX: DestReg = X86::AL; break;
10306       case X86::DX: DestReg = X86::DL; break;
10307       case X86::CX: DestReg = X86::CL; break;
10308       case X86::BX: DestReg = X86::BL; break;
10309       }
10310       if (DestReg) {
10311         Res.first = DestReg;
10312         Res.second = X86::GR8RegisterClass;
10313       }
10314     } else if (VT == MVT::i32) {
10315       unsigned DestReg = 0;
10316       switch (Res.first) {
10317       default: break;
10318       case X86::AX: DestReg = X86::EAX; break;
10319       case X86::DX: DestReg = X86::EDX; break;
10320       case X86::CX: DestReg = X86::ECX; break;
10321       case X86::BX: DestReg = X86::EBX; break;
10322       case X86::SI: DestReg = X86::ESI; break;
10323       case X86::DI: DestReg = X86::EDI; break;
10324       case X86::BP: DestReg = X86::EBP; break;
10325       case X86::SP: DestReg = X86::ESP; break;
10326       }
10327       if (DestReg) {
10328         Res.first = DestReg;
10329         Res.second = X86::GR32RegisterClass;
10330       }
10331     } else if (VT == MVT::i64) {
10332       unsigned DestReg = 0;
10333       switch (Res.first) {
10334       default: break;
10335       case X86::AX: DestReg = X86::RAX; break;
10336       case X86::DX: DestReg = X86::RDX; break;
10337       case X86::CX: DestReg = X86::RCX; break;
10338       case X86::BX: DestReg = X86::RBX; break;
10339       case X86::SI: DestReg = X86::RSI; break;
10340       case X86::DI: DestReg = X86::RDI; break;
10341       case X86::BP: DestReg = X86::RBP; break;
10342       case X86::SP: DestReg = X86::RSP; break;
10343       }
10344       if (DestReg) {
10345         Res.first = DestReg;
10346         Res.second = X86::GR64RegisterClass;
10347       }
10348     }
10349   } else if (Res.second == X86::FR32RegisterClass ||
10350              Res.second == X86::FR64RegisterClass ||
10351              Res.second == X86::VR128RegisterClass) {
10352     // Handle references to XMM physical registers that got mapped into the
10353     // wrong class.  This can happen with constraints like {xmm0} where the
10354     // target independent register mapper will just pick the first match it can
10355     // find, ignoring the required type.
10356     if (VT == MVT::f32)
10357       Res.second = X86::FR32RegisterClass;
10358     else if (VT == MVT::f64)
10359       Res.second = X86::FR64RegisterClass;
10360     else if (X86::VR128RegisterClass->hasType(VT))
10361       Res.second = X86::VR128RegisterClass;
10362   }
10363
10364   return Res;
10365 }